1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/Config.h"
15 #ifndef LLDB_DISABLE_POSIX
16 #include <netinet/in.h>
17 #include <sys/mman.h> // for mmap
18 #include <sys/socket.h>
22 #include <sys/types.h>
31 #include "lldb/Breakpoint/Watchpoint.h"
32 #include "lldb/Core/ArchSpec.h"
33 #include "lldb/Core/Debugger.h"
34 #include "lldb/Core/Module.h"
35 #include "lldb/Core/ModuleSpec.h"
36 #include "lldb/Core/PluginManager.h"
37 #include "lldb/Core/State.h"
38 #include "lldb/Core/StreamFile.h"
39 #include "lldb/Core/Value.h"
40 #include "lldb/DataFormatters/FormatManager.h"
41 #include "lldb/Host/ConnectionFileDescriptor.h"
42 #include "lldb/Host/FileSystem.h"
43 #include "lldb/Host/HostThread.h"
44 #include "lldb/Host/PosixApi.h"
45 #include "lldb/Host/PseudoTerminal.h"
46 #include "lldb/Host/StringConvert.h"
47 #include "lldb/Host/Symbols.h"
48 #include "lldb/Host/ThreadLauncher.h"
49 #include "lldb/Host/XML.h"
50 #include "lldb/Interpreter/Args.h"
51 #include "lldb/Interpreter/CommandInterpreter.h"
52 #include "lldb/Interpreter/CommandObject.h"
53 #include "lldb/Interpreter/CommandObjectMultiword.h"
54 #include "lldb/Interpreter/CommandReturnObject.h"
55 #include "lldb/Interpreter/OptionGroupBoolean.h"
56 #include "lldb/Interpreter/OptionGroupUInt64.h"
57 #include "lldb/Interpreter/OptionValueProperties.h"
58 #include "lldb/Interpreter/Options.h"
59 #include "lldb/Interpreter/Property.h"
60 #include "lldb/Symbol/ObjectFile.h"
61 #include "lldb/Target/ABI.h"
62 #include "lldb/Target/DynamicLoader.h"
63 #include "lldb/Target/SystemRuntime.h"
64 #include "lldb/Target/Target.h"
65 #include "lldb/Target/TargetList.h"
66 #include "lldb/Target/ThreadPlanCallFunction.h"
67 #include "lldb/Utility/CleanUp.h"
68 #include "lldb/Utility/FileSpec.h"
69 #include "lldb/Utility/StreamString.h"
70 #include "lldb/Utility/Timer.h"
73 #include "GDBRemoteRegisterContext.h"
74 //#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
75 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
76 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
77 #include "Plugins/Process/Utility/StopInfoMachException.h"
78 #include "ProcessGDBRemote.h"
79 #include "ProcessGDBRemoteLog.h"
80 #include "ThreadGDBRemote.h"
81 #include "Utility/StringExtractorGDBRemote.h"
82 #include "lldb/Host/Host.h"
84 #include "llvm/ADT/StringSwitch.h"
85 #include "llvm/Support/Threading.h"
86 #include "llvm/Support/raw_ostream.h"
88 #define DEBUGSERVER_BASENAME "debugserver"
90 using namespace lldb_private;
91 using namespace lldb_private::process_gdb_remote;
94 // Provide a function that can easily dump the packet history if we know a
95 // ProcessGDBRemote * value (which we can get from logs or from debugging).
96 // We need the function in the lldb namespace so it makes it into the final
97 // executable since the LLDB shared library only exports stuff in the lldb
98 // namespace. This allows you to attach with a debugger and call this
99 // function and get the packet history dumped to a file.
100 void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
102 Status error(strm.GetFile().Open(path, File::eOpenOptionWrite |
103 File::eOpenOptionCanCreate));
105 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
111 static PropertyDefinition g_properties[] = {
112 {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL, NULL,
113 "Specify the default packet timeout in seconds."},
114 {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL, NULL,
115 "The file that provides the description for remote target registers."},
116 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
118 enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile };
120 class PluginProperties : public Properties {
122 static ConstString GetSettingName() {
123 return ProcessGDBRemote::GetPluginNameStatic();
126 PluginProperties() : Properties() {
127 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
128 m_collection_sp->Initialize(g_properties);
131 virtual ~PluginProperties() {}
133 uint64_t GetPacketTimeout() {
134 const uint32_t idx = ePropertyPacketTimeout;
135 return m_collection_sp->GetPropertyAtIndexAsUInt64(
136 NULL, idx, g_properties[idx].default_uint_value);
139 bool SetPacketTimeout(uint64_t timeout) {
140 const uint32_t idx = ePropertyPacketTimeout;
141 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
144 FileSpec GetTargetDefinitionFile() const {
145 const uint32_t idx = ePropertyTargetDefinitionFile;
146 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
150 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
152 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
153 static ProcessKDPPropertiesSP g_settings_sp;
155 g_settings_sp.reset(new PluginProperties());
156 return g_settings_sp;
159 } // anonymous namespace end
161 // TODO Randomly assigning a port is unsafe. We should get an unused
162 // ephemeral port from the kernel and make sure we reserve it before passing
163 // it to debugserver.
165 #if defined(__APPLE__)
166 #define LOW_PORT (IPPORT_RESERVED)
167 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
169 #define LOW_PORT (1024u)
170 #define HIGH_PORT (49151u)
173 #if defined(__APPLE__) && \
174 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
175 static bool rand_initialized = false;
177 static inline uint16_t get_random_port() {
178 if (!rand_initialized) {
179 time_t seed = time(NULL);
181 rand_initialized = true;
184 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
188 ConstString ProcessGDBRemote::GetPluginNameStatic() {
189 static ConstString g_name("gdb-remote");
193 const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
194 return "GDB Remote protocol based debugging plug-in.";
197 void ProcessGDBRemote::Terminate() {
198 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
202 ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
203 ListenerSP listener_sp,
204 const FileSpec *crash_file_path) {
205 lldb::ProcessSP process_sp;
206 if (crash_file_path == NULL)
207 process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp));
211 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
212 bool plugin_specified_by_name) {
213 if (plugin_specified_by_name)
216 // For now we are just making sure the file exists for a given module
217 Module *exe_module = target_sp->GetExecutableModulePointer();
219 ObjectFile *exe_objfile = exe_module->GetObjectFile();
220 // We can't debug core files...
221 switch (exe_objfile->GetType()) {
222 case ObjectFile::eTypeInvalid:
223 case ObjectFile::eTypeCoreFile:
224 case ObjectFile::eTypeDebugInfo:
225 case ObjectFile::eTypeObjectFile:
226 case ObjectFile::eTypeSharedLibrary:
227 case ObjectFile::eTypeStubLibrary:
228 case ObjectFile::eTypeJIT:
230 case ObjectFile::eTypeExecutable:
231 case ObjectFile::eTypeDynamicLinker:
232 case ObjectFile::eTypeUnknown:
235 return exe_module->GetFileSpec().Exists();
237 // However, if there is no executable module, we return true since we might be
238 // preparing to attach.
242 //----------------------------------------------------------------------
243 // ProcessGDBRemote constructor
244 //----------------------------------------------------------------------
245 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
246 ListenerSP listener_sp)
247 : Process(target_sp, listener_sp), m_flags(0), m_gdb_comm(),
248 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
250 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
252 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
253 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
254 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
255 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
256 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
257 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
258 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
259 m_command_sp(), m_breakpoint_pc_offset(0),
260 m_initial_tid(LLDB_INVALID_THREAD_ID) {
261 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
262 "async thread should exit");
263 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
264 "async thread continue");
265 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
266 "async thread did exit");
268 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
270 const uint32_t async_event_mask =
271 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
273 if (m_async_listener_sp->StartListeningForEvents(
274 &m_async_broadcaster, async_event_mask) != async_event_mask) {
276 log->Printf("ProcessGDBRemote::%s failed to listen for "
277 "m_async_broadcaster events",
281 const uint32_t gdb_event_mask =
282 Communication::eBroadcastBitReadThreadDidExit |
283 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
284 if (m_async_listener_sp->StartListeningForEvents(
285 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
287 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
291 const uint64_t timeout_seconds =
292 GetGlobalPluginProperties()->GetPacketTimeout();
293 if (timeout_seconds > 0)
294 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
297 //----------------------------------------------------------------------
299 //----------------------------------------------------------------------
300 ProcessGDBRemote::~ProcessGDBRemote() {
301 // m_mach_process.UnregisterNotificationCallbacks (this);
303 // We need to call finalize on the process before destroying ourselves
304 // to make sure all of the broadcaster cleanup goes as planned. If we
305 // destruct this class, then Process::~Process() might have problems
306 // trying to fully destroy the broadcaster.
309 // The general Finalize is going to try to destroy the process and that SHOULD
310 // shut down the async thread. However, if we don't kill it it will get
312 // its connection will go away so when it wakes up it will crash. So kill it
315 KillDebugserverProcess();
318 //----------------------------------------------------------------------
320 //----------------------------------------------------------------------
321 ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
323 uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
325 bool ProcessGDBRemote::ParsePythonTargetDefinition(
326 const FileSpec &target_definition_fspec) {
327 ScriptInterpreter *interpreter =
328 GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
330 StructuredData::ObjectSP module_object_sp(
331 interpreter->LoadPluginModule(target_definition_fspec, error));
332 if (module_object_sp) {
333 StructuredData::DictionarySP target_definition_sp(
334 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
335 "gdb-server-target-definition", error));
337 if (target_definition_sp) {
338 StructuredData::ObjectSP target_object(
339 target_definition_sp->GetValueForKey("host-info"));
341 if (auto host_info_dict = target_object->GetAsDictionary()) {
342 StructuredData::ObjectSP triple_value =
343 host_info_dict->GetValueForKey("triple");
344 if (auto triple_string_value = triple_value->GetAsString()) {
345 std::string triple_string = triple_string_value->GetValue();
346 ArchSpec host_arch(triple_string.c_str());
347 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
348 GetTarget().SetArchitecture(host_arch);
353 m_breakpoint_pc_offset = 0;
354 StructuredData::ObjectSP breakpoint_pc_offset_value =
355 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
356 if (breakpoint_pc_offset_value) {
357 if (auto breakpoint_pc_int_value =
358 breakpoint_pc_offset_value->GetAsInteger())
359 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
362 if (m_register_info.SetRegisterInfo(*target_definition_sp,
363 GetTarget().GetArchitecture()) > 0) {
371 // If the remote stub didn't give us eh_frame or DWARF register numbers for a
373 // see if the ABI can provide them.
374 // DWARF and eh_frame register numbers are defined as a part of the ABI.
375 static void AugmentRegisterInfoViaABI(RegisterInfo ®_info,
376 ConstString reg_name, ABISP abi_sp) {
377 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM ||
378 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) {
380 RegisterInfo abi_reg_info;
381 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
382 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
383 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) {
384 reg_info.kinds[eRegisterKindEHFrame] =
385 abi_reg_info.kinds[eRegisterKindEHFrame];
387 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
388 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) {
389 reg_info.kinds[eRegisterKindDWARF] =
390 abi_reg_info.kinds[eRegisterKindDWARF];
392 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
393 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) {
394 reg_info.kinds[eRegisterKindGeneric] =
395 abi_reg_info.kinds[eRegisterKindGeneric];
402 static size_t SplitCommaSeparatedRegisterNumberString(
403 const llvm::StringRef &comma_separated_regiter_numbers,
404 std::vector<uint32_t> ®nums, int base) {
406 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
407 value_pair.second = comma_separated_regiter_numbers;
409 value_pair = value_pair.second.split(',');
410 if (!value_pair.first.empty()) {
411 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
412 LLDB_INVALID_REGNUM, base);
413 if (reg != LLDB_INVALID_REGNUM)
414 regnums.push_back(reg);
416 } while (!value_pair.second.empty());
417 return regnums.size();
420 void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
421 if (!force && m_register_info.GetNumRegisters() > 0)
424 m_register_info.Clear();
426 // Check if qHostInfo specified a specific packet timeout for this connection.
427 // If so then lets update our setting so the user knows what the timeout is
429 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
430 if (host_packet_timeout > std::chrono::seconds(0)) {
431 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
434 // Register info search order:
435 // 1 - Use the target definition python file if one is specified.
436 // 2 - If the target definition doesn't have any of the info from the
437 // target.xml (registers) then proceed to read the target.xml.
438 // 3 - Fall back on the qRegisterInfo packets.
440 FileSpec target_definition_fspec =
441 GetGlobalPluginProperties()->GetTargetDefinitionFile();
442 if (!target_definition_fspec.Exists()) {
443 // If the filename doesn't exist, it may be a ~ not having been expanded -
444 // try to resolve it.
445 target_definition_fspec.ResolvePath();
447 if (target_definition_fspec) {
448 // See if we can get register definitions from a python file
449 if (ParsePythonTargetDefinition(target_definition_fspec)) {
452 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
453 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
454 target_definition_fspec.GetPath().c_str());
458 const ArchSpec &target_arch = GetTarget().GetArchitecture();
459 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
460 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
462 // Use the process' architecture instead of the host arch, if available
463 ArchSpec arch_to_use;
464 if (remote_process_arch.IsValid())
465 arch_to_use = remote_process_arch;
467 arch_to_use = remote_host_arch;
469 if (!arch_to_use.IsValid())
470 arch_to_use = target_arch;
472 if (GetGDBServerRegisterInfo(arch_to_use))
476 uint32_t reg_offset = 0;
477 uint32_t reg_num = 0;
478 for (StringExtractorGDBRemote::ResponseType response_type =
479 StringExtractorGDBRemote::eResponse;
480 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
481 const int packet_len =
482 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
483 assert(packet_len < (int)sizeof(packet));
484 UNUSED_IF_ASSERT_DISABLED(packet_len);
485 StringExtractorGDBRemote response;
486 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
487 GDBRemoteCommunication::PacketResult::Success) {
488 response_type = response.GetResponseType();
489 if (response_type == StringExtractorGDBRemote::eResponse) {
490 llvm::StringRef name;
491 llvm::StringRef value;
492 ConstString reg_name;
493 ConstString alt_name;
494 ConstString set_name;
495 std::vector<uint32_t> value_regs;
496 std::vector<uint32_t> invalidate_regs;
497 std::vector<uint8_t> dwarf_opcode_bytes;
498 RegisterInfo reg_info = {
502 reg_offset, // offset
503 eEncodingUint, // encoding
504 eFormatHex, // format
506 LLDB_INVALID_REGNUM, // eh_frame reg num
507 LLDB_INVALID_REGNUM, // DWARF reg num
508 LLDB_INVALID_REGNUM, // generic reg num
509 reg_num, // process plugin reg num
510 reg_num // native register number
514 NULL, // Dwarf expression opcode bytes pointer
515 0 // Dwarf expression opcode bytes length
518 while (response.GetNameColonValue(name, value)) {
519 if (name.equals("name")) {
520 reg_name.SetString(value);
521 } else if (name.equals("alt-name")) {
522 alt_name.SetString(value);
523 } else if (name.equals("bitsize")) {
524 value.getAsInteger(0, reg_info.byte_size);
525 reg_info.byte_size /= CHAR_BIT;
526 } else if (name.equals("offset")) {
527 if (value.getAsInteger(0, reg_offset))
528 reg_offset = UINT32_MAX;
529 } else if (name.equals("encoding")) {
530 const Encoding encoding = Args::StringToEncoding(value);
531 if (encoding != eEncodingInvalid)
532 reg_info.encoding = encoding;
533 } else if (name.equals("format")) {
534 Format format = eFormatInvalid;
535 if (Args::StringToFormat(value.str().c_str(), format, NULL)
537 reg_info.format = format;
540 llvm::StringSwitch<Format>(value)
541 .Case("binary", eFormatBinary)
542 .Case("decimal", eFormatDecimal)
543 .Case("hex", eFormatHex)
544 .Case("float", eFormatFloat)
545 .Case("vector-sint8", eFormatVectorOfSInt8)
546 .Case("vector-uint8", eFormatVectorOfUInt8)
547 .Case("vector-sint16", eFormatVectorOfSInt16)
548 .Case("vector-uint16", eFormatVectorOfUInt16)
549 .Case("vector-sint32", eFormatVectorOfSInt32)
550 .Case("vector-uint32", eFormatVectorOfUInt32)
551 .Case("vector-float32", eFormatVectorOfFloat32)
552 .Case("vector-uint64", eFormatVectorOfUInt64)
553 .Case("vector-uint128", eFormatVectorOfUInt128)
554 .Default(eFormatInvalid);
556 } else if (name.equals("set")) {
557 set_name.SetString(value);
558 } else if (name.equals("gcc") || name.equals("ehframe")) {
559 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
560 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
561 } else if (name.equals("dwarf")) {
562 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
563 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
564 } else if (name.equals("generic")) {
565 reg_info.kinds[eRegisterKindGeneric] =
566 Args::StringToGenericRegister(value);
567 } else if (name.equals("container-regs")) {
568 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
569 } else if (name.equals("invalidate-regs")) {
570 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
571 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
572 size_t dwarf_opcode_len = value.size() / 2;
573 assert(dwarf_opcode_len > 0);
575 dwarf_opcode_bytes.resize(dwarf_opcode_len);
576 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
578 StringExtractor opcode_extractor(value);
580 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
581 assert(dwarf_opcode_len == ret_val);
582 UNUSED_IF_ASSERT_DISABLED(ret_val);
583 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
587 reg_info.byte_offset = reg_offset;
588 assert(reg_info.byte_size != 0);
589 reg_offset += reg_info.byte_size;
590 if (!value_regs.empty()) {
591 value_regs.push_back(LLDB_INVALID_REGNUM);
592 reg_info.value_regs = value_regs.data();
594 if (!invalidate_regs.empty()) {
595 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
596 reg_info.invalidate_regs = invalidate_regs.data();
599 // We have to make a temporary ABI here, and not use the GetABI because
601 // gets called in DidAttach, when the target architecture (and
602 // consequently the ABI we'll get from
603 // the process) may be wrong.
604 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use);
606 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use);
608 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
610 break; // ensure exit before reg_num is incremented
617 if (m_register_info.GetNumRegisters() > 0) {
618 m_register_info.Finalize(GetTarget().GetArchitecture());
622 // We didn't get anything if the accumulated reg_num is zero. See if we are
623 // debugging ARM and fill with a hard coded register set until we can get an
624 // updated debugserver down on the devices.
625 // On the other hand, if the accumulated reg_num is positive, see if we can
626 // add composite registers to the existing primordial ones.
627 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
629 if (!target_arch.IsValid()) {
630 if (arch_to_use.IsValid() &&
631 (arch_to_use.GetMachine() == llvm::Triple::arm ||
632 arch_to_use.GetMachine() == llvm::Triple::thumb) &&
633 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
634 m_register_info.HardcodeARMRegisters(from_scratch);
635 } else if (target_arch.GetMachine() == llvm::Triple::arm ||
636 target_arch.GetMachine() == llvm::Triple::thumb) {
637 m_register_info.HardcodeARMRegisters(from_scratch);
640 // At this point, we can finalize our register info.
641 m_register_info.Finalize(GetTarget().GetArchitecture());
644 Status ProcessGDBRemote::WillLaunch(Module *module) {
645 return WillLaunchOrAttach();
648 Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
649 return WillLaunchOrAttach();
652 Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
653 bool wait_for_launch) {
654 return WillLaunchOrAttach();
657 Status ProcessGDBRemote::DoConnectRemote(Stream *strm,
658 llvm::StringRef remote_url) {
659 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
660 Status error(WillLaunchOrAttach());
665 error = ConnectToDebugserver(remote_url);
671 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
672 if (pid == LLDB_INVALID_PROCESS_ID) {
673 // We don't have a valid process ID, so note that we are connected
674 // and could now request to launch or attach, or get remote process
676 SetPrivateState(eStateConnected);
678 // We have a valid process
681 StringExtractorGDBRemote response;
682 if (m_gdb_comm.GetStopReply(response)) {
683 SetLastStopPacket(response);
685 // '?' Packets must be handled differently in non-stop mode
686 if (GetTarget().GetNonStopModeEnabled())
687 HandleStopReplySequence();
689 Target &target = GetTarget();
690 if (!target.GetArchitecture().IsValid()) {
691 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
692 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
694 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
698 const StateType state = SetThreadStopInfo(response);
699 if (state != eStateInvalid) {
700 SetPrivateState(state);
702 error.SetErrorStringWithFormat(
703 "Process %" PRIu64 " was reported after connecting to "
704 "'%s', but state was not stopped: %s",
705 pid, remote_url.str().c_str(), StateAsCString(state));
707 error.SetErrorStringWithFormat("Process %" PRIu64
708 " was reported after connecting to '%s', "
709 "but no stop reply packet was received",
710 pid, remote_url.str().c_str());
714 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
715 ": normalizing target architecture initial triple: %s "
716 "(GetTarget().GetArchitecture().IsValid() %s, "
717 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
718 __FUNCTION__, GetID(),
719 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
720 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
721 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
723 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
724 m_gdb_comm.GetHostArchitecture().IsValid()) {
725 // Prefer the *process'* architecture over that of the *host*, if available.
726 if (m_gdb_comm.GetProcessArchitecture().IsValid())
727 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
729 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
733 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
734 ": normalized target architecture triple: %s",
735 __FUNCTION__, GetID(),
736 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
738 if (error.Success()) {
739 PlatformSP platform_sp = GetTarget().GetPlatform();
740 if (platform_sp && platform_sp->IsConnected())
741 SetUnixSignals(platform_sp->GetUnixSignals());
743 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
749 Status ProcessGDBRemote::WillLaunchOrAttach() {
751 m_stdio_communication.Clear();
755 //----------------------------------------------------------------------
757 //----------------------------------------------------------------------
758 Status ProcessGDBRemote::DoLaunch(Module *exe_module,
759 ProcessLaunchInfo &launch_info) {
760 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
764 log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__);
766 uint32_t launch_flags = launch_info.GetFlags().Get();
767 FileSpec stdin_file_spec{};
768 FileSpec stdout_file_spec{};
769 FileSpec stderr_file_spec{};
770 FileSpec working_dir = launch_info.GetWorkingDirectory();
772 const FileAction *file_action;
773 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
775 if (file_action->GetAction() == FileAction::eFileActionOpen)
776 stdin_file_spec = file_action->GetFileSpec();
778 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
780 if (file_action->GetAction() == FileAction::eFileActionOpen)
781 stdout_file_spec = file_action->GetFileSpec();
783 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
785 if (file_action->GetAction() == FileAction::eFileActionOpen)
786 stderr_file_spec = file_action->GetFileSpec();
790 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
791 log->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
792 "launch_info: stdin=%s, stdout=%s, stderr=%s",
794 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
795 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
796 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
798 log->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info",
802 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
803 if (stdin_file_spec || disable_stdio) {
804 // the inferior will be reading stdin from the specified file
805 // or stdio is completely disabled
806 m_stdin_forward = false;
808 m_stdin_forward = true;
811 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
812 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
813 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
814 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
815 // ::LogSetLogFile ("/dev/stdout");
817 ObjectFile *object_file = exe_module->GetObjectFile();
819 error = EstablishConnectionIfNeeded(launch_info);
820 if (error.Success()) {
821 lldb_utility::PseudoTerminal pty;
822 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
824 PlatformSP platform_sp(GetTarget().GetPlatform());
826 // set to /dev/null unless redirected to a file above
827 if (!stdin_file_spec)
828 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
829 if (!stdout_file_spec)
830 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
831 if (!stderr_file_spec)
832 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
833 } else if (platform_sp && platform_sp->IsHost()) {
834 // If the debugserver is local and we aren't disabling STDIO, lets use
835 // a pseudo terminal to instead of relying on the 'O' packets for stdio
836 // since 'O' packets can really slow down debugging if the inferior
837 // does a lot of output.
838 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
839 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) {
840 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
842 if (!stdin_file_spec)
843 stdin_file_spec = slave_name;
845 if (!stdout_file_spec)
846 stdout_file_spec = slave_name;
848 if (!stderr_file_spec)
849 stderr_file_spec = slave_name;
853 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
854 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
856 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
857 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
858 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
862 log->Printf("ProcessGDBRemote::%s final STDIO paths after all "
863 "adjustments: stdin=%s, stdout=%s, stderr=%s",
865 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
866 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
867 stderr_file_spec ? stderr_file_spec.GetCString()
871 m_gdb_comm.SetSTDIN(stdin_file_spec);
872 if (stdout_file_spec)
873 m_gdb_comm.SetSTDOUT(stdout_file_spec);
874 if (stderr_file_spec)
875 m_gdb_comm.SetSTDERR(stderr_file_spec);
877 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
878 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
880 m_gdb_comm.SendLaunchArchPacket(
881 GetTarget().GetArchitecture().GetArchitectureName());
883 const char *launch_event_data = launch_info.GetLaunchEventData();
884 if (launch_event_data != NULL && *launch_event_data != '\0')
885 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
888 m_gdb_comm.SetWorkingDir(working_dir);
891 // Send the environment and the program + arguments after we connect
892 const Args &environment = launch_info.GetEnvironmentEntries();
893 if (environment.GetArgumentCount()) {
894 size_t num_environment_entries = environment.GetArgumentCount();
895 for (size_t i = 0; i < num_environment_entries; ++i) {
896 const char *env_entry = environment.GetArgumentAtIndex(i);
897 if (env_entry == NULL ||
898 m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
904 // Scope for the scoped timeout object
905 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
906 std::chrono::seconds(10));
908 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
909 if (arg_packet_err == 0) {
910 std::string error_str;
911 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
912 SetID(m_gdb_comm.GetCurrentProcessID());
914 error.SetErrorString(error_str.c_str());
917 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
922 if (GetID() == LLDB_INVALID_PROCESS_ID) {
924 log->Printf("failed to connect to debugserver: %s",
926 KillDebugserverProcess();
930 StringExtractorGDBRemote response;
931 if (m_gdb_comm.GetStopReply(response)) {
932 SetLastStopPacket(response);
933 // '?' Packets must be handled differently in non-stop mode
934 if (GetTarget().GetNonStopModeEnabled())
935 HandleStopReplySequence();
937 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
939 if (process_arch.IsValid()) {
940 GetTarget().MergeArchitecture(process_arch);
942 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
943 if (host_arch.IsValid())
944 GetTarget().MergeArchitecture(host_arch);
947 SetPrivateState(SetThreadStopInfo(response));
949 if (!disable_stdio) {
950 if (pty.GetMasterFileDescriptor() !=
951 lldb_utility::PseudoTerminal::invalid_fd)
952 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
957 log->Printf("failed to connect to debugserver: %s", error.AsCString());
960 // Set our user ID to an invalid process ID.
961 SetID(LLDB_INVALID_PROCESS_ID);
962 error.SetErrorStringWithFormat(
963 "failed to get object file from '%s' for arch %s",
964 exe_module->GetFileSpec().GetFilename().AsCString(),
965 exe_module->GetArchitecture().GetArchitectureName());
970 Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
972 // Only connect if we have a valid connect URL
973 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
975 if (!connect_url.empty()) {
977 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
978 connect_url.str().c_str());
979 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
980 new ConnectionFileDescriptor());
982 const uint32_t max_retry_count = 50;
983 uint32_t retry_count = 0;
984 while (!m_gdb_comm.IsConnected()) {
985 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
986 m_gdb_comm.SetConnection(conn_ap.release());
988 } else if (error.WasInterrupted()) {
989 // If we were interrupted, don't keep retrying.
995 if (retry_count >= max_retry_count)
1003 if (!m_gdb_comm.IsConnected()) {
1004 if (error.Success())
1005 error.SetErrorString("not connected to remote gdb server");
1009 // Start the communications read thread so all incoming data can be
1010 // parsed into packets and queued as they arrive.
1011 if (GetTarget().GetNonStopModeEnabled())
1012 m_gdb_comm.StartReadThread();
1014 // We always seem to be able to open a connection to a local port
1015 // so we need to make sure we can then send data to it. If we can't
1016 // then we aren't actually connected to anything, so try and do the
1017 // handshake with the remote GDB server and make sure that goes
1019 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1020 m_gdb_comm.Disconnect();
1021 if (error.Success())
1022 error.SetErrorString("not connected to remote gdb server");
1026 // Send $QNonStop:1 packet on startup if required
1027 if (GetTarget().GetNonStopModeEnabled())
1028 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1030 m_gdb_comm.GetEchoSupported();
1031 m_gdb_comm.GetThreadSuffixSupported();
1032 m_gdb_comm.GetListThreadsInStopReplySupported();
1033 m_gdb_comm.GetHostInfo();
1034 m_gdb_comm.GetVContSupported('c');
1035 m_gdb_comm.GetVAttachOrWaitSupported();
1036 m_gdb_comm.EnableErrorStringInPacket();
1038 // Ask the remote server for the default thread id
1039 if (GetTarget().GetNonStopModeEnabled())
1040 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1042 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1043 for (size_t idx = 0; idx < num_cmds; idx++) {
1044 StringExtractorGDBRemote response;
1045 m_gdb_comm.SendPacketAndWaitForResponse(
1046 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1051 void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1052 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1054 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1055 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1056 BuildDynamicRegisterInfo(false);
1058 // See if the GDB server supports the qHostInfo information
1060 // See if the GDB server supports the qProcessInfo packet, if so
1061 // prefer that over the Host information as it will be more specific
1064 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1065 if (remote_process_arch.IsValid()) {
1066 process_arch = remote_process_arch;
1068 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1070 __FUNCTION__, process_arch.GetArchitectureName()
1071 ? process_arch.GetArchitectureName()
1073 process_arch.GetTriple().getTriple().c_str()
1074 ? process_arch.GetTriple().getTriple().c_str()
1077 process_arch = m_gdb_comm.GetHostArchitecture();
1079 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1080 "architecture, using gdb-remote host architecture %s %s",
1081 __FUNCTION__, process_arch.GetArchitectureName()
1082 ? process_arch.GetArchitectureName()
1084 process_arch.GetTriple().getTriple().c_str()
1085 ? process_arch.GetTriple().getTriple().c_str()
1089 if (process_arch.IsValid()) {
1090 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1091 if (target_arch.IsValid()) {
1094 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1095 __FUNCTION__, target_arch.GetArchitectureName()
1096 ? target_arch.GetArchitectureName()
1098 target_arch.GetTriple().getTriple().c_str()
1099 ? target_arch.GetTriple().getTriple().c_str()
1102 // If the remote host is ARM and we have apple as the vendor, then
1103 // ARM executables and shared libraries can have mixed ARM
1105 // You can have an armv6 executable, and if the host is armv7, then the
1106 // system will load the best possible architecture for all shared
1108 // it has, so we really need to take the remote host architecture as our
1109 // defacto architecture in this case.
1111 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1112 process_arch.GetMachine() == llvm::Triple::thumb) &&
1113 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1114 GetTarget().SetArchitecture(process_arch);
1116 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1117 "setting target arch to %s %s",
1118 __FUNCTION__, process_arch.GetArchitectureName()
1119 ? process_arch.GetArchitectureName()
1121 process_arch.GetTriple().getTriple().c_str()
1122 ? process_arch.GetTriple().getTriple().c_str()
1125 // Fill in what is missing in the triple
1126 const llvm::Triple &remote_triple = process_arch.GetTriple();
1127 llvm::Triple new_target_triple = target_arch.GetTriple();
1128 if (new_target_triple.getVendorName().size() == 0) {
1129 new_target_triple.setVendor(remote_triple.getVendor());
1131 if (new_target_triple.getOSName().size() == 0) {
1132 new_target_triple.setOS(remote_triple.getOS());
1134 if (new_target_triple.getEnvironmentName().size() == 0)
1135 new_target_triple.setEnvironment(
1136 remote_triple.getEnvironment());
1139 ArchSpec new_target_arch = target_arch;
1140 new_target_arch.SetTriple(new_target_triple);
1141 GetTarget().SetArchitecture(new_target_arch);
1146 log->Printf("ProcessGDBRemote::%s final target arch after "
1147 "adjustments for remote architecture: %s %s",
1148 __FUNCTION__, target_arch.GetArchitectureName()
1149 ? target_arch.GetArchitectureName()
1151 target_arch.GetTriple().getTriple().c_str()
1152 ? target_arch.GetTriple().getTriple().c_str()
1155 // The target doesn't have a valid architecture yet, set it from
1156 // the architecture we got from the remote GDB server
1157 GetTarget().SetArchitecture(process_arch);
1161 // Find out which StructuredDataPlugins are supported by the
1162 // debug monitor. These plugins transmit data over async $J packets.
1163 auto supported_packets_array =
1164 m_gdb_comm.GetSupportedStructuredDataPlugins();
1165 if (supported_packets_array)
1166 MapSupportedStructuredDataPlugins(*supported_packets_array);
1170 void ProcessGDBRemote::DidLaunch() {
1171 ArchSpec process_arch;
1172 DidLaunchOrAttach(process_arch);
1175 Status ProcessGDBRemote::DoAttachToProcessWithID(
1176 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1177 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1181 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1183 // Clear out and clean up from any current state
1185 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1186 error = EstablishConnectionIfNeeded(attach_info);
1187 if (error.Success()) {
1188 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1191 const int packet_len =
1192 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1194 m_async_broadcaster.BroadcastEvent(
1195 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1197 SetExitStatus(-1, error.AsCString());
1203 Status ProcessGDBRemote::DoAttachToProcessWithName(
1204 const char *process_name, const ProcessAttachInfo &attach_info) {
1206 // Clear out and clean up from any current state
1209 if (process_name && process_name[0]) {
1210 error = EstablishConnectionIfNeeded(attach_info);
1211 if (error.Success()) {
1212 StreamString packet;
1214 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1216 if (attach_info.GetWaitForLaunch()) {
1217 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1218 packet.PutCString("vAttachWait");
1220 if (attach_info.GetIgnoreExisting())
1221 packet.PutCString("vAttachWait");
1223 packet.PutCString("vAttachOrWait");
1226 packet.PutCString("vAttachName");
1227 packet.PutChar(';');
1228 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1229 endian::InlHostByteOrder(),
1230 endian::InlHostByteOrder());
1232 m_async_broadcaster.BroadcastEvent(
1233 eBroadcastBitAsyncContinue,
1234 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1237 SetExitStatus(-1, error.AsCString());
1242 lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1244 return m_gdb_comm.SendStartTracePacket(options, error);
1247 Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1248 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1251 Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1252 llvm::MutableArrayRef<uint8_t> &buffer,
1254 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1257 Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1258 llvm::MutableArrayRef<uint8_t> &buffer,
1260 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1263 Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1264 TraceOptions &options) {
1265 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1268 void ProcessGDBRemote::DidExit() {
1269 // When we exit, disconnect from the GDB server communications
1270 m_gdb_comm.Disconnect();
1273 void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1274 // If you can figure out what the architecture is, fill it in here.
1275 process_arch.Clear();
1276 DidLaunchOrAttach(process_arch);
1279 Status ProcessGDBRemote::WillResume() {
1280 m_continue_c_tids.clear();
1281 m_continue_C_tids.clear();
1282 m_continue_s_tids.clear();
1283 m_continue_S_tids.clear();
1284 m_jstopinfo_sp.reset();
1285 m_jthreadsinfo_sp.reset();
1289 Status ProcessGDBRemote::DoResume() {
1291 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1293 log->Printf("ProcessGDBRemote::Resume()");
1295 ListenerSP listener_sp(
1296 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1297 if (listener_sp->StartListeningForEvents(
1298 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1299 listener_sp->StartListeningForEvents(
1300 &m_async_broadcaster,
1301 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1303 const size_t num_threads = GetThreadList().GetSize();
1305 StreamString continue_packet;
1306 bool continue_packet_error = false;
1307 if (m_gdb_comm.HasAnyVContSupport()) {
1308 if (!GetTarget().GetNonStopModeEnabled() &&
1309 (m_continue_c_tids.size() == num_threads ||
1310 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1311 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1312 // All threads are continuing, just send a "c" packet
1313 continue_packet.PutCString("c");
1315 continue_packet.PutCString("vCont");
1317 if (!m_continue_c_tids.empty()) {
1318 if (m_gdb_comm.GetVContSupported('c')) {
1319 for (tid_collection::const_iterator
1320 t_pos = m_continue_c_tids.begin(),
1321 t_end = m_continue_c_tids.end();
1322 t_pos != t_end; ++t_pos)
1323 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1325 continue_packet_error = true;
1328 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1329 if (m_gdb_comm.GetVContSupported('C')) {
1330 for (tid_sig_collection::const_iterator
1331 s_pos = m_continue_C_tids.begin(),
1332 s_end = m_continue_C_tids.end();
1333 s_pos != s_end; ++s_pos)
1334 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1337 continue_packet_error = true;
1340 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1341 if (m_gdb_comm.GetVContSupported('s')) {
1342 for (tid_collection::const_iterator
1343 t_pos = m_continue_s_tids.begin(),
1344 t_end = m_continue_s_tids.end();
1345 t_pos != t_end; ++t_pos)
1346 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1348 continue_packet_error = true;
1351 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1352 if (m_gdb_comm.GetVContSupported('S')) {
1353 for (tid_sig_collection::const_iterator
1354 s_pos = m_continue_S_tids.begin(),
1355 s_end = m_continue_S_tids.end();
1356 s_pos != s_end; ++s_pos)
1357 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1360 continue_packet_error = true;
1363 if (continue_packet_error)
1364 continue_packet.Clear();
1367 continue_packet_error = true;
1369 if (continue_packet_error) {
1370 // Either no vCont support, or we tried to use part of the vCont
1371 // packet that wasn't supported by the remote GDB server.
1372 // We need to try and make a simple packet that can do our continue
1373 const size_t num_continue_c_tids = m_continue_c_tids.size();
1374 const size_t num_continue_C_tids = m_continue_C_tids.size();
1375 const size_t num_continue_s_tids = m_continue_s_tids.size();
1376 const size_t num_continue_S_tids = m_continue_S_tids.size();
1377 if (num_continue_c_tids > 0) {
1378 if (num_continue_c_tids == num_threads) {
1379 // All threads are resuming...
1380 m_gdb_comm.SetCurrentThreadForRun(-1);
1381 continue_packet.PutChar('c');
1382 continue_packet_error = false;
1383 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1384 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1385 // Only one thread is continuing
1386 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1387 continue_packet.PutChar('c');
1388 continue_packet_error = false;
1392 if (continue_packet_error && num_continue_C_tids > 0) {
1393 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1394 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1395 num_continue_S_tids == 0) {
1396 const int continue_signo = m_continue_C_tids.front().second;
1397 // Only one thread is continuing
1398 if (num_continue_C_tids > 1) {
1399 // More that one thread with a signal, yet we don't have
1400 // vCont support and we are being asked to resume each
1401 // thread with a signal, we need to make sure they are
1402 // all the same signal, or we can't issue the continue
1403 // accurately with the current support...
1404 if (num_continue_C_tids > 1) {
1405 continue_packet_error = false;
1406 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1407 if (m_continue_C_tids[i].second != continue_signo)
1408 continue_packet_error = true;
1411 if (!continue_packet_error)
1412 m_gdb_comm.SetCurrentThreadForRun(-1);
1414 // Set the continue thread ID
1415 continue_packet_error = false;
1416 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1418 if (!continue_packet_error) {
1419 // Add threads continuing with the same signo...
1420 continue_packet.Printf("C%2.2x", continue_signo);
1425 if (continue_packet_error && num_continue_s_tids > 0) {
1426 if (num_continue_s_tids == num_threads) {
1427 // All threads are resuming...
1428 m_gdb_comm.SetCurrentThreadForRun(-1);
1430 // If in Non-Stop-Mode use vCont when stepping
1431 if (GetTarget().GetNonStopModeEnabled()) {
1432 if (m_gdb_comm.GetVContSupported('s'))
1433 continue_packet.PutCString("vCont;s");
1435 continue_packet.PutChar('s');
1437 continue_packet.PutChar('s');
1439 continue_packet_error = false;
1440 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1441 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1442 // Only one thread is stepping
1443 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1444 continue_packet.PutChar('s');
1445 continue_packet_error = false;
1449 if (!continue_packet_error && num_continue_S_tids > 0) {
1450 if (num_continue_S_tids == num_threads) {
1451 const int step_signo = m_continue_S_tids.front().second;
1452 // Are all threads trying to step with the same signal?
1453 continue_packet_error = false;
1454 if (num_continue_S_tids > 1) {
1455 for (size_t i = 1; i < num_threads; ++i) {
1456 if (m_continue_S_tids[i].second != step_signo)
1457 continue_packet_error = true;
1460 if (!continue_packet_error) {
1461 // Add threads stepping with the same signo...
1462 m_gdb_comm.SetCurrentThreadForRun(-1);
1463 continue_packet.Printf("S%2.2x", step_signo);
1465 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1466 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1467 // Only one thread is stepping with signal
1468 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1469 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1470 continue_packet_error = false;
1475 if (continue_packet_error) {
1476 error.SetErrorString("can't make continue packet for this resume");
1479 if (!m_async_thread.IsJoinable()) {
1480 error.SetErrorString("Trying to resume but the async thread is dead.");
1482 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1483 "async thread is dead.");
1487 m_async_broadcaster.BroadcastEvent(
1488 eBroadcastBitAsyncContinue,
1489 new EventDataBytes(continue_packet.GetString().data(),
1490 continue_packet.GetSize()));
1492 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
1493 error.SetErrorString("Resume timed out.");
1495 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1496 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1497 error.SetErrorString("Broadcast continue, but the async thread was "
1498 "killed before we got an ack back.");
1500 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1501 "async thread was killed before we got an ack back.");
1510 void ProcessGDBRemote::HandleStopReplySequence() {
1513 StringExtractorGDBRemote response;
1514 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1516 // OK represents end of signal list
1517 if (response.IsOKResponse())
1520 // If not OK or a normal packet we have a problem
1521 if (!response.IsNormalResponse())
1524 SetLastStopPacket(response);
1528 void ProcessGDBRemote::ClearThreadIDList() {
1529 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1530 m_thread_ids.clear();
1531 m_thread_pcs.clear();
1535 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1536 m_thread_ids.clear();
1537 m_thread_pcs.clear();
1540 while ((comma_pos = value.find(',')) != std::string::npos) {
1541 value[comma_pos] = '\0';
1542 // thread in big endian hex
1543 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1544 if (tid != LLDB_INVALID_THREAD_ID)
1545 m_thread_ids.push_back(tid);
1546 value.erase(0, comma_pos + 1);
1548 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1549 if (tid != LLDB_INVALID_THREAD_ID)
1550 m_thread_ids.push_back(tid);
1551 return m_thread_ids.size();
1555 ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1556 m_thread_pcs.clear();
1559 while ((comma_pos = value.find(',')) != std::string::npos) {
1560 value[comma_pos] = '\0';
1561 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1562 if (pc != LLDB_INVALID_ADDRESS)
1563 m_thread_pcs.push_back(pc);
1564 value.erase(0, comma_pos + 1);
1566 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1567 if (pc != LLDB_INVALID_THREAD_ID)
1568 m_thread_pcs.push_back(pc);
1569 return m_thread_pcs.size();
1572 bool ProcessGDBRemote::UpdateThreadIDList() {
1573 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1575 if (m_jthreadsinfo_sp) {
1576 // If we have the JSON threads info, we can get the thread list from that
1577 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1578 if (thread_infos && thread_infos->GetSize() > 0) {
1579 m_thread_ids.clear();
1580 m_thread_pcs.clear();
1581 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1582 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1584 // Set the thread stop info from the JSON dictionary
1585 SetThreadStopInfo(thread_dict);
1586 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1587 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1588 m_thread_ids.push_back(tid);
1590 return true; // Keep iterating through all thread_info objects
1593 if (!m_thread_ids.empty())
1596 // See if we can get the thread IDs from the current stop reply packets
1597 // that might contain a "threads" key/value pair
1599 // Lock the thread stack while we access it
1600 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1601 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1602 m_last_stop_packet_mutex, std::defer_lock);
1603 if (stop_stack_lock.try_lock()) {
1604 // Get the number of stop packets on the stack
1605 int nItems = m_stop_packet_stack.size();
1606 // Iterate over them
1607 for (int i = 0; i < nItems; i++) {
1608 // Get the thread stop info
1609 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1610 const std::string &stop_info_str = stop_info.GetStringRef();
1612 m_thread_pcs.clear();
1613 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1614 if (thread_pcs_pos != std::string::npos) {
1615 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1616 const size_t end = stop_info_str.find(';', start);
1617 if (end != std::string::npos) {
1618 std::string value = stop_info_str.substr(start, end - start);
1619 UpdateThreadPCsFromStopReplyThreadsValue(value);
1623 const size_t threads_pos = stop_info_str.find(";threads:");
1624 if (threads_pos != std::string::npos) {
1625 const size_t start = threads_pos + strlen(";threads:");
1626 const size_t end = stop_info_str.find(';', start);
1627 if (end != std::string::npos) {
1628 std::string value = stop_info_str.substr(start, end - start);
1629 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1637 bool sequence_mutex_unavailable = false;
1638 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1639 if (sequence_mutex_unavailable) {
1640 return false; // We just didn't get the list
1645 bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1646 ThreadList &new_thread_list) {
1647 // locker will keep a mutex locked until it goes out of scope
1648 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
1649 LLDB_LOGV(log, "pid = {0}", GetID());
1651 size_t num_thread_ids = m_thread_ids.size();
1652 // The "m_thread_ids" thread ID list should always be updated after each stop
1653 // reply packet, but in case it isn't, update it here.
1654 if (num_thread_ids == 0) {
1655 if (!UpdateThreadIDList())
1657 num_thread_ids = m_thread_ids.size();
1660 ThreadList old_thread_list_copy(old_thread_list);
1661 if (num_thread_ids > 0) {
1662 for (size_t i = 0; i < num_thread_ids; ++i) {
1663 tid_t tid = m_thread_ids[i];
1665 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1667 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1668 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1669 thread_sp.get(), thread_sp->GetID());
1671 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1672 thread_sp.get(), thread_sp->GetID());
1675 SetThreadPc(thread_sp, i);
1676 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1680 // Whatever that is left in old_thread_list_copy are not
1681 // present in new_thread_list. Remove non-existent threads from internal id
1683 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1684 for (size_t i = 0; i < old_num_thread_ids; i++) {
1685 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1686 if (old_thread_sp) {
1687 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1688 m_thread_id_to_index_id_map.erase(old_thread_id);
1695 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1696 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1697 GetByteOrder() != eByteOrderInvalid) {
1698 ThreadGDBRemote *gdb_thread =
1699 static_cast<ThreadGDBRemote *>(thread_sp.get());
1700 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1702 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1703 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1704 if (pc_regnum != LLDB_INVALID_REGNUM) {
1705 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1711 bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1712 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1713 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1715 if (thread_infos_sp) {
1716 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1719 const size_t n = thread_infos->GetSize();
1720 for (size_t i = 0; i < n; ++i) {
1721 StructuredData::Dictionary *thread_dict =
1722 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1724 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1725 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1726 if (tid == thread->GetID())
1727 return (bool)SetThreadStopInfo(thread_dict);
1736 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1737 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1739 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1742 // See if we got thread stop info for any threads valid stop info reasons
1744 // via the "jstopinfo" packet stop reply packet key/value pair?
1745 if (m_jstopinfo_sp) {
1746 // If we have "jstopinfo" then we have stop descriptions for all threads
1747 // that have stop reasons, and if there is no entry for a thread, then
1748 // it has no stop reason.
1749 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1750 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1751 thread->SetStopInfo(StopInfoSP());
1756 // Fall back to using the qThreadStopInfo packet
1757 StringExtractorGDBRemote stop_packet;
1758 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1759 return SetThreadStopInfo(stop_packet) == eStateStopped;
1763 ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1764 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1765 uint8_t signo, const std::string &thread_name, const std::string &reason,
1766 const std::string &description, uint32_t exc_type,
1767 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1768 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1769 // queue_serial are valid
1770 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1771 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1773 if (tid != LLDB_INVALID_THREAD_ID) {
1774 // Scope for "locker" below
1776 // m_thread_list_real does have its own mutex, but we need to
1777 // hold onto the mutex between the call to
1778 // m_thread_list_real.FindThreadByID(...)
1779 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1780 std::lock_guard<std::recursive_mutex> guard(
1781 m_thread_list_real.GetMutex());
1782 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1785 // Create the thread if we need to
1786 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1787 m_thread_list_real.AddThread(thread_sp);
1792 ThreadGDBRemote *gdb_thread =
1793 static_cast<ThreadGDBRemote *>(thread_sp.get());
1794 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1796 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1797 if (iter != m_thread_ids.end()) {
1798 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1801 for (const auto &pair : expedited_register_map) {
1802 StringExtractor reg_value_extractor;
1803 reg_value_extractor.GetStringRef() = pair.second;
1804 DataBufferSP buffer_sp(new DataBufferHeap(
1805 reg_value_extractor.GetStringRef().size() / 2, 0));
1806 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1807 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1810 thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1812 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1813 // Check if the GDB server was able to provide the queue name, kind and
1815 if (queue_vars_valid)
1816 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1817 queue_serial, dispatch_queue_t,
1818 associated_with_dispatch_queue);
1820 gdb_thread->ClearQueueInfo();
1822 gdb_thread->SetAssociatedWithLibdispatchQueue(
1823 associated_with_dispatch_queue);
1825 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1826 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1828 // Make sure we update our thread stop reason just once
1829 if (!thread_sp->StopInfoIsUpToDate()) {
1830 thread_sp->SetStopInfo(StopInfoSP());
1831 // If there's a memory thread backed by this thread, we need to use it
1832 // to calcualte StopInfo.
1833 ThreadSP memory_thread_sp =
1834 m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1835 if (memory_thread_sp)
1836 thread_sp = memory_thread_sp;
1838 if (exc_type != 0) {
1839 const size_t exc_data_size = exc_data.size();
1841 thread_sp->SetStopInfo(
1842 StopInfoMachException::CreateStopReasonWithMachException(
1843 *thread_sp, exc_type, exc_data_size,
1844 exc_data_size >= 1 ? exc_data[0] : 0,
1845 exc_data_size >= 2 ? exc_data[1] : 0,
1846 exc_data_size >= 3 ? exc_data[2] : 0));
1848 bool handled = false;
1849 bool did_exec = false;
1850 if (!reason.empty()) {
1851 if (reason.compare("trace") == 0) {
1852 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1853 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1854 ->GetBreakpointSiteList()
1857 // If the current pc is a breakpoint site then the StopInfo should
1858 // be set to Breakpoint
1859 // Otherwise, it will be set to Trace.
1861 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1862 thread_sp->SetStopInfo(
1863 StopInfo::CreateStopReasonWithBreakpointSiteID(
1864 *thread_sp, bp_site_sp->GetID()));
1866 thread_sp->SetStopInfo(
1867 StopInfo::CreateStopReasonToTrace(*thread_sp));
1869 } else if (reason.compare("breakpoint") == 0) {
1870 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1871 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1872 ->GetBreakpointSiteList()
1875 // If the breakpoint is for this thread, then we'll report the
1876 // hit, but if it is for another thread,
1877 // we can just report no reason. We don't need to worry about
1878 // stepping over the breakpoint here, that
1879 // will be taken care of when the thread resumes and notices
1880 // that there's a breakpoint under the pc.
1882 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1883 thread_sp->SetStopInfo(
1884 StopInfo::CreateStopReasonWithBreakpointSiteID(
1885 *thread_sp, bp_site_sp->GetID()));
1887 StopInfoSP invalid_stop_info_sp;
1888 thread_sp->SetStopInfo(invalid_stop_info_sp);
1891 } else if (reason.compare("trap") == 0) {
1892 // Let the trap just use the standard signal stop reason below...
1893 } else if (reason.compare("watchpoint") == 0) {
1894 StringExtractor desc_extractor(description.c_str());
1895 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1896 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1897 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1898 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1899 if (wp_addr != LLDB_INVALID_ADDRESS) {
1901 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1902 if ((core >= ArchSpec::kCore_mips_first &&
1903 core <= ArchSpec::kCore_mips_last) ||
1904 (core >= ArchSpec::eCore_arm_generic &&
1905 core <= ArchSpec::eCore_arm_aarch64))
1906 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1910 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1912 wp_sp->SetHardwareIndex(wp_index);
1913 watch_id = wp_sp->GetID();
1916 if (watch_id == LLDB_INVALID_WATCH_ID) {
1917 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1918 GDBR_LOG_WATCHPOINTS));
1920 log->Printf("failed to find watchpoint");
1922 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1923 *thread_sp, watch_id, wp_hit_addr));
1925 } else if (reason.compare("exception") == 0) {
1926 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1927 *thread_sp, description.c_str()));
1929 } else if (reason.compare("exec") == 0) {
1931 thread_sp->SetStopInfo(
1932 StopInfo::CreateStopReasonWithExec(*thread_sp));
1935 } else if (!signo) {
1936 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1937 lldb::BreakpointSiteSP bp_site_sp =
1938 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1941 // If the current pc is a breakpoint site then the StopInfo should
1942 // be set to Breakpoint
1943 // even though the remote stub did not set it as such. This can
1945 // the thread is involuntarily interrupted (e.g. due to stops on
1947 // threads) just as it is about to execute the breakpoint
1949 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1950 thread_sp->SetStopInfo(
1951 StopInfo::CreateStopReasonWithBreakpointSiteID(
1952 *thread_sp, bp_site_sp->GetID()));
1957 if (!handled && signo && did_exec == false) {
1958 if (signo == SIGTRAP) {
1959 // Currently we are going to assume SIGTRAP means we are either
1960 // hitting a breakpoint or hardware single stepping.
1962 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1963 m_breakpoint_pc_offset;
1964 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1965 ->GetBreakpointSiteList()
1969 // If the breakpoint is for this thread, then we'll report the
1970 // hit, but if it is for another thread,
1971 // we can just report no reason. We don't need to worry about
1972 // stepping over the breakpoint here, that
1973 // will be taken care of when the thread resumes and notices
1974 // that there's a breakpoint under the pc.
1975 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1976 if (m_breakpoint_pc_offset != 0)
1977 thread_sp->GetRegisterContext()->SetPC(pc);
1978 thread_sp->SetStopInfo(
1979 StopInfo::CreateStopReasonWithBreakpointSiteID(
1980 *thread_sp, bp_site_sp->GetID()));
1982 StopInfoSP invalid_stop_info_sp;
1983 thread_sp->SetStopInfo(invalid_stop_info_sp);
1986 // If we were stepping then assume the stop was the result of
1987 // the trace. If we were
1988 // not stepping then report the SIGTRAP.
1989 // FIXME: We are still missing the case where we single step
1990 // over a trap instruction.
1991 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1992 thread_sp->SetStopInfo(
1993 StopInfo::CreateStopReasonToTrace(*thread_sp));
1995 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1996 *thread_sp, signo, description.c_str()));
2000 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2001 *thread_sp, signo, description.c_str()));
2004 if (!description.empty()) {
2005 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2007 const char *stop_info_desc = stop_info_sp->GetDescription();
2008 if (!stop_info_desc || !stop_info_desc[0])
2009 stop_info_sp->SetDescription(description.c_str());
2011 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2012 *thread_sp, description.c_str()));
2023 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2024 static ConstString g_key_tid("tid");
2025 static ConstString g_key_name("name");
2026 static ConstString g_key_reason("reason");
2027 static ConstString g_key_metype("metype");
2028 static ConstString g_key_medata("medata");
2029 static ConstString g_key_qaddr("qaddr");
2030 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2031 static ConstString g_key_associated_with_dispatch_queue(
2032 "associated_with_dispatch_queue");
2033 static ConstString g_key_queue_name("qname");
2034 static ConstString g_key_queue_kind("qkind");
2035 static ConstString g_key_queue_serial_number("qserialnum");
2036 static ConstString g_key_registers("registers");
2037 static ConstString g_key_memory("memory");
2038 static ConstString g_key_address("address");
2039 static ConstString g_key_bytes("bytes");
2040 static ConstString g_key_description("description");
2041 static ConstString g_key_signal("signal");
2043 // Stop with signal and thread info
2044 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2047 std::string thread_name;
2049 std::string description;
2050 uint32_t exc_type = 0;
2051 std::vector<addr_t> exc_data;
2052 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2053 ExpeditedRegisterMap expedited_register_map;
2054 bool queue_vars_valid = false;
2055 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2056 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2057 std::string queue_name;
2058 QueueKind queue_kind = eQueueKindUnknown;
2059 uint64_t queue_serial_number = 0;
2060 // Iterate through all of the thread dictionary key/value pairs from the
2061 // structured data dictionary
2063 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2064 &signo, &reason, &description, &exc_type, &exc_data,
2065 &thread_dispatch_qaddr, &queue_vars_valid,
2066 &associated_with_dispatch_queue, &dispatch_queue_t,
2067 &queue_name, &queue_kind, &queue_serial_number](
2069 StructuredData::Object *object) -> bool {
2070 if (key == g_key_tid) {
2071 // thread in big endian hex
2072 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2073 } else if (key == g_key_metype) {
2074 // exception type in big endian hex
2075 exc_type = object->GetIntegerValue(0);
2076 } else if (key == g_key_medata) {
2077 // exception data in big endian hex
2078 StructuredData::Array *array = object->GetAsArray();
2080 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2081 exc_data.push_back(object->GetIntegerValue());
2082 return true; // Keep iterating through all array items
2085 } else if (key == g_key_name) {
2086 thread_name = object->GetStringValue();
2087 } else if (key == g_key_qaddr) {
2088 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2089 } else if (key == g_key_queue_name) {
2090 queue_vars_valid = true;
2091 queue_name = object->GetStringValue();
2092 } else if (key == g_key_queue_kind) {
2093 std::string queue_kind_str = object->GetStringValue();
2094 if (queue_kind_str == "serial") {
2095 queue_vars_valid = true;
2096 queue_kind = eQueueKindSerial;
2097 } else if (queue_kind_str == "concurrent") {
2098 queue_vars_valid = true;
2099 queue_kind = eQueueKindConcurrent;
2101 } else if (key == g_key_queue_serial_number) {
2102 queue_serial_number = object->GetIntegerValue(0);
2103 if (queue_serial_number != 0)
2104 queue_vars_valid = true;
2105 } else if (key == g_key_dispatch_queue_t) {
2106 dispatch_queue_t = object->GetIntegerValue(0);
2107 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2108 queue_vars_valid = true;
2109 } else if (key == g_key_associated_with_dispatch_queue) {
2110 queue_vars_valid = true;
2111 bool associated = object->GetBooleanValue();
2113 associated_with_dispatch_queue = eLazyBoolYes;
2115 associated_with_dispatch_queue = eLazyBoolNo;
2116 } else if (key == g_key_reason) {
2117 reason = object->GetStringValue();
2118 } else if (key == g_key_description) {
2119 description = object->GetStringValue();
2120 } else if (key == g_key_registers) {
2121 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2123 if (registers_dict) {
2124 registers_dict->ForEach(
2125 [&expedited_register_map](ConstString key,
2126 StructuredData::Object *object) -> bool {
2127 const uint32_t reg =
2128 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2129 if (reg != UINT32_MAX)
2130 expedited_register_map[reg] = object->GetStringValue();
2131 return true; // Keep iterating through all array items
2134 } else if (key == g_key_memory) {
2135 StructuredData::Array *array = object->GetAsArray();
2137 array->ForEach([this](StructuredData::Object *object) -> bool {
2138 StructuredData::Dictionary *mem_cache_dict =
2139 object->GetAsDictionary();
2140 if (mem_cache_dict) {
2141 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2142 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2143 "address", mem_cache_addr)) {
2144 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2145 llvm::StringRef str;
2146 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2147 StringExtractor bytes(str);
2148 bytes.SetFilePos(0);
2150 const size_t byte_size = bytes.GetStringRef().size() / 2;
2151 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2152 const size_t bytes_copied =
2153 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2154 if (bytes_copied == byte_size)
2155 m_memory_cache.AddL1CacheData(mem_cache_addr,
2161 return true; // Keep iterating through all array items
2165 } else if (key == g_key_signal)
2166 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2167 return true; // Keep iterating through all dictionary key/value pairs
2170 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2171 reason, description, exc_type, exc_data,
2172 thread_dispatch_qaddr, queue_vars_valid,
2173 associated_with_dispatch_queue, dispatch_queue_t,
2174 queue_name, queue_kind, queue_serial_number);
2177 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2178 stop_packet.SetFilePos(0);
2179 const char stop_type = stop_packet.GetChar();
2180 switch (stop_type) {
2183 // This is a bit of a hack, but is is required. If we did exec, we
2184 // need to clear our thread lists and also know to rebuild our dynamic
2185 // register info before we lookup and threads and populate the expedited
2186 // register values so we need to know this right away so we can cleanup
2187 // and update our registers.
2188 const uint32_t stop_id = GetStopID();
2190 // Our first stop, make sure we have a process ID, and also make
2191 // sure we know about our registers
2192 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2193 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2194 if (pid != LLDB_INVALID_PROCESS_ID)
2197 BuildDynamicRegisterInfo(true);
2199 // Stop with signal and thread info
2200 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2201 const uint8_t signo = stop_packet.GetHexU8();
2202 llvm::StringRef key;
2203 llvm::StringRef value;
2204 std::string thread_name;
2206 std::string description;
2207 uint32_t exc_type = 0;
2208 std::vector<addr_t> exc_data;
2209 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2210 bool queue_vars_valid =
2211 false; // says if locals below that start with "queue_" are valid
2212 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2213 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2214 std::string queue_name;
2215 QueueKind queue_kind = eQueueKindUnknown;
2216 uint64_t queue_serial_number = 0;
2217 ExpeditedRegisterMap expedited_register_map;
2218 while (stop_packet.GetNameColonValue(key, value)) {
2219 if (key.compare("metype") == 0) {
2220 // exception type in big endian hex
2221 value.getAsInteger(16, exc_type);
2222 } else if (key.compare("medata") == 0) {
2223 // exception data in big endian hex
2225 value.getAsInteger(16, x);
2226 exc_data.push_back(x);
2227 } else if (key.compare("thread") == 0) {
2228 // thread in big endian hex
2229 if (value.getAsInteger(16, tid))
2230 tid = LLDB_INVALID_THREAD_ID;
2231 } else if (key.compare("threads") == 0) {
2232 std::lock_guard<std::recursive_mutex> guard(
2233 m_thread_list_real.GetMutex());
2235 m_thread_ids.clear();
2236 // A comma separated list of all threads in the current
2237 // process that includes the thread for this stop reply
2240 while (!value.empty()) {
2241 llvm::StringRef tid_str;
2242 std::tie(tid_str, value) = value.split(',');
2243 if (tid_str.getAsInteger(16, tid))
2244 tid = LLDB_INVALID_THREAD_ID;
2245 m_thread_ids.push_back(tid);
2247 } else if (key.compare("thread-pcs") == 0) {
2248 m_thread_pcs.clear();
2249 // A comma separated list of all threads in the current
2250 // process that includes the thread for this stop reply
2253 while (!value.empty()) {
2254 llvm::StringRef pc_str;
2255 std::tie(pc_str, value) = value.split(',');
2256 if (pc_str.getAsInteger(16, pc))
2257 pc = LLDB_INVALID_ADDRESS;
2258 m_thread_pcs.push_back(pc);
2260 } else if (key.compare("jstopinfo") == 0) {
2261 StringExtractor json_extractor(value);
2263 // Now convert the HEX bytes into a string value
2264 json_extractor.GetHexByteString(json);
2266 // This JSON contains thread IDs and thread stop info for all threads.
2267 // It doesn't contain expedited registers, memory or queue info.
2268 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2269 } else if (key.compare("hexname") == 0) {
2270 StringExtractor name_extractor(value);
2272 // Now convert the HEX bytes into a string value
2273 name_extractor.GetHexByteString(thread_name);
2274 } else if (key.compare("name") == 0) {
2275 thread_name = value;
2276 } else if (key.compare("qaddr") == 0) {
2277 value.getAsInteger(16, thread_dispatch_qaddr);
2278 } else if (key.compare("dispatch_queue_t") == 0) {
2279 queue_vars_valid = true;
2280 value.getAsInteger(16, dispatch_queue_t);
2281 } else if (key.compare("qname") == 0) {
2282 queue_vars_valid = true;
2283 StringExtractor name_extractor(value);
2284 // Now convert the HEX bytes into a string value
2285 name_extractor.GetHexByteString(queue_name);
2286 } else if (key.compare("qkind") == 0) {
2287 queue_kind = llvm::StringSwitch<QueueKind>(value)
2288 .Case("serial", eQueueKindSerial)
2289 .Case("concurrent", eQueueKindConcurrent)
2290 .Default(eQueueKindUnknown);
2291 queue_vars_valid = queue_kind != eQueueKindUnknown;
2292 } else if (key.compare("qserialnum") == 0) {
2293 if (!value.getAsInteger(0, queue_serial_number))
2294 queue_vars_valid = true;
2295 } else if (key.compare("reason") == 0) {
2297 } else if (key.compare("description") == 0) {
2298 StringExtractor desc_extractor(value);
2299 // Now convert the HEX bytes into a string value
2300 desc_extractor.GetHexByteString(description);
2301 } else if (key.compare("memory") == 0) {
2302 // Expedited memory. GDB servers can choose to send back expedited
2304 // that can populate the L1 memory cache in the process so that things
2306 // the frame pointer backchain can be expedited. This will help stack
2307 // backtracing be more efficient by not having to send as many memory
2309 // requests down the remote GDB server.
2311 // Key/value pair format: memory:<addr>=<bytes>;
2312 // <addr> is a number whose base will be interpreted by the prefix:
2313 // "0x[0-9a-fA-F]+" for hex
2314 // "0[0-7]+" for octal
2315 // "[1-9]+" for decimal
2316 // <bytes> is native endian ASCII hex bytes just like the register
2318 llvm::StringRef addr_str, bytes_str;
2319 std::tie(addr_str, bytes_str) = value.split('=');
2320 if (!addr_str.empty() && !bytes_str.empty()) {
2321 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2322 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2323 StringExtractor bytes(bytes_str);
2324 const size_t byte_size = bytes.GetBytesLeft() / 2;
2325 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2326 const size_t bytes_copied =
2327 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2328 if (bytes_copied == byte_size)
2329 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2332 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2333 key.compare("awatch") == 0) {
2334 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2335 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2336 value.getAsInteger(16, wp_addr);
2338 WatchpointSP wp_sp =
2339 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2340 uint32_t wp_index = LLDB_INVALID_INDEX32;
2343 wp_index = wp_sp->GetHardwareIndex();
2345 reason = "watchpoint";
2347 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2348 description = ostr.GetString();
2349 } else if (key.compare("library") == 0) {
2351 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2352 uint32_t reg = UINT32_MAX;
2353 if (!key.getAsInteger(16, reg))
2354 expedited_register_map[reg] = std::move(value);
2358 if (tid == LLDB_INVALID_THREAD_ID) {
2359 // A thread id may be invalid if the response is old style 'S' packet
2360 // which does not provide the
2361 // thread information. So update the thread list and choose the first one.
2362 UpdateThreadIDList();
2364 if (!m_thread_ids.empty()) {
2365 tid = m_thread_ids.front();
2369 ThreadSP thread_sp = SetThreadStopInfo(
2370 tid, expedited_register_map, signo, thread_name, reason, description,
2371 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2372 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2373 queue_kind, queue_serial_number);
2375 return eStateStopped;
2381 return eStateExited;
2386 return eStateInvalid;
2389 void ProcessGDBRemote::RefreshStateAfterStop() {
2390 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2392 m_thread_ids.clear();
2393 m_thread_pcs.clear();
2394 // Set the thread stop info. It might have a "threads" key whose value is
2395 // a list of all thread IDs in the current process, so m_thread_ids might
2398 // Scope for the lock
2400 // Lock the thread stack while we access it
2401 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2402 // Get the number of stop packets on the stack
2403 int nItems = m_stop_packet_stack.size();
2404 // Iterate over them
2405 for (int i = 0; i < nItems; i++) {
2406 // Get the thread stop info
2407 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2408 // Process thread stop info
2409 SetThreadStopInfo(stop_info);
2411 // Clear the thread stop stack
2412 m_stop_packet_stack.clear();
2415 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2416 if (m_thread_ids.empty()) {
2417 // No, we need to fetch the thread list manually
2418 UpdateThreadIDList();
2421 // If we have queried for a default thread id
2422 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2423 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2424 m_initial_tid = LLDB_INVALID_THREAD_ID;
2427 // Let all threads recover from stopping and do any clean up based
2428 // on the previous thread state (if any).
2429 m_thread_list_real.RefreshStateAfterStop();
2432 Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2435 if (m_public_state.GetValue() == eStateAttaching) {
2436 // We are being asked to halt during an attach. We need to just close
2437 // our file handle and debugserver will go away, and we can be done...
2438 m_gdb_comm.Disconnect();
2440 caused_stop = m_gdb_comm.Interrupt();
2444 Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2446 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2448 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2450 error = m_gdb_comm.Detach(keep_stopped);
2452 if (error.Success())
2454 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2456 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2457 error.AsCString() ? error.AsCString() : "<unknown error>");
2460 if (!error.Success())
2463 // Sleep for one second to let the process get all detached...
2466 SetPrivateState(eStateDetached);
2467 ResumePrivateStateThread();
2469 // KillDebugserverProcess ();
2473 Status ProcessGDBRemote::DoDestroy() {
2475 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2477 log->Printf("ProcessGDBRemote::DoDestroy()");
2479 #if 0 // XXX Currently no iOS target support on FreeBSD
2480 // There is a bug in older iOS debugservers where they don't shut down the
2482 // they are debugging properly. If the process is sitting at a breakpoint or
2484 // this can cause problems with restarting. So we check to see if any of our
2485 // threads are stopped
2486 // at a breakpoint, and if so we remove all the breakpoints, resume the
2487 // process, and THEN
2488 // destroy it again.
2490 // Note, we don't have a good way to test the version of debugserver, but I
2491 // happen to know that
2492 // the set of all the iOS debugservers which don't support
2493 // GetThreadSuffixSupported() and that of
2494 // the debugservers with this bug are equal. There really should be a better
2495 // way to test this!
2497 // We also use m_destroy_tried_resuming to make sure we only do this once, if
2498 // we resume and then halt and
2499 // get called here to destroy again and we're still at a breakpoint or
2500 // exception, then we should
2501 // just do the straight-forward kill.
2503 // And of course, if we weren't able to stop the process by the time we get
2505 // necessary (or helpful) to do any of this.
2507 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2508 m_public_state.GetValue() != eStateRunning) {
2509 PlatformSP platform_sp = GetTarget().GetPlatform();
2511 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2512 if (platform_sp && platform_sp->GetName() &&
2513 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2514 if (m_destroy_tried_resuming) {
2516 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2517 "destroy once already, not doing it again.");
2519 // At present, the plans are discarded and the breakpoints disabled
2520 // Process::Destroy,
2521 // but we really need it to happen here and it doesn't matter if we do
2523 m_thread_list.DiscardThreadPlans();
2524 DisableAllBreakpointSites();
2526 bool stop_looks_like_crash = false;
2527 ThreadList &threads = GetThreadList();
2530 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2532 size_t num_threads = threads.GetSize();
2533 for (size_t i = 0; i < num_threads; i++) {
2534 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2535 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2536 StopReason reason = eStopReasonInvalid;
2538 reason = stop_info_sp->GetStopReason();
2539 if (reason == eStopReasonBreakpoint ||
2540 reason == eStopReasonException) {
2543 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2544 " stopped with reason: %s.",
2545 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2546 stop_looks_like_crash = true;
2552 if (stop_looks_like_crash) {
2554 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2555 "breakpoint, continue and then kill.");
2556 m_destroy_tried_resuming = true;
2558 // If we are going to run again before killing, it would be good to
2559 // suspend all the threads
2560 // before resuming so they won't get into more trouble. Sadly, for
2561 // the threads stopped with
2562 // the breakpoint or exception, the exception doesn't get cleared if
2563 // it is suspended, so we do
2564 // have to run the risk of letting those threads proceed a bit.
2567 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2569 size_t num_threads = threads.GetSize();
2570 for (size_t i = 0; i < num_threads; i++) {
2571 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2572 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2573 StopReason reason = eStopReasonInvalid;
2575 reason = stop_info_sp->GetStopReason();
2576 if (reason != eStopReasonBreakpoint &&
2577 reason != eStopReasonException) {
2579 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2580 "thread: 0x%4.4" PRIx64 " before running.",
2581 thread_sp->GetProtocolID());
2582 thread_sp->SetResumeState(eStateSuspended);
2587 return Destroy(false);
2594 // Interrupt if our inferior is running...
2595 int exit_status = SIGABRT;
2596 std::string exit_string;
2598 if (m_gdb_comm.IsConnected()) {
2599 if (m_public_state.GetValue() != eStateAttaching) {
2600 StringExtractorGDBRemote response;
2601 bool send_async = true;
2602 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2603 std::chrono::seconds(3));
2605 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
2606 GDBRemoteCommunication::PacketResult::Success) {
2607 char packet_cmd = response.GetChar(0);
2609 if (packet_cmd == 'W' || packet_cmd == 'X') {
2610 #if defined(__APPLE__)
2611 // For Native processes on Mac OS X, we launch through the Host
2612 // Platform, then hand the process off
2613 // to debugserver, which becomes the parent process through
2614 // "PT_ATTACH". Then when we go to kill
2615 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2616 // call waitpid which returns
2617 // with no error and the correct status. But amusingly enough that
2618 // doesn't seem to actually reap
2619 // the process, but instead it is left around as a Zombie. Probably
2620 // the kernel is in the process of
2621 // switching ownership back to lldb which was the original parent, and
2622 // gets confused in the handoff.
2623 // Anyway, so call waitpid here to finally reap it.
2624 PlatformSP platform_sp(GetTarget().GetPlatform());
2625 if (platform_sp && platform_sp->IsHost()) {
2628 reap_pid = waitpid(GetID(), &status, WNOHANG);
2630 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2633 SetLastStopPacket(response);
2634 ClearThreadIDList();
2635 exit_status = response.GetHexU8();
2638 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2640 response.GetStringRef().c_str());
2641 exit_string.assign("got unexpected response to k packet: ");
2642 exit_string.append(response.GetStringRef());
2646 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2647 exit_string.assign("failed to send the k packet");
2651 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2653 exit_string.assign("killed or interrupted while attaching.");
2656 // If we missed setting the exit status on the way out, do it here.
2657 // NB set exit status can be called multiple times, the first one sets the
2659 exit_string.assign("destroying when not connected to debugserver");
2662 SetExitStatus(exit_status, exit_string.c_str());
2665 KillDebugserverProcess();
2669 void ProcessGDBRemote::SetLastStopPacket(
2670 const StringExtractorGDBRemote &response) {
2671 const bool did_exec =
2672 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2674 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2676 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2678 m_thread_list_real.Clear();
2679 m_thread_list.Clear();
2680 BuildDynamicRegisterInfo(true);
2681 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2686 // Lock the thread stack while we access it
2687 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2689 // We are are not using non-stop mode, there can only be one last stop
2690 // reply packet, so clear the list.
2691 if (GetTarget().GetNonStopModeEnabled() == false)
2692 m_stop_packet_stack.clear();
2694 // Add this stop packet to the stop packet stack
2695 // This stack will get popped and examined when we switch to the
2697 m_stop_packet_stack.push_back(response);
2701 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2702 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2705 //------------------------------------------------------------------
2707 //------------------------------------------------------------------
2709 bool ProcessGDBRemote::IsAlive() {
2710 return m_gdb_comm.IsConnected() && Process::IsAlive();
2713 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2714 // request the link map address via the $qShlibInfoAddr packet
2715 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2717 // the loaded module list can also provides a link map address
2718 if (addr == LLDB_INVALID_ADDRESS) {
2719 LoadedModuleInfoList list;
2720 if (GetLoadedModuleList(list).Success())
2721 addr = list.m_link_map;
2727 void ProcessGDBRemote::WillPublicStop() {
2728 // See if the GDB remote client supports the JSON threads info.
2729 // If so, we gather stop info for all threads, expedited registers,
2730 // expedited memory, runtime queue information (iOS and MacOSX only),
2731 // and more. Expediting memory will help stack backtracing be much
2732 // faster. Expediting registers will make sure we don't have to read
2733 // the thread registers for GPRs.
2734 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2736 if (m_jthreadsinfo_sp) {
2737 // Now set the stop info for each thread and also expedite any registers
2738 // and memory that was in the jThreadsInfo response.
2739 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2741 const size_t n = thread_infos->GetSize();
2742 for (size_t i = 0; i < n; ++i) {
2743 StructuredData::Dictionary *thread_dict =
2744 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2746 SetThreadStopInfo(thread_dict);
2752 //------------------------------------------------------------------
2754 //------------------------------------------------------------------
2755 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2758 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2759 // M and m packets take 2 bytes for 1 byte of memory
2760 size_t max_memory_size =
2761 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2762 if (size > max_memory_size) {
2763 // Keep memory read sizes down to a sane limit. This function will be
2764 // called multiple times in order to complete the task by
2765 // lldb_private::Process so it is ok to do this.
2766 size = max_memory_size;
2771 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2772 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2774 assert(packet_len + 1 < (int)sizeof(packet));
2775 UNUSED_IF_ASSERT_DISABLED(packet_len);
2776 StringExtractorGDBRemote response;
2777 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
2778 GDBRemoteCommunication::PacketResult::Success) {
2779 if (response.IsNormalResponse()) {
2781 if (binary_memory_read) {
2782 // The lower level GDBRemoteCommunication packet receive layer has
2783 // already de-quoted any
2784 // 0x7d character escaping that was present in the packet
2786 size_t data_received_size = response.GetBytesLeft();
2787 if (data_received_size > size) {
2788 // Don't write past the end of BUF if the remote debug server gave us
2790 // much data for some reason.
2791 data_received_size = size;
2793 memcpy(buf, response.GetStringRef().data(), data_received_size);
2794 return data_received_size;
2796 return response.GetHexBytes(
2797 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2799 } else if (response.IsErrorResponse())
2800 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2801 else if (response.IsUnsupportedResponse())
2802 error.SetErrorStringWithFormat(
2803 "GDB server does not support reading memory");
2805 error.SetErrorStringWithFormat(
2806 "unexpected response to GDB server memory read packet '%s': '%s'",
2807 packet, response.GetStringRef().c_str());
2809 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2814 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2815 size_t size, Status &error) {
2817 // M and m packets take 2 bytes for 1 byte of memory
2818 size_t max_memory_size = m_max_memory_size / 2;
2819 if (size > max_memory_size) {
2820 // Keep memory read sizes down to a sane limit. This function will be
2821 // called multiple times in order to complete the task by
2822 // lldb_private::Process so it is ok to do this.
2823 size = max_memory_size;
2826 StreamString packet;
2827 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2828 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2829 endian::InlHostByteOrder());
2830 StringExtractorGDBRemote response;
2831 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2833 GDBRemoteCommunication::PacketResult::Success) {
2834 if (response.IsOKResponse()) {
2837 } else if (response.IsErrorResponse())
2838 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2840 else if (response.IsUnsupportedResponse())
2841 error.SetErrorStringWithFormat(
2842 "GDB server does not support writing memory");
2844 error.SetErrorStringWithFormat(
2845 "unexpected response to GDB server memory write packet '%s': '%s'",
2846 packet.GetData(), response.GetStringRef().c_str());
2848 error.SetErrorStringWithFormat("failed to send packet: '%s'",
2854 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2855 uint32_t permissions,
2858 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2859 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2861 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2862 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2863 if (allocated_addr != LLDB_INVALID_ADDRESS ||
2864 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2865 return allocated_addr;
2868 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2869 // Call mmap() to create memory in the inferior..
2871 if (permissions & lldb::ePermissionsReadable)
2872 prot |= eMmapProtRead;
2873 if (permissions & lldb::ePermissionsWritable)
2874 prot |= eMmapProtWrite;
2875 if (permissions & lldb::ePermissionsExecutable)
2876 prot |= eMmapProtExec;
2878 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2879 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2880 m_addr_to_mmap_size[allocated_addr] = size;
2882 allocated_addr = LLDB_INVALID_ADDRESS;
2884 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
2885 "allocation, and InferiorCallMmap also failed - is stub "
2886 "missing register context save/restore capability?",
2891 if (allocated_addr == LLDB_INVALID_ADDRESS)
2892 error.SetErrorStringWithFormat(
2893 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2894 (uint64_t)size, GetPermissionsAsCString(permissions));
2897 return allocated_addr;
2900 Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2901 MemoryRegionInfo ®ion_info) {
2903 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2907 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2909 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2913 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2914 Status error(m_gdb_comm.GetWatchpointSupportInfo(
2915 num, after, GetTarget().GetArchitecture()));
2919 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2921 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2923 switch (supported) {
2924 case eLazyBoolCalculate:
2925 // We should never be deallocating memory without allocating memory
2926 // first so we should never get eLazyBoolCalculate
2927 error.SetErrorString(
2928 "tried to deallocate memory without ever allocating memory");
2932 if (!m_gdb_comm.DeallocateMemory(addr))
2933 error.SetErrorStringWithFormat(
2934 "unable to deallocate memory at 0x%" PRIx64, addr);
2938 // Call munmap() to deallocate memory in the inferior..
2940 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2941 if (pos != m_addr_to_mmap_size.end() &&
2942 InferiorCallMunmap(this, addr, pos->second))
2943 m_addr_to_mmap_size.erase(pos);
2945 error.SetErrorStringWithFormat(
2946 "unable to deallocate memory at 0x%" PRIx64, addr);
2954 //------------------------------------------------------------------
2956 //------------------------------------------------------------------
2957 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2959 if (m_stdio_communication.IsConnected()) {
2960 ConnectionStatus status;
2961 m_stdio_communication.Write(src, src_len, status, NULL);
2962 } else if (m_stdin_forward) {
2963 m_gdb_comm.SendStdinNotification(src, src_len);
2968 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2970 assert(bp_site != NULL);
2973 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2974 user_id_t site_id = bp_site->GetID();
2976 // Get the breakpoint address
2977 const addr_t addr = bp_site->GetLoadAddress();
2979 // Log that a breakpoint was requested
2981 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2982 ") address = 0x%" PRIx64,
2983 site_id, (uint64_t)addr);
2985 // Breakpoint already exists and is enabled
2986 if (bp_site->IsEnabled()) {
2988 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2989 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2990 site_id, (uint64_t)addr);
2994 // Get the software breakpoint trap opcode size
2995 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2997 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2999 // is supported by the remote stub. These are set to true by default, and
3000 // later set to false
3001 // only after we receive an unimplemented response when sending a breakpoint
3002 // packet. This means
3003 // initially that unless we were specifically instructed to use a hardware
3004 // breakpoint, LLDB will
3005 // attempt to set a software breakpoint. HardwareRequired() also queries a
3006 // boolean variable which
3007 // indicates if the user specifically asked for hardware breakpoints. If true
3009 // skip over software breakpoints.
3010 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3011 (!bp_site->HardwareRequired())) {
3012 // Try to send off a software breakpoint packet ($Z0)
3013 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3014 eBreakpointSoftware, true, addr, bp_op_size);
3015 if (error_no == 0) {
3016 // The breakpoint was placed successfully
3017 bp_site->SetEnabled(true);
3018 bp_site->SetType(BreakpointSite::eExternal);
3022 // SendGDBStoppointTypePacket() will return an error if it was unable to set
3024 // breakpoint. We need to differentiate between a error specific to placing
3026 // or if we have learned that this breakpoint type is unsupported. To do
3028 // must test the support boolean for this breakpoint type to see if it now
3030 // this breakpoint type is unsupported. If they are still supported then we
3032 // with the error code. If they are now unsupported, then we would like to
3034 // and try another form of breakpoint.
3035 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3036 if (error_no != UINT8_MAX)
3037 error.SetErrorStringWithFormat(
3038 "error: %d sending the breakpoint request", errno);
3040 error.SetErrorString("error sending the breakpoint request");
3044 // We reach here when software breakpoints have been found to be
3045 // unsupported. For future
3046 // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3048 // known not to be supported.
3050 log->Printf("Software breakpoints are unsupported");
3052 // So we will fall through and try a hardware breakpoint
3055 // The process of setting a hardware breakpoint is much the same as above. We
3057 // supported boolean for this breakpoint type, and if it is thought to be
3058 // supported then we
3059 // will try to set this breakpoint with a hardware breakpoint.
3060 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3061 // Try to send off a hardware breakpoint packet ($Z1)
3062 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3063 eBreakpointHardware, true, addr, bp_op_size);
3064 if (error_no == 0) {
3065 // The breakpoint was placed successfully
3066 bp_site->SetEnabled(true);
3067 bp_site->SetType(BreakpointSite::eHardware);
3071 // Check if the error was something other then an unsupported breakpoint
3073 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3074 // Unable to set this hardware breakpoint
3075 if (error_no != UINT8_MAX)
3076 error.SetErrorStringWithFormat(
3077 "error: %d sending the hardware breakpoint request "
3078 "(hardware breakpoint resources might be exhausted or unavailable)",
3081 error.SetErrorString("error sending the hardware breakpoint request "
3082 "(hardware breakpoint resources "
3083 "might be exhausted or unavailable)");
3087 // We will reach here when the stub gives an unsupported response to a
3088 // hardware breakpoint
3090 log->Printf("Hardware breakpoints are unsupported");
3092 // Finally we will falling through to a #trap style breakpoint
3095 // Don't fall through when hardware breakpoints were specifically requested
3096 if (bp_site->HardwareRequired()) {
3097 error.SetErrorString("hardware breakpoints are not supported");
3101 // As a last resort we want to place a manual breakpoint. An instruction
3102 // is placed into the process memory using memory write packets.
3103 return EnableSoftwareBreakpoint(bp_site);
3106 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3108 assert(bp_site != NULL);
3109 addr_t addr = bp_site->GetLoadAddress();
3110 user_id_t site_id = bp_site->GetID();
3111 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3113 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3114 ") addr = 0x%8.8" PRIx64,
3115 site_id, (uint64_t)addr);
3117 if (bp_site->IsEnabled()) {
3118 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3120 BreakpointSite::Type bp_type = bp_site->GetType();
3122 case BreakpointSite::eSoftware:
3123 error = DisableSoftwareBreakpoint(bp_site);
3126 case BreakpointSite::eHardware:
3127 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3129 error.SetErrorToGenericError();
3132 case BreakpointSite::eExternal: {
3133 GDBStoppointType stoppoint_type;
3134 if (bp_site->IsHardware())
3135 stoppoint_type = eBreakpointHardware;
3137 stoppoint_type = eBreakpointSoftware;
3139 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3141 error.SetErrorToGenericError();
3144 if (error.Success())
3145 bp_site->SetEnabled(false);
3148 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3149 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3150 site_id, (uint64_t)addr);
3154 if (error.Success())
3155 error.SetErrorToGenericError();
3159 // Pre-requisite: wp != NULL.
3160 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3162 bool watch_read = wp->WatchpointRead();
3163 bool watch_write = wp->WatchpointWrite();
3165 // watch_read and watch_write cannot both be false.
3166 assert(watch_read || watch_write);
3167 if (watch_read && watch_write)
3168 return eWatchpointReadWrite;
3169 else if (watch_read)
3170 return eWatchpointRead;
3171 else // Must be watch_write, then.
3172 return eWatchpointWrite;
3175 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3178 user_id_t watchID = wp->GetID();
3179 addr_t addr = wp->GetLoadAddress();
3181 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3183 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3185 if (wp->IsEnabled()) {
3187 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3188 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3189 watchID, (uint64_t)addr);
3193 GDBStoppointType type = GetGDBStoppointType(wp);
3194 // Pass down an appropriate z/Z packet...
3195 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3196 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3197 wp->GetByteSize()) == 0) {
3198 wp->SetEnabled(true, notify);
3201 error.SetErrorString("sending gdb watchpoint packet failed");
3203 error.SetErrorString("watchpoints not supported");
3205 error.SetErrorString("Watchpoint argument was NULL.");
3207 if (error.Success())
3208 error.SetErrorToGenericError();
3212 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3215 user_id_t watchID = wp->GetID();
3218 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3220 addr_t addr = wp->GetLoadAddress();
3223 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3224 ") addr = 0x%8.8" PRIx64,
3225 watchID, (uint64_t)addr);
3227 if (!wp->IsEnabled()) {
3229 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3230 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3231 watchID, (uint64_t)addr);
3232 // See also 'class WatchpointSentry' within StopInfo.cpp.
3233 // This disabling attempt might come from the user-supplied actions, we'll
3234 // route it in order for
3235 // the watchpoint object to intelligently process this action.
3236 wp->SetEnabled(false, notify);
3240 if (wp->IsHardware()) {
3241 GDBStoppointType type = GetGDBStoppointType(wp);
3242 // Pass down an appropriate z/Z packet...
3243 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3244 wp->GetByteSize()) == 0) {
3245 wp->SetEnabled(false, notify);
3248 error.SetErrorString("sending gdb watchpoint packet failed");
3250 // TODO: clear software watchpoints if we implement them
3252 error.SetErrorString("Watchpoint argument was NULL.");
3254 if (error.Success())
3255 error.SetErrorToGenericError();
3259 void ProcessGDBRemote::Clear() {
3261 m_thread_list_real.Clear();
3262 m_thread_list.Clear();
3265 Status ProcessGDBRemote::DoSignal(int signo) {
3267 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3269 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3271 if (!m_gdb_comm.SendAsyncSignal(signo))
3272 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3277 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3278 // Make sure we aren't already connected?
3279 if (m_gdb_comm.IsConnected())
3282 PlatformSP platform_sp(GetTarget().GetPlatform());
3283 if (platform_sp && !platform_sp->IsHost())
3284 return Status("Lost debug server connection");
3286 auto error = LaunchAndConnectToDebugserver(process_info);
3288 const char *error_string = error.AsCString();
3289 if (error_string == nullptr)
3290 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3294 #if defined(__APPLE__)
3295 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3298 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3299 static bool SetCloexecFlag(int fd) {
3300 #if defined(FD_CLOEXEC)
3301 int flags = ::fcntl(fd, F_GETFD);
3304 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3311 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3312 const ProcessInfo &process_info) {
3313 using namespace std::placeholders; // For _1, _2, etc.
3316 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3317 // If we locate debugserver, keep that located version around
3318 static FileSpec g_debugserver_file_spec;
3320 ProcessLaunchInfo debugserver_launch_info;
3321 // Make debugserver run in its own session so signals generated by
3322 // special terminal key sequences (^C) don't affect debugserver.
3323 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3325 const std::weak_ptr<ProcessGDBRemote> this_wp =
3326 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3327 debugserver_launch_info.SetMonitorProcessCallback(
3328 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3329 debugserver_launch_info.SetUserID(process_info.GetUserID());
3331 int communication_fd = -1;
3332 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3333 // Auto close the sockets we might open up unless everything goes OK. This
3334 // helps us not leak file descriptors when things go wrong.
3335 lldb_utility::CleanUp<int, int> our_socket(-1, -1, close);
3336 lldb_utility::CleanUp<int, int> gdb_socket(-1, -1, close);
3338 // Use a socketpair on Apple for now until other platforms can verify it
3339 // works and is fast enough
3341 int sockets[2]; /* the pair of socket descriptors */
3342 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3343 error.SetErrorToErrno();
3347 our_socket.set(sockets[0]);
3348 gdb_socket.set(sockets[1]);
3351 // Don't let any child processes inherit our communication socket
3352 SetCloexecFlag(our_socket.get());
3353 communication_fd = gdb_socket.get();
3356 error = m_gdb_comm.StartDebugserverProcess(
3357 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3358 nullptr, nullptr, communication_fd);
3360 if (error.Success())
3361 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3363 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3365 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3366 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3367 // Our process spawned correctly, we can now set our connection to use our
3368 // end of the socket pair
3369 m_gdb_comm.SetConnection(
3370 new ConnectionFileDescriptor(our_socket.release(), true));
3376 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3379 log->Printf("failed to start debugserver process: %s",
3384 if (m_gdb_comm.IsConnected()) {
3385 // Finish the connection process by doing the handshake without connecting
3387 ConnectToDebugserver("");
3389 error.SetErrorString("connection failed");
3395 bool ProcessGDBRemote::MonitorDebugserverProcess(
3396 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3397 bool exited, // True if the process did exit
3398 int signo, // Zero for no signal
3399 int exit_status // Exit value of process if signal is zero
3401 // "debugserver_pid" argument passed in is the process ID for
3402 // debugserver that we are tracking...
3403 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3404 const bool handled = true;
3407 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3408 ", signo=%i (0x%x), exit_status=%i)",
3409 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3411 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3413 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3414 static_cast<void *>(process_sp.get()));
3415 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3418 // Sleep for a half a second to make sure our inferior process has
3419 // time to set its exit status before we set it incorrectly when
3420 // both the debugserver and the inferior process shut down.
3422 // If our process hasn't yet exited, debugserver might have died.
3423 // If the process did exit, then we are reaping it.
3424 const StateType state = process_sp->GetState();
3426 if (state != eStateInvalid && state != eStateUnloaded &&
3427 state != eStateExited && state != eStateDetached) {
3428 char error_str[1024];
3430 const char *signal_cstr =
3431 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3433 ::snprintf(error_str, sizeof(error_str),
3434 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3436 ::snprintf(error_str, sizeof(error_str),
3437 DEBUGSERVER_BASENAME " died with signal %i", signo);
3439 ::snprintf(error_str, sizeof(error_str),
3440 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3444 process_sp->SetExitStatus(-1, error_str);
3446 // Debugserver has exited we need to let our ProcessGDBRemote
3447 // know that it no longer has a debugserver instance
3448 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3452 void ProcessGDBRemote::KillDebugserverProcess() {
3453 m_gdb_comm.Disconnect();
3454 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3455 Host::Kill(m_debugserver_pid, SIGINT);
3456 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3460 void ProcessGDBRemote::Initialize() {
3461 static llvm::once_flag g_once_flag;
3463 llvm::call_once(g_once_flag, []() {
3464 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3465 GetPluginDescriptionStatic(), CreateInstance,
3466 DebuggerInitialize);
3470 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3471 if (!PluginManager::GetSettingForProcessPlugin(
3472 debugger, PluginProperties::GetSettingName())) {
3473 const bool is_global_setting = true;
3474 PluginManager::CreateSettingForProcessPlugin(
3475 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3476 ConstString("Properties for the gdb-remote process plug-in."),
3481 bool ProcessGDBRemote::StartAsyncThread() {
3482 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3485 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3487 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3488 if (!m_async_thread.IsJoinable()) {
3489 // Create a thread that watches our internal state and controls which
3490 // events make it to clients (into the DCProcess event queue).
3493 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3494 ProcessGDBRemote::AsyncThread, this, NULL);
3496 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3500 return m_async_thread.IsJoinable();
3503 void ProcessGDBRemote::StopAsyncThread() {
3504 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3507 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3509 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3510 if (m_async_thread.IsJoinable()) {
3511 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3513 // This will shut down the async thread.
3514 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3516 // Stop the stdio thread
3517 m_async_thread.Join(nullptr);
3518 m_async_thread.Reset();
3521 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3525 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3526 // get the packet at a string
3527 const std::string &pkt = packet.GetStringRef();
3529 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3531 // pass as a thread stop info packet
3532 SetLastStopPacket(stop_info);
3534 // check for more stop reasons
3535 HandleStopReplySequence();
3537 // if the process is stopped then we need to fake a resume
3538 // so that we can stop properly with the new break. This
3539 // is possible due to SetPrivateState() broadcasting the
3540 // state change as a side effect.
3541 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3542 SetPrivateState(lldb::StateType::eStateRunning);
3545 // since we have some stopped packets we can halt the process
3546 SetPrivateState(lldb::StateType::eStateStopped);
3551 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3552 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3554 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3556 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3557 ") thread starting...",
3558 __FUNCTION__, arg, process->GetID());
3564 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3565 ") listener.WaitForEvent (NULL, event_sp)...",
3566 __FUNCTION__, arg, process->GetID());
3567 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3568 const uint32_t event_type = event_sp->GetType();
3569 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3571 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3572 ") Got an event of type: %d...",
3573 __FUNCTION__, arg, process->GetID(), event_type);
3575 switch (event_type) {
3576 case eBroadcastBitAsyncContinue: {
3577 const EventDataBytes *continue_packet =
3578 EventDataBytes::GetEventDataFromEvent(event_sp.get());
3580 if (continue_packet) {
3581 const char *continue_cstr =
3582 (const char *)continue_packet->GetBytes();
3583 const size_t continue_cstr_len = continue_packet->GetByteSize();
3585 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3586 ") got eBroadcastBitAsyncContinue: %s",
3587 __FUNCTION__, arg, process->GetID(), continue_cstr);
3589 if (::strstr(continue_cstr, "vAttach") == NULL)
3590 process->SetPrivateState(eStateRunning);
3591 StringExtractorGDBRemote response;
3593 // If in Non-Stop-Mode
3594 if (process->GetTarget().GetNonStopModeEnabled()) {
3595 // send the vCont packet
3596 if (!process->GetGDBRemote().SendvContPacket(
3597 llvm::StringRef(continue_cstr, continue_cstr_len),
3599 // Something went wrong
3604 // If in All-Stop-Mode
3606 StateType stop_state =
3607 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3608 *process, *process->GetUnixSignals(),
3609 llvm::StringRef(continue_cstr, continue_cstr_len),
3612 // We need to immediately clear the thread ID list so we are sure
3613 // to get a valid list of threads.
3614 // The thread ID list might be contained within the "response", or
3615 // the stop reply packet that
3616 // caused the stop. So clear it now before we give the stop reply
3617 // packet to the process
3618 // using the process->SetLastStopPacket()...
3619 process->ClearThreadIDList();
3621 switch (stop_state) {
3624 case eStateSuspended:
3625 process->SetLastStopPacket(response);
3626 process->SetPrivateState(stop_state);
3629 case eStateExited: {
3630 process->SetLastStopPacket(response);
3631 process->ClearThreadIDList();
3632 response.SetFilePos(1);
3634 int exit_status = response.GetHexU8();
3635 std::string desc_string;
3636 if (response.GetBytesLeft() > 0 &&
3637 response.GetChar('-') == ';') {
3638 llvm::StringRef desc_str;
3639 llvm::StringRef desc_token;
3640 while (response.GetNameColonValue(desc_token, desc_str)) {
3641 if (desc_token != "description")
3643 StringExtractor extractor(desc_str);
3644 extractor.GetHexByteString(desc_string);
3647 process->SetExitStatus(exit_status, desc_string.c_str());
3651 case eStateInvalid: {
3652 // Check to see if we were trying to attach and if we got back
3653 // the "E87" error code from debugserver -- this indicates that
3654 // the process is not debuggable. Return a slightly more
3656 // error message about why the attach failed.
3657 if (::strstr(continue_cstr, "vAttach") != NULL &&
3658 response.GetError() == 0x87) {
3659 process->SetExitStatus(-1, "cannot attach to process due to "
3660 "System Integrity Protection");
3662 // E01 code from vAttach means that the attach failed
3663 if (::strstr(continue_cstr, "vAttach") != NULL &&
3664 response.GetError() == 0x1) {
3665 process->SetExitStatus(-1, "unable to attach");
3667 process->SetExitStatus(-1, "lost connection");
3673 process->SetPrivateState(stop_state);
3675 } // switch(stop_state)
3676 } // else // if in All-stop-mode
3677 } // if (continue_packet)
3678 } // case eBroadcastBitAysncContinue
3681 case eBroadcastBitAsyncThreadShouldExit:
3683 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3684 ") got eBroadcastBitAsyncThreadShouldExit...",
3685 __FUNCTION__, arg, process->GetID());
3691 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3692 ") got unknown event 0x%8.8x",
3693 __FUNCTION__, arg, process->GetID(), event_type);
3697 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3698 switch (event_type) {
3699 case Communication::eBroadcastBitReadThreadDidExit:
3700 process->SetExitStatus(-1, "lost connection");
3704 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3705 lldb_private::Event *event = event_sp.get();
3706 const EventDataBytes *continue_packet =
3707 EventDataBytes::GetEventDataFromEvent(event);
3708 StringExtractorGDBRemote notify(
3709 (const char *)continue_packet->GetBytes());
3710 // Hand this over to the process to handle
3711 process->HandleNotifyPacket(notify);
3717 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3718 ") got unknown event 0x%8.8x",
3719 __FUNCTION__, arg, process->GetID(), event_type);
3726 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3727 ") listener.WaitForEvent (NULL, event_sp) => false",
3728 __FUNCTION__, arg, process->GetID());
3734 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3735 ") thread exiting...",
3736 __FUNCTION__, arg, process->GetID());
3742 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3743 // &matches, std::vector<lldb::pid_t> &pids)
3745 // // If we are planning to launch the debugserver remotely, then we need to
3746 // fire up a debugserver
3747 // // process and ask it for the list of processes. But if we are local, we
3748 // can let the Host do it.
3749 // if (m_local_debugserver)
3751 // return Host::ListProcessesMatchingName (name, matches, pids);
3755 // // FIXME: Implement talking to the remote debugserver.
3761 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3762 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3763 lldb::user_id_t break_loc_id) {
3764 // I don't think I have to do anything here, just make sure I notice the new
3765 // thread when it starts to
3766 // run so I can stop it if that's what I want to do.
3767 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3769 log->Printf("Hit New Thread Notification breakpoint.");
3773 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3774 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3775 LLDB_LOG(log, "Check if need to update ignored signals");
3777 // QPassSignals package is not supported by the server,
3778 // there is no way we can ignore any signals on server side.
3779 if (!m_gdb_comm.GetQPassSignalsSupported())
3782 // No signals, nothing to send.
3783 if (m_unix_signals_sp == nullptr)
3786 // Signals' version hasn't changed, no need to send anything.
3787 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3788 if (new_signals_version == m_last_signals_version) {
3789 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3790 m_last_signals_version);
3794 auto signals_to_ignore =
3795 m_unix_signals_sp->GetFilteredSignals(false, false, false);
3796 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3799 "Signals' version changed. old version={0}, new version={1}, "
3800 "signals ignored={2}, update result={3}",
3801 m_last_signals_version, new_signals_version,
3802 signals_to_ignore.size(), error);
3804 if (error.Success())
3805 m_last_signals_version = new_signals_version;
3810 bool ProcessGDBRemote::StartNoticingNewThreads() {
3811 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3812 if (m_thread_create_bp_sp) {
3813 if (log && log->GetVerbose())
3814 log->Printf("Enabled noticing new thread breakpoint.");
3815 m_thread_create_bp_sp->SetEnabled(true);
3817 PlatformSP platform_sp(GetTarget().GetPlatform());
3819 m_thread_create_bp_sp =
3820 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3821 if (m_thread_create_bp_sp) {
3822 if (log && log->GetVerbose())
3824 "Successfully created new thread notification breakpoint %i",
3825 m_thread_create_bp_sp->GetID());
3826 m_thread_create_bp_sp->SetCallback(
3827 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3830 log->Printf("Failed to create new thread notification breakpoint.");
3834 return m_thread_create_bp_sp.get() != NULL;
3837 bool ProcessGDBRemote::StopNoticingNewThreads() {
3838 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3839 if (log && log->GetVerbose())
3840 log->Printf("Disabling new thread notification breakpoint.");
3842 if (m_thread_create_bp_sp)
3843 m_thread_create_bp_sp->SetEnabled(false);
3848 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3849 if (m_dyld_ap.get() == NULL)
3850 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3851 return m_dyld_ap.get();
3854 Status ProcessGDBRemote::SendEventData(const char *data) {
3860 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3861 if (return_value != 0) {
3863 error.SetErrorString("Sending events is not supported for this process.");
3865 error.SetErrorStringWithFormat("Error sending event data: %d.",
3871 const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3873 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3874 std::string response_string;
3875 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3877 GDBRemoteCommunication::PacketResult::Success)
3878 buf.reset(new DataBufferHeap(response_string.c_str(),
3879 response_string.length()));
3884 StructuredData::ObjectSP
3885 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3886 StructuredData::ObjectSP object_sp;
3888 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3889 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3890 SystemRuntime *runtime = GetSystemRuntime();
3892 runtime->AddThreadExtendedInfoPacketHints(args_dict);
3894 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3896 StreamString packet;
3897 packet << "jThreadExtendedInfo:";
3898 args_dict->Dump(packet, false);
3900 // FIXME the final character of a JSON dictionary, '}', is the escape
3901 // character in gdb-remote binary mode. lldb currently doesn't escape
3902 // these characters in its packet output -- so we add the quoted version
3903 // of the } character here manually in case we talk to a debugserver which
3904 // un-escapes the characters at packet read time.
3905 packet << (char)(0x7d ^ 0x20);
3907 StringExtractorGDBRemote response;
3908 response.SetResponseValidatorToJSON();
3909 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3911 GDBRemoteCommunication::PacketResult::Success) {
3912 StringExtractorGDBRemote::ResponseType response_type =
3913 response.GetResponseType();
3914 if (response_type == StringExtractorGDBRemote::eResponse) {
3915 if (!response.Empty()) {
3916 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3924 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3925 lldb::addr_t image_list_address, lldb::addr_t image_count) {
3927 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3928 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3929 image_list_address);
3930 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3932 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3935 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3936 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3938 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3940 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3943 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3944 const std::vector<lldb::addr_t> &load_addresses) {
3945 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3946 StructuredData::ArraySP addresses(new StructuredData::Array);
3948 for (auto addr : load_addresses) {
3949 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3950 addresses->AddItem(addr_sp);
3953 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3955 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3958 StructuredData::ObjectSP
3959 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3960 StructuredData::ObjectSP args_dict) {
3961 StructuredData::ObjectSP object_sp;
3963 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3964 // Scope for the scoped timeout object
3965 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3966 std::chrono::seconds(10));
3968 StreamString packet;
3969 packet << "jGetLoadedDynamicLibrariesInfos:";
3970 args_dict->Dump(packet, false);
3972 // FIXME the final character of a JSON dictionary, '}', is the escape
3973 // character in gdb-remote binary mode. lldb currently doesn't escape
3974 // these characters in its packet output -- so we add the quoted version
3975 // of the } character here manually in case we talk to a debugserver which
3976 // un-escapes the characters at packet read time.
3977 packet << (char)(0x7d ^ 0x20);
3979 StringExtractorGDBRemote response;
3980 response.SetResponseValidatorToJSON();
3981 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3983 GDBRemoteCommunication::PacketResult::Success) {
3984 StringExtractorGDBRemote::ResponseType response_type =
3985 response.GetResponseType();
3986 if (response_type == StringExtractorGDBRemote::eResponse) {
3987 if (!response.Empty()) {
3988 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3996 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3997 StructuredData::ObjectSP object_sp;
3998 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4000 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4001 StreamString packet;
4002 packet << "jGetSharedCacheInfo:";
4003 args_dict->Dump(packet, false);
4005 // FIXME the final character of a JSON dictionary, '}', is the escape
4006 // character in gdb-remote binary mode. lldb currently doesn't escape
4007 // these characters in its packet output -- so we add the quoted version
4008 // of the } character here manually in case we talk to a debugserver which
4009 // un-escapes the characters at packet read time.
4010 packet << (char)(0x7d ^ 0x20);
4012 StringExtractorGDBRemote response;
4013 response.SetResponseValidatorToJSON();
4014 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4016 GDBRemoteCommunication::PacketResult::Success) {
4017 StringExtractorGDBRemote::ResponseType response_type =
4018 response.GetResponseType();
4019 if (response_type == StringExtractorGDBRemote::eResponse) {
4020 if (!response.Empty()) {
4021 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4029 Status ProcessGDBRemote::ConfigureStructuredData(
4030 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4031 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4034 // Establish the largest memory read/write payloads we should use.
4035 // If the remote stub has a max packet size, stay under that size.
4037 // If the remote stub's max packet size is crazy large, use a
4038 // reasonable largeish default.
4040 // If the remote stub doesn't advertise a max packet size, use a
4041 // conservative default.
4043 void ProcessGDBRemote::GetMaxMemorySize() {
4044 const uint64_t reasonable_largeish_default = 128 * 1024;
4045 const uint64_t conservative_default = 512;
4047 if (m_max_memory_size == 0) {
4048 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4049 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4050 // Save the stub's claimed maximum packet size
4051 m_remote_stub_max_memory_size = stub_max_size;
4053 // Even if the stub says it can support ginormous packets,
4054 // don't exceed our reasonable largeish default packet size.
4055 if (stub_max_size > reasonable_largeish_default) {
4056 stub_max_size = reasonable_largeish_default;
4059 // Memory packet have other overheads too like Maddr,size:#NN
4060 // Instead of calculating the bytes taken by size and addr every
4061 // time, we take a maximum guess here.
4062 if (stub_max_size > 70)
4063 stub_max_size -= 32 + 32 + 6;
4065 // In unlikely scenario that max packet size is less then 70, we will
4066 // hope that data being written is small enough to fit.
4067 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4068 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4070 log->Warning("Packet size is too small. "
4071 "LLDB may face problems while writing memory");
4074 m_max_memory_size = stub_max_size;
4076 m_max_memory_size = conservative_default;
4081 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4082 uint64_t user_specified_max) {
4083 if (user_specified_max != 0) {
4086 if (m_remote_stub_max_memory_size != 0) {
4087 if (m_remote_stub_max_memory_size < user_specified_max) {
4088 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4091 // as the remote stub says we can go.
4093 m_max_memory_size = user_specified_max; // user's packet size is good
4097 user_specified_max; // user's packet size is probably fine
4102 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4103 const ArchSpec &arch,
4104 ModuleSpec &module_spec) {
4105 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
4107 const ModuleCacheKey key(module_file_spec.GetPath(),
4108 arch.GetTriple().getTriple());
4109 auto cached = m_cached_module_specs.find(key);
4110 if (cached != m_cached_module_specs.end()) {
4111 module_spec = cached->second;
4112 return bool(module_spec);
4115 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4117 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4118 __FUNCTION__, module_file_spec.GetPath().c_str(),
4119 arch.GetTriple().getTriple().c_str());
4124 StreamString stream;
4125 module_spec.Dump(stream);
4126 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4127 __FUNCTION__, module_file_spec.GetPath().c_str(),
4128 arch.GetTriple().getTriple().c_str(), stream.GetData());
4131 m_cached_module_specs[key] = module_spec;
4135 void ProcessGDBRemote::PrefetchModuleSpecs(
4136 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4137 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4139 for (const FileSpec &spec : module_file_specs)
4140 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4141 triple.getTriple())] = ModuleSpec();
4142 for (const ModuleSpec &spec : *module_specs)
4143 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4144 triple.getTriple())] = spec;
4148 bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4150 if (m_gdb_comm.GetOSVersion(major, minor, update))
4152 // We failed to get the host OS version, defer to the base
4153 // implementation to correctly invalidate the arguments.
4154 return Process::GetHostOSVersion(major, minor, update);
4159 typedef std::vector<std::string> stringVec;
4161 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4162 struct RegisterSetInfo {
4166 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4168 struct GdbServerTargetInfo {
4172 RegisterSetMap reg_set_map;
4173 XMLNode feature_node;
4176 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4177 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4178 uint32_t &cur_reg_num, uint32_t ®_offset) {
4182 feature_node.ForEachChildElementWithName(
4183 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, ®_offset,
4184 &abi_sp](const XMLNode ®_node) -> bool {
4185 std::string gdb_group;
4186 std::string gdb_type;
4187 ConstString reg_name;
4188 ConstString alt_name;
4189 ConstString set_name;
4190 std::vector<uint32_t> value_regs;
4191 std::vector<uint32_t> invalidate_regs;
4192 std::vector<uint8_t> dwarf_opcode_bytes;
4193 bool encoding_set = false;
4194 bool format_set = false;
4195 RegisterInfo reg_info = {
4199 reg_offset, // offset
4200 eEncodingUint, // encoding
4201 eFormatHex, // format
4203 LLDB_INVALID_REGNUM, // eh_frame reg num
4204 LLDB_INVALID_REGNUM, // DWARF reg num
4205 LLDB_INVALID_REGNUM, // generic reg num
4206 cur_reg_num, // process plugin reg num
4207 cur_reg_num // native register number
4211 NULL, // Dwarf Expression opcode bytes pointer
4212 0 // Dwarf Expression opcode bytes length
4215 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4216 ®_name, &alt_name, &set_name, &value_regs,
4217 &invalidate_regs, &encoding_set, &format_set,
4218 ®_info, ®_offset, &dwarf_opcode_bytes](
4219 const llvm::StringRef &name,
4220 const llvm::StringRef &value) -> bool {
4221 if (name == "name") {
4222 reg_name.SetString(value);
4223 } else if (name == "bitsize") {
4224 reg_info.byte_size =
4225 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4226 } else if (name == "type") {
4227 gdb_type = value.str();
4228 } else if (name == "group") {
4229 gdb_group = value.str();
4230 } else if (name == "regnum") {
4231 const uint32_t regnum =
4232 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4233 if (regnum != LLDB_INVALID_REGNUM) {
4234 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4236 } else if (name == "offset") {
4237 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4238 } else if (name == "altname") {
4239 alt_name.SetString(value);
4240 } else if (name == "encoding") {
4241 encoding_set = true;
4242 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4243 } else if (name == "format") {
4245 Format format = eFormatInvalid;
4246 if (Args::StringToFormat(value.data(), format, NULL).Success())
4247 reg_info.format = format;
4248 else if (value == "vector-sint8")
4249 reg_info.format = eFormatVectorOfSInt8;
4250 else if (value == "vector-uint8")
4251 reg_info.format = eFormatVectorOfUInt8;
4252 else if (value == "vector-sint16")
4253 reg_info.format = eFormatVectorOfSInt16;
4254 else if (value == "vector-uint16")
4255 reg_info.format = eFormatVectorOfUInt16;
4256 else if (value == "vector-sint32")
4257 reg_info.format = eFormatVectorOfSInt32;
4258 else if (value == "vector-uint32")
4259 reg_info.format = eFormatVectorOfUInt32;
4260 else if (value == "vector-float32")
4261 reg_info.format = eFormatVectorOfFloat32;
4262 else if (value == "vector-uint64")
4263 reg_info.format = eFormatVectorOfUInt64;
4264 else if (value == "vector-uint128")
4265 reg_info.format = eFormatVectorOfUInt128;
4266 } else if (name == "group_id") {
4267 const uint32_t set_id =
4268 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4269 RegisterSetMap::const_iterator pos =
4270 target_info.reg_set_map.find(set_id);
4271 if (pos != target_info.reg_set_map.end())
4272 set_name = pos->second.name;
4273 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4274 reg_info.kinds[eRegisterKindEHFrame] =
4275 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4276 } else if (name == "dwarf_regnum") {
4277 reg_info.kinds[eRegisterKindDWARF] =
4278 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4279 } else if (name == "generic") {
4280 reg_info.kinds[eRegisterKindGeneric] =
4281 Args::StringToGenericRegister(value);
4282 } else if (name == "value_regnums") {
4283 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4284 } else if (name == "invalidate_regnums") {
4285 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4286 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4287 StringExtractor opcode_extractor;
4288 std::string opcode_string = value.str();
4289 size_t dwarf_opcode_len = opcode_string.length() / 2;
4290 assert(dwarf_opcode_len > 0);
4292 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4293 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4294 opcode_extractor.GetStringRef().swap(opcode_string);
4296 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4297 assert(dwarf_opcode_len == ret_val);
4298 UNUSED_IF_ASSERT_DISABLED(ret_val);
4299 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4301 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4303 return true; // Keep iterating through all attributes
4306 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4307 if (gdb_type.find("int") == 0) {
4308 reg_info.format = eFormatHex;
4309 reg_info.encoding = eEncodingUint;
4310 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4311 reg_info.format = eFormatAddressInfo;
4312 reg_info.encoding = eEncodingUint;
4313 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4314 reg_info.format = eFormatFloat;
4315 reg_info.encoding = eEncodingIEEE754;
4319 // Only update the register set name if we didn't get a "reg_set"
4321 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4322 if (!set_name && !gdb_group.empty())
4323 set_name.SetCString(gdb_group.c_str());
4325 reg_info.byte_offset = reg_offset;
4326 assert(reg_info.byte_size != 0);
4327 reg_offset += reg_info.byte_size;
4328 if (!value_regs.empty()) {
4329 value_regs.push_back(LLDB_INVALID_REGNUM);
4330 reg_info.value_regs = value_regs.data();
4332 if (!invalidate_regs.empty()) {
4333 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4334 reg_info.invalidate_regs = invalidate_regs.data();
4338 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
4339 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4341 return true; // Keep iterating through all "reg" elements
4348 // query the target of gdb-remote for extended target information
4349 // return: 'true' on success
4350 // 'false' on failure
4351 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4352 // Make sure LLDB has an XML parser it can use first
4353 if (!XMLDocument::XMLEnabled())
4356 // redirect libxml2's error handler since the default prints to stdout
4358 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4360 // check that we have extended feature read support
4361 if (!comm.GetQXferFeaturesReadSupported())
4364 // request the target xml file
4366 lldb_private::Status lldberr;
4367 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4372 XMLDocument xml_document;
4374 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4375 GdbServerTargetInfo target_info;
4377 XMLNode target_node = xml_document.GetRootElement("target");
4379 XMLNode feature_node;
4380 target_node.ForEachChildElement([&target_info, &feature_node](
4381 const XMLNode &node) -> bool {
4382 llvm::StringRef name = node.GetName();
4383 if (name == "architecture") {
4384 node.GetElementText(target_info.arch);
4385 } else if (name == "osabi") {
4386 node.GetElementText(target_info.osabi);
4387 } else if (name == "xi:include" || name == "include") {
4388 llvm::StringRef href = node.GetAttributeValue("href");
4390 target_info.includes.push_back(href.str());
4391 } else if (name == "feature") {
4392 feature_node = node;
4393 } else if (name == "groups") {
4394 node.ForEachChildElementWithName(
4395 "group", [&target_info](const XMLNode &node) -> bool {
4396 uint32_t set_id = UINT32_MAX;
4397 RegisterSetInfo set_info;
4399 node.ForEachAttribute(
4400 [&set_id, &set_info](const llvm::StringRef &name,
4401 const llvm::StringRef &value) -> bool {
4403 set_id = StringConvert::ToUInt32(value.data(),
4406 set_info.name = ConstString(value);
4407 return true; // Keep iterating through all attributes
4410 if (set_id != UINT32_MAX)
4411 target_info.reg_set_map[set_id] = set_info;
4412 return true; // Keep iterating through all "group" elements
4415 return true; // Keep iterating through all children of the target_node
4418 // Initialize these outside of ParseRegisters, since they should not be
4419 // reset inside each include feature
4420 uint32_t cur_reg_num = 0;
4421 uint32_t reg_offset = 0;
4423 // Don't use Process::GetABI, this code gets called from DidAttach, and in
4424 // that context we haven't
4425 // set the Target's architecture yet, so the ABI is also potentially
4427 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
4429 ParseRegisters(feature_node, target_info, this->m_register_info,
4430 abi_to_use_sp, cur_reg_num, reg_offset);
4433 for (const auto &include : target_info.includes) {
4434 // request register file
4435 std::string xml_data;
4436 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4440 XMLDocument include_xml_document;
4441 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4443 XMLNode include_feature_node =
4444 include_xml_document.GetRootElement("feature");
4445 if (include_feature_node) {
4446 ParseRegisters(include_feature_node, target_info,
4447 this->m_register_info, abi_to_use_sp, cur_reg_num,
4451 this->m_register_info.Finalize(arch_to_use);
4455 return m_register_info.GetNumRegisters() > 0;
4458 Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
4459 // Make sure LLDB has an XML parser it can use first
4460 if (!XMLDocument::XMLEnabled())
4461 return Status(0, ErrorType::eErrorTypeGeneric);
4463 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4465 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4467 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4469 // check that we have extended feature read support
4470 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4473 // request the loaded library list
4475 lldb_private::Status lldberr;
4477 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4479 return Status(0, ErrorType::eErrorTypeGeneric);
4481 // parse the xml file in memory
4483 log->Printf("parsing: %s", raw.c_str());
4486 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4487 return Status(0, ErrorType::eErrorTypeGeneric);
4489 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4493 // main link map structure
4494 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4495 if (!main_lm.empty()) {
4497 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4500 root_element.ForEachChildElementWithName(
4501 "library", [log, &list](const XMLNode &library) -> bool {
4503 LoadedModuleInfoList::LoadedModuleInfo module;
4505 library.ForEachAttribute(
4506 [&module](const llvm::StringRef &name,
4507 const llvm::StringRef &value) -> bool {
4510 module.set_name(value.str());
4511 else if (name == "lm") {
4512 // the address of the link_map struct.
4513 module.set_link_map(StringConvert::ToUInt64(
4514 value.data(), LLDB_INVALID_ADDRESS, 0));
4515 } else if (name == "l_addr") {
4516 // the displacement as read from the field 'l_addr' of the
4518 module.set_base(StringConvert::ToUInt64(
4519 value.data(), LLDB_INVALID_ADDRESS, 0));
4520 // base address is always a displacement, not an absolute
4522 module.set_base_is_offset(true);
4523 } else if (name == "l_ld") {
4524 // the memory address of the libraries PT_DYAMIC section.
4525 module.set_dynamic(StringConvert::ToUInt64(
4526 value.data(), LLDB_INVALID_ADDRESS, 0));
4529 return true; // Keep iterating over all properties of "library"
4534 lldb::addr_t lm = 0, base = 0, ld = 0;
4535 bool base_is_offset;
4537 module.get_name(name);
4538 module.get_link_map(lm);
4539 module.get_base(base);
4540 module.get_base_is_offset(base_is_offset);
4541 module.get_dynamic(ld);
4543 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4544 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4545 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4550 return true; // Keep iterating over all "library" elements in the root
4555 log->Printf("found %" PRId32 " modules in total",
4556 (int)list.m_list.size());
4557 } else if (comm.GetQXferLibrariesReadSupported()) {
4560 // request the loaded library list
4562 lldb_private::Status lldberr;
4564 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4566 return Status(0, ErrorType::eErrorTypeGeneric);
4569 log->Printf("parsing: %s", raw.c_str());
4572 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4573 return Status(0, ErrorType::eErrorTypeGeneric);
4575 XMLNode root_element = doc.GetRootElement("library-list");
4579 root_element.ForEachChildElementWithName(
4580 "library", [log, &list](const XMLNode &library) -> bool {
4581 LoadedModuleInfoList::LoadedModuleInfo module;
4583 llvm::StringRef name = library.GetAttributeValue("name");
4584 module.set_name(name.str());
4586 // The base address of a given library will be the address of its
4587 // first section. Most remotes send only one section for Windows
4588 // targets for example.
4589 const XMLNode §ion =
4590 library.FindFirstChildElementWithName("section");
4591 llvm::StringRef address = section.GetAttributeValue("address");
4593 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4594 // These addresses are absolute values.
4595 module.set_base_is_offset(false);
4599 lldb::addr_t base = 0;
4600 bool base_is_offset;
4601 module.get_name(name);
4602 module.get_base(base);
4603 module.get_base_is_offset(base_is_offset);
4605 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4606 (base_is_offset ? "offset" : "absolute"), name.c_str());
4610 return true; // Keep iterating over all "library" elements in the root
4615 log->Printf("found %" PRId32 " modules in total",
4616 (int)list.m_list.size());
4618 return Status(0, ErrorType::eErrorTypeGeneric);
4624 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4625 lldb::addr_t link_map,
4626 lldb::addr_t base_addr,
4627 bool value_is_offset) {
4628 DynamicLoader *loader = GetDynamicLoader();
4632 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4636 size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4637 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4639 // request a list of loaded libraries from GDBServer
4640 if (GetLoadedModuleList(module_list).Fail())
4643 // get a list of all the modules
4644 ModuleList new_modules;
4646 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4647 std::string mod_name;
4648 lldb::addr_t mod_base;
4649 lldb::addr_t link_map;
4650 bool mod_base_is_offset;
4653 valid &= modInfo.get_name(mod_name);
4654 valid &= modInfo.get_base(mod_base);
4655 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4659 if (!modInfo.get_link_map(link_map))
4660 link_map = LLDB_INVALID_ADDRESS;
4662 FileSpec file(mod_name, true);
4663 lldb::ModuleSP module_sp =
4664 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4666 if (module_sp.get())
4667 new_modules.Append(module_sp);
4670 if (new_modules.GetSize() > 0) {
4671 ModuleList removed_modules;
4672 Target &target = GetTarget();
4673 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4675 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4676 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4679 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4680 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4684 // The main executable will never be included in libraries-svr4, don't
4687 loaded_module.get() != target.GetExecutableModulePointer()) {
4688 removed_modules.Append(loaded_module);
4692 loaded_modules.Remove(removed_modules);
4693 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4695 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4696 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4700 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4703 lldb::ModuleSP module_copy_sp = module_sp;
4704 target.SetExecutableModule(module_copy_sp, false);
4708 loaded_modules.AppendIfNeeded(new_modules);
4709 m_process->GetTarget().ModulesDidLoad(new_modules);
4712 return new_modules.GetSize();
4715 size_t ProcessGDBRemote::LoadModules() {
4716 LoadedModuleInfoList module_list;
4717 return LoadModules(module_list);
4720 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4722 lldb::addr_t &load_addr) {
4724 load_addr = LLDB_INVALID_ADDRESS;
4726 std::string file_path = file.GetPath(false);
4727 if (file_path.empty())
4728 return Status("Empty file name specified");
4730 StreamString packet;
4731 packet.PutCString("qFileLoadAddress:");
4732 packet.PutCStringAsRawHex8(file_path.c_str());
4734 StringExtractorGDBRemote response;
4735 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4737 GDBRemoteCommunication::PacketResult::Success)
4738 return Status("Sending qFileLoadAddress packet failed");
4740 if (response.IsErrorResponse()) {
4741 if (response.GetError() == 1) {
4742 // The file is not loaded into the inferior
4744 load_addr = LLDB_INVALID_ADDRESS;
4749 "Fetching file load address from remote server returned an error");
4752 if (response.IsNormalResponse()) {
4754 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4759 "Unknown error happened during sending the load address packet");
4762 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4763 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4765 Process::ModulesDidLoad(module_list);
4767 // After loading shared libraries, we can ask our remote GDB server if
4768 // it needs any symbols.
4769 m_gdb_comm.ServeSymbolLookups(this);
4772 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4773 AppendSTDOUT(out.data(), out.size());
4776 static const char *end_delimiter = "--end--;";
4777 static const int end_delimiter_len = 8;
4779 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4780 std::string input = data.str(); // '1' to move beyond 'A'
4781 if (m_partial_profile_data.length() > 0) {
4782 m_partial_profile_data.append(input);
4783 input = m_partial_profile_data;
4784 m_partial_profile_data.clear();
4787 size_t found, pos = 0, len = input.length();
4788 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4789 StringExtractorGDBRemote profileDataExtractor(
4790 input.substr(pos, found).c_str());
4791 std::string profile_data =
4792 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4793 BroadcastAsyncProfileData(profile_data);
4795 pos = found + end_delimiter_len;
4799 // Last incomplete chunk.
4800 m_partial_profile_data = input.substr(pos);
4804 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4805 StringExtractorGDBRemote &profileDataExtractor) {
4806 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4808 llvm::raw_string_ostream output_stream(output);
4809 llvm::StringRef name, value;
4811 // Going to assuming thread_used_usec comes first, else bail out.
4812 while (profileDataExtractor.GetNameColonValue(name, value)) {
4813 if (name.compare("thread_used_id") == 0) {
4814 StringExtractor threadIDHexExtractor(value);
4815 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4817 bool has_used_usec = false;
4818 uint32_t curr_used_usec = 0;
4819 llvm::StringRef usec_name, usec_value;
4820 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4821 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4822 if (usec_name.equals("thread_used_usec")) {
4823 has_used_usec = true;
4824 usec_value.getAsInteger(0, curr_used_usec);
4826 // We didn't find what we want, it is probably
4827 // an older version. Bail out.
4828 profileDataExtractor.SetFilePos(input_file_pos);
4832 if (has_used_usec) {
4833 uint32_t prev_used_usec = 0;
4834 std::map<uint64_t, uint32_t>::iterator iterator =
4835 m_thread_id_to_used_usec_map.find(thread_id);
4836 if (iterator != m_thread_id_to_used_usec_map.end()) {
4837 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4840 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4841 // A good first time record is one that runs for at least 0.25 sec
4842 bool good_first_time =
4843 (prev_used_usec == 0) && (real_used_usec > 250000);
4844 bool good_subsequent_time =
4845 (prev_used_usec > 0) &&
4846 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4848 if (good_first_time || good_subsequent_time) {
4849 // We try to avoid doing too many index id reservation,
4850 // resulting in fast increase of index ids.
4852 output_stream << name << ":";
4853 int32_t index_id = AssignIndexIDToThread(thread_id);
4854 output_stream << index_id << ";";
4856 output_stream << usec_name << ":" << usec_value << ";";
4858 // Skip past 'thread_used_name'.
4859 llvm::StringRef local_name, local_value;
4860 profileDataExtractor.GetNameColonValue(local_name, local_value);
4863 // Store current time as previous time so that they can be compared
4865 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4867 // Bail out and use old string.
4868 output_stream << name << ":" << value << ";";
4871 output_stream << name << ":" << value << ";";
4874 output_stream << end_delimiter;
4875 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4877 return output_stream.str();
4880 void ProcessGDBRemote::HandleStopReply() {
4881 if (GetStopID() != 0)
4884 if (GetID() == LLDB_INVALID_PROCESS_ID) {
4885 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4886 if (pid != LLDB_INVALID_PROCESS_ID)
4889 BuildDynamicRegisterInfo(true);
4892 static const char *const s_async_json_packet_prefix = "JSON-async:";
4894 static StructuredData::ObjectSP
4895 ParseStructuredDataPacket(llvm::StringRef packet) {
4896 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
4898 if (!packet.consume_front(s_async_json_packet_prefix)) {
4901 "GDBRemoteCommmunicationClientBase::%s() received $J packet "
4902 "but was not a StructuredData packet: packet starts with "
4905 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4907 return StructuredData::ObjectSP();
4910 // This is an asynchronous JSON packet, destined for a
4911 // StructuredDataPlugin.
4912 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
4915 StreamString json_str;
4916 json_sp->Dump(json_str);
4918 log->Printf("ProcessGDBRemote::%s() "
4919 "received Async StructuredData packet: %s",
4920 __FUNCTION__, json_str.GetData());
4922 log->Printf("ProcessGDBRemote::%s"
4923 "() received StructuredData packet:"
4931 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4932 auto structured_data_sp = ParseStructuredDataPacket(data);
4933 if (structured_data_sp)
4934 RouteAsyncStructuredData(structured_data_sp);
4937 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
4939 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4940 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4941 "Tests packet speeds of various sizes to determine "
4942 "the performance characteristics of the GDB remote "
4946 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
4947 "The number of packets to send of each varying size "
4948 "(default is 1000).",
4950 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
4951 "The maximum number of bytes to send in a packet. Sizes "
4952 "increase in powers of 2 while the size is less than or "
4953 "equal to this option value. (default 1024).",
4955 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
4956 "The maximum number of bytes to receive in a packet. Sizes "
4957 "increase in powers of 2 while the size is less than or "
4958 "equal to this option value. (default 1024).",
4960 m_json(LLDB_OPT_SET_1, false, "json", 'j',
4961 "Print the output as JSON data for easy parsing.", false, true) {
4962 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4963 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4964 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4965 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4966 m_option_group.Finalize();
4969 ~CommandObjectProcessGDBRemoteSpeedTest() {}
4971 Options *GetOptions() override { return &m_option_group; }
4973 bool DoExecute(Args &command, CommandReturnObject &result) override {
4974 const size_t argc = command.GetArgumentCount();
4976 ProcessGDBRemote *process =
4977 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4980 StreamSP output_stream_sp(
4981 m_interpreter.GetDebugger().GetAsyncOutputStream());
4982 result.SetImmediateOutputStream(output_stream_sp);
4984 const uint32_t num_packets =
4985 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4986 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4987 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4988 const bool json = m_json.GetOptionValue().GetCurrentValue();
4989 const uint64_t k_recv_amount =
4990 4 * 1024 * 1024; // Receive amount in bytes
4991 process->GetGDBRemote().TestPacketSpeed(
4992 num_packets, max_send, max_recv, k_recv_amount, json,
4993 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
4994 result.SetStatus(eReturnStatusSuccessFinishResult);
4998 result.AppendErrorWithFormat("'%s' takes no arguments",
4999 m_cmd_name.c_str());
5001 result.SetStatus(eReturnStatusFailed);
5006 OptionGroupOptions m_option_group;
5007 OptionGroupUInt64 m_num_packets;
5008 OptionGroupUInt64 m_max_send;
5009 OptionGroupUInt64 m_max_recv;
5010 OptionGroupBoolean m_json;
5013 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5016 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5017 : CommandObjectParsed(interpreter, "process plugin packet history",
5018 "Dumps the packet history buffer. ", NULL) {}
5020 ~CommandObjectProcessGDBRemotePacketHistory() {}
5022 bool DoExecute(Args &command, CommandReturnObject &result) override {
5023 const size_t argc = command.GetArgumentCount();
5025 ProcessGDBRemote *process =
5026 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5029 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5030 result.SetStatus(eReturnStatusSuccessFinishResult);
5034 result.AppendErrorWithFormat("'%s' takes no arguments",
5035 m_cmd_name.c_str());
5037 result.SetStatus(eReturnStatusFailed);
5042 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5045 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5046 : CommandObjectParsed(
5047 interpreter, "process plugin packet xfer-size",
5048 "Maximum size that lldb will try to read/write one one chunk.",
5051 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5053 bool DoExecute(Args &command, CommandReturnObject &result) override {
5054 const size_t argc = command.GetArgumentCount();
5056 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5057 "amount to be transferred when "
5059 m_cmd_name.c_str());
5060 result.SetStatus(eReturnStatusFailed);
5064 ProcessGDBRemote *process =
5065 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5067 const char *packet_size = command.GetArgumentAtIndex(0);
5069 uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5070 if (errno == 0 && user_specified_max != 0) {
5071 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5072 result.SetStatus(eReturnStatusSuccessFinishResult);
5076 result.SetStatus(eReturnStatusFailed);
5081 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5084 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5085 : CommandObjectParsed(interpreter, "process plugin packet send",
5086 "Send a custom packet through the GDB remote "
5087 "protocol and print the answer. "
5088 "The packet header and footer will automatically "
5089 "be added to the packet prior to sending and "
5090 "stripped from the result.",
5093 ~CommandObjectProcessGDBRemotePacketSend() {}
5095 bool DoExecute(Args &command, CommandReturnObject &result) override {
5096 const size_t argc = command.GetArgumentCount();
5098 result.AppendErrorWithFormat(
5099 "'%s' takes a one or more packet content arguments",
5100 m_cmd_name.c_str());
5101 result.SetStatus(eReturnStatusFailed);
5105 ProcessGDBRemote *process =
5106 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5108 for (size_t i = 0; i < argc; ++i) {
5109 const char *packet_cstr = command.GetArgumentAtIndex(0);
5110 bool send_async = true;
5111 StringExtractorGDBRemote response;
5112 process->GetGDBRemote().SendPacketAndWaitForResponse(
5113 packet_cstr, response, send_async);
5114 result.SetStatus(eReturnStatusSuccessFinishResult);
5115 Stream &output_strm = result.GetOutputStream();
5116 output_strm.Printf(" packet: %s\n", packet_cstr);
5117 std::string &response_str = response.GetStringRef();
5119 if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5120 response_str = process->HarmonizeThreadIdsForProfileData(response);
5123 if (response_str.empty())
5124 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5126 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5133 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5136 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5137 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5138 "Send a qRcmd packet through the GDB remote protocol "
5139 "and print the response."
5140 "The argument passed to this command will be hex "
5141 "encoded into a valid 'qRcmd' packet, sent and the "
5142 "response will be printed.") {}
5144 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5146 bool DoExecute(const char *command, CommandReturnObject &result) override {
5147 if (command == NULL || command[0] == '\0') {
5148 result.AppendErrorWithFormat("'%s' takes a command string argument",
5149 m_cmd_name.c_str());
5150 result.SetStatus(eReturnStatusFailed);
5154 ProcessGDBRemote *process =
5155 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5157 StreamString packet;
5158 packet.PutCString("qRcmd,");
5159 packet.PutBytesAsRawHex8(command, strlen(command));
5161 bool send_async = true;
5162 StringExtractorGDBRemote response;
5163 process->GetGDBRemote().SendPacketAndWaitForResponse(
5164 packet.GetString(), response, send_async);
5165 result.SetStatus(eReturnStatusSuccessFinishResult);
5166 Stream &output_strm = result.GetOutputStream();
5167 output_strm.Printf(" packet: %s\n", packet.GetData());
5168 const std::string &response_str = response.GetStringRef();
5170 if (response_str.empty())
5171 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5173 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5179 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5182 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5183 : CommandObjectMultiword(interpreter, "process plugin packet",
5184 "Commands that deal with GDB remote packets.",
5189 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5191 "send", CommandObjectSP(
5192 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5196 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5200 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5201 LoadSubCommand("speed-test",
5202 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5206 ~CommandObjectProcessGDBRemotePacket() {}
5209 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5211 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5212 : CommandObjectMultiword(
5213 interpreter, "process plugin",
5214 "Commands for operating on a ProcessGDBRemote process.",
5215 "process plugin <subcommand> [<subcommand-options>]") {
5218 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5221 ~CommandObjectMultiwordProcessGDBRemote() {}
5224 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5226 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5227 GetTarget().GetDebugger().GetCommandInterpreter()));
5228 return m_command_sp.get();