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