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