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