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