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