ProcessGDBRemote.cpp revision 7c4fc6eb2da25c0426519a2664e1d277766bf01b
111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//
311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//                     The LLVM Compiler Infrastructure
411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//
5058d9f7682548d3a024e84774bb153a6f72c06fcmikesamuel// This file is distributed under the University of Illinois Open Source
611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// License. See LICENSE.TXT for details.
711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//
811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//===----------------------------------------------------------------------===//
911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
10d5f0fce02f33f8d4535581d64c76965338f9e9acmikesamuel// C Includes
1111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <errno.h>
1211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <spawn.h>
1311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <stdlib.h>
1411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <sys/mman.h>       // for mmap
1511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <sys/stat.h>
1611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <sys/types.h>
1711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <time.h>
1811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
1911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// C++ Includes
2011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <algorithm>
2111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include <map>
2211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
2311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// Other libraries and framework includes
2411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
2511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Breakpoint/WatchpointLocation.h"
2611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Interpreter/Args.h"
2711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/ArchSpec.h"
2811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/Debugger.h"
2911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/ConnectionFileDescriptor.h"
3011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Host/FileSpec.h"
3111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/InputReader.h"
3211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/Module.h"
3311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/PluginManager.h"
3411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/State.h"
3511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/StreamString.h"
3611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/Timer.h"
3711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Core/Value.h"
3811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Host/TimeValue.h"
3904fec67bccd1004fba68e662ba9709747aa65d30mikesamuel#include "lldb/Symbol/ObjectFile.h"
4004fec67bccd1004fba68e662ba9709747aa65d30mikesamuel#include "lldb/Target/DynamicLoader.h"
4111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Target/Target.h"
4211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Target/TargetList.h"
4311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Target/ThreadPlanCallFunction.h"
4411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Utility/PseudoTerminal.h"
4511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
4611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// Project includes
4711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "lldb/Host/Host.h"
4811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
4911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "Utility/StringExtractorGDBRemote.h"
50e8ee9d6af3d6cfe64ce14b041aa1f1d57608e305mikesamuel#include "GDBRemoteRegisterContext.h"
5111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "ProcessGDBRemote.h"
5211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "ProcessGDBRemoteLog.h"
5311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "ThreadGDBRemote.h"
5411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#include "StopInfoMachException.h"
5511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
5611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
5711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
5811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel#define DEBUGSERVER_BASENAME    "debugserver"
5911de3758b3338ab796baa74df47f9a9a937ff103mikesamuelusing namespace lldb;
6011de3758b3338ab796baa74df47f9a9a937ff103mikesamuelusing namespace lldb_private;
6111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
6211de3758b3338ab796baa74df47f9a9a937ff103mikesamuelstatic bool rand_initialized = false;
6311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
6411de3758b3338ab796baa74df47f9a9a937ff103mikesamuelstatic inline uint16_t
6511de3758b3338ab796baa74df47f9a9a937ff103mikesamuelget_random_port ()
6611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
6711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    if (!rand_initialized)
6811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    {
6911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        time_t seed = time(NULL);
7011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
7111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        rand_initialized = true;
7211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        srand(seed);
7311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    }
7411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return (rand() % (UINT16_MAX - 1000u)) + 1000u;
7511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
7611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
7711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
7811de3758b3338ab796baa74df47f9a9a937ff103mikesamuelconst char *
7911de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::GetPluginNameStatic()
8011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
8111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return "gdb-remote";
8211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
8311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
8404fec67bccd1004fba68e662ba9709747aa65d30mikesamuelconst char *
8504fec67bccd1004fba68e662ba9709747aa65d30mikesamuelProcessGDBRemote::GetPluginDescriptionStatic()
8604fec67bccd1004fba68e662ba9709747aa65d30mikesamuel{
8704fec67bccd1004fba68e662ba9709747aa65d30mikesamuel    return "GDB Remote protocol based debugging plug-in.";
8804fec67bccd1004fba68e662ba9709747aa65d30mikesamuel}
8904fec67bccd1004fba68e662ba9709747aa65d30mikesamuel
9004fec67bccd1004fba68e662ba9709747aa65d30mikesamuelvoid
9104fec67bccd1004fba68e662ba9709747aa65d30mikesamuelProcessGDBRemote::Terminate()
9204fec67bccd1004fba68e662ba9709747aa65d30mikesamuel{
9304fec67bccd1004fba68e662ba9709747aa65d30mikesamuel    PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
9404fec67bccd1004fba68e662ba9709747aa65d30mikesamuel}
9504fec67bccd1004fba68e662ba9709747aa65d30mikesamuel
9604fec67bccd1004fba68e662ba9709747aa65d30mikesamuel
9704fec67bccd1004fba68e662ba9709747aa65d30mikesamuelProcess*
9804fec67bccd1004fba68e662ba9709747aa65d30mikesamuelProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
9911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
10011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return new ProcessGDBRemote (target, listener);
10111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
10211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
10311de3758b3338ab796baa74df47f9a9a937ff103mikesamuelbool
10411de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
10511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
10611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    // For now we are just making sure the file exists for a given module
10711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    ModuleSP exe_module_sp(target.GetExecutableModule());
10811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    if (exe_module_sp.get())
10911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        return exe_module_sp->GetFileSpec().Exists();
11011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    // However, if there is no executable module, we return true since we might be preparing to attach.
11111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return true;
11211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
11311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
11411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//----------------------------------------------------------------------
11511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// ProcessGDBRemote constructor
11611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//----------------------------------------------------------------------
11711de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
11811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    Process (target, listener),
11911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_flags (0),
12011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_stdio_mutex (Mutex::eMutexTypeRecursive),
12111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_gdb_comm(false),
12211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
12311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
12411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_last_stop_packet (),
12511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_register_info (),
12611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
12711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_async_thread (LLDB_INVALID_HOST_THREAD),
12811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_continue_c_tids (),
12911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_continue_C_tids (),
13011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_continue_s_tids (),
13111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_continue_S_tids (),
13211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
13311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_max_memory_size (512),
13411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_waiting_for_attach (false),
13511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_thread_observation_bps()
13611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
13711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit,   "async thread should exit");
13811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue,           "async thread continue");
13911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
14011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
14111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//----------------------------------------------------------------------
14211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// Destructor
14311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//----------------------------------------------------------------------
14411de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::~ProcessGDBRemote()
14511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
14611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
14711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    {
14811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        Host::ThreadCancel (m_debugserver_thread, NULL);
14911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        thread_result_t thread_result;
15011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
15111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
15211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    }
15311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    //  m_mach_process.UnregisterNotificationCallbacks (this);
15411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    Clear();
15511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
15611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
15711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//----------------------------------------------------------------------
15811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel// PluginInterface
15911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel//----------------------------------------------------------------------
16011de3758b3338ab796baa74df47f9a9a937ff103mikesamuelconst char *
16111de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::GetPluginName()
16211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
16311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return "Process debugging plug-in that uses the GDB remote protocol";
16411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
16511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
16611de3758b3338ab796baa74df47f9a9a937ff103mikesamuelconst char *
16711de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::GetShortPluginName()
16811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
16911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return GetPluginNameStatic();
17011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
17111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
17211de3758b3338ab796baa74df47f9a9a937ff103mikesamueluint32_t
173846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuelProcessGDBRemote::GetPluginVersion()
174846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuel{
17511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    return 1;
17611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel}
177846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuel
178846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuelvoid
17911de3758b3338ab796baa74df47f9a9a937ff103mikesamuelProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
18011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel{
18111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    if (!force && m_register_info.GetNumRegisters() > 0)
182846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuel        return;
183846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuel
18411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    char packet[128];
18511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    m_register_info.Clear();
186846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuel    uint32_t reg_offset = 0;
187846d5d0377617bd20ac271a486f07bfe757cc7a2mikesamuel    uint32_t reg_num = 0;
18811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    StringExtractorGDBRemote::ResponseType response_type;
18911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    for (response_type = StringExtractorGDBRemote::eResponse;
19011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel         response_type == StringExtractorGDBRemote::eResponse;
19111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel         ++reg_num)
19211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel    {
19311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
19411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        assert (packet_len < sizeof(packet));
19511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        StringExtractorGDBRemote response;
19611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
19711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel        {
19811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel            response_type = response.GetResponseType();
19911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel            if (response_type == StringExtractorGDBRemote::eResponse)
20011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel            {
20111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                std::string name;
20211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                std::string value;
20311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                ConstString reg_name;
20404fec67bccd1004fba68e662ba9709747aa65d30mikesamuel                ConstString alt_name;
20504fec67bccd1004fba68e662ba9709747aa65d30mikesamuel                ConstString set_name;
20611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                RegisterInfo reg_info = { NULL,                 // Name
20711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    NULL,                 // Alt name
20811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    0,                    // byte size
20911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    reg_offset,           // offset
21011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    eEncodingUint,        // encoding
21111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    eFormatHex,           // formate
21211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    {
21311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        LLDB_INVALID_REGNUM, // GCC reg num
21411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        LLDB_INVALID_REGNUM, // DWARF reg num
215e8ee9d6af3d6cfe64ce14b041aa1f1d57608e305mikesamuel                        LLDB_INVALID_REGNUM, // generic reg num
21611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        reg_num,             // GDB reg num
21711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        reg_num           // native register number
21811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    }
21911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                };
22011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel
22111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                while (response.GetNameColonValue(name, value))
22211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                {
22311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    if (name.compare("name") == 0)
22411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    {
22511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        reg_name.SetCString(value.c_str());
22611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    }
22711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    else if (name.compare("alt-name") == 0)
22811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    {
22911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        alt_name.SetCString(value.c_str());
23011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    }
23111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    else if (name.compare("bitsize") == 0)
23211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    {
23311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
23411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    }
23511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    else if (name.compare("offset") == 0)
23611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    {
23711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
23811de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        if (reg_offset != offset)
23911de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        {
24011de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                            reg_offset = offset;
24111de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        }
24211de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    }
24311de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    else if (name.compare("encoding") == 0)
24411de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                    {
24511de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        if (value.compare("uint") == 0)
24611de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                            reg_info.encoding = eEncodingUint;
24711de3758b3338ab796baa74df47f9a9a937ff103mikesamuel                        else if (value.compare("sint") == 0)
248                            reg_info.encoding = eEncodingSint;
249                        else if (value.compare("ieee754") == 0)
250                            reg_info.encoding = eEncodingIEEE754;
251                        else if (value.compare("vector") == 0)
252                            reg_info.encoding = eEncodingVector;
253                    }
254                    else if (name.compare("format") == 0)
255                    {
256                        if (value.compare("binary") == 0)
257                            reg_info.format = eFormatBinary;
258                        else if (value.compare("decimal") == 0)
259                            reg_info.format = eFormatDecimal;
260                        else if (value.compare("hex") == 0)
261                            reg_info.format = eFormatHex;
262                        else if (value.compare("float") == 0)
263                            reg_info.format = eFormatFloat;
264                        else if (value.compare("vector-sint8") == 0)
265                            reg_info.format = eFormatVectorOfSInt8;
266                        else if (value.compare("vector-uint8") == 0)
267                            reg_info.format = eFormatVectorOfUInt8;
268                        else if (value.compare("vector-sint16") == 0)
269                            reg_info.format = eFormatVectorOfSInt16;
270                        else if (value.compare("vector-uint16") == 0)
271                            reg_info.format = eFormatVectorOfUInt16;
272                        else if (value.compare("vector-sint32") == 0)
273                            reg_info.format = eFormatVectorOfSInt32;
274                        else if (value.compare("vector-uint32") == 0)
275                            reg_info.format = eFormatVectorOfUInt32;
276                        else if (value.compare("vector-float32") == 0)
277                            reg_info.format = eFormatVectorOfFloat32;
278                        else if (value.compare("vector-uint128") == 0)
279                            reg_info.format = eFormatVectorOfUInt128;
280                    }
281                    else if (name.compare("set") == 0)
282                    {
283                        set_name.SetCString(value.c_str());
284                    }
285                    else if (name.compare("gcc") == 0)
286                    {
287                        reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
288                    }
289                    else if (name.compare("dwarf") == 0)
290                    {
291                        reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292                    }
293                    else if (name.compare("generic") == 0)
294                    {
295                        if (value.compare("pc") == 0)
296                            reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
297                        else if (value.compare("sp") == 0)
298                            reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
299                        else if (value.compare("fp") == 0)
300                            reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
301                        else if (value.compare("ra") == 0)
302                            reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
303                        else if (value.compare("flags") == 0)
304                            reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
305                        else if (value.find("arg") == 0)
306                        {
307                            if (value.size() == 4)
308                            {
309                                switch (value[3])
310                                {
311                                    case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
312                                    case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
313                                    case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
314                                    case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
315                                    case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
316                                    case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
317                                    case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
318                                    case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
319                                }
320                            }
321                        }
322                    }
323                }
324
325                reg_info.byte_offset = reg_offset;
326                assert (reg_info.byte_size != 0);
327                reg_offset += reg_info.byte_size;
328                m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
329            }
330        }
331        else
332        {
333            response_type = StringExtractorGDBRemote::eError;
334            break;
335        }
336    }
337
338    if (reg_num == 0)
339    {
340        // We didn't get anything. See if we are debugging ARM and fill with
341        // a hard coded register set until we can get an updated debugserver
342        // down on the devices.
343        if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
344            m_register_info.HardcodeARMRegisters();
345    }
346    m_register_info.Finalize ();
347}
348
349Error
350ProcessGDBRemote::WillLaunch (Module* module)
351{
352    return WillLaunchOrAttach ();
353}
354
355Error
356ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
357{
358    return WillLaunchOrAttach ();
359}
360
361Error
362ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
363{
364    return WillLaunchOrAttach ();
365}
366
367Error
368ProcessGDBRemote::DoConnectRemote (const char *remote_url)
369{
370    Error error (WillLaunchOrAttach ());
371
372    if (error.Fail())
373        return error;
374
375    error = ConnectToDebugserver (remote_url);
376
377    if (error.Fail())
378        return error;
379    StartAsyncThread ();
380
381    lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
382    if (pid == LLDB_INVALID_PROCESS_ID)
383    {
384        // We don't have a valid process ID, so note that we are connected
385        // and could now request to launch or attach, or get remote process
386        // listings...
387        SetPrivateState (eStateConnected);
388    }
389    else
390    {
391        // We have a valid process
392        SetID (pid);
393        UpdateThreadListIfNeeded ();
394        if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
395        {
396            const StateType state = SetThreadStopInfo (m_last_stop_packet);
397            if (state == eStateStopped)
398            {
399                SetPrivateState (state);
400            }
401            else
402                error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
403        }
404        else
405            error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
406    }
407    return error;
408}
409
410Error
411ProcessGDBRemote::WillLaunchOrAttach ()
412{
413    Error error;
414    m_stdio_communication.Clear ();
415    return error;
416}
417
418//----------------------------------------------------------------------
419// Process Control
420//----------------------------------------------------------------------
421Error
422ProcessGDBRemote::DoLaunch
423(
424    Module* module,
425    char const *argv[],
426    char const *envp[],
427    uint32_t launch_flags,
428    const char *stdin_path,
429    const char *stdout_path,
430    const char *stderr_path,
431    const char *working_dir
432)
433{
434    Error error;
435    //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
436    //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
437    //  ::LogSetLogFile ("/dev/stdout");
438    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
439
440    ObjectFile * object_file = module->GetObjectFile();
441    if (object_file)
442    {
443        char host_port[128];
444        snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
445        char connect_url[128];
446        snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
447
448        // Make sure we aren't already connected?
449        if (!m_gdb_comm.IsConnected())
450        {
451            error = StartDebugserverProcess (host_port);
452            if (error.Fail())
453            {
454                if (log)
455                    log->Printf("failed to start debugserver process: %s", error.AsCString());
456                return error;
457            }
458
459            error = ConnectToDebugserver (connect_url);
460        }
461
462        if (error.Success())
463        {
464            lldb_utility::PseudoTerminal pty;
465            const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
466
467            // If the debugserver is local and we aren't disabling STDIO, lets use
468            // a pseudo terminal to instead of relying on the 'O' packets for stdio
469            // since 'O' packets can really slow down debugging if the inferior
470            // does a lot of output.
471            PlatformSP platform_sp (m_target.GetPlatform());
472            if (platform_sp && platform_sp->IsHost() && !disable_stdio)
473            {
474                const char *slave_name = NULL;
475                if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
476                {
477                    if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
478                        slave_name = pty.GetSlaveName (NULL, 0);
479                }
480                if (stdin_path == NULL)
481                    stdin_path = slave_name;
482
483                if (stdout_path == NULL)
484                    stdout_path = slave_name;
485
486                if (stderr_path == NULL)
487                    stderr_path = slave_name;
488            }
489
490            // Set STDIN to /dev/null if we want STDIO disabled or if either
491            // STDOUT or STDERR have been set to something and STDIN hasn't
492            if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
493                stdin_path = "/dev/null";
494
495            // Set STDOUT to /dev/null if we want STDIO disabled or if either
496            // STDIN or STDERR have been set to something and STDOUT hasn't
497            if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
498                stdout_path = "/dev/null";
499
500            // Set STDERR to /dev/null if we want STDIO disabled or if either
501            // STDIN or STDOUT have been set to something and STDERR hasn't
502            if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
503                stderr_path = "/dev/null";
504
505            if (stdin_path)
506                m_gdb_comm.SetSTDIN (stdin_path);
507            if (stdout_path)
508                m_gdb_comm.SetSTDOUT (stdout_path);
509            if (stderr_path)
510                m_gdb_comm.SetSTDERR (stderr_path);
511
512            m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
513
514            m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
515
516            if (working_dir && working_dir[0])
517            {
518                m_gdb_comm.SetWorkingDir (working_dir);
519            }
520
521            // Send the environment and the program + arguments after we connect
522            if (envp)
523            {
524                const char *env_entry;
525                for (int i=0; (env_entry = envp[i]); ++i)
526                {
527                    if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
528                        break;
529                }
530            }
531
532            const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
533            int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
534            if (arg_packet_err == 0)
535            {
536                std::string error_str;
537                if (m_gdb_comm.GetLaunchSuccess (error_str))
538                {
539                    SetID (m_gdb_comm.GetCurrentProcessID ());
540                }
541                else
542                {
543                    error.SetErrorString (error_str.c_str());
544                }
545            }
546            else
547            {
548                error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
549            }
550
551            m_gdb_comm.SetPacketTimeout (old_packet_timeout);
552
553            if (GetID() == LLDB_INVALID_PROCESS_ID)
554            {
555                if (log)
556                    log->Printf("failed to connect to debugserver: %s", error.AsCString());
557                KillDebugserverProcess ();
558                return error;
559            }
560
561            if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
562            {
563                SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
564
565                if (!disable_stdio)
566                {
567                    if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
568                        SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
569                }
570            }
571        }
572        else
573        {
574            if (log)
575                log->Printf("failed to connect to debugserver: %s", error.AsCString());
576        }
577    }
578    else
579    {
580        // Set our user ID to an invalid process ID.
581        SetID(LLDB_INVALID_PROCESS_ID);
582        error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
583                                       module->GetFileSpec().GetFilename().AsCString(),
584                                       module->GetArchitecture().GetArchitectureName());
585    }
586    return error;
587
588}
589
590
591Error
592ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
593{
594    Error error;
595    // Sleep and wait a bit for debugserver to start to listen...
596    std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
597    if (conn_ap.get())
598    {
599        const uint32_t max_retry_count = 50;
600        uint32_t retry_count = 0;
601        while (!m_gdb_comm.IsConnected())
602        {
603            if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
604            {
605                m_gdb_comm.SetConnection (conn_ap.release());
606                break;
607            }
608            retry_count++;
609
610            if (retry_count >= max_retry_count)
611                break;
612
613            usleep (100000);
614        }
615    }
616
617    if (!m_gdb_comm.IsConnected())
618    {
619        if (error.Success())
620            error.SetErrorString("not connected to remote gdb server");
621        return error;
622    }
623
624    // We always seem to be able to open a connection to a local port
625    // so we need to make sure we can then send data to it. If we can't
626    // then we aren't actually connected to anything, so try and do the
627    // handshake with the remote GDB server and make sure that goes
628    // alright.
629    if (!m_gdb_comm.HandshakeWithServer (NULL))
630    {
631        m_gdb_comm.Disconnect();
632        if (error.Success())
633            error.SetErrorString("not connected to remote gdb server");
634        return error;
635    }
636    if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
637        m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
638                                                                  this,
639                                                                  m_debugserver_pid,
640                                                                  false);
641    m_gdb_comm.ResetDiscoverableSettings();
642    m_gdb_comm.QueryNoAckModeSupported ();
643    m_gdb_comm.GetThreadSuffixSupported ();
644    m_gdb_comm.GetHostInfo ();
645    m_gdb_comm.GetVContSupported ('c');
646    return error;
647}
648
649void
650ProcessGDBRemote::DidLaunchOrAttach ()
651{
652    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
653    if (log)
654        log->Printf ("ProcessGDBRemote::DidLaunch()");
655    if (GetID() != LLDB_INVALID_PROCESS_ID)
656    {
657        m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
658
659        BuildDynamicRegisterInfo (false);
660
661        // See if the GDB server supports the qHostInfo information
662
663        const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
664        if (gdb_remote_arch.IsValid())
665        {
666            ArchSpec &target_arch = GetTarget().GetArchitecture();
667
668            if (target_arch.IsValid())
669            {
670                // If the remote host is ARM and we have apple as the vendor, then
671                // ARM executables and shared libraries can have mixed ARM architectures.
672                // You can have an armv6 executable, and if the host is armv7, then the
673                // system will load the best possible architecture for all shared libraries
674                // it has, so we really need to take the remote host architecture as our
675                // defacto architecture in this case.
676
677                if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
678                    gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
679                {
680                    target_arch = gdb_remote_arch;
681                }
682                else
683                {
684                    // Fill in what is missing in the triple
685                    const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
686                    llvm::Triple &target_triple = target_arch.GetTriple();
687                    if (target_triple.getVendorName().size() == 0)
688                    {
689                        target_triple.setVendor (remote_triple.getVendor());
690
691                        if (target_triple.getOSName().size() == 0)
692                        {
693                            target_triple.setOS (remote_triple.getOS());
694
695                            if (target_triple.getEnvironmentName().size() == 0)
696                                target_triple.setEnvironment (remote_triple.getEnvironment());
697                        }
698                    }
699                }
700            }
701            else
702            {
703                // The target doesn't have a valid architecture yet, set it from
704                // the architecture we got from the remote GDB server
705                target_arch = gdb_remote_arch;
706            }
707        }
708    }
709}
710
711void
712ProcessGDBRemote::DidLaunch ()
713{
714    DidLaunchOrAttach ();
715}
716
717Error
718ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
719{
720    Error error;
721    // Clear out and clean up from any current state
722    Clear();
723    if (attach_pid != LLDB_INVALID_PROCESS_ID)
724    {
725        // Make sure we aren't already connected?
726        if (!m_gdb_comm.IsConnected())
727        {
728            char host_port[128];
729            snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
730            char connect_url[128];
731            snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
732
733            error = StartDebugserverProcess (host_port);
734
735            if (error.Fail())
736            {
737                const char *error_string = error.AsCString();
738                if (error_string == NULL)
739                    error_string = "unable to launch " DEBUGSERVER_BASENAME;
740
741                SetExitStatus (-1, error_string);
742            }
743            else
744            {
745                error = ConnectToDebugserver (connect_url);
746            }
747        }
748
749        if (error.Success())
750        {
751            char packet[64];
752            const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
753
754            m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
755        }
756    }
757    return error;
758}
759
760size_t
761ProcessGDBRemote::AttachInputReaderCallback
762(
763    void *baton,
764    InputReader *reader,
765    lldb::InputReaderAction notification,
766    const char *bytes,
767    size_t bytes_len
768)
769{
770    if (notification == eInputReaderGotToken)
771    {
772        ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
773        if (gdb_process->m_waiting_for_attach)
774            gdb_process->m_waiting_for_attach = false;
775        reader->SetIsDone(true);
776        return 1;
777    }
778    return 0;
779}
780
781Error
782ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
783{
784    Error error;
785    // Clear out and clean up from any current state
786    Clear();
787
788    if (process_name && process_name[0])
789    {
790        // Make sure we aren't already connected?
791        if (!m_gdb_comm.IsConnected())
792        {
793            char host_port[128];
794            snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
795            char connect_url[128];
796            snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
797
798            error = StartDebugserverProcess (host_port);
799            if (error.Fail())
800            {
801                const char *error_string = error.AsCString();
802                if (error_string == NULL)
803                    error_string = "unable to launch " DEBUGSERVER_BASENAME;
804
805                SetExitStatus (-1, error_string);
806            }
807            else
808            {
809                error = ConnectToDebugserver (connect_url);
810            }
811        }
812
813        if (error.Success())
814        {
815            StreamString packet;
816
817            if (wait_for_launch)
818                packet.PutCString("vAttachWait");
819            else
820                packet.PutCString("vAttachName");
821            packet.PutChar(';');
822            packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
823
824            m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
825
826        }
827    }
828    return error;
829}
830
831
832void
833ProcessGDBRemote::DidAttach ()
834{
835    DidLaunchOrAttach ();
836}
837
838Error
839ProcessGDBRemote::WillResume ()
840{
841    m_continue_c_tids.clear();
842    m_continue_C_tids.clear();
843    m_continue_s_tids.clear();
844    m_continue_S_tids.clear();
845    return Error();
846}
847
848Error
849ProcessGDBRemote::DoResume ()
850{
851    Error error;
852    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
853    if (log)
854        log->Printf ("ProcessGDBRemote::Resume()");
855
856    Listener listener ("gdb-remote.resume-packet-sent");
857    if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
858    {
859        StreamString continue_packet;
860        bool continue_packet_error = false;
861        if (m_gdb_comm.HasAnyVContSupport ())
862        {
863            continue_packet.PutCString ("vCont");
864
865            if (!m_continue_c_tids.empty())
866            {
867                if (m_gdb_comm.GetVContSupported ('c'))
868                {
869                    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)
870                        continue_packet.Printf(";c:%4.4x", *t_pos);
871                }
872                else
873                    continue_packet_error = true;
874            }
875
876            if (!continue_packet_error && !m_continue_C_tids.empty())
877            {
878                if (m_gdb_comm.GetVContSupported ('C'))
879                {
880                    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)
881                        continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
882                }
883                else
884                    continue_packet_error = true;
885            }
886
887            if (!continue_packet_error && !m_continue_s_tids.empty())
888            {
889                if (m_gdb_comm.GetVContSupported ('s'))
890                {
891                    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)
892                        continue_packet.Printf(";s:%4.4x", *t_pos);
893                }
894                else
895                    continue_packet_error = true;
896            }
897
898            if (!continue_packet_error && !m_continue_S_tids.empty())
899            {
900                if (m_gdb_comm.GetVContSupported ('S'))
901                {
902                    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)
903                        continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
904                }
905                else
906                    continue_packet_error = true;
907            }
908
909            if (continue_packet_error)
910                continue_packet.GetString().clear();
911        }
912        else
913            continue_packet_error = true;
914
915        if (continue_packet_error)
916        {
917            // Either no vCont support, or we tried to use part of the vCont
918            // packet that wasn't supported by the remote GDB server.
919            // We need to try and make a simple packet that can do our continue
920            const size_t num_threads = GetThreadList().GetSize();
921            const size_t num_continue_c_tids = m_continue_c_tids.size();
922            const size_t num_continue_C_tids = m_continue_C_tids.size();
923            const size_t num_continue_s_tids = m_continue_s_tids.size();
924            const size_t num_continue_S_tids = m_continue_S_tids.size();
925            if (num_continue_c_tids > 0)
926            {
927                if (num_continue_c_tids == num_threads)
928                {
929                    // All threads are resuming...
930                    m_gdb_comm.SetCurrentThreadForRun (-1);
931                    continue_packet.PutChar ('c');
932                    continue_packet_error = false;
933                }
934                else if (num_continue_c_tids == 1 &&
935                         num_continue_C_tids == 0 &&
936                         num_continue_s_tids == 0 &&
937                         num_continue_S_tids == 0 )
938                {
939                    // Only one thread is continuing
940                    m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
941                    continue_packet.PutChar ('c');
942                    continue_packet_error = false;
943                }
944            }
945
946            if (continue_packet_error && num_continue_C_tids > 0)
947            {
948                if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
949                    num_continue_C_tids > 0 &&
950                    num_continue_s_tids == 0 &&
951                    num_continue_S_tids == 0 )
952                {
953                    const int continue_signo = m_continue_C_tids.front().second;
954                    // Only one thread is continuing
955                    if (num_continue_C_tids > 1)
956                    {
957                        // More that one thread with a signal, yet we don't have
958                        // vCont support and we are being asked to resume each
959                        // thread with a signal, we need to make sure they are
960                        // all the same signal, or we can't issue the continue
961                        // accurately with the current support...
962                        if (num_continue_C_tids > 1)
963                        {
964                            continue_packet_error = false;
965                            for (size_t i=1; i<m_continue_C_tids.size(); ++i)
966                            {
967                                if (m_continue_C_tids[i].second != continue_signo)
968                                    continue_packet_error = true;
969                            }
970                        }
971                        if (!continue_packet_error)
972                            m_gdb_comm.SetCurrentThreadForRun (-1);
973                    }
974                    else
975                    {
976                        // Set the continue thread ID
977                        continue_packet_error = false;
978                        m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
979                    }
980                    if (!continue_packet_error)
981                    {
982                        // Add threads continuing with the same signo...
983                        continue_packet.Printf("C%2.2x", continue_signo);
984                    }
985                }
986            }
987
988            if (continue_packet_error && num_continue_s_tids > 0)
989            {
990                if (num_continue_s_tids == num_threads)
991                {
992                    // All threads are resuming...
993                    m_gdb_comm.SetCurrentThreadForRun (-1);
994                    continue_packet.PutChar ('s');
995                    continue_packet_error = false;
996                }
997                else if (num_continue_c_tids == 0 &&
998                         num_continue_C_tids == 0 &&
999                         num_continue_s_tids == 1 &&
1000                         num_continue_S_tids == 0 )
1001                {
1002                    // Only one thread is stepping
1003                    m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1004                    continue_packet.PutChar ('s');
1005                    continue_packet_error = false;
1006                }
1007            }
1008
1009            if (!continue_packet_error && num_continue_S_tids > 0)
1010            {
1011                if (num_continue_S_tids == num_threads)
1012                {
1013                    const int step_signo = m_continue_S_tids.front().second;
1014                    // Are all threads trying to step with the same signal?
1015                    continue_packet_error = false;
1016                    if (num_continue_S_tids > 1)
1017                    {
1018                        for (size_t i=1; i<num_threads; ++i)
1019                        {
1020                            if (m_continue_S_tids[i].second != step_signo)
1021                                continue_packet_error = true;
1022                        }
1023                    }
1024                    if (!continue_packet_error)
1025                    {
1026                        // Add threads stepping with the same signo...
1027                        m_gdb_comm.SetCurrentThreadForRun (-1);
1028                        continue_packet.Printf("S%2.2x", step_signo);
1029                    }
1030                }
1031                else if (num_continue_c_tids == 0 &&
1032                         num_continue_C_tids == 0 &&
1033                         num_continue_s_tids == 0 &&
1034                         num_continue_S_tids == 1 )
1035                {
1036                    // Only one thread is stepping with signal
1037                    m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1038                    continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1039                    continue_packet_error = false;
1040                }
1041            }
1042        }
1043
1044        if (continue_packet_error)
1045        {
1046            error.SetErrorString ("can't make continue packet for this resume");
1047        }
1048        else
1049        {
1050            EventSP event_sp;
1051            TimeValue timeout;
1052            timeout = TimeValue::Now();
1053            timeout.OffsetWithSeconds (5);
1054            m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1055
1056            if (listener.WaitForEvent (&timeout, event_sp) == false)
1057                error.SetErrorString("Resume timed out.");
1058        }
1059    }
1060
1061    return error;
1062}
1063
1064uint32_t
1065ProcessGDBRemote::UpdateThreadListIfNeeded ()
1066{
1067    // locker will keep a mutex locked until it goes out of scope
1068    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1069    if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1070        log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1071
1072    Mutex::Locker locker (m_thread_list.GetMutex ());
1073    const uint32_t stop_id = GetStopID();
1074    if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1075    {
1076        // Update the thread list's stop id immediately so we don't recurse into this function.
1077        ThreadList curr_thread_list (this);
1078        curr_thread_list.SetStopID(stop_id);
1079
1080        std::vector<lldb::tid_t> thread_ids;
1081        bool sequence_mutex_unavailable = false;
1082        const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1083        if (num_thread_ids > 0)
1084        {
1085            for (size_t i=0; i<num_thread_ids; ++i)
1086            {
1087                tid_t tid = thread_ids[i];
1088                ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
1089                if (!thread_sp)
1090                    thread_sp.reset (new ThreadGDBRemote (*this, tid));
1091                curr_thread_list.AddThread(thread_sp);
1092            }
1093        }
1094
1095        if (sequence_mutex_unavailable == false)
1096        {
1097            m_thread_list = curr_thread_list;
1098            SetThreadStopInfo (m_last_stop_packet);
1099        }
1100    }
1101    return GetThreadList().GetSize(false);
1102}
1103
1104
1105StateType
1106ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1107{
1108    stop_packet.SetFilePos (0);
1109    const char stop_type = stop_packet.GetChar();
1110    switch (stop_type)
1111    {
1112    case 'T':
1113    case 'S':
1114        {
1115            if (GetStopID() == 0)
1116            {
1117                // Our first stop, make sure we have a process ID, and also make
1118                // sure we know about our registers
1119                if (GetID() == LLDB_INVALID_PROCESS_ID)
1120                {
1121                    lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1122                    if (pid != LLDB_INVALID_PROCESS_ID)
1123                        SetID (pid);
1124                }
1125                BuildDynamicRegisterInfo (true);
1126            }
1127            // Stop with signal and thread info
1128            const uint8_t signo = stop_packet.GetHexU8();
1129            std::string name;
1130            std::string value;
1131            std::string thread_name;
1132            std::string reason;
1133            std::string description;
1134            uint32_t exc_type = 0;
1135            std::vector<addr_t> exc_data;
1136            uint32_t tid = LLDB_INVALID_THREAD_ID;
1137            addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1138            uint32_t exc_data_count = 0;
1139            ThreadSP thread_sp;
1140
1141            while (stop_packet.GetNameColonValue(name, value))
1142            {
1143                if (name.compare("metype") == 0)
1144                {
1145                    // exception type in big endian hex
1146                    exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1147                }
1148                else if (name.compare("mecount") == 0)
1149                {
1150                    // exception count in big endian hex
1151                    exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1152                }
1153                else if (name.compare("medata") == 0)
1154                {
1155                    // exception data in big endian hex
1156                    exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1157                }
1158                else if (name.compare("thread") == 0)
1159                {
1160                    // thread in big endian hex
1161                    tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1162                    Mutex::Locker locker (m_thread_list.GetMutex ());
1163                    thread_sp = m_thread_list.FindThreadByID(tid, false);
1164                    if (!thread_sp)
1165                    {
1166                        // Create the thread if we need to
1167                        thread_sp.reset (new ThreadGDBRemote (*this, tid));
1168                        m_thread_list.AddThread(thread_sp);
1169                    }
1170                }
1171                else if (name.compare("hexname") == 0)
1172                {
1173                    StringExtractor name_extractor;
1174                    // Swap "value" over into "name_extractor"
1175                    name_extractor.GetStringRef().swap(value);
1176                    // Now convert the HEX bytes into a string value
1177                    name_extractor.GetHexByteString (value);
1178                    thread_name.swap (value);
1179                }
1180                else if (name.compare("name") == 0)
1181                {
1182                    thread_name.swap (value);
1183                }
1184                else if (name.compare("qaddr") == 0)
1185                {
1186                    thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1187                }
1188                else if (name.compare("reason") == 0)
1189                {
1190                    reason.swap(value);
1191                }
1192                else if (name.compare("description") == 0)
1193                {
1194                    StringExtractor desc_extractor;
1195                    // Swap "value" over into "name_extractor"
1196                    desc_extractor.GetStringRef().swap(value);
1197                    // Now convert the HEX bytes into a string value
1198                    desc_extractor.GetHexByteString (thread_name);
1199                }
1200                else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1201                {
1202                    // We have a register number that contains an expedited
1203                    // register value. Lets supply this register to our thread
1204                    // so it won't have to go and read it.
1205                    if (thread_sp)
1206                    {
1207                        uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1208
1209                        if (reg != UINT32_MAX)
1210                        {
1211                            StringExtractor reg_value_extractor;
1212                            // Swap "value" over into "reg_value_extractor"
1213                            reg_value_extractor.GetStringRef().swap(value);
1214                            if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1215                            {
1216                                Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1217                                                                    name.c_str(),
1218                                                                    reg,
1219                                                                    reg,
1220                                                                    reg_value_extractor.GetStringRef().c_str(),
1221                                                                    stop_packet.GetStringRef().c_str());
1222                            }
1223                        }
1224                    }
1225                }
1226            }
1227
1228            if (thread_sp)
1229            {
1230                ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1231
1232                gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1233                gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1234                if (exc_type != 0)
1235                {
1236                    const size_t exc_data_size = exc_data.size();
1237
1238                    gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1239                                                                                                       exc_type,
1240                                                                                                       exc_data_size,
1241                                                                                                       exc_data_size >= 1 ? exc_data[0] : 0,
1242                                                                                                       exc_data_size >= 2 ? exc_data[1] : 0));
1243                }
1244                else
1245                {
1246                    bool handled = false;
1247                    if (!reason.empty())
1248                    {
1249                        if (reason.compare("trace") == 0)
1250                        {
1251                            gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1252                            handled = true;
1253                        }
1254                        else if (reason.compare("breakpoint") == 0)
1255                        {
1256                            addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1257                            lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1258                            if (bp_site_sp)
1259                            {
1260                                // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1261                                // we can just report no reason.  We don't need to worry about stepping over the breakpoint here, that
1262                                // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1263                                if (bp_site_sp->ValidForThisThread (gdb_thread))
1264                                {
1265                                    gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1266                                    handled = true;
1267                                }
1268                            }
1269
1270                            if (!handled)
1271                            {
1272                                gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1273                            }
1274                        }
1275                        else if (reason.compare("trap") == 0)
1276                        {
1277                            // Let the trap just use the standard signal stop reason below...
1278                        }
1279                        else if (reason.compare("watchpoint") == 0)
1280                        {
1281                            break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1282                            // TODO: locate the watchpoint somehow...
1283                            gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1284                            handled = true;
1285                        }
1286                        else if (reason.compare("exception") == 0)
1287                        {
1288                            gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1289                            handled = true;
1290                        }
1291                    }
1292
1293                    if (signo)
1294                    {
1295                        if (signo == SIGTRAP)
1296                        {
1297                            // Currently we are going to assume SIGTRAP means we are either
1298                            // hitting a breakpoint or hardware single stepping.
1299                            addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1300                            lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1301                            if (bp_site_sp)
1302                            {
1303                                // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1304                                // we can just report no reason.  We don't need to worry about stepping over the breakpoint here, that
1305                                // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1306                                if (bp_site_sp->ValidForThisThread (gdb_thread))
1307                                {
1308                                    gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1309                                    handled = true;
1310                                }
1311                            }
1312                            if (!handled)
1313                            {
1314                                // TODO: check for breakpoint or trap opcode in case there is a hard
1315                                // coded software trap
1316                                gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1317                                handled = true;
1318                            }
1319                        }
1320                        if (!handled)
1321                    gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1322                }
1323                else
1324                {
1325                    StopInfoSP invalid_stop_info_sp;
1326                    gdb_thread->SetStopInfo (invalid_stop_info_sp);
1327                }
1328
1329                    if (!description.empty())
1330                    {
1331                        lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1332                        if (stop_info_sp)
1333                        {
1334                            stop_info_sp->SetDescription (description.c_str());
1335                        }
1336                        else
1337                        {
1338                            gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1339                        }
1340                    }
1341                }
1342            }
1343            return eStateStopped;
1344        }
1345        break;
1346
1347    case 'W':
1348        // process exited
1349        return eStateExited;
1350
1351    default:
1352        break;
1353    }
1354    return eStateInvalid;
1355}
1356
1357void
1358ProcessGDBRemote::RefreshStateAfterStop ()
1359{
1360    // Let all threads recover from stopping and do any clean up based
1361    // on the previous thread state (if any).
1362    m_thread_list.RefreshStateAfterStop();
1363    SetThreadStopInfo (m_last_stop_packet);
1364}
1365
1366Error
1367ProcessGDBRemote::DoHalt (bool &caused_stop)
1368{
1369    Error error;
1370
1371    bool timed_out = false;
1372    Mutex::Locker locker;
1373
1374    if (m_public_state.GetValue() == eStateAttaching)
1375    {
1376        // We are being asked to halt during an attach. We need to just close
1377        // our file handle and debugserver will go away, and we can be done...
1378        m_gdb_comm.Disconnect();
1379    }
1380    else
1381    {
1382        if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1383        {
1384            if (timed_out)
1385                error.SetErrorString("timed out sending interrupt packet");
1386            else
1387                error.SetErrorString("unknown error sending interrupt packet");
1388        }
1389    }
1390    return error;
1391}
1392
1393Error
1394ProcessGDBRemote::InterruptIfRunning
1395(
1396    bool discard_thread_plans,
1397    bool catch_stop_event,
1398    EventSP &stop_event_sp
1399)
1400{
1401    Error error;
1402
1403    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1404
1405    bool paused_private_state_thread = false;
1406    const bool is_running = m_gdb_comm.IsRunning();
1407    if (log)
1408        log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
1409                     discard_thread_plans,
1410                     catch_stop_event,
1411                     is_running);
1412
1413    if (discard_thread_plans)
1414    {
1415        if (log)
1416            log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1417        m_thread_list.DiscardThreadPlans();
1418    }
1419    if (is_running)
1420    {
1421        if (catch_stop_event)
1422        {
1423            if (log)
1424                log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1425            PausePrivateStateThread();
1426            paused_private_state_thread = true;
1427        }
1428
1429        bool timed_out = false;
1430        bool sent_interrupt = false;
1431        Mutex::Locker locker;
1432
1433        if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
1434        {
1435            if (timed_out)
1436                error.SetErrorString("timed out sending interrupt packet");
1437            else
1438                error.SetErrorString("unknown error sending interrupt packet");
1439            if (paused_private_state_thread)
1440                ResumePrivateStateThread();
1441            return error;
1442        }
1443
1444        if (catch_stop_event)
1445        {
1446            // LISTEN HERE
1447            TimeValue timeout_time;
1448            timeout_time = TimeValue::Now();
1449            timeout_time.OffsetWithSeconds(5);
1450            StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
1451
1452            timed_out = state == eStateInvalid;
1453            if (log)
1454                log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
1455
1456            if (timed_out)
1457                error.SetErrorString("unable to verify target stopped");
1458        }
1459
1460        if (paused_private_state_thread)
1461        {
1462            if (log)
1463                log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
1464            ResumePrivateStateThread();
1465        }
1466    }
1467    return error;
1468}
1469
1470Error
1471ProcessGDBRemote::WillDetach ()
1472{
1473    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1474    if (log)
1475        log->Printf ("ProcessGDBRemote::WillDetach()");
1476
1477    bool discard_thread_plans = true;
1478    bool catch_stop_event = true;
1479    EventSP event_sp;
1480    return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
1481}
1482
1483Error
1484ProcessGDBRemote::DoDetach()
1485{
1486    Error error;
1487    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1488    if (log)
1489        log->Printf ("ProcessGDBRemote::DoDetach()");
1490
1491    DisableAllBreakpointSites ();
1492
1493    m_thread_list.DiscardThreadPlans();
1494
1495    size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1496    if (log)
1497    {
1498        if (response_size)
1499            log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1500        else
1501            log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
1502    }
1503    // Sleep for one second to let the process get all detached...
1504    StopAsyncThread ();
1505
1506    m_gdb_comm.StopReadThread();
1507    m_gdb_comm.Disconnect();    // Disconnect from the debug server.
1508
1509    SetPrivateState (eStateDetached);
1510    ResumePrivateStateThread();
1511
1512    //KillDebugserverProcess ();
1513    return error;
1514}
1515
1516Error
1517ProcessGDBRemote::DoDestroy ()
1518{
1519    Error error;
1520    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1521    if (log)
1522        log->Printf ("ProcessGDBRemote::DoDestroy()");
1523
1524    // Interrupt if our inferior is running...
1525    if (m_gdb_comm.IsConnected())
1526    {
1527        if (m_public_state.GetValue() == eStateAttaching)
1528        {
1529            // We are being asked to halt during an attach. We need to just close
1530            // our file handle and debugserver will go away, and we can be done...
1531            m_gdb_comm.Disconnect();
1532        }
1533        else
1534        {
1535
1536            StringExtractorGDBRemote response;
1537            bool send_async = true;
1538            if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
1539            {
1540                char packet_cmd = response.GetChar(0);
1541
1542                if (packet_cmd == 'W' || packet_cmd == 'X')
1543                {
1544                    m_last_stop_packet = response;
1545                    SetExitStatus(response.GetHexU8(), NULL);
1546                }
1547            }
1548            else
1549            {
1550                SetExitStatus(SIGABRT, NULL);
1551                //error.SetErrorString("kill packet failed");
1552            }
1553        }
1554    }
1555    StopAsyncThread ();
1556    m_gdb_comm.StopReadThread();
1557    KillDebugserverProcess ();
1558    m_gdb_comm.Disconnect();    // Disconnect from the debug server.
1559    return error;
1560}
1561
1562//------------------------------------------------------------------
1563// Process Queries
1564//------------------------------------------------------------------
1565
1566bool
1567ProcessGDBRemote::IsAlive ()
1568{
1569    return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
1570}
1571
1572addr_t
1573ProcessGDBRemote::GetImageInfoAddress()
1574{
1575    if (!m_gdb_comm.IsRunning())
1576    {
1577        StringExtractorGDBRemote response;
1578        if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
1579        {
1580            if (response.IsNormalResponse())
1581                return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1582        }
1583    }
1584    return LLDB_INVALID_ADDRESS;
1585}
1586
1587//------------------------------------------------------------------
1588// Process Memory
1589//------------------------------------------------------------------
1590size_t
1591ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1592{
1593    if (size > m_max_memory_size)
1594    {
1595        // Keep memory read sizes down to a sane limit. This function will be
1596        // called multiple times in order to complete the task by
1597        // lldb_private::Process so it is ok to do this.
1598        size = m_max_memory_size;
1599    }
1600
1601    char packet[64];
1602    const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1603    assert (packet_len + 1 < sizeof(packet));
1604    StringExtractorGDBRemote response;
1605    if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
1606    {
1607        if (response.IsNormalResponse())
1608        {
1609            error.Clear();
1610            return response.GetHexBytes(buf, size, '\xdd');
1611        }
1612        else if (response.IsErrorResponse())
1613            error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1614        else if (response.IsUnsupportedResponse())
1615            error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1616        else
1617            error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1618    }
1619    else
1620    {
1621        error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1622    }
1623    return 0;
1624}
1625
1626size_t
1627ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1628{
1629    if (size > m_max_memory_size)
1630    {
1631        // Keep memory read sizes down to a sane limit. This function will be
1632        // called multiple times in order to complete the task by
1633        // lldb_private::Process so it is ok to do this.
1634        size = m_max_memory_size;
1635    }
1636
1637    StreamString packet;
1638    packet.Printf("M%llx,%zx:", addr, size);
1639    packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1640    StringExtractorGDBRemote response;
1641    if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
1642    {
1643        if (response.IsOKResponse())
1644        {
1645            error.Clear();
1646            return size;
1647        }
1648        else if (response.IsErrorResponse())
1649            error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1650        else if (response.IsUnsupportedResponse())
1651            error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1652        else
1653            error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1654    }
1655    else
1656    {
1657        error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1658    }
1659    return 0;
1660}
1661
1662lldb::addr_t
1663ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1664{
1665    addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1666
1667    LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1668    switch (supported)
1669    {
1670        case eLazyBoolCalculate:
1671        case eLazyBoolYes:
1672            allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1673            if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1674                return allocated_addr;
1675
1676        case eLazyBoolNo:
1677            // Call mmap() to create memory in the inferior..
1678            unsigned prot = 0;
1679            if (permissions & lldb::ePermissionsReadable)
1680                prot |= eMmapProtRead;
1681            if (permissions & lldb::ePermissionsWritable)
1682                prot |= eMmapProtWrite;
1683            if (permissions & lldb::ePermissionsExecutable)
1684                prot |= eMmapProtExec;
1685
1686            if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1687                                 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1688                m_addr_to_mmap_size[allocated_addr] = size;
1689            else
1690                allocated_addr = LLDB_INVALID_ADDRESS;
1691            break;
1692    }
1693
1694    if (allocated_addr == LLDB_INVALID_ADDRESS)
1695        error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
1696    else
1697        error.Clear();
1698    return allocated_addr;
1699}
1700
1701Error
1702ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1703{
1704    Error error;
1705    LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1706
1707    switch (supported)
1708    {
1709        case eLazyBoolCalculate:
1710            // We should never be deallocating memory without allocating memory
1711            // first so we should never get eLazyBoolCalculate
1712            error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1713            break;
1714
1715        case eLazyBoolYes:
1716            if (!m_gdb_comm.DeallocateMemory (addr))
1717                error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1718            break;
1719
1720        case eLazyBoolNo:
1721            // Call munmap() to deallocate memory in the inferior..
1722            {
1723                MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
1724                if (pos != m_addr_to_mmap_size.end() &&
1725                    InferiorCallMunmap(this, addr, pos->second))
1726                    m_addr_to_mmap_size.erase (pos);
1727                else
1728                    error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1729            }
1730            break;
1731    }
1732
1733    return error;
1734}
1735
1736
1737//------------------------------------------------------------------
1738// Process STDIO
1739//------------------------------------------------------------------
1740
1741size_t
1742ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1743{
1744    Mutex::Locker locker(m_stdio_mutex);
1745    size_t bytes_available = m_stdout_data.size();
1746    if (bytes_available > 0)
1747    {
1748        LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1749        if (log)
1750            log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1751        if (bytes_available > buf_size)
1752        {
1753            memcpy(buf, m_stdout_data.c_str(), buf_size);
1754            m_stdout_data.erase(0, buf_size);
1755            bytes_available = buf_size;
1756        }
1757        else
1758        {
1759            memcpy(buf, m_stdout_data.c_str(), bytes_available);
1760            m_stdout_data.clear();
1761
1762            //ResetEventBits(eBroadcastBitSTDOUT);
1763        }
1764    }
1765    return bytes_available;
1766}
1767
1768size_t
1769ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1770{
1771    // Can we get STDERR through the remote protocol?
1772    return 0;
1773}
1774
1775size_t
1776ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1777{
1778    if (m_stdio_communication.IsConnected())
1779    {
1780        ConnectionStatus status;
1781        m_stdio_communication.Write(src, src_len, status, NULL);
1782    }
1783    return 0;
1784}
1785
1786Error
1787ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1788{
1789    Error error;
1790    assert (bp_site != NULL);
1791
1792    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
1793    user_id_t site_id = bp_site->GetID();
1794    const addr_t addr = bp_site->GetLoadAddress();
1795    if (log)
1796        log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1797
1798    if (bp_site->IsEnabled())
1799    {
1800        if (log)
1801            log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1802        return error;
1803    }
1804    else
1805    {
1806        const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1807
1808        if (bp_site->HardwarePreferred())
1809        {
1810            // Try and set hardware breakpoint, and if that fails, fall through
1811            // and set a software breakpoint?
1812            if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
1813            {
1814                if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
1815                {
1816                    bp_site->SetEnabled(true);
1817                    bp_site->SetType (BreakpointSite::eHardware);
1818                    return error;
1819                }
1820            }
1821        }
1822
1823        if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
1824        {
1825            if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1826            {
1827                bp_site->SetEnabled(true);
1828                bp_site->SetType (BreakpointSite::eExternal);
1829                return error;
1830            }
1831        }
1832
1833        return EnableSoftwareBreakpoint (bp_site);
1834    }
1835
1836    if (log)
1837    {
1838        const char *err_string = error.AsCString();
1839        log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1840                     bp_site->GetLoadAddress(),
1841                     err_string ? err_string : "NULL");
1842    }
1843    // We shouldn't reach here on a successful breakpoint enable...
1844    if (error.Success())
1845        error.SetErrorToGenericError();
1846    return error;
1847}
1848
1849Error
1850ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1851{
1852    Error error;
1853    assert (bp_site != NULL);
1854    addr_t addr = bp_site->GetLoadAddress();
1855    user_id_t site_id = bp_site->GetID();
1856    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
1857    if (log)
1858        log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1859
1860    if (bp_site->IsEnabled())
1861    {
1862        const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1863
1864        BreakpointSite::Type bp_type = bp_site->GetType();
1865        switch (bp_type)
1866        {
1867        case BreakpointSite::eSoftware:
1868            error = DisableSoftwareBreakpoint (bp_site);
1869            break;
1870
1871        case BreakpointSite::eHardware:
1872            if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1873                error.SetErrorToGenericError();
1874            break;
1875
1876        case BreakpointSite::eExternal:
1877            if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1878                error.SetErrorToGenericError();
1879            break;
1880        }
1881        if (error.Success())
1882            bp_site->SetEnabled(false);
1883    }
1884    else
1885    {
1886        if (log)
1887            log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1888        return error;
1889    }
1890
1891    if (error.Success())
1892        error.SetErrorToGenericError();
1893    return error;
1894}
1895
1896Error
1897ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1898{
1899    Error error;
1900    if (wp)
1901    {
1902        user_id_t watchID = wp->GetID();
1903        addr_t addr = wp->GetLoadAddress();
1904        LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
1905        if (log)
1906            log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1907        if (wp->IsEnabled())
1908        {
1909            if (log)
1910                log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1911            return error;
1912        }
1913        else
1914        {
1915            // Pass down an appropriate z/Z packet...
1916            error.SetErrorString("watchpoints not supported");
1917        }
1918    }
1919    else
1920    {
1921        error.SetErrorString("Watchpoint location argument was NULL.");
1922    }
1923    if (error.Success())
1924        error.SetErrorToGenericError();
1925    return error;
1926}
1927
1928Error
1929ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1930{
1931    Error error;
1932    if (wp)
1933    {
1934        user_id_t watchID = wp->GetID();
1935
1936        LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
1937
1938        addr_t addr = wp->GetLoadAddress();
1939        if (log)
1940            log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1941
1942        if (wp->IsHardware())
1943        {
1944            // Pass down an appropriate z/Z packet...
1945            error.SetErrorString("watchpoints not supported");
1946        }
1947        // TODO: clear software watchpoints if we implement them
1948    }
1949    else
1950    {
1951        error.SetErrorString("Watchpoint location argument was NULL.");
1952    }
1953    if (error.Success())
1954        error.SetErrorToGenericError();
1955    return error;
1956}
1957
1958void
1959ProcessGDBRemote::Clear()
1960{
1961    m_flags = 0;
1962    m_thread_list.Clear();
1963    {
1964        Mutex::Locker locker(m_stdio_mutex);
1965        m_stdout_data.clear();
1966    }
1967}
1968
1969Error
1970ProcessGDBRemote::DoSignal (int signo)
1971{
1972    Error error;
1973    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1974    if (log)
1975        log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1976
1977    if (!m_gdb_comm.SendAsyncSignal (signo))
1978        error.SetErrorStringWithFormat("failed to send signal %i", signo);
1979    return error;
1980}
1981
1982Error
1983ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)    // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1984{
1985    Error error;
1986    if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1987    {
1988        // If we locate debugserver, keep that located version around
1989        static FileSpec g_debugserver_file_spec;
1990
1991        ProcessLaunchInfo launch_info;
1992        char debugserver_path[PATH_MAX];
1993        FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
1994
1995        // Always check to see if we have an environment override for the path
1996        // to the debugserver to use and use it if we do.
1997        const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1998        if (env_debugserver_path)
1999            debugserver_file_spec.SetFile (env_debugserver_path, false);
2000        else
2001            debugserver_file_spec = g_debugserver_file_spec;
2002        bool debugserver_exists = debugserver_file_spec.Exists();
2003        if (!debugserver_exists)
2004        {
2005            // The debugserver binary is in the LLDB.framework/Resources
2006            // directory.
2007            if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
2008            {
2009                debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
2010                debugserver_exists = debugserver_file_spec.Exists();
2011                if (debugserver_exists)
2012                {
2013                    g_debugserver_file_spec = debugserver_file_spec;
2014                }
2015                else
2016                {
2017                    g_debugserver_file_spec.Clear();
2018                    debugserver_file_spec.Clear();
2019                }
2020            }
2021        }
2022
2023        if (debugserver_exists)
2024        {
2025            debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2026
2027            m_stdio_communication.Clear();
2028
2029            LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2030
2031            Args &debugserver_args = launch_info.GetArguments();
2032            char arg_cstr[PATH_MAX];
2033
2034            // Start args with "debugserver /file/path -r --"
2035            debugserver_args.AppendArgument(debugserver_path);
2036            debugserver_args.AppendArgument(debugserver_url);
2037            // use native registers, not the GDB registers
2038            debugserver_args.AppendArgument("--native-regs");
2039            // make debugserver run in its own session so signals generated by
2040            // special terminal key sequences (^C) don't affect debugserver
2041            debugserver_args.AppendArgument("--setsid");
2042
2043            const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2044            if (env_debugserver_log_file)
2045            {
2046                ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2047                debugserver_args.AppendArgument(arg_cstr);
2048            }
2049
2050            const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2051            if (env_debugserver_log_flags)
2052            {
2053                ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2054                debugserver_args.AppendArgument(arg_cstr);
2055            }
2056//            debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2057//            debugserver_args.AppendArgument("--log-flags=0x802e0e");
2058
2059            // We currently send down all arguments, attach pids, or attach
2060            // process names in dedicated GDB server packets, so we don't need
2061            // to pass them as arguments. This is currently because of all the
2062            // things we need to setup prior to launching: the environment,
2063            // current working dir, file actions, etc.
2064#if 0
2065            // Now append the program arguments
2066            if (inferior_argv)
2067            {
2068                // Terminate the debugserver args so we can now append the inferior args
2069                debugserver_args.AppendArgument("--");
2070
2071                for (int i = 0; inferior_argv[i] != NULL; ++i)
2072                    debugserver_args.AppendArgument (inferior_argv[i]);
2073            }
2074            else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2075            {
2076                ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2077                debugserver_args.AppendArgument (arg_cstr);
2078            }
2079            else if (attach_name && attach_name[0])
2080            {
2081                if (wait_for_launch)
2082                    debugserver_args.AppendArgument ("--waitfor");
2083                else
2084                    debugserver_args.AppendArgument ("--attach");
2085                debugserver_args.AppendArgument (attach_name);
2086            }
2087#endif
2088
2089            ProcessLaunchInfo::FileAction file_action;
2090
2091            // Close STDIN, STDOUT and STDERR. We might need to redirect them
2092            // to "/dev/null" if we run into any problems.
2093            file_action.Close (STDIN_FILENO);
2094            launch_info.AppendFileAction (file_action);
2095            file_action.Close (STDOUT_FILENO);
2096            launch_info.AppendFileAction (file_action);
2097            file_action.Close (STDERR_FILENO);
2098            launch_info.AppendFileAction (file_action);
2099
2100            if (log)
2101            {
2102                StreamString strm;
2103                debugserver_args.Dump (&strm);
2104                log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2105            }
2106
2107            error = Host::LaunchProcess(launch_info);
2108
2109            if (error.Success ())
2110                m_debugserver_pid = launch_info.GetProcessID();
2111            else
2112                m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2113
2114            if (error.Fail() || log)
2115                error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
2116        }
2117        else
2118        {
2119            error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2120        }
2121
2122        if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2123            StartAsyncThread ();
2124    }
2125    return error;
2126}
2127
2128bool
2129ProcessGDBRemote::MonitorDebugserverProcess
2130(
2131    void *callback_baton,
2132    lldb::pid_t debugserver_pid,
2133    int signo,          // Zero for no signal
2134    int exit_status     // Exit value of process if signal is zero
2135)
2136{
2137    // We pass in the ProcessGDBRemote inferior process it and name it
2138    // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2139    // pointer value itself, thus we need the double cast...
2140
2141    // "debugserver_pid" argument passed in is the process ID for
2142    // debugserver that we are tracking...
2143
2144    ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2145
2146    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2147    if (log)
2148        log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2149
2150    if (process)
2151    {
2152        // Sleep for a half a second to make sure our inferior process has
2153        // time to set its exit status before we set it incorrectly when
2154        // both the debugserver and the inferior process shut down.
2155        usleep (500000);
2156        // If our process hasn't yet exited, debugserver might have died.
2157        // If the process did exit, the we are reaping it.
2158        const StateType state = process->GetState();
2159
2160        if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2161            state != eStateInvalid &&
2162            state != eStateUnloaded &&
2163            state != eStateExited &&
2164            state != eStateDetached)
2165        {
2166            char error_str[1024];
2167            if (signo)
2168            {
2169                const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2170                if (signal_cstr)
2171                    ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2172                else
2173                    ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2174            }
2175            else
2176            {
2177                ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2178            }
2179
2180            process->SetExitStatus (-1, error_str);
2181        }
2182        // Debugserver has exited we need to let our ProcessGDBRemote
2183        // know that it no longer has a debugserver instance
2184        process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2185        // We are returning true to this function below, so we can
2186        // forget about the monitor handle.
2187        process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
2188    }
2189    return true;
2190}
2191
2192void
2193ProcessGDBRemote::KillDebugserverProcess ()
2194{
2195    if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2196    {
2197        ::kill (m_debugserver_pid, SIGINT);
2198        m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2199    }
2200}
2201
2202void
2203ProcessGDBRemote::Initialize()
2204{
2205    static bool g_initialized = false;
2206
2207    if (g_initialized == false)
2208    {
2209        g_initialized = true;
2210        PluginManager::RegisterPlugin (GetPluginNameStatic(),
2211                                       GetPluginDescriptionStatic(),
2212                                       CreateInstance);
2213
2214        Log::Callbacks log_callbacks = {
2215            ProcessGDBRemoteLog::DisableLog,
2216            ProcessGDBRemoteLog::EnableLog,
2217            ProcessGDBRemoteLog::ListLogCategories
2218        };
2219
2220        Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2221    }
2222}
2223
2224bool
2225ProcessGDBRemote::StartAsyncThread ()
2226{
2227    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2228
2229    if (log)
2230        log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2231
2232    // Create a thread that watches our internal state and controls which
2233    // events make it to clients (into the DCProcess event queue).
2234    m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2235    return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
2236}
2237
2238void
2239ProcessGDBRemote::StopAsyncThread ()
2240{
2241    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2242
2243    if (log)
2244        log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2245
2246    m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2247
2248    // Stop the stdio thread
2249    if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2250    {
2251        Host::ThreadJoin (m_async_thread, NULL, NULL);
2252    }
2253}
2254
2255
2256void *
2257ProcessGDBRemote::AsyncThread (void *arg)
2258{
2259    ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2260
2261    LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2262    if (log)
2263        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2264
2265    Listener listener ("ProcessGDBRemote::AsyncThread");
2266    EventSP event_sp;
2267    const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2268                                        eBroadcastBitAsyncThreadShouldExit;
2269
2270    if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2271    {
2272        listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2273
2274        bool done = false;
2275        while (!done)
2276        {
2277            if (log)
2278                log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2279            if (listener.WaitForEvent (NULL, event_sp))
2280            {
2281                const uint32_t event_type = event_sp->GetType();
2282                if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
2283                {
2284                    if (log)
2285                        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2286
2287                    switch (event_type)
2288                    {
2289                        case eBroadcastBitAsyncContinue:
2290                            {
2291                                const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2292
2293                                if (continue_packet)
2294                                {
2295                                    const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2296                                    const size_t continue_cstr_len = continue_packet->GetByteSize ();
2297                                    if (log)
2298                                        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2299
2300                                    if (::strstr (continue_cstr, "vAttach") == NULL)
2301                                        process->SetPrivateState(eStateRunning);
2302                                    StringExtractorGDBRemote response;
2303                                    StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2304
2305                                    switch (stop_state)
2306                                    {
2307                                    case eStateStopped:
2308                                    case eStateCrashed:
2309                                    case eStateSuspended:
2310                                        process->m_last_stop_packet = response;
2311                                        process->SetPrivateState (stop_state);
2312                                        break;
2313
2314                                    case eStateExited:
2315                                        process->m_last_stop_packet = response;
2316                                        response.SetFilePos(1);
2317                                        process->SetExitStatus(response.GetHexU8(), NULL);
2318                                        done = true;
2319                                        break;
2320
2321                                    case eStateInvalid:
2322                                        process->SetExitStatus(-1, "lost connection");
2323                                        break;
2324
2325                                    default:
2326                                        process->SetPrivateState (stop_state);
2327                                        break;
2328                                    }
2329                                }
2330                            }
2331                            break;
2332
2333                        case eBroadcastBitAsyncThreadShouldExit:
2334                            if (log)
2335                                log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2336                            done = true;
2337                            break;
2338
2339                        default:
2340                            if (log)
2341                                log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2342                            done = true;
2343                            break;
2344                    }
2345                }
2346                else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2347                {
2348                    if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2349                    {
2350                        process->SetExitStatus (-1, "lost connection");
2351                        done = true;
2352                    }
2353                }
2354            }
2355            else
2356            {
2357                if (log)
2358                    log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2359                done = true;
2360            }
2361        }
2362    }
2363
2364    if (log)
2365        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2366
2367    process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2368    return NULL;
2369}
2370
2371const char *
2372ProcessGDBRemote::GetDispatchQueueNameForThread
2373(
2374    addr_t thread_dispatch_qaddr,
2375    std::string &dispatch_queue_name
2376)
2377{
2378    dispatch_queue_name.clear();
2379    if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2380    {
2381        // Cache the dispatch_queue_offsets_addr value so we don't always have
2382        // to look it up
2383        if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2384        {
2385            static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2386            const Symbol *dispatch_queue_offsets_symbol = NULL;
2387            ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
2388            if (module_sp)
2389                dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2390
2391            if (dispatch_queue_offsets_symbol == NULL)
2392            {
2393                module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
2394                if (module_sp)
2395                    dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2396            }
2397            if (dispatch_queue_offsets_symbol)
2398                m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
2399
2400            if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2401                return NULL;
2402        }
2403
2404        uint8_t memory_buffer[8];
2405        DataExtractor data (memory_buffer,
2406                            sizeof(memory_buffer),
2407                            m_target.GetArchitecture().GetByteOrder(),
2408                            m_target.GetArchitecture().GetAddressByteSize());
2409
2410        // Excerpt from src/queue_private.h
2411        struct dispatch_queue_offsets_s
2412        {
2413            uint16_t dqo_version;
2414            uint16_t dqo_label;
2415            uint16_t dqo_label_size;
2416        } dispatch_queue_offsets;
2417
2418
2419        Error error;
2420        if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2421        {
2422            uint32_t data_offset = 0;
2423            if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2424            {
2425                if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2426                {
2427                    data_offset = 0;
2428                    lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2429                    lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2430                    dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2431                    size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2432                    if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2433                        dispatch_queue_name.erase (bytes_read);
2434                }
2435            }
2436        }
2437    }
2438    if (dispatch_queue_name.empty())
2439        return NULL;
2440    return dispatch_queue_name.c_str();
2441}
2442
2443//uint32_t
2444//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2445//{
2446//    // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2447//    // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2448//    if (m_local_debugserver)
2449//    {
2450//        return Host::ListProcessesMatchingName (name, matches, pids);
2451//    }
2452//    else
2453//    {
2454//        // FIXME: Implement talking to the remote debugserver.
2455//        return 0;
2456//    }
2457//
2458//}
2459//
2460bool
2461ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2462                             lldb_private::StoppointCallbackContext *context,
2463                             lldb::user_id_t break_id,
2464                             lldb::user_id_t break_loc_id)
2465{
2466    // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2467    // run so I can stop it if that's what I want to do.
2468    LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2469    if (log)
2470        log->Printf("Hit New Thread Notification breakpoint.");
2471    return false;
2472}
2473
2474
2475bool
2476ProcessGDBRemote::StartNoticingNewThreads()
2477{
2478    static const char *bp_names[] =
2479    {
2480        "start_wqthread",
2481        "_pthread_wqthread",
2482        "_pthread_start",
2483        NULL
2484    };
2485
2486    LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2487    size_t num_bps = m_thread_observation_bps.size();
2488    if (num_bps != 0)
2489    {
2490        for (int i = 0; i < num_bps; i++)
2491        {
2492            lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2493            if (break_sp)
2494            {
2495                if (log)
2496                    log->Printf("Enabled noticing new thread breakpoint.");
2497                break_sp->SetEnabled(true);
2498            }
2499        }
2500    }
2501    else
2502    {
2503        for (int i = 0; bp_names[i] != NULL; i++)
2504        {
2505            Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2506            if (breakpoint)
2507            {
2508                if (log)
2509                     log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2510                m_thread_observation_bps.push_back(breakpoint->GetID());
2511                breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2512            }
2513            else
2514            {
2515                if (log)
2516                    log->Printf("Failed to create new thread notification breakpoint.");
2517                return false;
2518            }
2519        }
2520    }
2521
2522    return true;
2523}
2524
2525bool
2526ProcessGDBRemote::StopNoticingNewThreads()
2527{
2528    LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2529    if (log)
2530        log->Printf ("Disabling new thread notification breakpoint.");
2531    size_t num_bps = m_thread_observation_bps.size();
2532    if (num_bps != 0)
2533    {
2534        for (int i = 0; i < num_bps; i++)
2535        {
2536
2537            lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2538            if (break_sp)
2539            {
2540                break_sp->SetEnabled(false);
2541            }
2542        }
2543    }
2544    return true;
2545}
2546
2547
2548