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