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