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