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             const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
908             int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
909             if (arg_packet_err == 0)
910             {
911                 std::string error_str;
912                 if (m_gdb_comm.GetLaunchSuccess (error_str))
913                 {
914                     SetID (m_gdb_comm.GetCurrentProcessID ());
915                 }
916                 else
917                 {
918                     error.SetErrorString (error_str.c_str());
919                 }
920             }
921             else
922             {
923                 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
924             }
925 
926             m_gdb_comm.SetPacketTimeout (old_packet_timeout);
927 
928             if (GetID() == LLDB_INVALID_PROCESS_ID)
929             {
930                 if (log)
931                     log->Printf("failed to connect to debugserver: %s", error.AsCString());
932                 KillDebugserverProcess ();
933                 return error;
934             }
935 
936             if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
937             {
938                 if (!m_target.GetArchitecture().IsValid())
939                 {
940                     if (m_gdb_comm.GetProcessArchitecture().IsValid())
941                     {
942                         m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
943                     }
944                     else
945                     {
946                         m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
947                     }
948                 }
949 
950                 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
951 
952                 if (!disable_stdio)
953                 {
954                     if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
955                         SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
956                 }
957             }
958         }
959         else
960         {
961             if (log)
962                 log->Printf("failed to connect to debugserver: %s", error.AsCString());
963         }
964     }
965     else
966     {
967         // Set our user ID to an invalid process ID.
968         SetID(LLDB_INVALID_PROCESS_ID);
969         error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
970                                         exe_module->GetFileSpec().GetFilename().AsCString(),
971                                         exe_module->GetArchitecture().GetArchitectureName());
972     }
973     return error;
974 
975 }
976 
977 
978 Error
979 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
980 {
981     Error error;
982     // Only connect if we have a valid connect URL
983     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
984 
985     if (connect_url && connect_url[0])
986     {
987         if (log)
988             log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
989         std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
990         if (conn_ap.get())
991         {
992             const uint32_t max_retry_count = 50;
993             uint32_t retry_count = 0;
994             while (!m_gdb_comm.IsConnected())
995             {
996                 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
997                 {
998                     m_gdb_comm.SetConnection (conn_ap.release());
999                     break;
1000                 }
1001                 else if (error.WasInterrupted())
1002                 {
1003                     // If we were interrupted, don't keep retrying.
1004                     break;
1005                 }
1006 
1007                 retry_count++;
1008 
1009                 if (retry_count >= max_retry_count)
1010                     break;
1011 
1012                 usleep (100000);
1013             }
1014         }
1015     }
1016 
1017     if (!m_gdb_comm.IsConnected())
1018     {
1019         if (error.Success())
1020             error.SetErrorString("not connected to remote gdb server");
1021         return error;
1022     }
1023 
1024     // We always seem to be able to open a connection to a local port
1025     // so we need to make sure we can then send data to it. If we can't
1026     // then we aren't actually connected to anything, so try and do the
1027     // handshake with the remote GDB server and make sure that goes
1028     // alright.
1029     if (!m_gdb_comm.HandshakeWithServer (&error))
1030     {
1031         m_gdb_comm.Disconnect();
1032         if (error.Success())
1033             error.SetErrorString("not connected to remote gdb server");
1034         return error;
1035     }
1036     m_gdb_comm.GetThreadSuffixSupported ();
1037     m_gdb_comm.GetListThreadsInStopReplySupported ();
1038     m_gdb_comm.GetHostInfo ();
1039     m_gdb_comm.GetVContSupported ('c');
1040     m_gdb_comm.GetVAttachOrWaitSupported();
1041 
1042     size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1043     for (size_t idx = 0; idx < num_cmds; idx++)
1044     {
1045         StringExtractorGDBRemote response;
1046         m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1047     }
1048     return error;
1049 }
1050 
1051 void
1052 ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
1053 {
1054     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1055     if (log)
1056         log->Printf ("ProcessGDBRemote::DidLaunch()");
1057     if (GetID() != LLDB_INVALID_PROCESS_ID)
1058     {
1059         BuildDynamicRegisterInfo (false);
1060 
1061         // See if the GDB server supports the qHostInfo information
1062 
1063 
1064         // See if the GDB server supports the qProcessInfo packet, if so
1065         // prefer that over the Host information as it will be more specific
1066         // to our process.
1067 
1068         const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1069         if (remote_process_arch.IsValid())
1070         {
1071             process_arch = remote_process_arch;
1072             if (log)
1073                 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1074                              __FUNCTION__,
1075                              process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1076                              process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1077         }
1078         else
1079         {
1080             process_arch = m_gdb_comm.GetHostArchitecture();
1081             if (log)
1082                 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1083                              __FUNCTION__,
1084                              process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1085                              process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1086         }
1087 
1088         if (process_arch.IsValid())
1089         {
1090             ArchSpec &target_arch = GetTarget().GetArchitecture();
1091             if (target_arch.IsValid())
1092             {
1093                 if (log)
1094                     log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1095                                  __FUNCTION__,
1096                                  target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1097                                  target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1098 
1099                 // If the remote host is ARM and we have apple as the vendor, then
1100                 // ARM executables and shared libraries can have mixed ARM architectures.
1101                 // You can have an armv6 executable, and if the host is armv7, then the
1102                 // system will load the best possible architecture for all shared libraries
1103                 // it has, so we really need to take the remote host architecture as our
1104                 // defacto architecture in this case.
1105 
1106                 if (process_arch.GetMachine() == llvm::Triple::arm &&
1107                     process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1108                 {
1109                     GetTarget().SetArchitecture (process_arch);
1110                     if (log)
1111                         log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1112                                      __FUNCTION__,
1113                                      process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1114                                      process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1115                 }
1116                 else
1117                 {
1118                     // Fill in what is missing in the triple
1119                     const llvm::Triple &remote_triple = process_arch.GetTriple();
1120                     llvm::Triple &target_triple = target_arch.GetTriple();
1121                     if (target_triple.getVendorName().size() == 0)
1122                     {
1123                         target_triple.setVendor (remote_triple.getVendor());
1124 
1125                         if (target_triple.getOSName().size() == 0)
1126                         {
1127                             target_triple.setOS (remote_triple.getOS());
1128 
1129                             if (target_triple.getEnvironmentName().size() == 0)
1130                                 target_triple.setEnvironment (remote_triple.getEnvironment());
1131                         }
1132                     }
1133 
1134                 }
1135 
1136                 if (log)
1137                     log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1138                                  __FUNCTION__,
1139                                  target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1140                                  target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1141             }
1142             else
1143             {
1144                 // The target doesn't have a valid architecture yet, set it from
1145                 // the architecture we got from the remote GDB server
1146                 GetTarget().SetArchitecture (process_arch);
1147             }
1148         }
1149     }
1150 }
1151 
1152 void
1153 ProcessGDBRemote::DidLaunch ()
1154 {
1155     ArchSpec process_arch;
1156     DidLaunchOrAttach (process_arch);
1157 }
1158 
1159 Error
1160 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
1161 {
1162     ProcessAttachInfo attach_info;
1163     return DoAttachToProcessWithID(attach_pid, attach_info);
1164 }
1165 
1166 Error
1167 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1168 {
1169     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1170     Error error;
1171 
1172     if (log)
1173         log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1174 
1175     // Clear out and clean up from any current state
1176     Clear();
1177     if (attach_pid != LLDB_INVALID_PROCESS_ID)
1178     {
1179         // Make sure we aren't already connected?
1180         if (!m_gdb_comm.IsConnected())
1181         {
1182             error = LaunchAndConnectToDebugserver (attach_info);
1183 
1184             if (error.Fail())
1185             {
1186                 const char *error_string = error.AsCString();
1187                 if (error_string == NULL)
1188                     error_string = "unable to launch " DEBUGSERVER_BASENAME;
1189 
1190                 SetExitStatus (-1, error_string);
1191             }
1192         }
1193 
1194         if (error.Success())
1195         {
1196             m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1197 
1198             char packet[64];
1199             const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1200             SetID (attach_pid);
1201             m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1202         }
1203     }
1204 
1205     return error;
1206 }
1207 
1208 Error
1209 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1210 {
1211     Error error;
1212     // Clear out and clean up from any current state
1213     Clear();
1214 
1215     if (process_name && process_name[0])
1216     {
1217         // Make sure we aren't already connected?
1218         if (!m_gdb_comm.IsConnected())
1219         {
1220             error = LaunchAndConnectToDebugserver (attach_info);
1221 
1222             if (error.Fail())
1223             {
1224                 const char *error_string = error.AsCString();
1225                 if (error_string == NULL)
1226                     error_string = "unable to launch " DEBUGSERVER_BASENAME;
1227 
1228                 SetExitStatus (-1, error_string);
1229             }
1230         }
1231 
1232         if (error.Success())
1233         {
1234             StreamString packet;
1235 
1236             m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1237 
1238             if (attach_info.GetWaitForLaunch())
1239             {
1240                 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1241                 {
1242                     packet.PutCString ("vAttachWait");
1243                 }
1244                 else
1245                 {
1246                     if (attach_info.GetIgnoreExisting())
1247                         packet.PutCString("vAttachWait");
1248                     else
1249                         packet.PutCString ("vAttachOrWait");
1250                 }
1251             }
1252             else
1253                 packet.PutCString("vAttachName");
1254             packet.PutChar(';');
1255             packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1256 
1257             m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1258 
1259         }
1260     }
1261     return error;
1262 }
1263 
1264 
1265 bool
1266 ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1267 {
1268     m_gdb_comm.Disconnect();
1269     return Process::SetExitStatus (exit_status, cstr);
1270 }
1271 
1272 void
1273 ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
1274 {
1275     // If you can figure out what the architecture is, fill it in here.
1276     process_arch.Clear();
1277     DidLaunchOrAttach (process_arch);
1278 }
1279 
1280 
1281 Error
1282 ProcessGDBRemote::WillResume ()
1283 {
1284     m_continue_c_tids.clear();
1285     m_continue_C_tids.clear();
1286     m_continue_s_tids.clear();
1287     m_continue_S_tids.clear();
1288     return Error();
1289 }
1290 
1291 Error
1292 ProcessGDBRemote::DoResume ()
1293 {
1294     Error error;
1295     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1296     if (log)
1297         log->Printf ("ProcessGDBRemote::Resume()");
1298 
1299     Listener listener ("gdb-remote.resume-packet-sent");
1300     if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1301     {
1302         listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1303 
1304         const size_t num_threads = GetThreadList().GetSize();
1305 
1306         StreamString continue_packet;
1307         bool continue_packet_error = false;
1308         if (m_gdb_comm.HasAnyVContSupport ())
1309         {
1310             if (m_continue_c_tids.size() == num_threads ||
1311                 (m_continue_c_tids.empty() &&
1312                  m_continue_C_tids.empty() &&
1313                  m_continue_s_tids.empty() &&
1314                  m_continue_S_tids.empty()))
1315             {
1316                 // All threads are continuing, just send a "c" packet
1317                 continue_packet.PutCString ("c");
1318             }
1319             else
1320             {
1321                 continue_packet.PutCString ("vCont");
1322 
1323                 if (!m_continue_c_tids.empty())
1324                 {
1325                     if (m_gdb_comm.GetVContSupported ('c'))
1326                     {
1327                         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)
1328                             continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1329                     }
1330                     else
1331                         continue_packet_error = true;
1332                 }
1333 
1334                 if (!continue_packet_error && !m_continue_C_tids.empty())
1335                 {
1336                     if (m_gdb_comm.GetVContSupported ('C'))
1337                     {
1338                         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)
1339                             continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1340                     }
1341                     else
1342                         continue_packet_error = true;
1343                 }
1344 
1345                 if (!continue_packet_error && !m_continue_s_tids.empty())
1346                 {
1347                     if (m_gdb_comm.GetVContSupported ('s'))
1348                     {
1349                         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)
1350                             continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1351                     }
1352                     else
1353                         continue_packet_error = true;
1354                 }
1355 
1356                 if (!continue_packet_error && !m_continue_S_tids.empty())
1357                 {
1358                     if (m_gdb_comm.GetVContSupported ('S'))
1359                     {
1360                         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)
1361                             continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1362                     }
1363                     else
1364                         continue_packet_error = true;
1365                 }
1366 
1367                 if (continue_packet_error)
1368                     continue_packet.GetString().clear();
1369             }
1370         }
1371         else
1372             continue_packet_error = true;
1373 
1374         if (continue_packet_error)
1375         {
1376             // Either no vCont support, or we tried to use part of the vCont
1377             // packet that wasn't supported by the remote GDB server.
1378             // We need to try and make a simple packet that can do our continue
1379             const size_t num_continue_c_tids = m_continue_c_tids.size();
1380             const size_t num_continue_C_tids = m_continue_C_tids.size();
1381             const size_t num_continue_s_tids = m_continue_s_tids.size();
1382             const size_t num_continue_S_tids = m_continue_S_tids.size();
1383             if (num_continue_c_tids > 0)
1384             {
1385                 if (num_continue_c_tids == num_threads)
1386                 {
1387                     // All threads are resuming...
1388                     m_gdb_comm.SetCurrentThreadForRun (-1);
1389                     continue_packet.PutChar ('c');
1390                     continue_packet_error = false;
1391                 }
1392                 else if (num_continue_c_tids == 1 &&
1393                          num_continue_C_tids == 0 &&
1394                          num_continue_s_tids == 0 &&
1395                          num_continue_S_tids == 0 )
1396                 {
1397                     // Only one thread is continuing
1398                     m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1399                     continue_packet.PutChar ('c');
1400                     continue_packet_error = false;
1401                 }
1402             }
1403 
1404             if (continue_packet_error && num_continue_C_tids > 0)
1405             {
1406                 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1407                     num_continue_C_tids > 0 &&
1408                     num_continue_s_tids == 0 &&
1409                     num_continue_S_tids == 0 )
1410                 {
1411                     const int continue_signo = m_continue_C_tids.front().second;
1412                     // Only one thread is continuing
1413                     if (num_continue_C_tids > 1)
1414                     {
1415                         // More that one thread with a signal, yet we don't have
1416                         // vCont support and we are being asked to resume each
1417                         // thread with a signal, we need to make sure they are
1418                         // all the same signal, or we can't issue the continue
1419                         // accurately with the current support...
1420                         if (num_continue_C_tids > 1)
1421                         {
1422                             continue_packet_error = false;
1423                             for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1424                             {
1425                                 if (m_continue_C_tids[i].second != continue_signo)
1426                                     continue_packet_error = true;
1427                             }
1428                         }
1429                         if (!continue_packet_error)
1430                             m_gdb_comm.SetCurrentThreadForRun (-1);
1431                     }
1432                     else
1433                     {
1434                         // Set the continue thread ID
1435                         continue_packet_error = false;
1436                         m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1437                     }
1438                     if (!continue_packet_error)
1439                     {
1440                         // Add threads continuing with the same signo...
1441                         continue_packet.Printf("C%2.2x", continue_signo);
1442                     }
1443                 }
1444             }
1445 
1446             if (continue_packet_error && num_continue_s_tids > 0)
1447             {
1448                 if (num_continue_s_tids == num_threads)
1449                 {
1450                     // All threads are resuming...
1451                     m_gdb_comm.SetCurrentThreadForRun (-1);
1452                     continue_packet.PutChar ('s');
1453                     continue_packet_error = false;
1454                 }
1455                 else if (num_continue_c_tids == 0 &&
1456                          num_continue_C_tids == 0 &&
1457                          num_continue_s_tids == 1 &&
1458                          num_continue_S_tids == 0 )
1459                 {
1460                     // Only one thread is stepping
1461                     m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1462                     continue_packet.PutChar ('s');
1463                     continue_packet_error = false;
1464                 }
1465             }
1466 
1467             if (!continue_packet_error && num_continue_S_tids > 0)
1468             {
1469                 if (num_continue_S_tids == num_threads)
1470                 {
1471                     const int step_signo = m_continue_S_tids.front().second;
1472                     // Are all threads trying to step with the same signal?
1473                     continue_packet_error = false;
1474                     if (num_continue_S_tids > 1)
1475                     {
1476                         for (size_t i=1; i<num_threads; ++i)
1477                         {
1478                             if (m_continue_S_tids[i].second != step_signo)
1479                                 continue_packet_error = true;
1480                         }
1481                     }
1482                     if (!continue_packet_error)
1483                     {
1484                         // Add threads stepping with the same signo...
1485                         m_gdb_comm.SetCurrentThreadForRun (-1);
1486                         continue_packet.Printf("S%2.2x", step_signo);
1487                     }
1488                 }
1489                 else if (num_continue_c_tids == 0 &&
1490                          num_continue_C_tids == 0 &&
1491                          num_continue_s_tids == 0 &&
1492                          num_continue_S_tids == 1 )
1493                 {
1494                     // Only one thread is stepping with signal
1495                     m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1496                     continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1497                     continue_packet_error = false;
1498                 }
1499             }
1500         }
1501 
1502         if (continue_packet_error)
1503         {
1504             error.SetErrorString ("can't make continue packet for this resume");
1505         }
1506         else
1507         {
1508             EventSP event_sp;
1509             TimeValue timeout;
1510             timeout = TimeValue::Now();
1511             timeout.OffsetWithSeconds (5);
1512             if (!m_async_thread.IsJoinable())
1513             {
1514                 error.SetErrorString ("Trying to resume but the async thread is dead.");
1515                 if (log)
1516                     log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1517                 return error;
1518             }
1519 
1520             m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1521 
1522             if (listener.WaitForEvent (&timeout, event_sp) == false)
1523             {
1524                 error.SetErrorString("Resume timed out.");
1525                 if (log)
1526                     log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1527             }
1528             else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1529             {
1530                 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1531                 if (log)
1532                     log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1533                 return error;
1534             }
1535         }
1536     }
1537 
1538     return error;
1539 }
1540 
1541 void
1542 ProcessGDBRemote::ClearThreadIDList ()
1543 {
1544     Mutex::Locker locker(m_thread_list_real.GetMutex());
1545     m_thread_ids.clear();
1546 }
1547 
1548 bool
1549 ProcessGDBRemote::UpdateThreadIDList ()
1550 {
1551     Mutex::Locker locker(m_thread_list_real.GetMutex());
1552     bool sequence_mutex_unavailable = false;
1553     m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1554     if (sequence_mutex_unavailable)
1555     {
1556         return false; // We just didn't get the list
1557     }
1558     return true;
1559 }
1560 
1561 bool
1562 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1563 {
1564     // locker will keep a mutex locked until it goes out of scope
1565     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1566     if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1567         log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1568 
1569     size_t num_thread_ids = m_thread_ids.size();
1570     // The "m_thread_ids" thread ID list should always be updated after each stop
1571     // reply packet, but in case it isn't, update it here.
1572     if (num_thread_ids == 0)
1573     {
1574         if (!UpdateThreadIDList ())
1575             return false;
1576         num_thread_ids = m_thread_ids.size();
1577     }
1578 
1579     ThreadList old_thread_list_copy(old_thread_list);
1580     if (num_thread_ids > 0)
1581     {
1582         for (size_t i=0; i<num_thread_ids; ++i)
1583         {
1584             tid_t tid = m_thread_ids[i];
1585             ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1586             if (!thread_sp)
1587             {
1588                 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1589                 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1590                     log->Printf(
1591                             "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1592                             __FUNCTION__, static_cast<void*>(thread_sp.get()),
1593                             thread_sp->GetID());
1594             }
1595             else
1596             {
1597                 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1598                     log->Printf(
1599                            "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1600                            __FUNCTION__, static_cast<void*>(thread_sp.get()),
1601                            thread_sp->GetID());
1602             }
1603             new_thread_list.AddThread(thread_sp);
1604         }
1605     }
1606 
1607     // Whatever that is left in old_thread_list_copy are not
1608     // present in new_thread_list. Remove non-existent threads from internal id table.
1609     size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1610     for (size_t i=0; i<old_num_thread_ids; i++)
1611     {
1612         ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1613         if (old_thread_sp)
1614         {
1615             lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1616             m_thread_id_to_index_id_map.erase(old_thread_id);
1617         }
1618     }
1619 
1620     return true;
1621 }
1622 
1623 
1624 StateType
1625 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1626 {
1627     stop_packet.SetFilePos (0);
1628     const char stop_type = stop_packet.GetChar();
1629     switch (stop_type)
1630     {
1631     case 'T':
1632     case 'S':
1633         {
1634             // This is a bit of a hack, but is is required. If we did exec, we
1635             // need to clear our thread lists and also know to rebuild our dynamic
1636             // register info before we lookup and threads and populate the expedited
1637             // register values so we need to know this right away so we can cleanup
1638             // and update our registers.
1639             const uint32_t stop_id = GetStopID();
1640             if (stop_id == 0)
1641             {
1642                 // Our first stop, make sure we have a process ID, and also make
1643                 // sure we know about our registers
1644                 if (GetID() == LLDB_INVALID_PROCESS_ID)
1645                 {
1646                     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1647                     if (pid != LLDB_INVALID_PROCESS_ID)
1648                         SetID (pid);
1649                 }
1650                 BuildDynamicRegisterInfo (true);
1651             }
1652             // Stop with signal and thread info
1653             const uint8_t signo = stop_packet.GetHexU8();
1654             std::string name;
1655             std::string value;
1656             std::string thread_name;
1657             std::string reason;
1658             std::string description;
1659             uint32_t exc_type = 0;
1660             std::vector<addr_t> exc_data;
1661             addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1662             ThreadSP thread_sp;
1663             ThreadGDBRemote *gdb_thread = NULL;
1664 
1665             while (stop_packet.GetNameColonValue(name, value))
1666             {
1667                 if (name.compare("metype") == 0)
1668                 {
1669                     // exception type in big endian hex
1670                     exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
1671                 }
1672                 else if (name.compare("medata") == 0)
1673                 {
1674                     // exception data in big endian hex
1675                     exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
1676                 }
1677                 else if (name.compare("thread") == 0)
1678                 {
1679                     // thread in big endian hex
1680                     lldb::tid_t tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1681                     // m_thread_list_real does have its own mutex, but we need to
1682                     // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1683                     // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1684                     Mutex::Locker locker (m_thread_list_real.GetMutex ());
1685                     thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1686 
1687                     if (!thread_sp)
1688                     {
1689                         // Create the thread if we need to
1690                         thread_sp.reset (new ThreadGDBRemote (*this, tid));
1691                         Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1692                         if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1693                             log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1694                                          __FUNCTION__,
1695                                          static_cast<void*>(thread_sp.get()),
1696                                          thread_sp->GetID());
1697 
1698                         m_thread_list_real.AddThread(thread_sp);
1699                     }
1700                     gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1701 
1702                 }
1703                 else if (name.compare("threads") == 0)
1704                 {
1705                     Mutex::Locker locker(m_thread_list_real.GetMutex());
1706                     m_thread_ids.clear();
1707                     // A comma separated list of all threads in the current
1708                     // process that includes the thread for this stop reply
1709                     // packet
1710                     size_t comma_pos;
1711                     lldb::tid_t tid;
1712                     while ((comma_pos = value.find(',')) != std::string::npos)
1713                     {
1714                         value[comma_pos] = '\0';
1715                         // thread in big endian hex
1716                         tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1717                         if (tid != LLDB_INVALID_THREAD_ID)
1718                             m_thread_ids.push_back (tid);
1719                         value.erase(0, comma_pos + 1);
1720                     }
1721                     tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1722                     if (tid != LLDB_INVALID_THREAD_ID)
1723                         m_thread_ids.push_back (tid);
1724                 }
1725                 else if (name.compare("hexname") == 0)
1726                 {
1727                     StringExtractor name_extractor;
1728                     // Swap "value" over into "name_extractor"
1729                     name_extractor.GetStringRef().swap(value);
1730                     // Now convert the HEX bytes into a string value
1731                     name_extractor.GetHexByteString (value);
1732                     thread_name.swap (value);
1733                 }
1734                 else if (name.compare("name") == 0)
1735                 {
1736                     thread_name.swap (value);
1737                 }
1738                 else if (name.compare("qaddr") == 0)
1739                 {
1740                     thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
1741                 }
1742                 else if (name.compare("reason") == 0)
1743                 {
1744                     reason.swap(value);
1745                 }
1746                 else if (name.compare("description") == 0)
1747                 {
1748                     StringExtractor desc_extractor;
1749                     // Swap "value" over into "name_extractor"
1750                     desc_extractor.GetStringRef().swap(value);
1751                     // Now convert the HEX bytes into a string value
1752                     desc_extractor.GetHexByteString (value);
1753                     description.swap(value);
1754                 }
1755                 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1756                 {
1757                     // We have a register number that contains an expedited
1758                     // register value. Lets supply this register to our thread
1759                     // so it won't have to go and read it.
1760                     if (gdb_thread)
1761                     {
1762                         uint32_t reg = StringConvert::ToUInt32 (name.c_str(), UINT32_MAX, 16);
1763 
1764                         if (reg != UINT32_MAX)
1765                         {
1766                             StringExtractor reg_value_extractor;
1767                             // Swap "value" over into "reg_value_extractor"
1768                             reg_value_extractor.GetStringRef().swap(value);
1769                             if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
1770                             {
1771                                 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1772                                                                     name.c_str(),
1773                                                                     reg,
1774                                                                     reg,
1775                                                                     reg_value_extractor.GetStringRef().c_str(),
1776                                                                     stop_packet.GetStringRef().c_str());
1777                             }
1778                         }
1779                     }
1780                 }
1781             }
1782 
1783             // If the response is old style 'S' packet which does not provide us with thread information
1784             // then update the thread list and choose the first one.
1785             if (!thread_sp)
1786             {
1787                 UpdateThreadIDList ();
1788 
1789                 if (!m_thread_ids.empty ())
1790                 {
1791                     Mutex::Locker locker (m_thread_list_real.GetMutex ());
1792                     thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1793                     if (thread_sp)
1794                         gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1795                 }
1796             }
1797 
1798             if (thread_sp)
1799             {
1800                 // Clear the stop info just in case we don't set it to anything
1801                 thread_sp->SetStopInfo (StopInfoSP());
1802 
1803                 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1804                 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1805                 if (exc_type != 0)
1806                 {
1807                     const size_t exc_data_size = exc_data.size();
1808 
1809                     thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1810                                                                                                       exc_type,
1811                                                                                                       exc_data_size,
1812                                                                                                       exc_data_size >= 1 ? exc_data[0] : 0,
1813                                                                                                       exc_data_size >= 2 ? exc_data[1] : 0,
1814                                                                                                       exc_data_size >= 3 ? exc_data[2] : 0));
1815                 }
1816                 else
1817                 {
1818                     bool handled = false;
1819                     bool did_exec = false;
1820                     if (!reason.empty())
1821                     {
1822                         if (reason.compare("trace") == 0)
1823                         {
1824                             thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1825                             handled = true;
1826                         }
1827                         else if (reason.compare("breakpoint") == 0)
1828                         {
1829                             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1830                             lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1831                             if (bp_site_sp)
1832                             {
1833                                 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1834                                 // we can just report no reason.  We don't need to worry about stepping over the breakpoint here, that
1835                                 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1836                                 handled = true;
1837                                 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1838                                 {
1839                                     thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1840                                 }
1841                                 else
1842                                 {
1843                                     StopInfoSP invalid_stop_info_sp;
1844                                     thread_sp->SetStopInfo (invalid_stop_info_sp);
1845                                 }
1846                             }
1847                         }
1848                         else if (reason.compare("trap") == 0)
1849                         {
1850                             // Let the trap just use the standard signal stop reason below...
1851                         }
1852                         else if (reason.compare("watchpoint") == 0)
1853                         {
1854                             StringExtractor desc_extractor(description.c_str());
1855                             addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1856                             uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1857                             watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1858                             if (wp_addr != LLDB_INVALID_ADDRESS)
1859                             {
1860                                 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1861                                 if (wp_sp)
1862                                 {
1863                                     wp_sp->SetHardwareIndex(wp_index);
1864                                     watch_id = wp_sp->GetID();
1865                                 }
1866                             }
1867                             if (watch_id == LLDB_INVALID_WATCH_ID)
1868                             {
1869                                 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
1870                                 if (log) log->Printf ("failed to find watchpoint");
1871                             }
1872                             thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1873                             handled = true;
1874                         }
1875                         else if (reason.compare("exception") == 0)
1876                         {
1877                             thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1878                             handled = true;
1879                         }
1880                         else if (reason.compare("exec") == 0)
1881                         {
1882                             did_exec = true;
1883                             thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1884                             handled = true;
1885                         }
1886                     }
1887 
1888                     if (!handled && signo && did_exec == false)
1889                     {
1890                         if (signo == SIGTRAP)
1891                         {
1892                             // Currently we are going to assume SIGTRAP means we are either
1893                             // hitting a breakpoint or hardware single stepping.
1894                             handled = true;
1895                             addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1896                             lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1897 
1898                             if (bp_site_sp)
1899                             {
1900                                 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1901                                 // we can just report no reason.  We don't need to worry about stepping over the breakpoint here, that
1902                                 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1903                                 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1904                                 {
1905                                     if(m_breakpoint_pc_offset != 0)
1906                                         thread_sp->GetRegisterContext()->SetPC(pc);
1907                                     thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1908                                 }
1909                                 else
1910                                 {
1911                                     StopInfoSP invalid_stop_info_sp;
1912                                     thread_sp->SetStopInfo (invalid_stop_info_sp);
1913                                 }
1914                             }
1915                             else
1916                             {
1917                                 // If we were stepping then assume the stop was the result of the trace.  If we were
1918                                 // not stepping then report the SIGTRAP.
1919                                 // FIXME: We are still missing the case where we single step over a trap instruction.
1920                                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1921                                     thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1922                                 else
1923                                     thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
1924                             }
1925                         }
1926                         if (!handled)
1927                             thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1928                     }
1929 
1930                     if (!description.empty())
1931                     {
1932                         lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
1933                         if (stop_info_sp)
1934                         {
1935                             stop_info_sp->SetDescription (description.c_str());
1936                         }
1937                         else
1938                         {
1939                             thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1940                         }
1941                     }
1942                 }
1943             }
1944             return eStateStopped;
1945         }
1946         break;
1947 
1948     case 'W':
1949     case 'X':
1950         // process exited
1951         return eStateExited;
1952 
1953     default:
1954         break;
1955     }
1956     return eStateInvalid;
1957 }
1958 
1959 void
1960 ProcessGDBRemote::RefreshStateAfterStop ()
1961 {
1962     Mutex::Locker locker(m_thread_list_real.GetMutex());
1963     m_thread_ids.clear();
1964     // Set the thread stop info. It might have a "threads" key whose value is
1965     // a list of all thread IDs in the current process, so m_thread_ids might
1966     // get set.
1967     SetThreadStopInfo (m_last_stop_packet);
1968     // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1969     if (m_thread_ids.empty())
1970     {
1971         // No, we need to fetch the thread list manually
1972         UpdateThreadIDList();
1973     }
1974 
1975     // Let all threads recover from stopping and do any clean up based
1976     // on the previous thread state (if any).
1977     m_thread_list_real.RefreshStateAfterStop();
1978 
1979 }
1980 
1981 Error
1982 ProcessGDBRemote::DoHalt (bool &caused_stop)
1983 {
1984     Error error;
1985 
1986     bool timed_out = false;
1987     Mutex::Locker locker;
1988 
1989     if (m_public_state.GetValue() == eStateAttaching)
1990     {
1991         // We are being asked to halt during an attach. We need to just close
1992         // our file handle and debugserver will go away, and we can be done...
1993         m_gdb_comm.Disconnect();
1994     }
1995     else
1996     {
1997         if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
1998         {
1999             if (timed_out)
2000                 error.SetErrorString("timed out sending interrupt packet");
2001             else
2002                 error.SetErrorString("unknown error sending interrupt packet");
2003         }
2004 
2005         caused_stop = m_gdb_comm.GetInterruptWasSent ();
2006     }
2007     return error;
2008 }
2009 
2010 Error
2011 ProcessGDBRemote::DoDetach(bool keep_stopped)
2012 {
2013     Error error;
2014     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2015     if (log)
2016         log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2017 
2018     error = m_gdb_comm.Detach (keep_stopped);
2019     if (log)
2020     {
2021         if (error.Success())
2022             log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2023         else
2024             log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
2025     }
2026 
2027     if (!error.Success())
2028         return error;
2029 
2030     // Sleep for one second to let the process get all detached...
2031     StopAsyncThread ();
2032 
2033     SetPrivateState (eStateDetached);
2034     ResumePrivateStateThread();
2035 
2036     //KillDebugserverProcess ();
2037     return error;
2038 }
2039 
2040 
2041 Error
2042 ProcessGDBRemote::DoDestroy ()
2043 {
2044     Error error;
2045     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2046     if (log)
2047         log->Printf ("ProcessGDBRemote::DoDestroy()");
2048 
2049     // There is a bug in older iOS debugservers where they don't shut down the process
2050     // they are debugging properly.  If the process is sitting at a breakpoint or an exception,
2051     // this can cause problems with restarting.  So we check to see if any of our threads are stopped
2052     // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2053     // destroy it again.
2054     //
2055     // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2056     // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2057     // the debugservers with this bug are equal.  There really should be a better way to test this!
2058     //
2059     // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2060     // get called here to destroy again and we're still at a breakpoint or exception, then we should
2061     // just do the straight-forward kill.
2062     //
2063     // And of course, if we weren't able to stop the process by the time we get here, it isn't
2064     // necessary (or helpful) to do any of this.
2065 
2066     if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2067     {
2068         PlatformSP platform_sp = GetTarget().GetPlatform();
2069 
2070         // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2071         if (platform_sp
2072             && platform_sp->GetName()
2073             && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
2074         {
2075             if (m_destroy_tried_resuming)
2076             {
2077                 if (log)
2078                     log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
2079             }
2080             else
2081             {
2082                 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2083                 // but we really need it to happen here and it doesn't matter if we do it twice.
2084                 m_thread_list.DiscardThreadPlans();
2085                 DisableAllBreakpointSites();
2086 
2087                 bool stop_looks_like_crash = false;
2088                 ThreadList &threads = GetThreadList();
2089 
2090                 {
2091                     Mutex::Locker locker(threads.GetMutex());
2092 
2093                     size_t num_threads = threads.GetSize();
2094                     for (size_t i = 0; i < num_threads; i++)
2095                     {
2096                         ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2097                         StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2098                         StopReason reason = eStopReasonInvalid;
2099                         if (stop_info_sp)
2100                             reason = stop_info_sp->GetStopReason();
2101                         if (reason == eStopReasonBreakpoint
2102                             || reason == eStopReasonException)
2103                         {
2104                             if (log)
2105                                 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2106                                              thread_sp->GetProtocolID(),
2107                                              stop_info_sp->GetDescription());
2108                             stop_looks_like_crash = true;
2109                             break;
2110                         }
2111                     }
2112                 }
2113 
2114                 if (stop_looks_like_crash)
2115                 {
2116                     if (log)
2117                         log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2118                     m_destroy_tried_resuming = true;
2119 
2120                     // If we are going to run again before killing, it would be good to suspend all the threads
2121                     // before resuming so they won't get into more trouble.  Sadly, for the threads stopped with
2122                     // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2123                     // have to run the risk of letting those threads proceed a bit.
2124 
2125                     {
2126                         Mutex::Locker locker(threads.GetMutex());
2127 
2128                         size_t num_threads = threads.GetSize();
2129                         for (size_t i = 0; i < num_threads; i++)
2130                         {
2131                             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2132                             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2133                             StopReason reason = eStopReasonInvalid;
2134                             if (stop_info_sp)
2135                                 reason = stop_info_sp->GetStopReason();
2136                             if (reason != eStopReasonBreakpoint
2137                                 && reason != eStopReasonException)
2138                             {
2139                                 if (log)
2140                                     log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2141                                                  thread_sp->GetProtocolID());
2142                                 thread_sp->SetResumeState(eStateSuspended);
2143                             }
2144                         }
2145                     }
2146                     Resume ();
2147                     return Destroy();
2148                 }
2149             }
2150         }
2151     }
2152 
2153     // Interrupt if our inferior is running...
2154     int exit_status = SIGABRT;
2155     std::string exit_string;
2156 
2157     if (m_gdb_comm.IsConnected())
2158     {
2159         if (m_public_state.GetValue() != eStateAttaching)
2160         {
2161 
2162             StringExtractorGDBRemote response;
2163             bool send_async = true;
2164             const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2165 
2166             if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2167             {
2168                 char packet_cmd = response.GetChar(0);
2169 
2170                 if (packet_cmd == 'W' || packet_cmd == 'X')
2171                 {
2172 #if defined(__APPLE__)
2173                     // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2174                     // to debugserver, which becomes the parent process through "PT_ATTACH".  Then when we go to kill
2175                     // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2176                     // with no error and the correct status.  But amusingly enough that doesn't seem to actually reap
2177                     // the process, but instead it is left around as a Zombie.  Probably the kernel is in the process of
2178                     // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2179                     // Anyway, so call waitpid here to finally reap it.
2180                     PlatformSP platform_sp(GetTarget().GetPlatform());
2181                     if (platform_sp && platform_sp->IsHost())
2182                     {
2183                         int status;
2184                         ::pid_t reap_pid;
2185                         reap_pid = waitpid (GetID(), &status, WNOHANG);
2186                         if (log)
2187                             log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2188                     }
2189 #endif
2190                     SetLastStopPacket (response);
2191                     ClearThreadIDList ();
2192                     exit_status = response.GetHexU8();
2193                 }
2194                 else
2195                 {
2196                     if (log)
2197                         log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2198                     exit_string.assign("got unexpected response to k packet: ");
2199                     exit_string.append(response.GetStringRef());
2200                 }
2201             }
2202             else
2203             {
2204                 if (log)
2205                     log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2206                 exit_string.assign("failed to send the k packet");
2207             }
2208 
2209             m_gdb_comm.SetPacketTimeout(old_packet_timeout);
2210         }
2211         else
2212         {
2213             if (log)
2214                 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
2215             exit_string.assign ("killed or interrupted while attaching.");
2216         }
2217     }
2218     else
2219     {
2220         // If we missed setting the exit status on the way out, do it here.
2221         // NB set exit status can be called multiple times, the first one sets the status.
2222         exit_string.assign("destroying when not connected to debugserver");
2223     }
2224 
2225     SetExitStatus(exit_status, exit_string.c_str());
2226 
2227     StopAsyncThread ();
2228     KillDebugserverProcess ();
2229     return error;
2230 }
2231 
2232 void
2233 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2234 {
2235     lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2236     const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2237     if (did_exec)
2238     {
2239         Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2240         if (log)
2241             log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2242 
2243         m_thread_list_real.Clear();
2244         m_thread_list.Clear();
2245         BuildDynamicRegisterInfo (true);
2246         m_gdb_comm.ResetDiscoverableSettings();
2247     }
2248     m_last_stop_packet = response;
2249 }
2250 
2251 
2252 //------------------------------------------------------------------
2253 // Process Queries
2254 //------------------------------------------------------------------
2255 
2256 bool
2257 ProcessGDBRemote::IsAlive ()
2258 {
2259     return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2260 }
2261 
2262 addr_t
2263 ProcessGDBRemote::GetImageInfoAddress()
2264 {
2265     return m_gdb_comm.GetShlibInfoAddr();
2266 }
2267 
2268 //------------------------------------------------------------------
2269 // Process Memory
2270 //------------------------------------------------------------------
2271 size_t
2272 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2273 {
2274     GetMaxMemorySize ();
2275     if (size > m_max_memory_size)
2276     {
2277         // Keep memory read sizes down to a sane limit. This function will be
2278         // called multiple times in order to complete the task by
2279         // lldb_private::Process so it is ok to do this.
2280         size = m_max_memory_size;
2281     }
2282 
2283     char packet[64];
2284     int packet_len;
2285     bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2286     if (binary_memory_read)
2287     {
2288         packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2289     }
2290     else
2291     {
2292         packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2293     }
2294     assert (packet_len + 1 < (int)sizeof(packet));
2295     StringExtractorGDBRemote response;
2296     if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
2297     {
2298         if (response.IsNormalResponse())
2299         {
2300             error.Clear();
2301             if (binary_memory_read)
2302             {
2303                 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2304                 // 0x7d character escaping that was present in the packet
2305 
2306                 size_t data_received_size = response.GetBytesLeft();
2307                 if (data_received_size > size)
2308                 {
2309                     // Don't write past the end of BUF if the remote debug server gave us too
2310                     // much data for some reason.
2311                     data_received_size = size;
2312                 }
2313                 memcpy (buf, response.GetStringRef().data(), data_received_size);
2314                 return data_received_size;
2315             }
2316             else
2317             {
2318                 return response.GetHexBytes(buf, size, '\xdd');
2319             }
2320         }
2321         else if (response.IsErrorResponse())
2322             error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2323         else if (response.IsUnsupportedResponse())
2324             error.SetErrorStringWithFormat("GDB server does not support reading memory");
2325         else
2326             error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2327     }
2328     else
2329     {
2330         error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2331     }
2332     return 0;
2333 }
2334 
2335 size_t
2336 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2337 {
2338     GetMaxMemorySize ();
2339     if (size > m_max_memory_size)
2340     {
2341         // Keep memory read sizes down to a sane limit. This function will be
2342         // called multiple times in order to complete the task by
2343         // lldb_private::Process so it is ok to do this.
2344         size = m_max_memory_size;
2345     }
2346 
2347     StreamString packet;
2348     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2349     packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2350     StringExtractorGDBRemote response;
2351     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
2352     {
2353         if (response.IsOKResponse())
2354         {
2355             error.Clear();
2356             return size;
2357         }
2358         else if (response.IsErrorResponse())
2359             error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2360         else if (response.IsUnsupportedResponse())
2361             error.SetErrorStringWithFormat("GDB server does not support writing memory");
2362         else
2363             error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2364     }
2365     else
2366     {
2367         error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2368     }
2369     return 0;
2370 }
2371 
2372 lldb::addr_t
2373 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2374 {
2375     lldb_private::Log *log (lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
2376     addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2377 
2378     LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2379     switch (supported)
2380     {
2381         case eLazyBoolCalculate:
2382         case eLazyBoolYes:
2383             allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2384             if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2385                 return allocated_addr;
2386 
2387         case eLazyBoolNo:
2388             // Call mmap() to create memory in the inferior..
2389             unsigned prot = 0;
2390             if (permissions & lldb::ePermissionsReadable)
2391                 prot |= eMmapProtRead;
2392             if (permissions & lldb::ePermissionsWritable)
2393                 prot |= eMmapProtWrite;
2394             if (permissions & lldb::ePermissionsExecutable)
2395                 prot |= eMmapProtExec;
2396 
2397             if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2398                                  eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2399                 m_addr_to_mmap_size[allocated_addr] = size;
2400             else
2401             {
2402                 allocated_addr = LLDB_INVALID_ADDRESS;
2403                 if (log)
2404                     log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2405             }
2406             break;
2407     }
2408 
2409     if (allocated_addr == LLDB_INVALID_ADDRESS)
2410         error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
2411     else
2412         error.Clear();
2413     return allocated_addr;
2414 }
2415 
2416 Error
2417 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2418                                        MemoryRegionInfo &region_info)
2419 {
2420 
2421     Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2422     return error;
2423 }
2424 
2425 Error
2426 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2427 {
2428 
2429     Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2430     return error;
2431 }
2432 
2433 Error
2434 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2435 {
2436     Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2437     return error;
2438 }
2439 
2440 Error
2441 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2442 {
2443     Error error;
2444     LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2445 
2446     switch (supported)
2447     {
2448         case eLazyBoolCalculate:
2449             // We should never be deallocating memory without allocating memory
2450             // first so we should never get eLazyBoolCalculate
2451             error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2452             break;
2453 
2454         case eLazyBoolYes:
2455             if (!m_gdb_comm.DeallocateMemory (addr))
2456                 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2457             break;
2458 
2459         case eLazyBoolNo:
2460             // Call munmap() to deallocate memory in the inferior..
2461             {
2462                 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2463                 if (pos != m_addr_to_mmap_size.end() &&
2464                     InferiorCallMunmap(this, addr, pos->second))
2465                     m_addr_to_mmap_size.erase (pos);
2466                 else
2467                     error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2468             }
2469             break;
2470     }
2471 
2472     return error;
2473 }
2474 
2475 
2476 //------------------------------------------------------------------
2477 // Process STDIO
2478 //------------------------------------------------------------------
2479 size_t
2480 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2481 {
2482     if (m_stdio_communication.IsConnected())
2483     {
2484         ConnectionStatus status;
2485         m_stdio_communication.Write(src, src_len, status, NULL);
2486     }
2487     else if (m_stdin_forward)
2488     {
2489         m_gdb_comm.SendStdinNotification(src, src_len);
2490     }
2491     return 0;
2492 }
2493 
2494 Error
2495 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
2496 {
2497     Error error;
2498     assert(bp_site != NULL);
2499 
2500     // Get logging info
2501     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2502     user_id_t site_id = bp_site->GetID();
2503 
2504     // Get the breakpoint address
2505     const addr_t addr = bp_site->GetLoadAddress();
2506 
2507     // Log that a breakpoint was requested
2508     if (log)
2509         log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2510 
2511     // Breakpoint already exists and is enabled
2512     if (bp_site->IsEnabled())
2513     {
2514         if (log)
2515             log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
2516         return error;
2517     }
2518 
2519     // Get the software breakpoint trap opcode size
2520     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2521 
2522     // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2523     // is supported by the remote stub. These are set to true by default, and later set to false
2524     // only after we receive an unimplemented response when sending a breakpoint packet. This means
2525     // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2526     // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2527     // indicates if the user specifically asked for hardware breakpoints.  If true then we will
2528     // skip over software breakpoints.
2529     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2530     {
2531         // Try to send off a software breakpoint packet ($Z0)
2532         if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2533         {
2534             // The breakpoint was placed successfully
2535             bp_site->SetEnabled(true);
2536             bp_site->SetType(BreakpointSite::eExternal);
2537             return error;
2538         }
2539 
2540         // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2541         // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2542         // or if we have learned that this breakpoint type is unsupported. To do this, we
2543         // must test the support boolean for this breakpoint type to see if it now indicates that
2544         // this breakpoint type is unsupported.  If they are still supported then we should return
2545         // with the error code.  If they are now unsupported, then we would like to fall through
2546         // and try another form of breakpoint.
2547         if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2548             return error;
2549 
2550         // We reach here when software breakpoints have been found to be unsupported. For future
2551         // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2552         // known not to be supported.
2553         if (log)
2554             log->Printf("Software breakpoints are unsupported");
2555 
2556         // So we will fall through and try a hardware breakpoint
2557     }
2558 
2559     // The process of setting a hardware breakpoint is much the same as above.  We check the
2560     // supported boolean for this breakpoint type, and if it is thought to be supported then we
2561     // will try to set this breakpoint with a hardware breakpoint.
2562     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2563     {
2564         // Try to send off a hardware breakpoint packet ($Z1)
2565         if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
2566         {
2567             // The breakpoint was placed successfully
2568             bp_site->SetEnabled(true);
2569             bp_site->SetType(BreakpointSite::eHardware);
2570             return error;
2571         }
2572 
2573         // Check if the error was something other then an unsupported breakpoint type
2574         if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2575         {
2576             // Unable to set this hardware breakpoint
2577             error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2578             return error;
2579         }
2580 
2581         // We will reach here when the stub gives an unsupported response to a hardware breakpoint
2582         if (log)
2583             log->Printf("Hardware breakpoints are unsupported");
2584 
2585         // Finally we will falling through to a #trap style breakpoint
2586     }
2587 
2588     // Don't fall through when hardware breakpoints were specifically requested
2589     if (bp_site->HardwareRequired())
2590     {
2591         error.SetErrorString("hardware breakpoints are not supported");
2592         return error;
2593     }
2594 
2595     // As a last resort we want to place a manual breakpoint. An instruction
2596     // is placed into the process memory using memory write packets.
2597     return EnableSoftwareBreakpoint(bp_site);
2598 }
2599 
2600 Error
2601 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
2602 {
2603     Error error;
2604     assert (bp_site != NULL);
2605     addr_t addr = bp_site->GetLoadAddress();
2606     user_id_t site_id = bp_site->GetID();
2607     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2608     if (log)
2609         log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
2610 
2611     if (bp_site->IsEnabled())
2612     {
2613         const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2614 
2615         BreakpointSite::Type bp_type = bp_site->GetType();
2616         switch (bp_type)
2617         {
2618         case BreakpointSite::eSoftware:
2619             error = DisableSoftwareBreakpoint (bp_site);
2620             break;
2621 
2622         case BreakpointSite::eHardware:
2623             if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
2624                 error.SetErrorToGenericError();
2625             break;
2626 
2627         case BreakpointSite::eExternal:
2628             {
2629                 GDBStoppointType stoppoint_type;
2630                 if (bp_site->IsHardware())
2631                     stoppoint_type = eBreakpointHardware;
2632                 else
2633                     stoppoint_type = eBreakpointSoftware;
2634 
2635                 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
2636                 error.SetErrorToGenericError();
2637             }
2638             break;
2639         }
2640         if (error.Success())
2641             bp_site->SetEnabled(false);
2642     }
2643     else
2644     {
2645         if (log)
2646             log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
2647         return error;
2648     }
2649 
2650     if (error.Success())
2651         error.SetErrorToGenericError();
2652     return error;
2653 }
2654 
2655 // Pre-requisite: wp != NULL.
2656 static GDBStoppointType
2657 GetGDBStoppointType (Watchpoint *wp)
2658 {
2659     assert(wp);
2660     bool watch_read = wp->WatchpointRead();
2661     bool watch_write = wp->WatchpointWrite();
2662 
2663     // watch_read and watch_write cannot both be false.
2664     assert(watch_read || watch_write);
2665     if (watch_read && watch_write)
2666         return eWatchpointReadWrite;
2667     else if (watch_read)
2668         return eWatchpointRead;
2669     else // Must be watch_write, then.
2670         return eWatchpointWrite;
2671 }
2672 
2673 Error
2674 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
2675 {
2676     Error error;
2677     if (wp)
2678     {
2679         user_id_t watchID = wp->GetID();
2680         addr_t addr = wp->GetLoadAddress();
2681         Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2682         if (log)
2683             log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
2684         if (wp->IsEnabled())
2685         {
2686             if (log)
2687                 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
2688             return error;
2689         }
2690 
2691         GDBStoppointType type = GetGDBStoppointType(wp);
2692         // Pass down an appropriate z/Z packet...
2693         if (m_gdb_comm.SupportsGDBStoppointPacket (type))
2694         {
2695             if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2696             {
2697                 wp->SetEnabled(true, notify);
2698                 return error;
2699             }
2700             else
2701                 error.SetErrorString("sending gdb watchpoint packet failed");
2702         }
2703         else
2704             error.SetErrorString("watchpoints not supported");
2705     }
2706     else
2707     {
2708         error.SetErrorString("Watchpoint argument was NULL.");
2709     }
2710     if (error.Success())
2711         error.SetErrorToGenericError();
2712     return error;
2713 }
2714 
2715 Error
2716 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
2717 {
2718     Error error;
2719     if (wp)
2720     {
2721         user_id_t watchID = wp->GetID();
2722 
2723         Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2724 
2725         addr_t addr = wp->GetLoadAddress();
2726 
2727         if (log)
2728             log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
2729 
2730         if (!wp->IsEnabled())
2731         {
2732             if (log)
2733                 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
2734             // See also 'class WatchpointSentry' within StopInfo.cpp.
2735             // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2736             // the watchpoint object to intelligently process this action.
2737             wp->SetEnabled(false, notify);
2738             return error;
2739         }
2740 
2741         if (wp->IsHardware())
2742         {
2743             GDBStoppointType type = GetGDBStoppointType(wp);
2744             // Pass down an appropriate z/Z packet...
2745             if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2746             {
2747                 wp->SetEnabled(false, notify);
2748                 return error;
2749             }
2750             else
2751                 error.SetErrorString("sending gdb watchpoint packet failed");
2752         }
2753         // TODO: clear software watchpoints if we implement them
2754     }
2755     else
2756     {
2757         error.SetErrorString("Watchpoint argument was NULL.");
2758     }
2759     if (error.Success())
2760         error.SetErrorToGenericError();
2761     return error;
2762 }
2763 
2764 void
2765 ProcessGDBRemote::Clear()
2766 {
2767     m_flags = 0;
2768     m_thread_list_real.Clear();
2769     m_thread_list.Clear();
2770 }
2771 
2772 Error
2773 ProcessGDBRemote::DoSignal (int signo)
2774 {
2775     Error error;
2776     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2777     if (log)
2778         log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2779 
2780     if (!m_gdb_comm.SendAsyncSignal (signo))
2781         error.SetErrorStringWithFormat("failed to send signal %i", signo);
2782     return error;
2783 }
2784 
2785 Error
2786 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
2787 {
2788     Error error;
2789     if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2790     {
2791         // If we locate debugserver, keep that located version around
2792         static FileSpec g_debugserver_file_spec;
2793 
2794         ProcessLaunchInfo debugserver_launch_info;
2795         // Make debugserver run in its own session so signals generated by
2796         // special terminal key sequences (^C) don't affect debugserver.
2797         debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
2798 
2799         debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2800         debugserver_launch_info.SetUserID(process_info.GetUserID());
2801 
2802 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
2803         // On iOS, still do a local connection using a random port
2804         const char *hostname = "127.0.0.1";
2805         uint16_t port = get_random_port ();
2806 #else
2807         // Set hostname being NULL to do the reverse connect where debugserver
2808         // will bind to port zero and it will communicate back to us the port
2809         // that we will connect to
2810         const char *hostname = NULL;
2811         uint16_t port = 0;
2812 #endif
2813 
2814         error = m_gdb_comm.StartDebugserverProcess (hostname,
2815                                                     port,
2816                                                     debugserver_launch_info,
2817                                                     port);
2818 
2819         if (error.Success ())
2820             m_debugserver_pid = debugserver_launch_info.GetProcessID();
2821         else
2822             m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2823 
2824         if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2825             StartAsyncThread ();
2826 
2827         if (error.Fail())
2828         {
2829             Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2830 
2831             if (log)
2832                 log->Printf("failed to start debugserver process: %s", error.AsCString());
2833             return error;
2834         }
2835 
2836         if (m_gdb_comm.IsConnected())
2837         {
2838             // Finish the connection process by doing the handshake without connecting (send NULL URL)
2839             ConnectToDebugserver (NULL);
2840         }
2841         else
2842         {
2843             StreamString connect_url;
2844             connect_url.Printf("connect://%s:%u", hostname, port);
2845             error = ConnectToDebugserver (connect_url.GetString().c_str());
2846         }
2847 
2848     }
2849     return error;
2850 }
2851 
2852 bool
2853 ProcessGDBRemote::MonitorDebugserverProcess
2854 (
2855     void *callback_baton,
2856     lldb::pid_t debugserver_pid,
2857     bool exited,        // True if the process did exit
2858     int signo,          // Zero for no signal
2859     int exit_status     // Exit value of process if signal is zero
2860 )
2861 {
2862     // The baton is a "ProcessGDBRemote *". Now this class might be gone
2863     // and might not exist anymore, so we need to carefully try to get the
2864     // target for this process first since we have a race condition when
2865     // we are done running between getting the notice that the inferior
2866     // process has died and the debugserver that was debugging this process.
2867     // In our test suite, we are also continually running process after
2868     // process, so we must be very careful to make sure:
2869     // 1 - process object hasn't been deleted already
2870     // 2 - that a new process object hasn't been recreated in its place
2871 
2872     // "debugserver_pid" argument passed in is the process ID for
2873     // debugserver that we are tracking...
2874     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2875 
2876     ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2877 
2878     // Get a shared pointer to the target that has a matching process pointer.
2879     // This target could be gone, or the target could already have a new process
2880     // object inside of it
2881     TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2882 
2883     if (log)
2884         log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2885 
2886     if (target_sp)
2887     {
2888         // We found a process in a target that matches, but another thread
2889         // might be in the process of launching a new process that will
2890         // soon replace it, so get a shared pointer to the process so we
2891         // can keep it alive.
2892         ProcessSP process_sp (target_sp->GetProcessSP());
2893         // Now we have a shared pointer to the process that can't go away on us
2894         // so we now make sure it was the same as the one passed in, and also make
2895         // sure that our previous "process *" didn't get deleted and have a new
2896         // "process *" created in its place with the same pointer. To verify this
2897         // we make sure the process has our debugserver process ID. If we pass all
2898         // of these tests, then we are sure that this process is the one we were
2899         // looking for.
2900         if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
2901         {
2902             // Sleep for a half a second to make sure our inferior process has
2903             // time to set its exit status before we set it incorrectly when
2904             // both the debugserver and the inferior process shut down.
2905             usleep (500000);
2906             // If our process hasn't yet exited, debugserver might have died.
2907             // If the process did exit, the we are reaping it.
2908             const StateType state = process->GetState();
2909 
2910             if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2911                 state != eStateInvalid &&
2912                 state != eStateUnloaded &&
2913                 state != eStateExited &&
2914                 state != eStateDetached)
2915             {
2916                 char error_str[1024];
2917                 if (signo)
2918                 {
2919                     const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2920                     if (signal_cstr)
2921                         ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2922                     else
2923                         ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2924                 }
2925                 else
2926                 {
2927                     ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2928                 }
2929 
2930                 process->SetExitStatus (-1, error_str);
2931             }
2932             // Debugserver has exited we need to let our ProcessGDBRemote
2933             // know that it no longer has a debugserver instance
2934             process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2935         }
2936     }
2937     return true;
2938 }
2939 
2940 void
2941 ProcessGDBRemote::KillDebugserverProcess ()
2942 {
2943     m_gdb_comm.Disconnect();
2944     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2945     {
2946         Host::Kill (m_debugserver_pid, SIGINT);
2947         m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2948     }
2949 }
2950 
2951 void
2952 ProcessGDBRemote::Initialize()
2953 {
2954     static bool g_initialized = false;
2955 
2956     if (g_initialized == false)
2957     {
2958         g_initialized = true;
2959         PluginManager::RegisterPlugin (GetPluginNameStatic(),
2960                                        GetPluginDescriptionStatic(),
2961                                        CreateInstance,
2962                                        DebuggerInitialize);
2963 
2964         Log::Callbacks log_callbacks = {
2965             ProcessGDBRemoteLog::DisableLog,
2966             ProcessGDBRemoteLog::EnableLog,
2967             ProcessGDBRemoteLog::ListLogCategories
2968         };
2969 
2970         Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2971     }
2972 }
2973 
2974 void
2975 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2976 {
2977     if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2978     {
2979         const bool is_global_setting = true;
2980         PluginManager::CreateSettingForProcessPlugin (debugger,
2981                                                       GetGlobalPluginProperties()->GetValueProperties(),
2982                                                       ConstString ("Properties for the gdb-remote process plug-in."),
2983                                                       is_global_setting);
2984     }
2985 }
2986 
2987 bool
2988 ProcessGDBRemote::StartAsyncThread ()
2989 {
2990     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2991 
2992     if (log)
2993         log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2994 
2995     Mutex::Locker start_locker(m_async_thread_state_mutex);
2996     if (!m_async_thread.IsJoinable())
2997     {
2998         // Create a thread that watches our internal state and controls which
2999         // events make it to clients (into the DCProcess event queue).
3000 
3001         m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
3002     }
3003     else if (log)
3004         log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
3005 
3006     return m_async_thread.IsJoinable();
3007 }
3008 
3009 void
3010 ProcessGDBRemote::StopAsyncThread ()
3011 {
3012     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3013 
3014     if (log)
3015         log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3016 
3017     Mutex::Locker start_locker(m_async_thread_state_mutex);
3018     if (m_async_thread.IsJoinable())
3019     {
3020         m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3021 
3022         //  This will shut down the async thread.
3023         m_gdb_comm.Disconnect();    // Disconnect from the debug server.
3024 
3025         // Stop the stdio thread
3026         m_async_thread.Join(nullptr);
3027     }
3028     else if (log)
3029         log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
3030 }
3031 
3032 
3033 thread_result_t
3034 ProcessGDBRemote::AsyncThread (void *arg)
3035 {
3036     ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3037 
3038     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3039     if (log)
3040         log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
3041 
3042     Listener listener ("ProcessGDBRemote::AsyncThread");
3043     EventSP event_sp;
3044     const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3045                                         eBroadcastBitAsyncThreadShouldExit;
3046 
3047     if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3048     {
3049         listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3050 
3051         bool done = false;
3052         while (!done)
3053         {
3054             if (log)
3055                 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3056             if (listener.WaitForEvent (NULL, event_sp))
3057             {
3058                 const uint32_t event_type = event_sp->GetType();
3059                 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
3060                 {
3061                     if (log)
3062                         log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3063 
3064                     switch (event_type)
3065                     {
3066                         case eBroadcastBitAsyncContinue:
3067                             {
3068                                 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3069 
3070                                 if (continue_packet)
3071                                 {
3072                                     const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3073                                     const size_t continue_cstr_len = continue_packet->GetByteSize ();
3074                                     if (log)
3075                                         log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3076 
3077                                     if (::strstr (continue_cstr, "vAttach") == NULL)
3078                                         process->SetPrivateState(eStateRunning);
3079                                     StringExtractorGDBRemote response;
3080                                     StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3081 
3082                                     // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3083                                     // The thread ID list might be contained within the "response", or the stop reply packet that
3084                                     // caused the stop. So clear it now before we give the stop reply packet to the process
3085                                     // using the process->SetLastStopPacket()...
3086                                     process->ClearThreadIDList ();
3087 
3088                                     switch (stop_state)
3089                                     {
3090                                     case eStateStopped:
3091                                     case eStateCrashed:
3092                                     case eStateSuspended:
3093                                         process->SetLastStopPacket (response);
3094                                         process->SetPrivateState (stop_state);
3095                                         break;
3096 
3097                                     case eStateExited:
3098                                     {
3099                                         process->SetLastStopPacket (response);
3100                                         process->ClearThreadIDList();
3101                                         response.SetFilePos(1);
3102 
3103                                         int exit_status = response.GetHexU8();
3104                                         const char *desc_cstr = NULL;
3105                                         StringExtractor extractor;
3106                                         std::string desc_string;
3107                                         if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3108                                         {
3109                                             std::string desc_token;
3110                                             while (response.GetNameColonValue (desc_token, desc_string))
3111                                             {
3112                                                 if (desc_token == "description")
3113                                                 {
3114                                                     extractor.GetStringRef().swap(desc_string);
3115                                                     extractor.SetFilePos(0);
3116                                                     extractor.GetHexByteString (desc_string);
3117                                                     desc_cstr = desc_string.c_str();
3118                                                 }
3119                                             }
3120                                         }
3121                                         process->SetExitStatus(exit_status, desc_cstr);
3122                                         done = true;
3123                                         break;
3124                                     }
3125                                     case eStateInvalid:
3126                                         process->SetExitStatus(-1, "lost connection");
3127                                         break;
3128 
3129                                     default:
3130                                         process->SetPrivateState (stop_state);
3131                                         break;
3132                                     }
3133                                 }
3134                             }
3135                             break;
3136 
3137                         case eBroadcastBitAsyncThreadShouldExit:
3138                             if (log)
3139                                 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3140                             done = true;
3141                             break;
3142 
3143                         default:
3144                             if (log)
3145                                 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3146                             done = true;
3147                             break;
3148                     }
3149                 }
3150                 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3151                 {
3152                     if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3153                     {
3154                         process->SetExitStatus (-1, "lost connection");
3155                         done = true;
3156                     }
3157                 }
3158             }
3159             else
3160             {
3161                 if (log)
3162                     log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3163                 done = true;
3164             }
3165         }
3166     }
3167 
3168     if (log)
3169         log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
3170 
3171     process->m_async_thread.Reset();
3172     return NULL;
3173 }
3174 
3175 //uint32_t
3176 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3177 //{
3178 //    // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3179 //    // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3180 //    if (m_local_debugserver)
3181 //    {
3182 //        return Host::ListProcessesMatchingName (name, matches, pids);
3183 //    }
3184 //    else
3185 //    {
3186 //        // FIXME: Implement talking to the remote debugserver.
3187 //        return 0;
3188 //    }
3189 //
3190 //}
3191 //
3192 bool
3193 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3194                              lldb_private::StoppointCallbackContext *context,
3195                              lldb::user_id_t break_id,
3196                              lldb::user_id_t break_loc_id)
3197 {
3198     // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3199     // run so I can stop it if that's what I want to do.
3200     Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3201     if (log)
3202         log->Printf("Hit New Thread Notification breakpoint.");
3203     return false;
3204 }
3205 
3206 
3207 bool
3208 ProcessGDBRemote::StartNoticingNewThreads()
3209 {
3210     Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3211     if (m_thread_create_bp_sp)
3212     {
3213         if (log && log->GetVerbose())
3214             log->Printf("Enabled noticing new thread breakpoint.");
3215         m_thread_create_bp_sp->SetEnabled(true);
3216     }
3217     else
3218     {
3219         PlatformSP platform_sp (m_target.GetPlatform());
3220         if (platform_sp)
3221         {
3222             m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3223             if (m_thread_create_bp_sp)
3224             {
3225                 if (log && log->GetVerbose())
3226                     log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3227                 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3228             }
3229             else
3230             {
3231                 if (log)
3232                     log->Printf("Failed to create new thread notification breakpoint.");
3233             }
3234         }
3235     }
3236     return m_thread_create_bp_sp.get() != NULL;
3237 }
3238 
3239 bool
3240 ProcessGDBRemote::StopNoticingNewThreads()
3241 {
3242     Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3243     if (log && log->GetVerbose())
3244         log->Printf ("Disabling new thread notification breakpoint.");
3245 
3246     if (m_thread_create_bp_sp)
3247         m_thread_create_bp_sp->SetEnabled(false);
3248 
3249     return true;
3250 }
3251 
3252 lldb_private::DynamicLoader *
3253 ProcessGDBRemote::GetDynamicLoader ()
3254 {
3255     if (m_dyld_ap.get() == NULL)
3256         m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3257     return m_dyld_ap.get();
3258 }
3259 
3260 Error
3261 ProcessGDBRemote::SendEventData(const char *data)
3262 {
3263     int return_value;
3264     bool was_supported;
3265 
3266     Error error;
3267 
3268     return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3269     if (return_value != 0)
3270     {
3271         if (!was_supported)
3272             error.SetErrorString("Sending events is not supported for this process.");
3273         else
3274             error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3275     }
3276     return error;
3277 }
3278 
3279 const DataBufferSP
3280 ProcessGDBRemote::GetAuxvData()
3281 {
3282     DataBufferSP buf;
3283     if (m_gdb_comm.GetQXferAuxvReadSupported())
3284     {
3285         std::string response_string;
3286         if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3287             buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3288     }
3289     return buf;
3290 }
3291 
3292 StructuredData::ObjectSP
3293 ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3294 {
3295     StructuredData::ObjectSP object_sp;
3296 
3297     if (m_gdb_comm.GetThreadExtendedInfoSupported())
3298     {
3299         StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3300         SystemRuntime *runtime = GetSystemRuntime();
3301         if (runtime)
3302         {
3303             runtime->AddThreadExtendedInfoPacketHints (args_dict);
3304         }
3305         args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3306 
3307         StreamString packet;
3308         packet << "jThreadExtendedInfo:";
3309         args_dict->Dump (packet);
3310 
3311         // FIXME the final character of a JSON dictionary, '}', is the escape
3312         // character in gdb-remote binary mode.  lldb currently doesn't escape
3313         // these characters in its packet output -- so we add the quoted version
3314         // of the } character here manually in case we talk to a debugserver which
3315         // un-escapes the characters at packet read time.
3316         packet << (char) (0x7d ^ 0x20);
3317 
3318         StringExtractorGDBRemote response;
3319         if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3320         {
3321             StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3322             if (response_type == StringExtractorGDBRemote::eResponse)
3323             {
3324                 if (!response.Empty())
3325                 {
3326                     // The packet has already had the 0x7d xor quoting stripped out at the
3327                     // GDBRemoteCommunication packet receive level.
3328                     object_sp = StructuredData::ParseJSON (response.GetStringRef());
3329                 }
3330             }
3331         }
3332     }
3333     return object_sp;
3334 }
3335 
3336 // Establish the largest memory read/write payloads we should use.
3337 // If the remote stub has a max packet size, stay under that size.
3338 //
3339 // If the remote stub's max packet size is crazy large, use a
3340 // reasonable largeish default.
3341 //
3342 // If the remote stub doesn't advertise a max packet size, use a
3343 // conservative default.
3344 
3345 void
3346 ProcessGDBRemote::GetMaxMemorySize()
3347 {
3348     const uint64_t reasonable_largeish_default = 128 * 1024;
3349     const uint64_t conservative_default = 512;
3350 
3351     if (m_max_memory_size == 0)
3352     {
3353         uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3354         if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3355         {
3356             // Save the stub's claimed maximum packet size
3357             m_remote_stub_max_memory_size = stub_max_size;
3358 
3359             // Even if the stub says it can support ginormous packets,
3360             // don't exceed our reasonable largeish default packet size.
3361             if (stub_max_size > reasonable_largeish_default)
3362             {
3363                 stub_max_size = reasonable_largeish_default;
3364             }
3365 
3366             m_max_memory_size = stub_max_size;
3367         }
3368         else
3369         {
3370             m_max_memory_size = conservative_default;
3371         }
3372     }
3373 }
3374 
3375 void
3376 ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3377 {
3378     if (user_specified_max != 0)
3379     {
3380         GetMaxMemorySize ();
3381 
3382         if (m_remote_stub_max_memory_size != 0)
3383         {
3384             if (m_remote_stub_max_memory_size < user_specified_max)
3385             {
3386                 m_max_memory_size = m_remote_stub_max_memory_size;   // user specified a packet size too big, go as big
3387                                                                      // as the remote stub says we can go.
3388             }
3389             else
3390             {
3391                 m_max_memory_size = user_specified_max;             // user's packet size is good
3392             }
3393         }
3394         else
3395         {
3396             m_max_memory_size = user_specified_max;                 // user's packet size is probably fine
3397         }
3398     }
3399 }
3400 
3401 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
3402 {
3403 private:
3404 
3405 public:
3406     CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
3407     CommandObjectParsed (interpreter,
3408                          "process plugin packet history",
3409                          "Dumps the packet history buffer. ",
3410                          NULL)
3411     {
3412     }
3413 
3414     ~CommandObjectProcessGDBRemotePacketHistory ()
3415     {
3416     }
3417 
3418     bool
3419     DoExecute (Args& command, CommandReturnObject &result)
3420     {
3421         const size_t argc = command.GetArgumentCount();
3422         if (argc == 0)
3423         {
3424             ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3425             if (process)
3426             {
3427                 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3428                 result.SetStatus (eReturnStatusSuccessFinishResult);
3429                 return true;
3430             }
3431         }
3432         else
3433         {
3434             result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3435         }
3436         result.SetStatus (eReturnStatusFailed);
3437         return false;
3438     }
3439 };
3440 
3441 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
3442 {
3443 private:
3444 
3445 public:
3446     CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
3447     CommandObjectParsed (interpreter,
3448                          "process plugin packet xfer-size",
3449                          "Maximum size that lldb will try to read/write one one chunk.",
3450                          NULL)
3451     {
3452     }
3453 
3454     ~CommandObjectProcessGDBRemotePacketXferSize ()
3455     {
3456     }
3457 
3458     bool
3459     DoExecute (Args& command, CommandReturnObject &result)
3460     {
3461         const size_t argc = command.GetArgumentCount();
3462         if (argc == 0)
3463         {
3464             result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
3465             result.SetStatus (eReturnStatusFailed);
3466             return false;
3467         }
3468 
3469         ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3470         if (process)
3471         {
3472             const char *packet_size = command.GetArgumentAtIndex(0);
3473             errno = 0;
3474             uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
3475             if (errno == 0 && user_specified_max != 0)
3476             {
3477                 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
3478                 result.SetStatus (eReturnStatusSuccessFinishResult);
3479                 return true;
3480             }
3481         }
3482         result.SetStatus (eReturnStatusFailed);
3483         return false;
3484     }
3485 };
3486 
3487 
3488 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3489 {
3490 private:
3491 
3492 public:
3493     CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3494         CommandObjectParsed (interpreter,
3495                              "process plugin packet send",
3496                              "Send a custom packet through the GDB remote protocol and print the answer. "
3497                              "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3498                              NULL)
3499     {
3500     }
3501 
3502     ~CommandObjectProcessGDBRemotePacketSend ()
3503     {
3504     }
3505 
3506     bool
3507     DoExecute (Args& command, CommandReturnObject &result)
3508     {
3509         const size_t argc = command.GetArgumentCount();
3510         if (argc == 0)
3511         {
3512             result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3513             result.SetStatus (eReturnStatusFailed);
3514             return false;
3515         }
3516 
3517         ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3518         if (process)
3519         {
3520             for (size_t i=0; i<argc; ++ i)
3521             {
3522                 const char *packet_cstr = command.GetArgumentAtIndex(0);
3523                 bool send_async = true;
3524                 StringExtractorGDBRemote response;
3525                 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3526                 result.SetStatus (eReturnStatusSuccessFinishResult);
3527                 Stream &output_strm = result.GetOutputStream();
3528                 output_strm.Printf ("  packet: %s\n", packet_cstr);
3529                 std::string &response_str = response.GetStringRef();
3530 
3531                 if (strstr(packet_cstr, "qGetProfileData") != NULL)
3532                 {
3533                     response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3534                 }
3535 
3536                 if (response_str.empty())
3537                     output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3538                 else
3539                     output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3540             }
3541         }
3542         return true;
3543     }
3544 };
3545 
3546 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3547 {
3548 private:
3549 
3550 public:
3551     CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3552         CommandObjectRaw (interpreter,
3553                          "process plugin packet monitor",
3554                          "Send a qRcmd packet through the GDB remote protocol and print the response."
3555                          "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
3556                          NULL)
3557     {
3558     }
3559 
3560     ~CommandObjectProcessGDBRemotePacketMonitor ()
3561     {
3562     }
3563 
3564     bool
3565     DoExecute (const char *command, CommandReturnObject &result)
3566     {
3567         if (command == NULL || command[0] == '\0')
3568         {
3569             result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3570             result.SetStatus (eReturnStatusFailed);
3571             return false;
3572         }
3573 
3574         ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3575         if (process)
3576         {
3577             StreamString packet;
3578             packet.PutCString("qRcmd,");
3579             packet.PutBytesAsRawHex8(command, strlen(command));
3580             const char *packet_cstr = packet.GetString().c_str();
3581 
3582             bool send_async = true;
3583             StringExtractorGDBRemote response;
3584             process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3585             result.SetStatus (eReturnStatusSuccessFinishResult);
3586             Stream &output_strm = result.GetOutputStream();
3587             output_strm.Printf ("  packet: %s\n", packet_cstr);
3588             const std::string &response_str = response.GetStringRef();
3589 
3590             if (response_str.empty())
3591                 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3592             else
3593                 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3594         }
3595         return true;
3596     }
3597 };
3598 
3599 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3600 {
3601 private:
3602 
3603 public:
3604     CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3605         CommandObjectMultiword (interpreter,
3606                                 "process plugin packet",
3607                                 "Commands that deal with GDB remote packets.",
3608                                 NULL)
3609     {
3610         LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3611         LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3612         LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
3613         LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
3614     }
3615 
3616     ~CommandObjectProcessGDBRemotePacket ()
3617     {
3618     }
3619 };
3620 
3621 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3622 {
3623 public:
3624     CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3625         CommandObjectMultiword (interpreter,
3626                                 "process plugin",
3627                                 "A set of commands for operating on a ProcessGDBRemote process.",
3628                                 "process plugin <subcommand> [<subcommand-options>]")
3629     {
3630         LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket    (interpreter)));
3631     }
3632 
3633     ~CommandObjectMultiwordProcessGDBRemote ()
3634     {
3635     }
3636 };
3637 
3638 CommandObject *
3639 ProcessGDBRemote::GetPluginCommandObject()
3640 {
3641     if (!m_command_sp)
3642         m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3643     return m_command_sp.get();
3644 }
3645