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