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