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