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