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