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