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