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