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