1254721Semaste//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2254721Semaste//
3254721Semaste//                     The LLVM Compiler Infrastructure
4254721Semaste//
5254721Semaste// This file is distributed under the University of Illinois Open Source
6254721Semaste// License. See LICENSE.TXT for details.
7254721Semaste//
8254721Semaste//===----------------------------------------------------------------------===//
9254721Semaste
10254721Semaste#include "lldb/lldb-python.h"
11263363Semaste#include "lldb/Host/Config.h"
12254721Semaste
13254721Semaste// C Includes
14254721Semaste#include <errno.h>
15263363Semaste#include <stdlib.h>
16263363Semaste#ifndef LLDB_DISABLE_POSIX
17254721Semaste#include <spawn.h>
18254721Semaste#include <netinet/in.h>
19254721Semaste#include <sys/mman.h>       // for mmap
20263363Semaste#endif
21254721Semaste#include <sys/stat.h>
22254721Semaste#include <sys/types.h>
23254721Semaste#include <time.h>
24254721Semaste
25254721Semaste// C++ Includes
26254721Semaste#include <algorithm>
27254721Semaste#include <map>
28254721Semaste
29254721Semaste// Other libraries and framework includes
30254721Semaste
31254721Semaste#include "lldb/Breakpoint/Watchpoint.h"
32254721Semaste#include "lldb/Interpreter/Args.h"
33254721Semaste#include "lldb/Core/ArchSpec.h"
34254721Semaste#include "lldb/Core/Debugger.h"
35254721Semaste#include "lldb/Core/ConnectionFileDescriptor.h"
36254721Semaste#include "lldb/Host/FileSpec.h"
37254721Semaste#include "lldb/Core/Module.h"
38254721Semaste#include "lldb/Core/ModuleSpec.h"
39254721Semaste#include "lldb/Core/PluginManager.h"
40254721Semaste#include "lldb/Core/State.h"
41254721Semaste#include "lldb/Core/StreamFile.h"
42254721Semaste#include "lldb/Core/StreamString.h"
43254721Semaste#include "lldb/Core/Timer.h"
44254721Semaste#include "lldb/Core/Value.h"
45254721Semaste#include "lldb/Host/Symbols.h"
46254721Semaste#include "lldb/Host/TimeValue.h"
47254721Semaste#include "lldb/Interpreter/CommandInterpreter.h"
48254721Semaste#include "lldb/Interpreter/CommandObject.h"
49254721Semaste#include "lldb/Interpreter/CommandObjectMultiword.h"
50254721Semaste#include "lldb/Interpreter/CommandReturnObject.h"
51263363Semaste#ifndef LLDB_DISABLE_PYTHON
52263363Semaste#include "lldb/Interpreter/PythonDataObjects.h"
53263363Semaste#endif
54254721Semaste#include "lldb/Symbol/ObjectFile.h"
55254721Semaste#include "lldb/Target/DynamicLoader.h"
56254721Semaste#include "lldb/Target/Target.h"
57254721Semaste#include "lldb/Target/TargetList.h"
58254721Semaste#include "lldb/Target/ThreadPlanCallFunction.h"
59254721Semaste#include "lldb/Utility/PseudoTerminal.h"
60254721Semaste
61254721Semaste// Project includes
62254721Semaste#include "lldb/Host/Host.h"
63254721Semaste#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
64254721Semaste#include "Plugins/Process/Utility/StopInfoMachException.h"
65254721Semaste#include "Utility/StringExtractorGDBRemote.h"
66254721Semaste#include "GDBRemoteRegisterContext.h"
67254721Semaste#include "ProcessGDBRemote.h"
68254721Semaste#include "ProcessGDBRemoteLog.h"
69254721Semaste#include "ThreadGDBRemote.h"
70254721Semaste
71254721Semaste
72254721Semastenamespace lldb
73254721Semaste{
74254721Semaste    // Provide a function that can easily dump the packet history if we know a
75254721Semaste    // ProcessGDBRemote * value (which we can get from logs or from debugging).
76254721Semaste    // We need the function in the lldb namespace so it makes it into the final
77254721Semaste    // executable since the LLDB shared library only exports stuff in the lldb
78254721Semaste    // namespace. This allows you to attach with a debugger and call this
79254721Semaste    // function and get the packet history dumped to a file.
80254721Semaste    void
81254721Semaste    DumpProcessGDBRemotePacketHistory (void *p, const char *path)
82254721Semaste    {
83254721Semaste        lldb_private::StreamFile strm;
84254721Semaste        lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
85254721Semaste        if (error.Success())
86254721Semaste            ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
87254721Semaste    }
88254721Semaste}
89254721Semaste
90254721Semaste#define DEBUGSERVER_BASENAME    "debugserver"
91254721Semasteusing namespace lldb;
92254721Semasteusing namespace lldb_private;
93254721Semaste
94254721Semaste
95254721Semastenamespace {
96269024Semaste
97254721Semaste    static PropertyDefinition
98254721Semaste    g_properties[] =
99254721Semaste    {
100254721Semaste        { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
101263363Semaste        { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
102254721Semaste        {  NULL            , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL  }
103254721Semaste    };
104254721Semaste
105254721Semaste    enum
106254721Semaste    {
107263363Semaste        ePropertyPacketTimeout,
108263363Semaste        ePropertyTargetDefinitionFile
109254721Semaste    };
110254721Semaste
111254721Semaste    class PluginProperties : public Properties
112254721Semaste    {
113254721Semaste    public:
114254721Semaste
115254721Semaste        static ConstString
116254721Semaste        GetSettingName ()
117254721Semaste        {
118254721Semaste            return ProcessGDBRemote::GetPluginNameStatic();
119254721Semaste        }
120254721Semaste
121254721Semaste        PluginProperties() :
122254721Semaste        Properties ()
123254721Semaste        {
124254721Semaste            m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
125254721Semaste            m_collection_sp->Initialize(g_properties);
126254721Semaste        }
127254721Semaste
128254721Semaste        virtual
129254721Semaste        ~PluginProperties()
130254721Semaste        {
131254721Semaste        }
132254721Semaste
133254721Semaste        uint64_t
134254721Semaste        GetPacketTimeout()
135254721Semaste        {
136254721Semaste            const uint32_t idx = ePropertyPacketTimeout;
137254721Semaste            return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
138254721Semaste        }
139263363Semaste
140263363Semaste        bool
141263363Semaste        SetPacketTimeout(uint64_t timeout)
142263363Semaste        {
143263363Semaste            const uint32_t idx = ePropertyPacketTimeout;
144263363Semaste            return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
145263363Semaste        }
146263363Semaste
147263363Semaste        FileSpec
148263363Semaste        GetTargetDefinitionFile () const
149263363Semaste        {
150263363Semaste            const uint32_t idx = ePropertyTargetDefinitionFile;
151263363Semaste            return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
152263363Semaste        }
153254721Semaste    };
154254721Semaste
155254721Semaste    typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
156254721Semaste
157254721Semaste    static const ProcessKDPPropertiesSP &
158254721Semaste    GetGlobalPluginProperties()
159254721Semaste    {
160254721Semaste        static ProcessKDPPropertiesSP g_settings_sp;
161254721Semaste        if (!g_settings_sp)
162254721Semaste            g_settings_sp.reset (new PluginProperties ());
163254721Semaste        return g_settings_sp;
164254721Semaste    }
165254721Semaste
166254721Semaste} // anonymous namespace end
167254721Semaste
168254721Semastestatic bool rand_initialized = false;
169254721Semaste
170254721Semaste// TODO Randomly assigning a port is unsafe.  We should get an unused
171254721Semaste// ephemeral port from the kernel and make sure we reserve it before passing
172254721Semaste// it to debugserver.
173254721Semaste
174254721Semaste#if defined (__APPLE__)
175254721Semaste#define LOW_PORT    (IPPORT_RESERVED)
176254721Semaste#define HIGH_PORT   (IPPORT_HIFIRSTAUTO)
177254721Semaste#else
178254721Semaste#define LOW_PORT    (1024u)
179254721Semaste#define HIGH_PORT   (49151u)
180254721Semaste#endif
181254721Semaste
182254721Semastestatic inline uint16_t
183254721Semasteget_random_port ()
184254721Semaste{
185254721Semaste    if (!rand_initialized)
186254721Semaste    {
187254721Semaste        time_t seed = time(NULL);
188269024Semaste
189254721Semaste        rand_initialized = true;
190254721Semaste        srand(seed);
191254721Semaste    }
192254721Semaste    return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
193254721Semaste}
194254721Semaste
195254721Semaste
196254721Semastelldb_private::ConstString
197254721SemasteProcessGDBRemote::GetPluginNameStatic()
198254721Semaste{
199254721Semaste    static ConstString g_name("gdb-remote");
200254721Semaste    return g_name;
201254721Semaste}
202254721Semaste
203254721Semasteconst char *
204254721SemasteProcessGDBRemote::GetPluginDescriptionStatic()
205254721Semaste{
206254721Semaste    return "GDB Remote protocol based debugging plug-in.";
207254721Semaste}
208254721Semaste
209254721Semastevoid
210254721SemasteProcessGDBRemote::Terminate()
211254721Semaste{
212254721Semaste    PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
213254721Semaste}
214254721Semaste
215254721Semaste
216254721Semastelldb::ProcessSP
217254721SemasteProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
218254721Semaste{
219254721Semaste    lldb::ProcessSP process_sp;
220254721Semaste    if (crash_file_path == NULL)
221254721Semaste        process_sp.reset (new ProcessGDBRemote (target, listener));
222254721Semaste    return process_sp;
223254721Semaste}
224254721Semaste
225254721Semastebool
226254721SemasteProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
227254721Semaste{
228254721Semaste    if (plugin_specified_by_name)
229254721Semaste        return true;
230254721Semaste
231254721Semaste    // For now we are just making sure the file exists for a given module
232254721Semaste    Module *exe_module = target.GetExecutableModulePointer();
233254721Semaste    if (exe_module)
234254721Semaste    {
235254721Semaste        ObjectFile *exe_objfile = exe_module->GetObjectFile();
236254721Semaste        // We can't debug core files...
237254721Semaste        switch (exe_objfile->GetType())
238254721Semaste        {
239254721Semaste            case ObjectFile::eTypeInvalid:
240254721Semaste            case ObjectFile::eTypeCoreFile:
241254721Semaste            case ObjectFile::eTypeDebugInfo:
242254721Semaste            case ObjectFile::eTypeObjectFile:
243254721Semaste            case ObjectFile::eTypeSharedLibrary:
244254721Semaste            case ObjectFile::eTypeStubLibrary:
245254721Semaste                return false;
246254721Semaste            case ObjectFile::eTypeExecutable:
247254721Semaste            case ObjectFile::eTypeDynamicLinker:
248254721Semaste            case ObjectFile::eTypeUnknown:
249254721Semaste                break;
250254721Semaste        }
251254721Semaste        return exe_module->GetFileSpec().Exists();
252254721Semaste    }
253254721Semaste    // However, if there is no executable module, we return true since we might be preparing to attach.
254254721Semaste    return true;
255254721Semaste}
256254721Semaste
257254721Semaste//----------------------------------------------------------------------
258254721Semaste// ProcessGDBRemote constructor
259254721Semaste//----------------------------------------------------------------------
260254721SemasteProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
261254721Semaste    Process (target, listener),
262254721Semaste    m_flags (0),
263254721Semaste    m_gdb_comm(false),
264254721Semaste    m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
265254721Semaste    m_last_stop_packet (),
266254721Semaste    m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
267254721Semaste    m_register_info (),
268254721Semaste    m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
269254721Semaste    m_async_thread (LLDB_INVALID_HOST_THREAD),
270254721Semaste    m_async_thread_state(eAsyncThreadNotStarted),
271254721Semaste    m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
272254721Semaste    m_thread_ids (),
273254721Semaste    m_continue_c_tids (),
274254721Semaste    m_continue_C_tids (),
275254721Semaste    m_continue_s_tids (),
276254721Semaste    m_continue_S_tids (),
277254721Semaste    m_max_memory_size (512),
278254721Semaste    m_addr_to_mmap_size (),
279254721Semaste    m_thread_create_bp_sp (),
280254721Semaste    m_waiting_for_attach (false),
281254721Semaste    m_destroy_tried_resuming (false),
282263363Semaste    m_command_sp (),
283263363Semaste    m_breakpoint_pc_offset (0)
284254721Semaste{
285254721Semaste    m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit,   "async thread should exit");
286254721Semaste    m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue,           "async thread continue");
287254721Semaste    m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit,      "async thread did exit");
288254721Semaste    const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
289254721Semaste    if (timeout_seconds > 0)
290254721Semaste        m_gdb_comm.SetPacketTimeout(timeout_seconds);
291254721Semaste}
292254721Semaste
293254721Semaste//----------------------------------------------------------------------
294254721Semaste// Destructor
295254721Semaste//----------------------------------------------------------------------
296254721SemasteProcessGDBRemote::~ProcessGDBRemote()
297254721Semaste{
298254721Semaste    //  m_mach_process.UnregisterNotificationCallbacks (this);
299254721Semaste    Clear();
300254721Semaste    // We need to call finalize on the process before destroying ourselves
301254721Semaste    // to make sure all of the broadcaster cleanup goes as planned. If we
302254721Semaste    // destruct this class, then Process::~Process() might have problems
303254721Semaste    // trying to fully destroy the broadcaster.
304254721Semaste    Finalize();
305254721Semaste
306254721Semaste    // The general Finalize is going to try to destroy the process and that SHOULD
307254721Semaste    // shut down the async thread.  However, if we don't kill it it will get stranded and
308254721Semaste    // its connection will go away so when it wakes up it will crash.  So kill it for sure here.
309254721Semaste    StopAsyncThread();
310254721Semaste    KillDebugserverProcess();
311254721Semaste}
312254721Semaste
313254721Semaste//----------------------------------------------------------------------
314254721Semaste// PluginInterface
315254721Semaste//----------------------------------------------------------------------
316254721SemasteConstString
317254721SemasteProcessGDBRemote::GetPluginName()
318254721Semaste{
319254721Semaste    return GetPluginNameStatic();
320254721Semaste}
321254721Semaste
322254721Semasteuint32_t
323254721SemasteProcessGDBRemote::GetPluginVersion()
324254721Semaste{
325254721Semaste    return 1;
326254721Semaste}
327254721Semaste
328263363Semastebool
329263363SemasteProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
330263363Semaste{
331263363Semaste#ifndef LLDB_DISABLE_PYTHON
332263363Semaste    ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
333263363Semaste    Error error;
334263363Semaste    lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
335263363Semaste    if (module_object_sp)
336263363Semaste    {
337263363Semaste        lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
338263363Semaste                                                                                              &GetTarget(),
339263363Semaste                                                                                              "gdb-server-target-definition",
340263363Semaste                                                                                              error));
341263363Semaste
342263363Semaste        PythonDictionary target_dict(target_definition_sp);
343263363Semaste
344263363Semaste        if (target_dict)
345263363Semaste        {
346263363Semaste            PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
347263363Semaste            if (host_info_dict)
348263363Semaste            {
349263363Semaste                ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
350263363Semaste
351263363Semaste                if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
352263363Semaste                {
353263363Semaste                    GetTarget().SetArchitecture(host_arch);
354263363Semaste                }
355263363Semaste
356263363Semaste            }
357263363Semaste            m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
358263363Semaste
359263363Semaste            if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
360263363Semaste            {
361263363Semaste                return true;
362263363Semaste            }
363263363Semaste        }
364263363Semaste    }
365263363Semaste#endif
366263363Semaste    return false;
367263363Semaste}
368263363Semaste
369263363Semaste
370254721Semastevoid
371254721SemasteProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
372254721Semaste{
373254721Semaste    if (!force && m_register_info.GetNumRegisters() > 0)
374254721Semaste        return;
375254721Semaste
376254721Semaste    char packet[128];
377254721Semaste    m_register_info.Clear();
378254721Semaste    uint32_t reg_offset = 0;
379254721Semaste    uint32_t reg_num = 0;
380254721Semaste    for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
381254721Semaste         response_type == StringExtractorGDBRemote::eResponse;
382254721Semaste         ++reg_num)
383254721Semaste    {
384254721Semaste        const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
385254721Semaste        assert (packet_len < (int)sizeof(packet));
386254721Semaste        StringExtractorGDBRemote response;
387269024Semaste        if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
388254721Semaste        {
389254721Semaste            response_type = response.GetResponseType();
390254721Semaste            if (response_type == StringExtractorGDBRemote::eResponse)
391254721Semaste            {
392254721Semaste                std::string name;
393254721Semaste                std::string value;
394254721Semaste                ConstString reg_name;
395254721Semaste                ConstString alt_name;
396254721Semaste                ConstString set_name;
397254721Semaste                std::vector<uint32_t> value_regs;
398254721Semaste                std::vector<uint32_t> invalidate_regs;
399254721Semaste                RegisterInfo reg_info = { NULL,                 // Name
400254721Semaste                    NULL,                 // Alt name
401254721Semaste                    0,                    // byte size
402254721Semaste                    reg_offset,           // offset
403254721Semaste                    eEncodingUint,        // encoding
404254721Semaste                    eFormatHex,           // formate
405254721Semaste                    {
406254721Semaste                        LLDB_INVALID_REGNUM, // GCC reg num
407254721Semaste                        LLDB_INVALID_REGNUM, // DWARF reg num
408254721Semaste                        LLDB_INVALID_REGNUM, // generic reg num
409254721Semaste                        reg_num,             // GDB reg num
410254721Semaste                        reg_num           // native register number
411254721Semaste                    },
412254721Semaste                    NULL,
413254721Semaste                    NULL
414254721Semaste                };
415254721Semaste
416254721Semaste                while (response.GetNameColonValue(name, value))
417254721Semaste                {
418254721Semaste                    if (name.compare("name") == 0)
419254721Semaste                    {
420254721Semaste                        reg_name.SetCString(value.c_str());
421254721Semaste                    }
422254721Semaste                    else if (name.compare("alt-name") == 0)
423254721Semaste                    {
424254721Semaste                        alt_name.SetCString(value.c_str());
425254721Semaste                    }
426254721Semaste                    else if (name.compare("bitsize") == 0)
427254721Semaste                    {
428254721Semaste                        reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
429254721Semaste                    }
430254721Semaste                    else if (name.compare("offset") == 0)
431254721Semaste                    {
432254721Semaste                        uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
433254721Semaste                        if (reg_offset != offset)
434254721Semaste                        {
435254721Semaste                            reg_offset = offset;
436254721Semaste                        }
437254721Semaste                    }
438254721Semaste                    else if (name.compare("encoding") == 0)
439254721Semaste                    {
440254721Semaste                        const Encoding encoding = Args::StringToEncoding (value.c_str());
441254721Semaste                        if (encoding != eEncodingInvalid)
442254721Semaste                            reg_info.encoding = encoding;
443254721Semaste                    }
444254721Semaste                    else if (name.compare("format") == 0)
445254721Semaste                    {
446254721Semaste                        Format format = eFormatInvalid;
447254721Semaste                        if (Args::StringToFormat (value.c_str(), format, NULL).Success())
448254721Semaste                            reg_info.format = format;
449254721Semaste                        else if (value.compare("binary") == 0)
450254721Semaste                            reg_info.format = eFormatBinary;
451254721Semaste                        else if (value.compare("decimal") == 0)
452254721Semaste                            reg_info.format = eFormatDecimal;
453254721Semaste                        else if (value.compare("hex") == 0)
454254721Semaste                            reg_info.format = eFormatHex;
455254721Semaste                        else if (value.compare("float") == 0)
456254721Semaste                            reg_info.format = eFormatFloat;
457254721Semaste                        else if (value.compare("vector-sint8") == 0)
458254721Semaste                            reg_info.format = eFormatVectorOfSInt8;
459254721Semaste                        else if (value.compare("vector-uint8") == 0)
460254721Semaste                            reg_info.format = eFormatVectorOfUInt8;
461254721Semaste                        else if (value.compare("vector-sint16") == 0)
462254721Semaste                            reg_info.format = eFormatVectorOfSInt16;
463254721Semaste                        else if (value.compare("vector-uint16") == 0)
464254721Semaste                            reg_info.format = eFormatVectorOfUInt16;
465254721Semaste                        else if (value.compare("vector-sint32") == 0)
466254721Semaste                            reg_info.format = eFormatVectorOfSInt32;
467254721Semaste                        else if (value.compare("vector-uint32") == 0)
468254721Semaste                            reg_info.format = eFormatVectorOfUInt32;
469254721Semaste                        else if (value.compare("vector-float32") == 0)
470254721Semaste                            reg_info.format = eFormatVectorOfFloat32;
471254721Semaste                        else if (value.compare("vector-uint128") == 0)
472254721Semaste                            reg_info.format = eFormatVectorOfUInt128;
473254721Semaste                    }
474254721Semaste                    else if (name.compare("set") == 0)
475254721Semaste                    {
476254721Semaste                        set_name.SetCString(value.c_str());
477254721Semaste                    }
478254721Semaste                    else if (name.compare("gcc") == 0)
479254721Semaste                    {
480254721Semaste                        reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
481254721Semaste                    }
482254721Semaste                    else if (name.compare("dwarf") == 0)
483254721Semaste                    {
484254721Semaste                        reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
485254721Semaste                    }
486254721Semaste                    else if (name.compare("generic") == 0)
487254721Semaste                    {
488254721Semaste                        reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
489254721Semaste                    }
490254721Semaste                    else if (name.compare("container-regs") == 0)
491254721Semaste                    {
492254721Semaste                        std::pair<llvm::StringRef, llvm::StringRef> value_pair;
493254721Semaste                        value_pair.second = value;
494254721Semaste                        do
495254721Semaste                        {
496254721Semaste                            value_pair = value_pair.second.split(',');
497254721Semaste                            if (!value_pair.first.empty())
498254721Semaste                            {
499254721Semaste                                uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
500254721Semaste                                if (reg != LLDB_INVALID_REGNUM)
501254721Semaste                                    value_regs.push_back (reg);
502254721Semaste                            }
503254721Semaste                        } while (!value_pair.second.empty());
504254721Semaste                    }
505254721Semaste                    else if (name.compare("invalidate-regs") == 0)
506254721Semaste                    {
507254721Semaste                        std::pair<llvm::StringRef, llvm::StringRef> value_pair;
508254721Semaste                        value_pair.second = value;
509254721Semaste                        do
510254721Semaste                        {
511254721Semaste                            value_pair = value_pair.second.split(',');
512254721Semaste                            if (!value_pair.first.empty())
513254721Semaste                            {
514254721Semaste                                uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
515254721Semaste                                if (reg != LLDB_INVALID_REGNUM)
516254721Semaste                                    invalidate_regs.push_back (reg);
517254721Semaste                            }
518254721Semaste                        } while (!value_pair.second.empty());
519254721Semaste                    }
520254721Semaste                }
521254721Semaste
522254721Semaste                reg_info.byte_offset = reg_offset;
523254721Semaste                assert (reg_info.byte_size != 0);
524254721Semaste                reg_offset += reg_info.byte_size;
525254721Semaste                if (!value_regs.empty())
526254721Semaste                {
527254721Semaste                    value_regs.push_back(LLDB_INVALID_REGNUM);
528254721Semaste                    reg_info.value_regs = value_regs.data();
529254721Semaste                }
530254721Semaste                if (!invalidate_regs.empty())
531254721Semaste                {
532254721Semaste                    invalidate_regs.push_back(LLDB_INVALID_REGNUM);
533254721Semaste                    reg_info.invalidate_regs = invalidate_regs.data();
534254721Semaste                }
535254721Semaste
536254721Semaste                m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
537254721Semaste            }
538269024Semaste            else
539269024Semaste            {
540269024Semaste                break;  // ensure exit before reg_num is incremented
541269024Semaste            }
542254721Semaste        }
543254721Semaste        else
544254721Semaste        {
545254721Semaste            break;
546254721Semaste        }
547254721Semaste    }
548254721Semaste
549263363Semaste    // Check if qHostInfo specified a specific packet timeout for this connection.
550263363Semaste    // If so then lets update our setting so the user knows what the timeout is
551263363Semaste    // and can see it.
552263363Semaste    const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
553263363Semaste    if (host_packet_timeout)
554263363Semaste    {
555263363Semaste        GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
556263363Semaste    }
557263363Semaste
558263363Semaste
559263363Semaste    if (reg_num == 0)
560263363Semaste    {
561263363Semaste        FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
562263363Semaste
563263363Semaste        if (target_definition_fspec)
564263363Semaste        {
565263363Semaste            // See if we can get register definitions from a python file
566263363Semaste            if (ParsePythonTargetDefinition (target_definition_fspec))
567263363Semaste                return;
568263363Semaste        }
569263363Semaste    }
570263363Semaste
571254721Semaste    // We didn't get anything if the accumulated reg_num is zero.  See if we are
572254721Semaste    // debugging ARM and fill with a hard coded register set until we can get an
573254721Semaste    // updated debugserver down on the devices.
574254721Semaste    // On the other hand, if the accumulated reg_num is positive, see if we can
575254721Semaste    // add composite registers to the existing primordial ones.
576254721Semaste    bool from_scratch = (reg_num == 0);
577254721Semaste
578254721Semaste    const ArchSpec &target_arch = GetTarget().GetArchitecture();
579254721Semaste    const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
580254721Semaste    const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
581254721Semaste
582254721Semaste    // Use the process' architecture instead of the host arch, if available
583254721Semaste    ArchSpec remote_arch;
584254721Semaste    if (remote_process_arch.IsValid ())
585254721Semaste        remote_arch = remote_process_arch;
586254721Semaste    else
587254721Semaste        remote_arch = remote_host_arch;
588254721Semaste
589254721Semaste    if (!target_arch.IsValid())
590254721Semaste    {
591254721Semaste        if (remote_arch.IsValid()
592254721Semaste              && remote_arch.GetMachine() == llvm::Triple::arm
593254721Semaste              && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
594254721Semaste            m_register_info.HardcodeARMRegisters(from_scratch);
595254721Semaste    }
596254721Semaste    else if (target_arch.GetMachine() == llvm::Triple::arm)
597254721Semaste    {
598254721Semaste        m_register_info.HardcodeARMRegisters(from_scratch);
599254721Semaste    }
600254721Semaste
601254721Semaste    // At this point, we can finalize our register info.
602254721Semaste    m_register_info.Finalize ();
603254721Semaste}
604254721Semaste
605254721SemasteError
606254721SemasteProcessGDBRemote::WillLaunch (Module* module)
607254721Semaste{
608254721Semaste    return WillLaunchOrAttach ();
609254721Semaste}
610254721Semaste
611254721SemasteError
612254721SemasteProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
613254721Semaste{
614254721Semaste    return WillLaunchOrAttach ();
615254721Semaste}
616254721Semaste
617254721SemasteError
618254721SemasteProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
619254721Semaste{
620254721Semaste    return WillLaunchOrAttach ();
621254721Semaste}
622254721Semaste
623254721SemasteError
624254721SemasteProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
625254721Semaste{
626254721Semaste    Error error (WillLaunchOrAttach ());
627254721Semaste
628254721Semaste    if (error.Fail())
629254721Semaste        return error;
630254721Semaste
631254721Semaste    error = ConnectToDebugserver (remote_url);
632254721Semaste
633254721Semaste    if (error.Fail())
634254721Semaste        return error;
635254721Semaste    StartAsyncThread ();
636254721Semaste
637254721Semaste    lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
638254721Semaste    if (pid == LLDB_INVALID_PROCESS_ID)
639254721Semaste    {
640254721Semaste        // We don't have a valid process ID, so note that we are connected
641254721Semaste        // and could now request to launch or attach, or get remote process
642254721Semaste        // listings...
643254721Semaste        SetPrivateState (eStateConnected);
644254721Semaste    }
645254721Semaste    else
646254721Semaste    {
647254721Semaste        // We have a valid process
648254721Semaste        SetID (pid);
649254721Semaste        GetThreadList();
650269024Semaste        if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
651254721Semaste        {
652269024Semaste            if (!m_target.GetArchitecture().IsValid())
653269024Semaste            {
654269024Semaste                if (m_gdb_comm.GetProcessArchitecture().IsValid())
655269024Semaste                {
656269024Semaste                    m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
657269024Semaste                }
658269024Semaste                else
659269024Semaste                {
660269024Semaste                    m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
661269024Semaste                }
662263363Semaste            }
663263363Semaste
664254721Semaste            const StateType state = SetThreadStopInfo (m_last_stop_packet);
665254721Semaste            if (state == eStateStopped)
666254721Semaste            {
667254721Semaste                SetPrivateState (state);
668254721Semaste            }
669254721Semaste            else
670254721Semaste                error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
671254721Semaste        }
672254721Semaste        else
673254721Semaste            error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
674254721Semaste    }
675254721Semaste
676254721Semaste    if (error.Success()
677254721Semaste        && !GetTarget().GetArchitecture().IsValid()
678254721Semaste        && m_gdb_comm.GetHostArchitecture().IsValid())
679254721Semaste    {
680254721Semaste        // Prefer the *process'* architecture over that of the *host*, if available.
681254721Semaste        if (m_gdb_comm.GetProcessArchitecture().IsValid())
682254721Semaste            GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
683254721Semaste        else
684254721Semaste            GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
685254721Semaste    }
686254721Semaste
687254721Semaste    return error;
688254721Semaste}
689254721Semaste
690254721SemasteError
691254721SemasteProcessGDBRemote::WillLaunchOrAttach ()
692254721Semaste{
693254721Semaste    Error error;
694254721Semaste    m_stdio_communication.Clear ();
695254721Semaste    return error;
696254721Semaste}
697254721Semaste
698254721Semaste//----------------------------------------------------------------------
699254721Semaste// Process Control
700254721Semaste//----------------------------------------------------------------------
701254721SemasteError
702269024SemasteProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
703254721Semaste{
704254721Semaste    Error error;
705254721Semaste
706254721Semaste    uint32_t launch_flags = launch_info.GetFlags().Get();
707254721Semaste    const char *stdin_path = NULL;
708254721Semaste    const char *stdout_path = NULL;
709254721Semaste    const char *stderr_path = NULL;
710254721Semaste    const char *working_dir = launch_info.GetWorkingDirectory();
711254721Semaste
712254721Semaste    const ProcessLaunchInfo::FileAction *file_action;
713254721Semaste    file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
714254721Semaste    if (file_action)
715254721Semaste    {
716254721Semaste        if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
717254721Semaste            stdin_path = file_action->GetPath();
718254721Semaste    }
719254721Semaste    file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
720254721Semaste    if (file_action)
721254721Semaste    {
722254721Semaste        if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
723254721Semaste            stdout_path = file_action->GetPath();
724254721Semaste    }
725254721Semaste    file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
726254721Semaste    if (file_action)
727254721Semaste    {
728254721Semaste        if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
729254721Semaste            stderr_path = file_action->GetPath();
730254721Semaste    }
731254721Semaste
732254721Semaste    //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
733254721Semaste    //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
734254721Semaste    //  ::LogSetLogFile ("/dev/stdout");
735254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
736254721Semaste
737254721Semaste    ObjectFile * object_file = exe_module->GetObjectFile();
738254721Semaste    if (object_file)
739254721Semaste    {
740254721Semaste        // Make sure we aren't already connected?
741254721Semaste        if (!m_gdb_comm.IsConnected())
742254721Semaste        {
743269024Semaste            error = LaunchAndConnectToDebugserver (launch_info);
744254721Semaste        }
745254721Semaste
746254721Semaste        if (error.Success())
747254721Semaste        {
748254721Semaste            lldb_utility::PseudoTerminal pty;
749254721Semaste            const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
750254721Semaste
751254721Semaste            // If the debugserver is local and we aren't disabling STDIO, lets use
752254721Semaste            // a pseudo terminal to instead of relying on the 'O' packets for stdio
753254721Semaste            // since 'O' packets can really slow down debugging if the inferior
754254721Semaste            // does a lot of output.
755254721Semaste            PlatformSP platform_sp (m_target.GetPlatform());
756254721Semaste            if (platform_sp && platform_sp->IsHost() && !disable_stdio)
757254721Semaste            {
758254721Semaste                const char *slave_name = NULL;
759254721Semaste                if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
760254721Semaste                {
761254721Semaste                    if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
762254721Semaste                        slave_name = pty.GetSlaveName (NULL, 0);
763254721Semaste                }
764254721Semaste                if (stdin_path == NULL)
765254721Semaste                    stdin_path = slave_name;
766254721Semaste
767254721Semaste                if (stdout_path == NULL)
768254721Semaste                    stdout_path = slave_name;
769254721Semaste
770254721Semaste                if (stderr_path == NULL)
771254721Semaste                    stderr_path = slave_name;
772254721Semaste            }
773254721Semaste
774254721Semaste            // Set STDIN to /dev/null if we want STDIO disabled or if either
775254721Semaste            // STDOUT or STDERR have been set to something and STDIN hasn't
776254721Semaste            if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
777254721Semaste                stdin_path = "/dev/null";
778254721Semaste
779254721Semaste            // Set STDOUT to /dev/null if we want STDIO disabled or if either
780254721Semaste            // STDIN or STDERR have been set to something and STDOUT hasn't
781254721Semaste            if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
782254721Semaste                stdout_path = "/dev/null";
783254721Semaste
784254721Semaste            // Set STDERR to /dev/null if we want STDIO disabled or if either
785254721Semaste            // STDIN or STDOUT have been set to something and STDERR hasn't
786254721Semaste            if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
787254721Semaste                stderr_path = "/dev/null";
788254721Semaste
789254721Semaste            if (stdin_path)
790254721Semaste                m_gdb_comm.SetSTDIN (stdin_path);
791254721Semaste            if (stdout_path)
792254721Semaste                m_gdb_comm.SetSTDOUT (stdout_path);
793254721Semaste            if (stderr_path)
794254721Semaste                m_gdb_comm.SetSTDERR (stderr_path);
795254721Semaste
796254721Semaste            m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
797254721Semaste
798254721Semaste            m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
799254721Semaste
800254721Semaste            if (working_dir && working_dir[0])
801254721Semaste            {
802254721Semaste                m_gdb_comm.SetWorkingDir (working_dir);
803254721Semaste            }
804254721Semaste
805254721Semaste            // Send the environment and the program + arguments after we connect
806254721Semaste            const Args &environment = launch_info.GetEnvironmentEntries();
807254721Semaste            if (environment.GetArgumentCount())
808254721Semaste            {
809254721Semaste                size_t num_environment_entries = environment.GetArgumentCount();
810254721Semaste                for (size_t i=0; i<num_environment_entries; ++i)
811254721Semaste                {
812254721Semaste                    const char *env_entry = environment.GetArgumentAtIndex(i);
813254721Semaste                    if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
814254721Semaste                        break;
815254721Semaste                }
816254721Semaste            }
817254721Semaste
818254721Semaste            const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
819263367Semaste            int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
820254721Semaste            if (arg_packet_err == 0)
821254721Semaste            {
822254721Semaste                std::string error_str;
823254721Semaste                if (m_gdb_comm.GetLaunchSuccess (error_str))
824254721Semaste                {
825254721Semaste                    SetID (m_gdb_comm.GetCurrentProcessID ());
826254721Semaste                }
827254721Semaste                else
828254721Semaste                {
829254721Semaste                    error.SetErrorString (error_str.c_str());
830254721Semaste                }
831254721Semaste            }
832254721Semaste            else
833254721Semaste            {
834254721Semaste                error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
835254721Semaste            }
836254721Semaste
837254721Semaste            m_gdb_comm.SetPacketTimeout (old_packet_timeout);
838254721Semaste
839254721Semaste            if (GetID() == LLDB_INVALID_PROCESS_ID)
840254721Semaste            {
841254721Semaste                if (log)
842254721Semaste                    log->Printf("failed to connect to debugserver: %s", error.AsCString());
843254721Semaste                KillDebugserverProcess ();
844254721Semaste                return error;
845254721Semaste            }
846254721Semaste
847269024Semaste            if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
848254721Semaste            {
849269024Semaste                if (!m_target.GetArchitecture().IsValid())
850269024Semaste                {
851269024Semaste                    if (m_gdb_comm.GetProcessArchitecture().IsValid())
852269024Semaste                    {
853269024Semaste                        m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
854269024Semaste                    }
855269024Semaste                    else
856269024Semaste                    {
857269024Semaste                        m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
858269024Semaste                    }
859263363Semaste                }
860263363Semaste
861254721Semaste                SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
862254721Semaste
863254721Semaste                if (!disable_stdio)
864254721Semaste                {
865254721Semaste                    if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
866254721Semaste                        SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
867254721Semaste                }
868254721Semaste            }
869254721Semaste        }
870254721Semaste        else
871254721Semaste        {
872254721Semaste            if (log)
873254721Semaste                log->Printf("failed to connect to debugserver: %s", error.AsCString());
874254721Semaste        }
875254721Semaste    }
876254721Semaste    else
877254721Semaste    {
878254721Semaste        // Set our user ID to an invalid process ID.
879254721Semaste        SetID(LLDB_INVALID_PROCESS_ID);
880254721Semaste        error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
881254721Semaste                                        exe_module->GetFileSpec().GetFilename().AsCString(),
882254721Semaste                                        exe_module->GetArchitecture().GetArchitectureName());
883254721Semaste    }
884254721Semaste    return error;
885254721Semaste
886254721Semaste}
887254721Semaste
888254721Semaste
889254721SemasteError
890254721SemasteProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
891254721Semaste{
892254721Semaste    Error error;
893269024Semaste    // Only connect if we have a valid connect URL
894269024Semaste
895269024Semaste    if (connect_url && connect_url[0])
896254721Semaste    {
897269024Semaste        std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
898269024Semaste        if (conn_ap.get())
899254721Semaste        {
900269024Semaste            const uint32_t max_retry_count = 50;
901269024Semaste            uint32_t retry_count = 0;
902269024Semaste            while (!m_gdb_comm.IsConnected())
903254721Semaste            {
904269024Semaste                if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
905269024Semaste                {
906269024Semaste                    m_gdb_comm.SetConnection (conn_ap.release());
907269024Semaste                    break;
908269024Semaste                }
909269024Semaste                else if (error.WasInterrupted())
910269024Semaste                {
911269024Semaste                    // If we were interrupted, don't keep retrying.
912269024Semaste                    break;
913269024Semaste                }
914269024Semaste
915269024Semaste                retry_count++;
916269024Semaste
917269024Semaste                if (retry_count >= max_retry_count)
918269024Semaste                    break;
919269024Semaste
920269024Semaste                usleep (100000);
921254721Semaste            }
922254721Semaste        }
923254721Semaste    }
924254721Semaste
925254721Semaste    if (!m_gdb_comm.IsConnected())
926254721Semaste    {
927254721Semaste        if (error.Success())
928254721Semaste            error.SetErrorString("not connected to remote gdb server");
929254721Semaste        return error;
930254721Semaste    }
931254721Semaste
932254721Semaste    // We always seem to be able to open a connection to a local port
933254721Semaste    // so we need to make sure we can then send data to it. If we can't
934254721Semaste    // then we aren't actually connected to anything, so try and do the
935254721Semaste    // handshake with the remote GDB server and make sure that goes
936254721Semaste    // alright.
937263367Semaste    if (!m_gdb_comm.HandshakeWithServer (&error))
938254721Semaste    {
939254721Semaste        m_gdb_comm.Disconnect();
940254721Semaste        if (error.Success())
941254721Semaste            error.SetErrorString("not connected to remote gdb server");
942254721Semaste        return error;
943254721Semaste    }
944254721Semaste    m_gdb_comm.GetThreadSuffixSupported ();
945254721Semaste    m_gdb_comm.GetListThreadsInStopReplySupported ();
946254721Semaste    m_gdb_comm.GetHostInfo ();
947254721Semaste    m_gdb_comm.GetVContSupported ('c');
948254721Semaste    m_gdb_comm.GetVAttachOrWaitSupported();
949254721Semaste
950254721Semaste    size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
951254721Semaste    for (size_t idx = 0; idx < num_cmds; idx++)
952254721Semaste    {
953254721Semaste        StringExtractorGDBRemote response;
954254721Semaste        m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
955254721Semaste    }
956254721Semaste    return error;
957254721Semaste}
958254721Semaste
959254721Semastevoid
960254721SemasteProcessGDBRemote::DidLaunchOrAttach ()
961254721Semaste{
962254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
963254721Semaste    if (log)
964254721Semaste        log->Printf ("ProcessGDBRemote::DidLaunch()");
965254721Semaste    if (GetID() != LLDB_INVALID_PROCESS_ID)
966254721Semaste    {
967254721Semaste        BuildDynamicRegisterInfo (false);
968254721Semaste
969254721Semaste        // See if the GDB server supports the qHostInfo information
970254721Semaste
971254721Semaste        ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
972254721Semaste
973254721Semaste        // See if the GDB server supports the qProcessInfo packet, if so
974254721Semaste        // prefer that over the Host information as it will be more specific
975254721Semaste        // to our process.
976254721Semaste
977254721Semaste        if (m_gdb_comm.GetProcessArchitecture().IsValid())
978254721Semaste            gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
979254721Semaste
980254721Semaste        if (gdb_remote_arch.IsValid())
981254721Semaste        {
982254721Semaste            ArchSpec &target_arch = GetTarget().GetArchitecture();
983254721Semaste
984254721Semaste            if (target_arch.IsValid())
985254721Semaste            {
986254721Semaste                // If the remote host is ARM and we have apple as the vendor, then
987254721Semaste                // ARM executables and shared libraries can have mixed ARM architectures.
988254721Semaste                // You can have an armv6 executable, and if the host is armv7, then the
989254721Semaste                // system will load the best possible architecture for all shared libraries
990254721Semaste                // it has, so we really need to take the remote host architecture as our
991254721Semaste                // defacto architecture in this case.
992254721Semaste
993254721Semaste                if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
994254721Semaste                    gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
995254721Semaste                {
996254721Semaste                    target_arch = gdb_remote_arch;
997254721Semaste                }
998254721Semaste                else
999254721Semaste                {
1000254721Semaste                    // Fill in what is missing in the triple
1001254721Semaste                    const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
1002254721Semaste                    llvm::Triple &target_triple = target_arch.GetTriple();
1003254721Semaste                    if (target_triple.getVendorName().size() == 0)
1004254721Semaste                    {
1005254721Semaste                        target_triple.setVendor (remote_triple.getVendor());
1006254721Semaste
1007254721Semaste                        if (target_triple.getOSName().size() == 0)
1008254721Semaste                        {
1009254721Semaste                            target_triple.setOS (remote_triple.getOS());
1010254721Semaste
1011254721Semaste                            if (target_triple.getEnvironmentName().size() == 0)
1012254721Semaste                                target_triple.setEnvironment (remote_triple.getEnvironment());
1013254721Semaste                        }
1014254721Semaste                    }
1015254721Semaste                }
1016254721Semaste            }
1017254721Semaste            else
1018254721Semaste            {
1019254721Semaste                // The target doesn't have a valid architecture yet, set it from
1020254721Semaste                // the architecture we got from the remote GDB server
1021254721Semaste                target_arch = gdb_remote_arch;
1022254721Semaste            }
1023254721Semaste        }
1024254721Semaste    }
1025254721Semaste}
1026254721Semaste
1027254721Semastevoid
1028254721SemasteProcessGDBRemote::DidLaunch ()
1029254721Semaste{
1030254721Semaste    DidLaunchOrAttach ();
1031254721Semaste}
1032254721Semaste
1033254721SemasteError
1034254721SemasteProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
1035254721Semaste{
1036254721Semaste    ProcessAttachInfo attach_info;
1037254721Semaste    return DoAttachToProcessWithID(attach_pid, attach_info);
1038254721Semaste}
1039254721Semaste
1040254721SemasteError
1041254721SemasteProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1042254721Semaste{
1043254721Semaste    Error error;
1044254721Semaste    // Clear out and clean up from any current state
1045254721Semaste    Clear();
1046254721Semaste    if (attach_pid != LLDB_INVALID_PROCESS_ID)
1047254721Semaste    {
1048254721Semaste        // Make sure we aren't already connected?
1049254721Semaste        if (!m_gdb_comm.IsConnected())
1050254721Semaste        {
1051269024Semaste            error = LaunchAndConnectToDebugserver (attach_info);
1052254721Semaste
1053254721Semaste            if (error.Fail())
1054254721Semaste            {
1055254721Semaste                const char *error_string = error.AsCString();
1056254721Semaste                if (error_string == NULL)
1057254721Semaste                    error_string = "unable to launch " DEBUGSERVER_BASENAME;
1058254721Semaste
1059254721Semaste                SetExitStatus (-1, error_string);
1060254721Semaste            }
1061254721Semaste        }
1062254721Semaste
1063254721Semaste        if (error.Success())
1064254721Semaste        {
1065254721Semaste            char packet[64];
1066254721Semaste            const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1067254721Semaste            SetID (attach_pid);
1068254721Semaste            m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1069254721Semaste        }
1070254721Semaste    }
1071254721Semaste    return error;
1072254721Semaste}
1073254721Semaste
1074254721SemasteError
1075269024SemasteProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1076254721Semaste{
1077254721Semaste    Error error;
1078254721Semaste    // Clear out and clean up from any current state
1079254721Semaste    Clear();
1080254721Semaste
1081254721Semaste    if (process_name && process_name[0])
1082254721Semaste    {
1083254721Semaste        // Make sure we aren't already connected?
1084254721Semaste        if (!m_gdb_comm.IsConnected())
1085254721Semaste        {
1086269024Semaste            error = LaunchAndConnectToDebugserver (attach_info);
1087254721Semaste
1088254721Semaste            if (error.Fail())
1089254721Semaste            {
1090254721Semaste                const char *error_string = error.AsCString();
1091254721Semaste                if (error_string == NULL)
1092254721Semaste                    error_string = "unable to launch " DEBUGSERVER_BASENAME;
1093254721Semaste
1094254721Semaste                SetExitStatus (-1, error_string);
1095254721Semaste            }
1096254721Semaste        }
1097254721Semaste
1098254721Semaste        if (error.Success())
1099254721Semaste        {
1100254721Semaste            StreamString packet;
1101254721Semaste
1102269024Semaste            if (attach_info.GetWaitForLaunch())
1103254721Semaste            {
1104254721Semaste                if (!m_gdb_comm.GetVAttachOrWaitSupported())
1105254721Semaste                {
1106254721Semaste                    packet.PutCString ("vAttachWait");
1107254721Semaste                }
1108254721Semaste                else
1109254721Semaste                {
1110254721Semaste                    if (attach_info.GetIgnoreExisting())
1111254721Semaste                        packet.PutCString("vAttachWait");
1112254721Semaste                    else
1113254721Semaste                        packet.PutCString ("vAttachOrWait");
1114254721Semaste                }
1115254721Semaste            }
1116254721Semaste            else
1117254721Semaste                packet.PutCString("vAttachName");
1118254721Semaste            packet.PutChar(';');
1119254721Semaste            packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1120254721Semaste
1121254721Semaste            m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1122254721Semaste
1123254721Semaste        }
1124254721Semaste    }
1125254721Semaste    return error;
1126254721Semaste}
1127254721Semaste
1128254721Semaste
1129263367Semastebool
1130263367SemasteProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1131263367Semaste{
1132263367Semaste    m_gdb_comm.Disconnect();
1133263367Semaste    return Process::SetExitStatus (exit_status, cstr);
1134263367Semaste}
1135263367Semaste
1136254721Semastevoid
1137254721SemasteProcessGDBRemote::DidAttach ()
1138254721Semaste{
1139254721Semaste    DidLaunchOrAttach ();
1140254721Semaste}
1141254721Semaste
1142254721Semaste
1143254721SemasteError
1144254721SemasteProcessGDBRemote::WillResume ()
1145254721Semaste{
1146254721Semaste    m_continue_c_tids.clear();
1147254721Semaste    m_continue_C_tids.clear();
1148254721Semaste    m_continue_s_tids.clear();
1149254721Semaste    m_continue_S_tids.clear();
1150254721Semaste    return Error();
1151254721Semaste}
1152254721Semaste
1153254721SemasteError
1154254721SemasteProcessGDBRemote::DoResume ()
1155254721Semaste{
1156254721Semaste    Error error;
1157254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1158254721Semaste    if (log)
1159254721Semaste        log->Printf ("ProcessGDBRemote::Resume()");
1160254721Semaste
1161254721Semaste    Listener listener ("gdb-remote.resume-packet-sent");
1162254721Semaste    if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1163254721Semaste    {
1164254721Semaste        listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1165254721Semaste
1166254721Semaste        const size_t num_threads = GetThreadList().GetSize();
1167254721Semaste
1168254721Semaste        StreamString continue_packet;
1169254721Semaste        bool continue_packet_error = false;
1170254721Semaste        if (m_gdb_comm.HasAnyVContSupport ())
1171254721Semaste        {
1172269024Semaste            if (m_continue_c_tids.size() == num_threads ||
1173269024Semaste                (m_continue_c_tids.empty() &&
1174269024Semaste                 m_continue_C_tids.empty() &&
1175269024Semaste                 m_continue_s_tids.empty() &&
1176269024Semaste                 m_continue_S_tids.empty()))
1177254721Semaste            {
1178254721Semaste                // All threads are continuing, just send a "c" packet
1179254721Semaste                continue_packet.PutCString ("c");
1180254721Semaste            }
1181254721Semaste            else
1182254721Semaste            {
1183254721Semaste                continue_packet.PutCString ("vCont");
1184254721Semaste
1185254721Semaste                if (!m_continue_c_tids.empty())
1186254721Semaste                {
1187254721Semaste                    if (m_gdb_comm.GetVContSupported ('c'))
1188254721Semaste                    {
1189254721Semaste                        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)
1190254721Semaste                            continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1191254721Semaste                    }
1192254721Semaste                    else
1193254721Semaste                        continue_packet_error = true;
1194254721Semaste                }
1195254721Semaste
1196254721Semaste                if (!continue_packet_error && !m_continue_C_tids.empty())
1197254721Semaste                {
1198254721Semaste                    if (m_gdb_comm.GetVContSupported ('C'))
1199254721Semaste                    {
1200254721Semaste                        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)
1201254721Semaste                            continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1202254721Semaste                    }
1203254721Semaste                    else
1204254721Semaste                        continue_packet_error = true;
1205254721Semaste                }
1206254721Semaste
1207254721Semaste                if (!continue_packet_error && !m_continue_s_tids.empty())
1208254721Semaste                {
1209254721Semaste                    if (m_gdb_comm.GetVContSupported ('s'))
1210254721Semaste                    {
1211254721Semaste                        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)
1212254721Semaste                            continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1213254721Semaste                    }
1214254721Semaste                    else
1215254721Semaste                        continue_packet_error = true;
1216254721Semaste                }
1217254721Semaste
1218254721Semaste                if (!continue_packet_error && !m_continue_S_tids.empty())
1219254721Semaste                {
1220254721Semaste                    if (m_gdb_comm.GetVContSupported ('S'))
1221254721Semaste                    {
1222254721Semaste                        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)
1223254721Semaste                            continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1224254721Semaste                    }
1225254721Semaste                    else
1226254721Semaste                        continue_packet_error = true;
1227254721Semaste                }
1228254721Semaste
1229254721Semaste                if (continue_packet_error)
1230254721Semaste                    continue_packet.GetString().clear();
1231254721Semaste            }
1232254721Semaste        }
1233254721Semaste        else
1234254721Semaste            continue_packet_error = true;
1235254721Semaste
1236254721Semaste        if (continue_packet_error)
1237254721Semaste        {
1238254721Semaste            // Either no vCont support, or we tried to use part of the vCont
1239254721Semaste            // packet that wasn't supported by the remote GDB server.
1240254721Semaste            // We need to try and make a simple packet that can do our continue
1241254721Semaste            const size_t num_continue_c_tids = m_continue_c_tids.size();
1242254721Semaste            const size_t num_continue_C_tids = m_continue_C_tids.size();
1243254721Semaste            const size_t num_continue_s_tids = m_continue_s_tids.size();
1244254721Semaste            const size_t num_continue_S_tids = m_continue_S_tids.size();
1245254721Semaste            if (num_continue_c_tids > 0)
1246254721Semaste            {
1247254721Semaste                if (num_continue_c_tids == num_threads)
1248254721Semaste                {
1249254721Semaste                    // All threads are resuming...
1250254721Semaste                    m_gdb_comm.SetCurrentThreadForRun (-1);
1251254721Semaste                    continue_packet.PutChar ('c');
1252254721Semaste                    continue_packet_error = false;
1253254721Semaste                }
1254254721Semaste                else if (num_continue_c_tids == 1 &&
1255254721Semaste                         num_continue_C_tids == 0 &&
1256254721Semaste                         num_continue_s_tids == 0 &&
1257254721Semaste                         num_continue_S_tids == 0 )
1258254721Semaste                {
1259254721Semaste                    // Only one thread is continuing
1260254721Semaste                    m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1261254721Semaste                    continue_packet.PutChar ('c');
1262254721Semaste                    continue_packet_error = false;
1263254721Semaste                }
1264254721Semaste            }
1265254721Semaste
1266254721Semaste            if (continue_packet_error && num_continue_C_tids > 0)
1267254721Semaste            {
1268254721Semaste                if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1269254721Semaste                    num_continue_C_tids > 0 &&
1270254721Semaste                    num_continue_s_tids == 0 &&
1271254721Semaste                    num_continue_S_tids == 0 )
1272254721Semaste                {
1273254721Semaste                    const int continue_signo = m_continue_C_tids.front().second;
1274254721Semaste                    // Only one thread is continuing
1275254721Semaste                    if (num_continue_C_tids > 1)
1276254721Semaste                    {
1277254721Semaste                        // More that one thread with a signal, yet we don't have
1278254721Semaste                        // vCont support and we are being asked to resume each
1279254721Semaste                        // thread with a signal, we need to make sure they are
1280254721Semaste                        // all the same signal, or we can't issue the continue
1281254721Semaste                        // accurately with the current support...
1282254721Semaste                        if (num_continue_C_tids > 1)
1283254721Semaste                        {
1284254721Semaste                            continue_packet_error = false;
1285254721Semaste                            for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1286254721Semaste                            {
1287254721Semaste                                if (m_continue_C_tids[i].second != continue_signo)
1288254721Semaste                                    continue_packet_error = true;
1289254721Semaste                            }
1290254721Semaste                        }
1291254721Semaste                        if (!continue_packet_error)
1292254721Semaste                            m_gdb_comm.SetCurrentThreadForRun (-1);
1293254721Semaste                    }
1294254721Semaste                    else
1295254721Semaste                    {
1296254721Semaste                        // Set the continue thread ID
1297254721Semaste                        continue_packet_error = false;
1298254721Semaste                        m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1299254721Semaste                    }
1300254721Semaste                    if (!continue_packet_error)
1301254721Semaste                    {
1302254721Semaste                        // Add threads continuing with the same signo...
1303254721Semaste                        continue_packet.Printf("C%2.2x", continue_signo);
1304254721Semaste                    }
1305254721Semaste                }
1306254721Semaste            }
1307254721Semaste
1308254721Semaste            if (continue_packet_error && num_continue_s_tids > 0)
1309254721Semaste            {
1310254721Semaste                if (num_continue_s_tids == num_threads)
1311254721Semaste                {
1312254721Semaste                    // All threads are resuming...
1313254721Semaste                    m_gdb_comm.SetCurrentThreadForRun (-1);
1314254721Semaste                    continue_packet.PutChar ('s');
1315254721Semaste                    continue_packet_error = false;
1316254721Semaste                }
1317254721Semaste                else if (num_continue_c_tids == 0 &&
1318254721Semaste                         num_continue_C_tids == 0 &&
1319254721Semaste                         num_continue_s_tids == 1 &&
1320254721Semaste                         num_continue_S_tids == 0 )
1321254721Semaste                {
1322254721Semaste                    // Only one thread is stepping
1323254721Semaste                    m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1324254721Semaste                    continue_packet.PutChar ('s');
1325254721Semaste                    continue_packet_error = false;
1326254721Semaste                }
1327254721Semaste            }
1328254721Semaste
1329254721Semaste            if (!continue_packet_error && num_continue_S_tids > 0)
1330254721Semaste            {
1331254721Semaste                if (num_continue_S_tids == num_threads)
1332254721Semaste                {
1333254721Semaste                    const int step_signo = m_continue_S_tids.front().second;
1334254721Semaste                    // Are all threads trying to step with the same signal?
1335254721Semaste                    continue_packet_error = false;
1336254721Semaste                    if (num_continue_S_tids > 1)
1337254721Semaste                    {
1338254721Semaste                        for (size_t i=1; i<num_threads; ++i)
1339254721Semaste                        {
1340254721Semaste                            if (m_continue_S_tids[i].second != step_signo)
1341254721Semaste                                continue_packet_error = true;
1342254721Semaste                        }
1343254721Semaste                    }
1344254721Semaste                    if (!continue_packet_error)
1345254721Semaste                    {
1346254721Semaste                        // Add threads stepping with the same signo...
1347254721Semaste                        m_gdb_comm.SetCurrentThreadForRun (-1);
1348254721Semaste                        continue_packet.Printf("S%2.2x", step_signo);
1349254721Semaste                    }
1350254721Semaste                }
1351254721Semaste                else if (num_continue_c_tids == 0 &&
1352254721Semaste                         num_continue_C_tids == 0 &&
1353254721Semaste                         num_continue_s_tids == 0 &&
1354254721Semaste                         num_continue_S_tids == 1 )
1355254721Semaste                {
1356254721Semaste                    // Only one thread is stepping with signal
1357254721Semaste                    m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1358254721Semaste                    continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1359254721Semaste                    continue_packet_error = false;
1360254721Semaste                }
1361254721Semaste            }
1362254721Semaste        }
1363254721Semaste
1364254721Semaste        if (continue_packet_error)
1365254721Semaste        {
1366254721Semaste            error.SetErrorString ("can't make continue packet for this resume");
1367254721Semaste        }
1368254721Semaste        else
1369254721Semaste        {
1370254721Semaste            EventSP event_sp;
1371254721Semaste            TimeValue timeout;
1372254721Semaste            timeout = TimeValue::Now();
1373254721Semaste            timeout.OffsetWithSeconds (5);
1374254721Semaste            if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1375254721Semaste            {
1376254721Semaste                error.SetErrorString ("Trying to resume but the async thread is dead.");
1377254721Semaste                if (log)
1378254721Semaste                    log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1379254721Semaste                return error;
1380254721Semaste            }
1381254721Semaste
1382254721Semaste            m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1383254721Semaste
1384254721Semaste            if (listener.WaitForEvent (&timeout, event_sp) == false)
1385254721Semaste            {
1386254721Semaste                error.SetErrorString("Resume timed out.");
1387254721Semaste                if (log)
1388254721Semaste                    log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1389254721Semaste            }
1390254721Semaste            else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1391254721Semaste            {
1392254721Semaste                error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1393254721Semaste                if (log)
1394254721Semaste                    log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1395254721Semaste                return error;
1396254721Semaste            }
1397254721Semaste        }
1398254721Semaste    }
1399254721Semaste
1400254721Semaste    return error;
1401254721Semaste}
1402254721Semaste
1403254721Semastevoid
1404254721SemasteProcessGDBRemote::ClearThreadIDList ()
1405254721Semaste{
1406254721Semaste    Mutex::Locker locker(m_thread_list_real.GetMutex());
1407254721Semaste    m_thread_ids.clear();
1408254721Semaste}
1409254721Semaste
1410254721Semastebool
1411254721SemasteProcessGDBRemote::UpdateThreadIDList ()
1412254721Semaste{
1413254721Semaste    Mutex::Locker locker(m_thread_list_real.GetMutex());
1414254721Semaste    bool sequence_mutex_unavailable = false;
1415254721Semaste    m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1416254721Semaste    if (sequence_mutex_unavailable)
1417254721Semaste    {
1418254721Semaste        return false; // We just didn't get the list
1419254721Semaste    }
1420254721Semaste    return true;
1421254721Semaste}
1422254721Semaste
1423254721Semastebool
1424254721SemasteProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1425254721Semaste{
1426254721Semaste    // locker will keep a mutex locked until it goes out of scope
1427254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1428254721Semaste    if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1429254721Semaste        log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1430254721Semaste
1431254721Semaste    size_t num_thread_ids = m_thread_ids.size();
1432254721Semaste    // The "m_thread_ids" thread ID list should always be updated after each stop
1433254721Semaste    // reply packet, but in case it isn't, update it here.
1434254721Semaste    if (num_thread_ids == 0)
1435254721Semaste    {
1436254721Semaste        if (!UpdateThreadIDList ())
1437254721Semaste            return false;
1438254721Semaste        num_thread_ids = m_thread_ids.size();
1439254721Semaste    }
1440254721Semaste
1441254721Semaste    ThreadList old_thread_list_copy(old_thread_list);
1442254721Semaste    if (num_thread_ids > 0)
1443254721Semaste    {
1444254721Semaste        for (size_t i=0; i<num_thread_ids; ++i)
1445254721Semaste        {
1446254721Semaste            tid_t tid = m_thread_ids[i];
1447254721Semaste            ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1448254721Semaste            if (!thread_sp)
1449254721Semaste            {
1450254721Semaste                thread_sp.reset (new ThreadGDBRemote (*this, tid));
1451254721Semaste                if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1452254721Semaste                    log->Printf(
1453254721Semaste                            "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1454254721Semaste                            __FUNCTION__,
1455254721Semaste                            thread_sp.get(),
1456254721Semaste                            thread_sp->GetID());
1457254721Semaste            }
1458254721Semaste            else
1459254721Semaste            {
1460254721Semaste                if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1461254721Semaste                    log->Printf(
1462254721Semaste                           "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1463254721Semaste                           __FUNCTION__,
1464254721Semaste                           thread_sp.get(),
1465254721Semaste                           thread_sp->GetID());
1466254721Semaste            }
1467254721Semaste            new_thread_list.AddThread(thread_sp);
1468254721Semaste        }
1469254721Semaste    }
1470254721Semaste
1471254721Semaste    // Whatever that is left in old_thread_list_copy are not
1472254721Semaste    // present in new_thread_list. Remove non-existent threads from internal id table.
1473254721Semaste    size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1474254721Semaste    for (size_t i=0; i<old_num_thread_ids; i++)
1475254721Semaste    {
1476254721Semaste        ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1477254721Semaste        if (old_thread_sp)
1478254721Semaste        {
1479254721Semaste            lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1480254721Semaste            m_thread_id_to_index_id_map.erase(old_thread_id);
1481254721Semaste        }
1482254721Semaste    }
1483254721Semaste
1484254721Semaste    return true;
1485254721Semaste}
1486254721Semaste
1487254721Semaste
1488254721SemasteStateType
1489254721SemasteProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1490254721Semaste{
1491254721Semaste    stop_packet.SetFilePos (0);
1492254721Semaste    const char stop_type = stop_packet.GetChar();
1493254721Semaste    switch (stop_type)
1494254721Semaste    {
1495254721Semaste    case 'T':
1496254721Semaste    case 'S':
1497254721Semaste        {
1498254721Semaste            // This is a bit of a hack, but is is required. If we did exec, we
1499254721Semaste            // need to clear our thread lists and also know to rebuild our dynamic
1500254721Semaste            // register info before we lookup and threads and populate the expedited
1501254721Semaste            // register values so we need to know this right away so we can cleanup
1502254721Semaste            // and update our registers.
1503254721Semaste            const uint32_t stop_id = GetStopID();
1504254721Semaste            if (stop_id == 0)
1505254721Semaste            {
1506254721Semaste                // Our first stop, make sure we have a process ID, and also make
1507254721Semaste                // sure we know about our registers
1508254721Semaste                if (GetID() == LLDB_INVALID_PROCESS_ID)
1509254721Semaste                {
1510254721Semaste                    lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1511254721Semaste                    if (pid != LLDB_INVALID_PROCESS_ID)
1512254721Semaste                        SetID (pid);
1513254721Semaste                }
1514254721Semaste                BuildDynamicRegisterInfo (true);
1515254721Semaste            }
1516254721Semaste            // Stop with signal and thread info
1517254721Semaste            const uint8_t signo = stop_packet.GetHexU8();
1518254721Semaste            std::string name;
1519254721Semaste            std::string value;
1520254721Semaste            std::string thread_name;
1521254721Semaste            std::string reason;
1522254721Semaste            std::string description;
1523254721Semaste            uint32_t exc_type = 0;
1524254721Semaste            std::vector<addr_t> exc_data;
1525254721Semaste            addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1526254721Semaste            ThreadSP thread_sp;
1527254721Semaste            ThreadGDBRemote *gdb_thread = NULL;
1528254721Semaste
1529254721Semaste            while (stop_packet.GetNameColonValue(name, value))
1530254721Semaste            {
1531254721Semaste                if (name.compare("metype") == 0)
1532254721Semaste                {
1533254721Semaste                    // exception type in big endian hex
1534254721Semaste                    exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1535254721Semaste                }
1536254721Semaste                else if (name.compare("medata") == 0)
1537254721Semaste                {
1538254721Semaste                    // exception data in big endian hex
1539254721Semaste                    exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1540254721Semaste                }
1541254721Semaste                else if (name.compare("thread") == 0)
1542254721Semaste                {
1543254721Semaste                    // thread in big endian hex
1544254721Semaste                    lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1545254721Semaste                    // m_thread_list_real does have its own mutex, but we need to
1546254721Semaste                    // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1547254721Semaste                    // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1548254721Semaste                    Mutex::Locker locker (m_thread_list_real.GetMutex ());
1549254721Semaste                    thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1550254721Semaste
1551254721Semaste                    if (!thread_sp)
1552254721Semaste                    {
1553254721Semaste                        // Create the thread if we need to
1554254721Semaste                        thread_sp.reset (new ThreadGDBRemote (*this, tid));
1555254721Semaste                        Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1556254721Semaste                        if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1557254721Semaste                            log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1558254721Semaste                                         __FUNCTION__,
1559254721Semaste                                         thread_sp.get(),
1560254721Semaste                                         thread_sp->GetID());
1561254721Semaste
1562254721Semaste                        m_thread_list_real.AddThread(thread_sp);
1563254721Semaste                    }
1564254721Semaste                    gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1565254721Semaste
1566254721Semaste                }
1567254721Semaste                else if (name.compare("threads") == 0)
1568254721Semaste                {
1569254721Semaste                    Mutex::Locker locker(m_thread_list_real.GetMutex());
1570254721Semaste                    m_thread_ids.clear();
1571254721Semaste                    // A comma separated list of all threads in the current
1572254721Semaste                    // process that includes the thread for this stop reply
1573254721Semaste                    // packet
1574254721Semaste                    size_t comma_pos;
1575254721Semaste                    lldb::tid_t tid;
1576254721Semaste                    while ((comma_pos = value.find(',')) != std::string::npos)
1577254721Semaste                    {
1578254721Semaste                        value[comma_pos] = '\0';
1579254721Semaste                        // thread in big endian hex
1580254721Semaste                        tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1581254721Semaste                        if (tid != LLDB_INVALID_THREAD_ID)
1582254721Semaste                            m_thread_ids.push_back (tid);
1583254721Semaste                        value.erase(0, comma_pos + 1);
1584254721Semaste
1585254721Semaste                    }
1586254721Semaste                    tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1587254721Semaste                    if (tid != LLDB_INVALID_THREAD_ID)
1588254721Semaste                        m_thread_ids.push_back (tid);
1589254721Semaste                }
1590254721Semaste                else if (name.compare("hexname") == 0)
1591254721Semaste                {
1592254721Semaste                    StringExtractor name_extractor;
1593254721Semaste                    // Swap "value" over into "name_extractor"
1594254721Semaste                    name_extractor.GetStringRef().swap(value);
1595254721Semaste                    // Now convert the HEX bytes into a string value
1596254721Semaste                    name_extractor.GetHexByteString (value);
1597254721Semaste                    thread_name.swap (value);
1598254721Semaste                }
1599254721Semaste                else if (name.compare("name") == 0)
1600254721Semaste                {
1601254721Semaste                    thread_name.swap (value);
1602254721Semaste                }
1603254721Semaste                else if (name.compare("qaddr") == 0)
1604254721Semaste                {
1605254721Semaste                    thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1606254721Semaste                }
1607254721Semaste                else if (name.compare("reason") == 0)
1608254721Semaste                {
1609254721Semaste                    reason.swap(value);
1610254721Semaste                }
1611254721Semaste                else if (name.compare("description") == 0)
1612254721Semaste                {
1613254721Semaste                    StringExtractor desc_extractor;
1614254721Semaste                    // Swap "value" over into "name_extractor"
1615254721Semaste                    desc_extractor.GetStringRef().swap(value);
1616254721Semaste                    // Now convert the HEX bytes into a string value
1617254721Semaste                    desc_extractor.GetHexByteString (thread_name);
1618254721Semaste                }
1619254721Semaste                else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1620254721Semaste                {
1621254721Semaste                    // We have a register number that contains an expedited
1622254721Semaste                    // register value. Lets supply this register to our thread
1623254721Semaste                    // so it won't have to go and read it.
1624254721Semaste                    if (gdb_thread)
1625254721Semaste                    {
1626254721Semaste                        uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1627254721Semaste
1628254721Semaste                        if (reg != UINT32_MAX)
1629254721Semaste                        {
1630254721Semaste                            StringExtractor reg_value_extractor;
1631254721Semaste                            // Swap "value" over into "reg_value_extractor"
1632254721Semaste                            reg_value_extractor.GetStringRef().swap(value);
1633254721Semaste                            if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
1634254721Semaste                            {
1635254721Semaste                                Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1636254721Semaste                                                                    name.c_str(),
1637254721Semaste                                                                    reg,
1638254721Semaste                                                                    reg,
1639254721Semaste                                                                    reg_value_extractor.GetStringRef().c_str(),
1640254721Semaste                                                                    stop_packet.GetStringRef().c_str());
1641254721Semaste                            }
1642254721Semaste                        }
1643254721Semaste                    }
1644254721Semaste                }
1645254721Semaste            }
1646254721Semaste
1647269024Semaste            // If the response is old style 'S' packet which does not provide us with thread information
1648269024Semaste            // then update the thread list and choose the first one.
1649269024Semaste            if (!thread_sp)
1650269024Semaste            {
1651269024Semaste                UpdateThreadIDList ();
1652269024Semaste
1653269024Semaste                if (!m_thread_ids.empty ())
1654269024Semaste                {
1655269024Semaste                    Mutex::Locker locker (m_thread_list_real.GetMutex ());
1656269024Semaste                    thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1657269024Semaste                    if (thread_sp)
1658269024Semaste                        gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1659269024Semaste                }
1660269024Semaste            }
1661269024Semaste
1662254721Semaste            if (thread_sp)
1663254721Semaste            {
1664254721Semaste                // Clear the stop info just in case we don't set it to anything
1665254721Semaste                thread_sp->SetStopInfo (StopInfoSP());
1666254721Semaste
1667254721Semaste                gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1668254721Semaste                gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1669254721Semaste                if (exc_type != 0)
1670254721Semaste                {
1671254721Semaste                    const size_t exc_data_size = exc_data.size();
1672254721Semaste
1673254721Semaste                    thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1674254721Semaste                                                                                                      exc_type,
1675254721Semaste                                                                                                      exc_data_size,
1676254721Semaste                                                                                                      exc_data_size >= 1 ? exc_data[0] : 0,
1677254721Semaste                                                                                                      exc_data_size >= 2 ? exc_data[1] : 0,
1678254721Semaste                                                                                                      exc_data_size >= 3 ? exc_data[2] : 0));
1679254721Semaste                }
1680254721Semaste                else
1681254721Semaste                {
1682254721Semaste                    bool handled = false;
1683254721Semaste                    bool did_exec = false;
1684254721Semaste                    if (!reason.empty())
1685254721Semaste                    {
1686254721Semaste                        if (reason.compare("trace") == 0)
1687254721Semaste                        {
1688254721Semaste                            thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1689254721Semaste                            handled = true;
1690254721Semaste                        }
1691254721Semaste                        else if (reason.compare("breakpoint") == 0)
1692254721Semaste                        {
1693254721Semaste                            addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1694254721Semaste                            lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1695254721Semaste                            if (bp_site_sp)
1696254721Semaste                            {
1697254721Semaste                                // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1698254721Semaste                                // we can just report no reason.  We don't need to worry about stepping over the breakpoint here, that
1699254721Semaste                                // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1700254721Semaste                                handled = true;
1701254721Semaste                                if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1702254721Semaste                                {
1703254721Semaste                                    thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1704254721Semaste                                }
1705254721Semaste                                else
1706254721Semaste                                {
1707254721Semaste                                    StopInfoSP invalid_stop_info_sp;
1708254721Semaste                                    thread_sp->SetStopInfo (invalid_stop_info_sp);
1709254721Semaste                                }
1710254721Semaste                            }
1711254721Semaste
1712254721Semaste                        }
1713254721Semaste                        else if (reason.compare("trap") == 0)
1714254721Semaste                        {
1715254721Semaste                            // Let the trap just use the standard signal stop reason below...
1716254721Semaste                        }
1717254721Semaste                        else if (reason.compare("watchpoint") == 0)
1718254721Semaste                        {
1719254721Semaste                            break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1720254721Semaste                            // TODO: locate the watchpoint somehow...
1721254721Semaste                            thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1722254721Semaste                            handled = true;
1723254721Semaste                        }
1724254721Semaste                        else if (reason.compare("exception") == 0)
1725254721Semaste                        {
1726254721Semaste                            thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1727254721Semaste                            handled = true;
1728254721Semaste                        }
1729254721Semaste                        else if (reason.compare("exec") == 0)
1730254721Semaste                        {
1731254721Semaste                            did_exec = true;
1732254721Semaste                            thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1733254721Semaste                            handled = true;
1734254721Semaste                        }
1735254721Semaste                    }
1736254721Semaste
1737269024Semaste                    if (!handled && signo && did_exec == false)
1738254721Semaste                    {
1739254721Semaste                        if (signo == SIGTRAP)
1740254721Semaste                        {
1741254721Semaste                            // Currently we are going to assume SIGTRAP means we are either
1742254721Semaste                            // hitting a breakpoint or hardware single stepping.
1743254721Semaste                            handled = true;
1744263363Semaste                            addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1745254721Semaste                            lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1746254721Semaste
1747254721Semaste                            if (bp_site_sp)
1748254721Semaste                            {
1749254721Semaste                                // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1750254721Semaste                                // we can just report no reason.  We don't need to worry about stepping over the breakpoint here, that
1751254721Semaste                                // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1752254721Semaste                                if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1753254721Semaste                                {
1754263363Semaste                                    if(m_breakpoint_pc_offset != 0)
1755263363Semaste                                        thread_sp->GetRegisterContext()->SetPC(pc);
1756254721Semaste                                    thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1757254721Semaste                                }
1758254721Semaste                                else
1759254721Semaste                                {
1760254721Semaste                                    StopInfoSP invalid_stop_info_sp;
1761254721Semaste                                    thread_sp->SetStopInfo (invalid_stop_info_sp);
1762254721Semaste                                }
1763254721Semaste                            }
1764254721Semaste                            else
1765254721Semaste                            {
1766254721Semaste                                // If we were stepping then assume the stop was the result of the trace.  If we were
1767254721Semaste                                // not stepping then report the SIGTRAP.
1768254721Semaste                                // FIXME: We are still missing the case where we single step over a trap instruction.
1769254721Semaste                                if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1770254721Semaste                                    thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1771254721Semaste                                else
1772254721Semaste                                    thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
1773254721Semaste                            }
1774254721Semaste                        }
1775254721Semaste                        if (!handled)
1776254721Semaste                            thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1777254721Semaste                    }
1778254721Semaste
1779254721Semaste                    if (!description.empty())
1780254721Semaste                    {
1781254721Semaste                        lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
1782254721Semaste                        if (stop_info_sp)
1783254721Semaste                        {
1784254721Semaste                            stop_info_sp->SetDescription (description.c_str());
1785254721Semaste                        }
1786254721Semaste                        else
1787254721Semaste                        {
1788254721Semaste                            thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1789254721Semaste                        }
1790254721Semaste                    }
1791254721Semaste                }
1792254721Semaste            }
1793254721Semaste            return eStateStopped;
1794254721Semaste        }
1795254721Semaste        break;
1796254721Semaste
1797254721Semaste    case 'W':
1798254721Semaste        // process exited
1799254721Semaste        return eStateExited;
1800254721Semaste
1801254721Semaste    default:
1802254721Semaste        break;
1803254721Semaste    }
1804254721Semaste    return eStateInvalid;
1805254721Semaste}
1806254721Semaste
1807254721Semastevoid
1808254721SemasteProcessGDBRemote::RefreshStateAfterStop ()
1809254721Semaste{
1810254721Semaste    Mutex::Locker locker(m_thread_list_real.GetMutex());
1811254721Semaste    m_thread_ids.clear();
1812254721Semaste    // Set the thread stop info. It might have a "threads" key whose value is
1813254721Semaste    // a list of all thread IDs in the current process, so m_thread_ids might
1814254721Semaste    // get set.
1815254721Semaste    SetThreadStopInfo (m_last_stop_packet);
1816254721Semaste    // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1817254721Semaste    if (m_thread_ids.empty())
1818254721Semaste    {
1819254721Semaste        // No, we need to fetch the thread list manually
1820254721Semaste        UpdateThreadIDList();
1821254721Semaste    }
1822254721Semaste
1823254721Semaste    // Let all threads recover from stopping and do any clean up based
1824254721Semaste    // on the previous thread state (if any).
1825254721Semaste    m_thread_list_real.RefreshStateAfterStop();
1826254721Semaste
1827254721Semaste}
1828254721Semaste
1829254721SemasteError
1830254721SemasteProcessGDBRemote::DoHalt (bool &caused_stop)
1831254721Semaste{
1832254721Semaste    Error error;
1833254721Semaste
1834254721Semaste    bool timed_out = false;
1835254721Semaste    Mutex::Locker locker;
1836254721Semaste
1837254721Semaste    if (m_public_state.GetValue() == eStateAttaching)
1838254721Semaste    {
1839254721Semaste        // We are being asked to halt during an attach. We need to just close
1840254721Semaste        // our file handle and debugserver will go away, and we can be done...
1841254721Semaste        m_gdb_comm.Disconnect();
1842254721Semaste    }
1843254721Semaste    else
1844254721Semaste    {
1845254721Semaste        if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
1846254721Semaste        {
1847254721Semaste            if (timed_out)
1848254721Semaste                error.SetErrorString("timed out sending interrupt packet");
1849254721Semaste            else
1850254721Semaste                error.SetErrorString("unknown error sending interrupt packet");
1851254721Semaste        }
1852254721Semaste
1853254721Semaste        caused_stop = m_gdb_comm.GetInterruptWasSent ();
1854254721Semaste    }
1855254721Semaste    return error;
1856254721Semaste}
1857254721Semaste
1858254721SemasteError
1859254721SemasteProcessGDBRemote::DoDetach(bool keep_stopped)
1860254721Semaste{
1861254721Semaste    Error error;
1862254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1863254721Semaste    if (log)
1864254721Semaste        log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1865254721Semaste
1866254721Semaste    DisableAllBreakpointSites ();
1867254721Semaste
1868254721Semaste    m_thread_list.DiscardThreadPlans();
1869254721Semaste
1870254721Semaste    error = m_gdb_comm.Detach (keep_stopped);
1871254721Semaste    if (log)
1872254721Semaste    {
1873254721Semaste        if (error.Success())
1874254721Semaste            log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1875254721Semaste        else
1876254721Semaste            log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
1877254721Semaste    }
1878254721Semaste
1879254721Semaste    if (!error.Success())
1880254721Semaste        return error;
1881254721Semaste
1882254721Semaste    // Sleep for one second to let the process get all detached...
1883254721Semaste    StopAsyncThread ();
1884254721Semaste
1885254721Semaste    SetPrivateState (eStateDetached);
1886254721Semaste    ResumePrivateStateThread();
1887254721Semaste
1888254721Semaste    //KillDebugserverProcess ();
1889254721Semaste    return error;
1890254721Semaste}
1891254721Semaste
1892254721Semaste
1893254721SemasteError
1894254721SemasteProcessGDBRemote::DoDestroy ()
1895254721Semaste{
1896254721Semaste    Error error;
1897254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1898254721Semaste    if (log)
1899254721Semaste        log->Printf ("ProcessGDBRemote::DoDestroy()");
1900254721Semaste
1901254851Semaste#if 0 // XXX Currently no iOS target support on FreeBSD
1902254721Semaste    // There is a bug in older iOS debugservers where they don't shut down the process
1903254721Semaste    // they are debugging properly.  If the process is sitting at a breakpoint or an exception,
1904254721Semaste    // this can cause problems with restarting.  So we check to see if any of our threads are stopped
1905254721Semaste    // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1906254721Semaste    // destroy it again.
1907254721Semaste    //
1908254721Semaste    // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1909254721Semaste    // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1910254721Semaste    // the debugservers with this bug are equal.  There really should be a better way to test this!
1911254721Semaste    //
1912254721Semaste    // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1913254721Semaste    // get called here to destroy again and we're still at a breakpoint or exception, then we should
1914254721Semaste    // just do the straight-forward kill.
1915254721Semaste    //
1916254721Semaste    // And of course, if we weren't able to stop the process by the time we get here, it isn't
1917254721Semaste    // necessary (or helpful) to do any of this.
1918254721Semaste
1919254721Semaste    if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1920254721Semaste    {
1921254721Semaste        PlatformSP platform_sp = GetTarget().GetPlatform();
1922254721Semaste
1923254721Semaste        // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1924254721Semaste        if (platform_sp
1925254721Semaste            && platform_sp->GetName()
1926254721Semaste            && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
1927254721Semaste        {
1928254721Semaste            if (m_destroy_tried_resuming)
1929254721Semaste            {
1930254721Semaste                if (log)
1931254721Semaste                    log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1932254721Semaste            }
1933254721Semaste            else
1934254721Semaste            {
1935254721Semaste                // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1936254721Semaste                // but we really need it to happen here and it doesn't matter if we do it twice.
1937254721Semaste                m_thread_list.DiscardThreadPlans();
1938254721Semaste                DisableAllBreakpointSites();
1939254721Semaste
1940254721Semaste                bool stop_looks_like_crash = false;
1941254721Semaste                ThreadList &threads = GetThreadList();
1942254721Semaste
1943254721Semaste                {
1944254721Semaste                    Mutex::Locker locker(threads.GetMutex());
1945254721Semaste
1946254721Semaste                    size_t num_threads = threads.GetSize();
1947254721Semaste                    for (size_t i = 0; i < num_threads; i++)
1948254721Semaste                    {
1949254721Semaste                        ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1950254721Semaste                        StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1951254721Semaste                        StopReason reason = eStopReasonInvalid;
1952254721Semaste                        if (stop_info_sp)
1953254721Semaste                            reason = stop_info_sp->GetStopReason();
1954254721Semaste                        if (reason == eStopReasonBreakpoint
1955254721Semaste                            || reason == eStopReasonException)
1956254721Semaste                        {
1957254721Semaste                            if (log)
1958254721Semaste                                log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1959254721Semaste                                             thread_sp->GetProtocolID(),
1960254721Semaste                                             stop_info_sp->GetDescription());
1961254721Semaste                            stop_looks_like_crash = true;
1962254721Semaste                            break;
1963254721Semaste                        }
1964254721Semaste                    }
1965254721Semaste                }
1966254721Semaste
1967254721Semaste                if (stop_looks_like_crash)
1968254721Semaste                {
1969254721Semaste                    if (log)
1970254721Semaste                        log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1971254721Semaste                    m_destroy_tried_resuming = true;
1972254721Semaste
1973254721Semaste                    // If we are going to run again before killing, it would be good to suspend all the threads
1974254721Semaste                    // before resuming so they won't get into more trouble.  Sadly, for the threads stopped with
1975254721Semaste                    // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1976254721Semaste                    // have to run the risk of letting those threads proceed a bit.
1977254721Semaste
1978254721Semaste                    {
1979254721Semaste                        Mutex::Locker locker(threads.GetMutex());
1980254721Semaste
1981254721Semaste                        size_t num_threads = threads.GetSize();
1982254721Semaste                        for (size_t i = 0; i < num_threads; i++)
1983254721Semaste                        {
1984254721Semaste                            ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1985254721Semaste                            StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1986254721Semaste                            StopReason reason = eStopReasonInvalid;
1987254721Semaste                            if (stop_info_sp)
1988254721Semaste                                reason = stop_info_sp->GetStopReason();
1989254721Semaste                            if (reason != eStopReasonBreakpoint
1990254721Semaste                                && reason != eStopReasonException)
1991254721Semaste                            {
1992254721Semaste                                if (log)
1993254721Semaste                                    log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1994254721Semaste                                                 thread_sp->GetProtocolID());
1995254721Semaste                                thread_sp->SetResumeState(eStateSuspended);
1996254721Semaste                            }
1997254721Semaste                        }
1998254721Semaste                    }
1999254721Semaste                    Resume ();
2000254721Semaste                    return Destroy();
2001254721Semaste                }
2002254721Semaste            }
2003254721Semaste        }
2004254721Semaste    }
2005254851Semaste#endif
2006254721Semaste
2007254721Semaste    // Interrupt if our inferior is running...
2008254721Semaste    int exit_status = SIGABRT;
2009254721Semaste    std::string exit_string;
2010254721Semaste
2011254721Semaste    if (m_gdb_comm.IsConnected())
2012254721Semaste    {
2013254721Semaste        if (m_public_state.GetValue() != eStateAttaching)
2014254721Semaste        {
2015254721Semaste
2016254721Semaste            StringExtractorGDBRemote response;
2017254721Semaste            bool send_async = true;
2018254721Semaste            const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2019254721Semaste
2020269024Semaste            if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2021254721Semaste            {
2022254721Semaste                char packet_cmd = response.GetChar(0);
2023254721Semaste
2024254721Semaste                if (packet_cmd == 'W' || packet_cmd == 'X')
2025254721Semaste                {
2026269024Semaste#if defined(__APPLE__)
2027269024Semaste                    // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2028269024Semaste                    // to debugserver, which becomes the parent process through "PT_ATTACH".  Then when we go to kill
2029269024Semaste                    // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2030269024Semaste                    // with no error and the correct status.  But amusingly enough that doesn't seem to actually reap
2031269024Semaste                    // the process, but instead it is left around as a Zombie.  Probably the kernel is in the process of
2032269024Semaste                    // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2033269024Semaste                    // Anyway, so call waitpid here to finally reap it.
2034269024Semaste                    PlatformSP platform_sp(GetTarget().GetPlatform());
2035269024Semaste                    if (platform_sp && platform_sp->IsHost())
2036269024Semaste                    {
2037269024Semaste                        int status;
2038269024Semaste                        ::pid_t reap_pid;
2039269024Semaste                        reap_pid = waitpid (GetID(), &status, WNOHANG);
2040269024Semaste                        if (log)
2041269024Semaste                            log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2042269024Semaste                    }
2043269024Semaste#endif
2044254721Semaste                    SetLastStopPacket (response);
2045254721Semaste                    ClearThreadIDList ();
2046254721Semaste                    exit_status = response.GetHexU8();
2047254721Semaste                }
2048254721Semaste                else
2049254721Semaste                {
2050254721Semaste                    if (log)
2051254721Semaste                        log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2052254721Semaste                    exit_string.assign("got unexpected response to k packet: ");
2053254721Semaste                    exit_string.append(response.GetStringRef());
2054254721Semaste                }
2055254721Semaste            }
2056254721Semaste            else
2057254721Semaste            {
2058254721Semaste                if (log)
2059254721Semaste                    log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2060254721Semaste                exit_string.assign("failed to send the k packet");
2061254721Semaste            }
2062254721Semaste
2063254721Semaste            m_gdb_comm.SetPacketTimeout(old_packet_timeout);
2064254721Semaste        }
2065254721Semaste        else
2066254721Semaste        {
2067254721Semaste            if (log)
2068254721Semaste                log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2069254721Semaste            exit_string.assign ("killed or interrupted while attaching.");
2070254721Semaste        }
2071254721Semaste    }
2072254721Semaste    else
2073254721Semaste    {
2074254721Semaste        // If we missed setting the exit status on the way out, do it here.
2075254721Semaste        // NB set exit status can be called multiple times, the first one sets the status.
2076254721Semaste        exit_string.assign("destroying when not connected to debugserver");
2077254721Semaste    }
2078254721Semaste
2079254721Semaste    SetExitStatus(exit_status, exit_string.c_str());
2080254721Semaste
2081254721Semaste    StopAsyncThread ();
2082254721Semaste    KillDebugserverProcess ();
2083254721Semaste    return error;
2084254721Semaste}
2085254721Semaste
2086254721Semastevoid
2087254721SemasteProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2088254721Semaste{
2089254721Semaste    lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2090254721Semaste    const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2091254721Semaste    if (did_exec)
2092254721Semaste    {
2093254721Semaste        Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2094254721Semaste        if (log)
2095254721Semaste            log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2096254721Semaste
2097254721Semaste        m_thread_list_real.Clear();
2098254721Semaste        m_thread_list.Clear();
2099254721Semaste        BuildDynamicRegisterInfo (true);
2100254721Semaste        m_gdb_comm.ResetDiscoverableSettings();
2101254721Semaste    }
2102254721Semaste    m_last_stop_packet = response;
2103254721Semaste}
2104254721Semaste
2105254721Semaste
2106254721Semaste//------------------------------------------------------------------
2107254721Semaste// Process Queries
2108254721Semaste//------------------------------------------------------------------
2109254721Semaste
2110254721Semastebool
2111254721SemasteProcessGDBRemote::IsAlive ()
2112254721Semaste{
2113254721Semaste    return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2114254721Semaste}
2115254721Semaste
2116254721Semasteaddr_t
2117254721SemasteProcessGDBRemote::GetImageInfoAddress()
2118254721Semaste{
2119254721Semaste    return m_gdb_comm.GetShlibInfoAddr();
2120254721Semaste}
2121254721Semaste
2122254721Semaste//------------------------------------------------------------------
2123254721Semaste// Process Memory
2124254721Semaste//------------------------------------------------------------------
2125254721Semastesize_t
2126254721SemasteProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2127254721Semaste{
2128254721Semaste    if (size > m_max_memory_size)
2129254721Semaste    {
2130254721Semaste        // Keep memory read sizes down to a sane limit. This function will be
2131254721Semaste        // called multiple times in order to complete the task by
2132254721Semaste        // lldb_private::Process so it is ok to do this.
2133254721Semaste        size = m_max_memory_size;
2134254721Semaste    }
2135254721Semaste
2136254721Semaste    char packet[64];
2137254721Semaste    const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2138254721Semaste    assert (packet_len + 1 < (int)sizeof(packet));
2139254721Semaste    StringExtractorGDBRemote response;
2140269024Semaste    if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
2141254721Semaste    {
2142254721Semaste        if (response.IsNormalResponse())
2143254721Semaste        {
2144254721Semaste            error.Clear();
2145254721Semaste            return response.GetHexBytes(buf, size, '\xdd');
2146254721Semaste        }
2147254721Semaste        else if (response.IsErrorResponse())
2148254721Semaste            error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2149254721Semaste        else if (response.IsUnsupportedResponse())
2150254721Semaste            error.SetErrorStringWithFormat("GDB server does not support reading memory");
2151254721Semaste        else
2152254721Semaste            error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2153254721Semaste    }
2154254721Semaste    else
2155254721Semaste    {
2156254721Semaste        error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2157254721Semaste    }
2158254721Semaste    return 0;
2159254721Semaste}
2160254721Semaste
2161254721Semastesize_t
2162254721SemasteProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2163254721Semaste{
2164254721Semaste    if (size > m_max_memory_size)
2165254721Semaste    {
2166254721Semaste        // Keep memory read sizes down to a sane limit. This function will be
2167254721Semaste        // called multiple times in order to complete the task by
2168254721Semaste        // lldb_private::Process so it is ok to do this.
2169254721Semaste        size = m_max_memory_size;
2170254721Semaste    }
2171254721Semaste
2172254721Semaste    StreamString packet;
2173254721Semaste    packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2174254721Semaste    packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2175254721Semaste    StringExtractorGDBRemote response;
2176269024Semaste    if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
2177254721Semaste    {
2178254721Semaste        if (response.IsOKResponse())
2179254721Semaste        {
2180254721Semaste            error.Clear();
2181254721Semaste            return size;
2182254721Semaste        }
2183254721Semaste        else if (response.IsErrorResponse())
2184254721Semaste            error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2185254721Semaste        else if (response.IsUnsupportedResponse())
2186254721Semaste            error.SetErrorStringWithFormat("GDB server does not support writing memory");
2187254721Semaste        else
2188254721Semaste            error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2189254721Semaste    }
2190254721Semaste    else
2191254721Semaste    {
2192254721Semaste        error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2193254721Semaste    }
2194254721Semaste    return 0;
2195254721Semaste}
2196254721Semaste
2197254721Semastelldb::addr_t
2198254721SemasteProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2199254721Semaste{
2200254721Semaste    addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2201254721Semaste
2202254721Semaste    LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2203254721Semaste    switch (supported)
2204254721Semaste    {
2205254721Semaste        case eLazyBoolCalculate:
2206254721Semaste        case eLazyBoolYes:
2207254721Semaste            allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2208254721Semaste            if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2209254721Semaste                return allocated_addr;
2210254721Semaste
2211254721Semaste        case eLazyBoolNo:
2212254721Semaste            // Call mmap() to create memory in the inferior..
2213254721Semaste            unsigned prot = 0;
2214254721Semaste            if (permissions & lldb::ePermissionsReadable)
2215254721Semaste                prot |= eMmapProtRead;
2216254721Semaste            if (permissions & lldb::ePermissionsWritable)
2217254721Semaste                prot |= eMmapProtWrite;
2218254721Semaste            if (permissions & lldb::ePermissionsExecutable)
2219254721Semaste                prot |= eMmapProtExec;
2220254721Semaste
2221254721Semaste            if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2222254721Semaste                                 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2223254721Semaste                m_addr_to_mmap_size[allocated_addr] = size;
2224254721Semaste            else
2225254721Semaste                allocated_addr = LLDB_INVALID_ADDRESS;
2226254721Semaste            break;
2227254721Semaste    }
2228254721Semaste
2229254721Semaste    if (allocated_addr == LLDB_INVALID_ADDRESS)
2230254721Semaste        error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
2231254721Semaste    else
2232254721Semaste        error.Clear();
2233254721Semaste    return allocated_addr;
2234254721Semaste}
2235254721Semaste
2236254721SemasteError
2237254721SemasteProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2238254721Semaste                                       MemoryRegionInfo &region_info)
2239254721Semaste{
2240254721Semaste
2241254721Semaste    Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2242254721Semaste    return error;
2243254721Semaste}
2244254721Semaste
2245254721SemasteError
2246254721SemasteProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2247254721Semaste{
2248254721Semaste
2249254721Semaste    Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2250254721Semaste    return error;
2251254721Semaste}
2252254721Semaste
2253254721SemasteError
2254254721SemasteProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2255254721Semaste{
2256254721Semaste    Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2257254721Semaste    return error;
2258254721Semaste}
2259254721Semaste
2260254721SemasteError
2261254721SemasteProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2262254721Semaste{
2263254721Semaste    Error error;
2264254721Semaste    LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2265254721Semaste
2266254721Semaste    switch (supported)
2267254721Semaste    {
2268254721Semaste        case eLazyBoolCalculate:
2269254721Semaste            // We should never be deallocating memory without allocating memory
2270254721Semaste            // first so we should never get eLazyBoolCalculate
2271254721Semaste            error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2272254721Semaste            break;
2273254721Semaste
2274254721Semaste        case eLazyBoolYes:
2275254721Semaste            if (!m_gdb_comm.DeallocateMemory (addr))
2276254721Semaste                error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2277254721Semaste            break;
2278254721Semaste
2279254721Semaste        case eLazyBoolNo:
2280254721Semaste            // Call munmap() to deallocate memory in the inferior..
2281254721Semaste            {
2282254721Semaste                MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2283254721Semaste                if (pos != m_addr_to_mmap_size.end() &&
2284254721Semaste                    InferiorCallMunmap(this, addr, pos->second))
2285254721Semaste                    m_addr_to_mmap_size.erase (pos);
2286254721Semaste                else
2287254721Semaste                    error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2288254721Semaste            }
2289254721Semaste            break;
2290254721Semaste    }
2291254721Semaste
2292254721Semaste    return error;
2293254721Semaste}
2294254721Semaste
2295254721Semaste
2296254721Semaste//------------------------------------------------------------------
2297254721Semaste// Process STDIO
2298254721Semaste//------------------------------------------------------------------
2299254721Semastesize_t
2300254721SemasteProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2301254721Semaste{
2302254721Semaste    if (m_stdio_communication.IsConnected())
2303254721Semaste    {
2304254721Semaste        ConnectionStatus status;
2305254721Semaste        m_stdio_communication.Write(src, src_len, status, NULL);
2306254721Semaste    }
2307254721Semaste    return 0;
2308254721Semaste}
2309254721Semaste
2310254721SemasteError
2311254721SemasteProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
2312254721Semaste{
2313254721Semaste    Error error;
2314269024Semaste    assert(bp_site != NULL);
2315254721Semaste
2316269024Semaste    // Get logging info
2317269024Semaste    Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2318254721Semaste    user_id_t site_id = bp_site->GetID();
2319269024Semaste
2320269024Semaste    // Get the breakpoint address
2321254721Semaste    const addr_t addr = bp_site->GetLoadAddress();
2322269024Semaste
2323269024Semaste    // Log that a breakpoint was requested
2324254721Semaste    if (log)
2325269024Semaste        log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2326254721Semaste
2327269024Semaste    // Breakpoint already exists and is enabled
2328254721Semaste    if (bp_site->IsEnabled())
2329254721Semaste    {
2330254721Semaste        if (log)
2331269024Semaste            log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
2332254721Semaste        return error;
2333254721Semaste    }
2334269024Semaste
2335269024Semaste    // Get the software breakpoint trap opcode size
2336269024Semaste    const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2337269024Semaste
2338269024Semaste    // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2339269024Semaste    // is supported by the remote stub. These are set to true by default, and later set to false
2340269024Semaste    // only after we receive an unimplemented response when sending a breakpoint packet. This means
2341269024Semaste    // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2342269024Semaste    // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2343269024Semaste    // indicates if the user specifically asked for hardware breakpoints.  If true then we will
2344269024Semaste    // skip over software breakpoints.
2345269024Semaste    if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2346254721Semaste    {
2347269024Semaste        // Try to send off a software breakpoint packet ($Z0)
2348269024Semaste        if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2349269024Semaste        {
2350269024Semaste            // The breakpoint was placed successfully
2351269024Semaste            bp_site->SetEnabled(true);
2352269024Semaste            bp_site->SetType(BreakpointSite::eExternal);
2353269024Semaste            return error;
2354269024Semaste        }
2355254721Semaste
2356269024Semaste        // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2357269024Semaste        // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2358269024Semaste        // or if we have learned that this breakpoint type is unsupported. To do this, we
2359269024Semaste        // must test the support boolean for this breakpoint type to see if it now indicates that
2360269024Semaste        // this breakpoint type is unsupported.  If they are still supported then we should return
2361269024Semaste        // with the error code.  If they are now unsupported, then we would like to fall through
2362269024Semaste        // and try another form of breakpoint.
2363269024Semaste        if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2364269024Semaste            return error;
2365269024Semaste
2366269024Semaste        // We reach here when software breakpoints have been found to be unsupported. For future
2367269024Semaste        // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2368269024Semaste        // known not to be supported.
2369269024Semaste        if (log)
2370269024Semaste            log->Printf("Software breakpoints are unsupported");
2371269024Semaste
2372269024Semaste        // So we will fall through and try a hardware breakpoint
2373269024Semaste    }
2374269024Semaste
2375269024Semaste    // The process of setting a hardware breakpoint is much the same as above.  We check the
2376269024Semaste    // supported boolean for this breakpoint type, and if it is thought to be supported then we
2377269024Semaste    // will try to set this breakpoint with a hardware breakpoint.
2378269024Semaste    if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2379269024Semaste    {
2380269024Semaste        // Try to send off a hardware breakpoint packet ($Z1)
2381269024Semaste        if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
2382254721Semaste        {
2383269024Semaste            // The breakpoint was placed successfully
2384269024Semaste            bp_site->SetEnabled(true);
2385269024Semaste            bp_site->SetType(BreakpointSite::eHardware);
2386263363Semaste            return error;
2387254721Semaste        }
2388269024Semaste
2389269024Semaste        // Check if the error was something other then an unsupported breakpoint type
2390269024Semaste        if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2391254721Semaste        {
2392269024Semaste            // Unable to set this hardware breakpoint
2393269024Semaste            error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2394269024Semaste            return error;
2395254721Semaste        }
2396254721Semaste
2397269024Semaste        // We will reach here when the stub gives an unsported response to a hardware breakpoint
2398269024Semaste        if (log)
2399269024Semaste            log->Printf("Hardware breakpoints are unsupported");
2400269024Semaste
2401269024Semaste        // Finally we will falling through to a #trap style breakpoint
2402254721Semaste    }
2403254721Semaste
2404269024Semaste    // Don't fall through when hardware breakpoints were specifically requested
2405269024Semaste    if (bp_site->HardwareRequired())
2406254721Semaste    {
2407269024Semaste        error.SetErrorString("hardware breakpoints are not supported");
2408269024Semaste        return error;
2409254721Semaste    }
2410269024Semaste
2411269024Semaste    // As a last resort we want to place a manual breakpoint. An instruction
2412269024Semaste    // is placed into the process memory using memory write packets.
2413269024Semaste    return EnableSoftwareBreakpoint(bp_site);
2414254721Semaste}
2415254721Semaste
2416254721SemasteError
2417254721SemasteProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
2418254721Semaste{
2419254721Semaste    Error error;
2420254721Semaste    assert (bp_site != NULL);
2421254721Semaste    addr_t addr = bp_site->GetLoadAddress();
2422254721Semaste    user_id_t site_id = bp_site->GetID();
2423254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2424254721Semaste    if (log)
2425254721Semaste        log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
2426254721Semaste
2427254721Semaste    if (bp_site->IsEnabled())
2428254721Semaste    {
2429254721Semaste        const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2430254721Semaste
2431254721Semaste        BreakpointSite::Type bp_type = bp_site->GetType();
2432254721Semaste        switch (bp_type)
2433254721Semaste        {
2434254721Semaste        case BreakpointSite::eSoftware:
2435254721Semaste            error = DisableSoftwareBreakpoint (bp_site);
2436254721Semaste            break;
2437254721Semaste
2438254721Semaste        case BreakpointSite::eHardware:
2439269024Semaste            if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
2440254721Semaste                error.SetErrorToGenericError();
2441254721Semaste            break;
2442254721Semaste
2443254721Semaste        case BreakpointSite::eExternal:
2444254721Semaste            if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2445254721Semaste                error.SetErrorToGenericError();
2446254721Semaste            break;
2447254721Semaste        }
2448254721Semaste        if (error.Success())
2449254721Semaste            bp_site->SetEnabled(false);
2450254721Semaste    }
2451254721Semaste    else
2452254721Semaste    {
2453254721Semaste        if (log)
2454254721Semaste            log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
2455254721Semaste        return error;
2456254721Semaste    }
2457254721Semaste
2458254721Semaste    if (error.Success())
2459254721Semaste        error.SetErrorToGenericError();
2460254721Semaste    return error;
2461254721Semaste}
2462254721Semaste
2463254721Semaste// Pre-requisite: wp != NULL.
2464254721Semastestatic GDBStoppointType
2465254721SemasteGetGDBStoppointType (Watchpoint *wp)
2466254721Semaste{
2467254721Semaste    assert(wp);
2468254721Semaste    bool watch_read = wp->WatchpointRead();
2469254721Semaste    bool watch_write = wp->WatchpointWrite();
2470254721Semaste
2471254721Semaste    // watch_read and watch_write cannot both be false.
2472254721Semaste    assert(watch_read || watch_write);
2473254721Semaste    if (watch_read && watch_write)
2474254721Semaste        return eWatchpointReadWrite;
2475254721Semaste    else if (watch_read)
2476254721Semaste        return eWatchpointRead;
2477254721Semaste    else // Must be watch_write, then.
2478254721Semaste        return eWatchpointWrite;
2479254721Semaste}
2480254721Semaste
2481254721SemasteError
2482254721SemasteProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
2483254721Semaste{
2484254721Semaste    Error error;
2485254721Semaste    if (wp)
2486254721Semaste    {
2487254721Semaste        user_id_t watchID = wp->GetID();
2488254721Semaste        addr_t addr = wp->GetLoadAddress();
2489254721Semaste        Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2490254721Semaste        if (log)
2491254721Semaste            log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
2492254721Semaste        if (wp->IsEnabled())
2493254721Semaste        {
2494254721Semaste            if (log)
2495254721Semaste                log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
2496254721Semaste            return error;
2497254721Semaste        }
2498254721Semaste
2499254721Semaste        GDBStoppointType type = GetGDBStoppointType(wp);
2500254721Semaste        // Pass down an appropriate z/Z packet...
2501254721Semaste        if (m_gdb_comm.SupportsGDBStoppointPacket (type))
2502254721Semaste        {
2503254721Semaste            if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2504254721Semaste            {
2505254721Semaste                wp->SetEnabled(true, notify);
2506254721Semaste                return error;
2507254721Semaste            }
2508254721Semaste            else
2509254721Semaste                error.SetErrorString("sending gdb watchpoint packet failed");
2510254721Semaste        }
2511254721Semaste        else
2512254721Semaste            error.SetErrorString("watchpoints not supported");
2513254721Semaste    }
2514254721Semaste    else
2515254721Semaste    {
2516254721Semaste        error.SetErrorString("Watchpoint argument was NULL.");
2517254721Semaste    }
2518254721Semaste    if (error.Success())
2519254721Semaste        error.SetErrorToGenericError();
2520254721Semaste    return error;
2521254721Semaste}
2522254721Semaste
2523254721SemasteError
2524254721SemasteProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
2525254721Semaste{
2526254721Semaste    Error error;
2527254721Semaste    if (wp)
2528254721Semaste    {
2529254721Semaste        user_id_t watchID = wp->GetID();
2530254721Semaste
2531254721Semaste        Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2532254721Semaste
2533254721Semaste        addr_t addr = wp->GetLoadAddress();
2534254721Semaste
2535254721Semaste        if (log)
2536254721Semaste            log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
2537254721Semaste
2538254721Semaste        if (!wp->IsEnabled())
2539254721Semaste        {
2540254721Semaste            if (log)
2541254721Semaste                log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
2542254721Semaste            // See also 'class WatchpointSentry' within StopInfo.cpp.
2543254721Semaste            // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2544254721Semaste            // the watchpoint object to intelligently process this action.
2545254721Semaste            wp->SetEnabled(false, notify);
2546254721Semaste            return error;
2547254721Semaste        }
2548254721Semaste
2549254721Semaste        if (wp->IsHardware())
2550254721Semaste        {
2551254721Semaste            GDBStoppointType type = GetGDBStoppointType(wp);
2552254721Semaste            // Pass down an appropriate z/Z packet...
2553254721Semaste            if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2554254721Semaste            {
2555254721Semaste                wp->SetEnabled(false, notify);
2556254721Semaste                return error;
2557254721Semaste            }
2558254721Semaste            else
2559254721Semaste                error.SetErrorString("sending gdb watchpoint packet failed");
2560254721Semaste        }
2561254721Semaste        // TODO: clear software watchpoints if we implement them
2562254721Semaste    }
2563254721Semaste    else
2564254721Semaste    {
2565254721Semaste        error.SetErrorString("Watchpoint argument was NULL.");
2566254721Semaste    }
2567254721Semaste    if (error.Success())
2568254721Semaste        error.SetErrorToGenericError();
2569254721Semaste    return error;
2570254721Semaste}
2571254721Semaste
2572254721Semastevoid
2573254721SemasteProcessGDBRemote::Clear()
2574254721Semaste{
2575254721Semaste    m_flags = 0;
2576254721Semaste    m_thread_list_real.Clear();
2577254721Semaste    m_thread_list.Clear();
2578254721Semaste}
2579254721Semaste
2580254721SemasteError
2581254721SemasteProcessGDBRemote::DoSignal (int signo)
2582254721Semaste{
2583254721Semaste    Error error;
2584254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2585254721Semaste    if (log)
2586254721Semaste        log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2587254721Semaste
2588254721Semaste    if (!m_gdb_comm.SendAsyncSignal (signo))
2589254721Semaste        error.SetErrorStringWithFormat("failed to send signal %i", signo);
2590254721Semaste    return error;
2591254721Semaste}
2592254721Semaste
2593254721SemasteError
2594269024SemasteProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
2595254721Semaste{
2596254721Semaste    Error error;
2597254721Semaste    if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2598254721Semaste    {
2599254721Semaste        // If we locate debugserver, keep that located version around
2600254721Semaste        static FileSpec g_debugserver_file_spec;
2601254721Semaste
2602254721Semaste        ProcessLaunchInfo debugserver_launch_info;
2603269024Semaste        debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2604269024Semaste        debugserver_launch_info.SetUserID(process_info.GetUserID());
2605254721Semaste
2606269024Semaste#if defined (__APPLE__) && defined (__arm__)
2607269024Semaste        // On iOS, still do a local connection using a random port
2608269024Semaste        const char *hostname = "localhost";
2609269024Semaste        uint16_t port = get_random_port ();
2610269024Semaste#else
2611269024Semaste        // Set hostname being NULL to do the reverse connect where debugserver
2612269024Semaste        // will bind to port zero and it will communicate back to us the port
2613269024Semaste        // that we will connect to
2614269024Semaste        const char *hostname = NULL;
2615269024Semaste        uint16_t port = 0;
2616269024Semaste#endif
2617269024Semaste
2618269024Semaste        error = m_gdb_comm.StartDebugserverProcess (hostname,
2619269024Semaste                                                    port,
2620269024Semaste                                                    debugserver_launch_info,
2621269024Semaste                                                    port);
2622269024Semaste
2623269024Semaste        if (error.Success ())
2624269024Semaste            m_debugserver_pid = debugserver_launch_info.GetProcessID();
2625254721Semaste        else
2626269024Semaste            m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2627254721Semaste
2628269024Semaste        if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2629269024Semaste            StartAsyncThread ();
2630269024Semaste
2631269024Semaste        if (error.Fail())
2632254721Semaste        {
2633254721Semaste            Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2634254721Semaste
2635254721Semaste            if (log)
2636269024Semaste                log->Printf("failed to start debugserver process: %s", error.AsCString());
2637269024Semaste            return error;
2638254721Semaste        }
2639269024Semaste
2640269024Semaste        if (m_gdb_comm.IsConnected())
2641269024Semaste        {
2642269024Semaste            // Finish the connection process by doing the handshake without connecting (send NULL URL)
2643269024Semaste            ConnectToDebugserver (NULL);
2644269024Semaste        }
2645254721Semaste        else
2646254721Semaste        {
2647269024Semaste            StreamString connect_url;
2648269024Semaste            connect_url.Printf("connect://%s:%u", hostname, port);
2649269024Semaste            error = ConnectToDebugserver (connect_url.GetString().c_str());
2650254721Semaste        }
2651254721Semaste
2652254721Semaste    }
2653254721Semaste    return error;
2654254721Semaste}
2655254721Semaste
2656254721Semastebool
2657254721SemasteProcessGDBRemote::MonitorDebugserverProcess
2658254721Semaste(
2659254721Semaste    void *callback_baton,
2660254721Semaste    lldb::pid_t debugserver_pid,
2661254721Semaste    bool exited,        // True if the process did exit
2662254721Semaste    int signo,          // Zero for no signal
2663254721Semaste    int exit_status     // Exit value of process if signal is zero
2664254721Semaste)
2665254721Semaste{
2666254721Semaste    // The baton is a "ProcessGDBRemote *". Now this class might be gone
2667254721Semaste    // and might not exist anymore, so we need to carefully try to get the
2668254721Semaste    // target for this process first since we have a race condition when
2669254721Semaste    // we are done running between getting the notice that the inferior
2670254721Semaste    // process has died and the debugserver that was debugging this process.
2671254721Semaste    // In our test suite, we are also continually running process after
2672254721Semaste    // process, so we must be very careful to make sure:
2673254721Semaste    // 1 - process object hasn't been deleted already
2674254721Semaste    // 2 - that a new process object hasn't been recreated in its place
2675254721Semaste
2676254721Semaste    // "debugserver_pid" argument passed in is the process ID for
2677254721Semaste    // debugserver that we are tracking...
2678254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2679254721Semaste
2680254721Semaste    ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2681254721Semaste
2682254721Semaste    // Get a shared pointer to the target that has a matching process pointer.
2683254721Semaste    // This target could be gone, or the target could already have a new process
2684254721Semaste    // object inside of it
2685254721Semaste    TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2686254721Semaste
2687254721Semaste    if (log)
2688254721Semaste        log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2689254721Semaste
2690254721Semaste    if (target_sp)
2691254721Semaste    {
2692254721Semaste        // We found a process in a target that matches, but another thread
2693254721Semaste        // might be in the process of launching a new process that will
2694254721Semaste        // soon replace it, so get a shared pointer to the process so we
2695254721Semaste        // can keep it alive.
2696254721Semaste        ProcessSP process_sp (target_sp->GetProcessSP());
2697254721Semaste        // Now we have a shared pointer to the process that can't go away on us
2698254721Semaste        // so we now make sure it was the same as the one passed in, and also make
2699254721Semaste        // sure that our previous "process *" didn't get deleted and have a new
2700254721Semaste        // "process *" created in its place with the same pointer. To verify this
2701254721Semaste        // we make sure the process has our debugserver process ID. If we pass all
2702254721Semaste        // of these tests, then we are sure that this process is the one we were
2703254721Semaste        // looking for.
2704254721Semaste        if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
2705254721Semaste        {
2706254721Semaste            // Sleep for a half a second to make sure our inferior process has
2707254721Semaste            // time to set its exit status before we set it incorrectly when
2708254721Semaste            // both the debugserver and the inferior process shut down.
2709254721Semaste            usleep (500000);
2710254721Semaste            // If our process hasn't yet exited, debugserver might have died.
2711254721Semaste            // If the process did exit, the we are reaping it.
2712254721Semaste            const StateType state = process->GetState();
2713254721Semaste
2714254721Semaste            if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2715254721Semaste                state != eStateInvalid &&
2716254721Semaste                state != eStateUnloaded &&
2717254721Semaste                state != eStateExited &&
2718254721Semaste                state != eStateDetached)
2719254721Semaste            {
2720254721Semaste                char error_str[1024];
2721254721Semaste                if (signo)
2722254721Semaste                {
2723254721Semaste                    const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2724254721Semaste                    if (signal_cstr)
2725254721Semaste                        ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2726254721Semaste                    else
2727254721Semaste                        ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2728254721Semaste                }
2729254721Semaste                else
2730254721Semaste                {
2731254721Semaste                    ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2732254721Semaste                }
2733254721Semaste
2734254721Semaste                process->SetExitStatus (-1, error_str);
2735254721Semaste            }
2736254721Semaste            // Debugserver has exited we need to let our ProcessGDBRemote
2737254721Semaste            // know that it no longer has a debugserver instance
2738254721Semaste            process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2739254721Semaste        }
2740254721Semaste    }
2741254721Semaste    return true;
2742254721Semaste}
2743254721Semaste
2744254721Semastevoid
2745254721SemasteProcessGDBRemote::KillDebugserverProcess ()
2746254721Semaste{
2747263367Semaste    m_gdb_comm.Disconnect();
2748254721Semaste    if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2749254721Semaste    {
2750263363Semaste        Host::Kill (m_debugserver_pid, SIGINT);
2751254721Semaste        m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2752254721Semaste    }
2753254721Semaste}
2754254721Semaste
2755254721Semastevoid
2756254721SemasteProcessGDBRemote::Initialize()
2757254721Semaste{
2758254721Semaste    static bool g_initialized = false;
2759254721Semaste
2760254721Semaste    if (g_initialized == false)
2761254721Semaste    {
2762254721Semaste        g_initialized = true;
2763254721Semaste        PluginManager::RegisterPlugin (GetPluginNameStatic(),
2764254721Semaste                                       GetPluginDescriptionStatic(),
2765254721Semaste                                       CreateInstance,
2766254721Semaste                                       DebuggerInitialize);
2767254721Semaste
2768254721Semaste        Log::Callbacks log_callbacks = {
2769254721Semaste            ProcessGDBRemoteLog::DisableLog,
2770254721Semaste            ProcessGDBRemoteLog::EnableLog,
2771254721Semaste            ProcessGDBRemoteLog::ListLogCategories
2772254721Semaste        };
2773254721Semaste
2774254721Semaste        Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2775254721Semaste    }
2776254721Semaste}
2777254721Semaste
2778254721Semastevoid
2779254721SemasteProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2780254721Semaste{
2781254721Semaste    if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2782254721Semaste    {
2783254721Semaste        const bool is_global_setting = true;
2784254721Semaste        PluginManager::CreateSettingForProcessPlugin (debugger,
2785254721Semaste                                                      GetGlobalPluginProperties()->GetValueProperties(),
2786254721Semaste                                                      ConstString ("Properties for the gdb-remote process plug-in."),
2787254721Semaste                                                      is_global_setting);
2788254721Semaste    }
2789254721Semaste}
2790254721Semaste
2791254721Semastebool
2792254721SemasteProcessGDBRemote::StartAsyncThread ()
2793254721Semaste{
2794254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2795254721Semaste
2796254721Semaste    if (log)
2797254721Semaste        log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2798254721Semaste
2799254721Semaste    Mutex::Locker start_locker(m_async_thread_state_mutex);
2800254721Semaste    if (m_async_thread_state == eAsyncThreadNotStarted)
2801254721Semaste    {
2802254721Semaste        // Create a thread that watches our internal state and controls which
2803254721Semaste        // events make it to clients (into the DCProcess event queue).
2804254721Semaste        m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2805254721Semaste        if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2806254721Semaste        {
2807254721Semaste            m_async_thread_state = eAsyncThreadRunning;
2808254721Semaste            return true;
2809254721Semaste        }
2810254721Semaste        else
2811254721Semaste            return false;
2812254721Semaste    }
2813254721Semaste    else
2814254721Semaste    {
2815254721Semaste        // Somebody tried to start the async thread while it was either being started or stopped.  If the former, and
2816254721Semaste        // it started up successfully, then say all's well.  Otherwise it is an error, since we aren't going to restart it.
2817254721Semaste        if (log)
2818254721Semaste            log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2819254721Semaste        if (m_async_thread_state == eAsyncThreadRunning)
2820254721Semaste            return true;
2821254721Semaste        else
2822254721Semaste            return false;
2823254721Semaste    }
2824254721Semaste}
2825254721Semaste
2826254721Semastevoid
2827254721SemasteProcessGDBRemote::StopAsyncThread ()
2828254721Semaste{
2829254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2830254721Semaste
2831254721Semaste    if (log)
2832254721Semaste        log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2833254721Semaste
2834254721Semaste    Mutex::Locker start_locker(m_async_thread_state_mutex);
2835254721Semaste    if (m_async_thread_state == eAsyncThreadRunning)
2836254721Semaste    {
2837254721Semaste        m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2838254721Semaste
2839254721Semaste        //  This will shut down the async thread.
2840254721Semaste        m_gdb_comm.Disconnect();    // Disconnect from the debug server.
2841254721Semaste
2842254721Semaste        // Stop the stdio thread
2843254721Semaste        if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2844254721Semaste        {
2845254721Semaste            Host::ThreadJoin (m_async_thread, NULL, NULL);
2846254721Semaste        }
2847254721Semaste        m_async_thread_state = eAsyncThreadDone;
2848254721Semaste    }
2849254721Semaste    else
2850254721Semaste    {
2851254721Semaste        if (log)
2852254721Semaste            log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2853254721Semaste    }
2854254721Semaste}
2855254721Semaste
2856254721Semaste
2857263363Semastethread_result_t
2858254721SemasteProcessGDBRemote::AsyncThread (void *arg)
2859254721Semaste{
2860254721Semaste    ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2861254721Semaste
2862254721Semaste    Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2863254721Semaste    if (log)
2864254721Semaste        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
2865254721Semaste
2866254721Semaste    Listener listener ("ProcessGDBRemote::AsyncThread");
2867254721Semaste    EventSP event_sp;
2868254721Semaste    const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2869254721Semaste                                        eBroadcastBitAsyncThreadShouldExit;
2870254721Semaste
2871254721Semaste    if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2872254721Semaste    {
2873254721Semaste        listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2874254721Semaste
2875254721Semaste        bool done = false;
2876254721Semaste        while (!done)
2877254721Semaste        {
2878254721Semaste            if (log)
2879254721Semaste                log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2880254721Semaste            if (listener.WaitForEvent (NULL, event_sp))
2881254721Semaste            {
2882254721Semaste                const uint32_t event_type = event_sp->GetType();
2883254721Semaste                if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
2884254721Semaste                {
2885254721Semaste                    if (log)
2886254721Semaste                        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2887254721Semaste
2888254721Semaste                    switch (event_type)
2889254721Semaste                    {
2890254721Semaste                        case eBroadcastBitAsyncContinue:
2891254721Semaste                            {
2892254721Semaste                                const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2893254721Semaste
2894254721Semaste                                if (continue_packet)
2895254721Semaste                                {
2896254721Semaste                                    const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2897254721Semaste                                    const size_t continue_cstr_len = continue_packet->GetByteSize ();
2898254721Semaste                                    if (log)
2899254721Semaste                                        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2900254721Semaste
2901254721Semaste                                    if (::strstr (continue_cstr, "vAttach") == NULL)
2902254721Semaste                                        process->SetPrivateState(eStateRunning);
2903254721Semaste                                    StringExtractorGDBRemote response;
2904254721Semaste                                    StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2905254721Semaste
2906254721Semaste                                    // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2907254721Semaste                                    // The thread ID list might be contained within the "response", or the stop reply packet that
2908254721Semaste                                    // caused the stop. So clear it now before we give the stop reply packet to the process
2909254721Semaste                                    // using the process->SetLastStopPacket()...
2910254721Semaste                                    process->ClearThreadIDList ();
2911254721Semaste
2912254721Semaste                                    switch (stop_state)
2913254721Semaste                                    {
2914254721Semaste                                    case eStateStopped:
2915254721Semaste                                    case eStateCrashed:
2916254721Semaste                                    case eStateSuspended:
2917254721Semaste                                        process->SetLastStopPacket (response);
2918254721Semaste                                        process->SetPrivateState (stop_state);
2919254721Semaste                                        break;
2920254721Semaste
2921254721Semaste                                    case eStateExited:
2922254721Semaste                                        process->SetLastStopPacket (response);
2923254721Semaste                                        process->ClearThreadIDList();
2924254721Semaste                                        response.SetFilePos(1);
2925254721Semaste                                        process->SetExitStatus(response.GetHexU8(), NULL);
2926254721Semaste                                        done = true;
2927254721Semaste                                        break;
2928254721Semaste
2929254721Semaste                                    case eStateInvalid:
2930254721Semaste                                        process->SetExitStatus(-1, "lost connection");
2931254721Semaste                                        break;
2932254721Semaste
2933254721Semaste                                    default:
2934254721Semaste                                        process->SetPrivateState (stop_state);
2935254721Semaste                                        break;
2936254721Semaste                                    }
2937254721Semaste                                }
2938254721Semaste                            }
2939254721Semaste                            break;
2940254721Semaste
2941254721Semaste                        case eBroadcastBitAsyncThreadShouldExit:
2942254721Semaste                            if (log)
2943254721Semaste                                log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2944254721Semaste                            done = true;
2945254721Semaste                            break;
2946254721Semaste
2947254721Semaste                        default:
2948254721Semaste                            if (log)
2949254721Semaste                                log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2950254721Semaste                            done = true;
2951254721Semaste                            break;
2952254721Semaste                    }
2953254721Semaste                }
2954254721Semaste                else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2955254721Semaste                {
2956254721Semaste                    if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2957254721Semaste                    {
2958254721Semaste                        process->SetExitStatus (-1, "lost connection");
2959254721Semaste                        done = true;
2960254721Semaste                    }
2961254721Semaste                }
2962254721Semaste            }
2963254721Semaste            else
2964254721Semaste            {
2965254721Semaste                if (log)
2966254721Semaste                    log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2967254721Semaste                done = true;
2968254721Semaste            }
2969254721Semaste        }
2970254721Semaste    }
2971254721Semaste
2972254721Semaste    if (log)
2973254721Semaste        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
2974254721Semaste
2975254721Semaste    process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2976254721Semaste    return NULL;
2977254721Semaste}
2978254721Semaste
2979254721Semaste//uint32_t
2980254721Semaste//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2981254721Semaste//{
2982254721Semaste//    // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2983254721Semaste//    // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2984254721Semaste//    if (m_local_debugserver)
2985254721Semaste//    {
2986254721Semaste//        return Host::ListProcessesMatchingName (name, matches, pids);
2987254721Semaste//    }
2988254721Semaste//    else
2989254721Semaste//    {
2990254721Semaste//        // FIXME: Implement talking to the remote debugserver.
2991254721Semaste//        return 0;
2992254721Semaste//    }
2993254721Semaste//
2994254721Semaste//}
2995254721Semaste//
2996254721Semastebool
2997254721SemasteProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2998254721Semaste                             lldb_private::StoppointCallbackContext *context,
2999254721Semaste                             lldb::user_id_t break_id,
3000254721Semaste                             lldb::user_id_t break_loc_id)
3001254721Semaste{
3002254721Semaste    // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3003254721Semaste    // run so I can stop it if that's what I want to do.
3004254721Semaste    Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3005254721Semaste    if (log)
3006254721Semaste        log->Printf("Hit New Thread Notification breakpoint.");
3007254721Semaste    return false;
3008254721Semaste}
3009254721Semaste
3010254721Semaste
3011254721Semastebool
3012254721SemasteProcessGDBRemote::StartNoticingNewThreads()
3013254721Semaste{
3014254721Semaste    Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3015254721Semaste    if (m_thread_create_bp_sp)
3016254721Semaste    {
3017254721Semaste        if (log && log->GetVerbose())
3018254721Semaste            log->Printf("Enabled noticing new thread breakpoint.");
3019254721Semaste        m_thread_create_bp_sp->SetEnabled(true);
3020254721Semaste    }
3021254721Semaste    else
3022254721Semaste    {
3023254721Semaste        PlatformSP platform_sp (m_target.GetPlatform());
3024254721Semaste        if (platform_sp)
3025254721Semaste        {
3026254721Semaste            m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3027254721Semaste            if (m_thread_create_bp_sp)
3028254721Semaste            {
3029254721Semaste                if (log && log->GetVerbose())
3030254721Semaste                    log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3031254721Semaste                m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3032254721Semaste            }
3033254721Semaste            else
3034254721Semaste            {
3035254721Semaste                if (log)
3036254721Semaste                    log->Printf("Failed to create new thread notification breakpoint.");
3037254721Semaste            }
3038254721Semaste        }
3039254721Semaste    }
3040254721Semaste    return m_thread_create_bp_sp.get() != NULL;
3041254721Semaste}
3042254721Semaste
3043254721Semastebool
3044254721SemasteProcessGDBRemote::StopNoticingNewThreads()
3045254721Semaste{
3046254721Semaste    Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3047254721Semaste    if (log && log->GetVerbose())
3048254721Semaste        log->Printf ("Disabling new thread notification breakpoint.");
3049254721Semaste
3050254721Semaste    if (m_thread_create_bp_sp)
3051254721Semaste        m_thread_create_bp_sp->SetEnabled(false);
3052254721Semaste
3053254721Semaste    return true;
3054254721Semaste}
3055254721Semaste
3056254721Semastelldb_private::DynamicLoader *
3057254721SemasteProcessGDBRemote::GetDynamicLoader ()
3058254721Semaste{
3059254721Semaste    if (m_dyld_ap.get() == NULL)
3060254721Semaste        m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3061254721Semaste    return m_dyld_ap.get();
3062254721Semaste}
3063254721Semaste
3064254721Semaste
3065254721Semasteclass CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
3066254721Semaste{
3067254721Semasteprivate:
3068254721Semaste
3069254721Semastepublic:
3070254721Semaste    CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
3071254721Semaste    CommandObjectParsed (interpreter,
3072254721Semaste                         "process plugin packet history",
3073254721Semaste                         "Dumps the packet history buffer. ",
3074254721Semaste                         NULL)
3075254721Semaste    {
3076254721Semaste    }
3077254721Semaste
3078254721Semaste    ~CommandObjectProcessGDBRemotePacketHistory ()
3079254721Semaste    {
3080254721Semaste    }
3081254721Semaste
3082254721Semaste    bool
3083254721Semaste    DoExecute (Args& command, CommandReturnObject &result)
3084254721Semaste    {
3085254721Semaste        const size_t argc = command.GetArgumentCount();
3086254721Semaste        if (argc == 0)
3087254721Semaste        {
3088254721Semaste            ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3089254721Semaste            if (process)
3090254721Semaste            {
3091254721Semaste                process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3092254721Semaste                result.SetStatus (eReturnStatusSuccessFinishResult);
3093254721Semaste                return true;
3094254721Semaste            }
3095254721Semaste        }
3096254721Semaste        else
3097254721Semaste        {
3098254721Semaste            result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3099254721Semaste        }
3100254721Semaste        result.SetStatus (eReturnStatusFailed);
3101254721Semaste        return false;
3102254721Semaste    }
3103254721Semaste};
3104254721Semaste
3105254721Semasteclass CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3106254721Semaste{
3107254721Semasteprivate:
3108254721Semaste
3109254721Semastepublic:
3110254721Semaste    CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3111254721Semaste        CommandObjectParsed (interpreter,
3112254721Semaste                             "process plugin packet send",
3113254721Semaste                             "Send a custom packet through the GDB remote protocol and print the answer. "
3114254721Semaste                             "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3115254721Semaste                             NULL)
3116254721Semaste    {
3117254721Semaste    }
3118254721Semaste
3119254721Semaste    ~CommandObjectProcessGDBRemotePacketSend ()
3120254721Semaste    {
3121254721Semaste    }
3122254721Semaste
3123254721Semaste    bool
3124254721Semaste    DoExecute (Args& command, CommandReturnObject &result)
3125254721Semaste    {
3126254721Semaste        const size_t argc = command.GetArgumentCount();
3127254721Semaste        if (argc == 0)
3128254721Semaste        {
3129254721Semaste            result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3130254721Semaste            result.SetStatus (eReturnStatusFailed);
3131254721Semaste            return false;
3132254721Semaste        }
3133254721Semaste
3134254721Semaste        ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3135254721Semaste        if (process)
3136254721Semaste        {
3137254721Semaste            for (size_t i=0; i<argc; ++ i)
3138254721Semaste            {
3139254721Semaste                const char *packet_cstr = command.GetArgumentAtIndex(0);
3140254721Semaste                bool send_async = true;
3141254721Semaste                StringExtractorGDBRemote response;
3142254721Semaste                process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3143254721Semaste                result.SetStatus (eReturnStatusSuccessFinishResult);
3144254721Semaste                Stream &output_strm = result.GetOutputStream();
3145254721Semaste                output_strm.Printf ("  packet: %s\n", packet_cstr);
3146254721Semaste                std::string &response_str = response.GetStringRef();
3147254721Semaste
3148254721Semaste                if (strstr(packet_cstr, "qGetProfileData") != NULL)
3149254721Semaste                {
3150254721Semaste                    response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3151254721Semaste                }
3152254721Semaste
3153254721Semaste                if (response_str.empty())
3154254721Semaste                    output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3155254721Semaste                else
3156254721Semaste                    output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3157254721Semaste            }
3158254721Semaste        }
3159254721Semaste        return true;
3160254721Semaste    }
3161254721Semaste};
3162254721Semaste
3163254721Semasteclass CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3164254721Semaste{
3165254721Semasteprivate:
3166254721Semaste
3167254721Semastepublic:
3168254721Semaste    CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3169254721Semaste        CommandObjectRaw (interpreter,
3170254721Semaste                         "process plugin packet monitor",
3171254721Semaste                         "Send a qRcmd packet through the GDB remote protocol and print the response."
3172254721Semaste                         "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
3173254721Semaste                         NULL)
3174254721Semaste    {
3175254721Semaste    }
3176254721Semaste
3177254721Semaste    ~CommandObjectProcessGDBRemotePacketMonitor ()
3178254721Semaste    {
3179254721Semaste    }
3180254721Semaste
3181254721Semaste    bool
3182254721Semaste    DoExecute (const char *command, CommandReturnObject &result)
3183254721Semaste    {
3184254721Semaste        if (command == NULL || command[0] == '\0')
3185254721Semaste        {
3186254721Semaste            result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3187254721Semaste            result.SetStatus (eReturnStatusFailed);
3188254721Semaste            return false;
3189254721Semaste        }
3190254721Semaste
3191254721Semaste        ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3192254721Semaste        if (process)
3193254721Semaste        {
3194254721Semaste            StreamString packet;
3195254721Semaste            packet.PutCString("qRcmd,");
3196254721Semaste            packet.PutBytesAsRawHex8(command, strlen(command));
3197254721Semaste            const char *packet_cstr = packet.GetString().c_str();
3198254721Semaste
3199254721Semaste            bool send_async = true;
3200254721Semaste            StringExtractorGDBRemote response;
3201254721Semaste            process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3202254721Semaste            result.SetStatus (eReturnStatusSuccessFinishResult);
3203254721Semaste            Stream &output_strm = result.GetOutputStream();
3204254721Semaste            output_strm.Printf ("  packet: %s\n", packet_cstr);
3205254721Semaste            const std::string &response_str = response.GetStringRef();
3206254721Semaste
3207254721Semaste            if (response_str.empty())
3208254721Semaste                output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3209254721Semaste            else
3210254721Semaste                output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3211254721Semaste        }
3212254721Semaste        return true;
3213254721Semaste    }
3214254721Semaste};
3215254721Semaste
3216254721Semasteclass CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3217254721Semaste{
3218254721Semasteprivate:
3219254721Semaste
3220254721Semastepublic:
3221254721Semaste    CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3222254721Semaste        CommandObjectMultiword (interpreter,
3223254721Semaste                                "process plugin packet",
3224254721Semaste                                "Commands that deal with GDB remote packets.",
3225254721Semaste                                NULL)
3226254721Semaste    {
3227254721Semaste        LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3228254721Semaste        LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3229254721Semaste        LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
3230254721Semaste    }
3231254721Semaste
3232254721Semaste    ~CommandObjectProcessGDBRemotePacket ()
3233254721Semaste    {
3234254721Semaste    }
3235254721Semaste};
3236254721Semaste
3237254721Semasteclass CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3238254721Semaste{
3239254721Semastepublic:
3240254721Semaste    CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3241254721Semaste        CommandObjectMultiword (interpreter,
3242254721Semaste                                "process plugin",
3243254721Semaste                                "A set of commands for operating on a ProcessGDBRemote process.",
3244254721Semaste                                "process plugin <subcommand> [<subcommand-options>]")
3245254721Semaste    {
3246254721Semaste        LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket    (interpreter)));
3247254721Semaste    }
3248254721Semaste
3249254721Semaste    ~CommandObjectMultiwordProcessGDBRemote ()
3250254721Semaste    {
3251254721Semaste    }
3252254721Semaste};
3253254721Semaste
3254254721SemasteCommandObject *
3255254721SemasteProcessGDBRemote::GetPluginCommandObject()
3256254721Semaste{
3257254721Semaste    if (!m_command_sp)
3258254721Semaste        m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3259254721Semaste    return m_command_sp.get();
3260254721Semaste}
3261