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