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