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