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