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