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