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