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