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