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