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