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