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