summaryrefslogtreecommitdiffstats
path: root/lldb/source/Plugins/Process/gdb-remote
diff options
context:
space:
mode:
Diffstat (limited to 'lldb/source/Plugins/Process/gdb-remote')
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp813
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h270
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp508
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h250
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBServer.cpp1148
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBServerLog.cpp80
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/GDBServerLog.h55
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp2272
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h404
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp121
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h53
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp296
-rw-r--r--lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h156
13 files changed, 6426 insertions, 0 deletions
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp
new file mode 100644
index 00000000000..cac2101e4c0
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp
@@ -0,0 +1,813 @@
+//===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+
+#include "GDBRemoteCommunication.h"
+
+// C Includes
+// C++ Includes
+// Other libraries and framework includes
+#include "lldb/Core/Args.h"
+#include "lldb/Core/ConnectionFileDescriptor.h"
+#include "lldb/Core/Log.h"
+#include "lldb/Core/State.h"
+#include "lldb/Core/StreamString.h"
+#include "lldb/Host/TimeValue.h"
+
+// Project includes
+#include "StringExtractorGDBRemote.h"
+#include "ProcessGDBRemote.h"
+#include "ProcessGDBRemoteLog.h"
+
+using namespace lldb;
+using namespace lldb_private;
+
+//----------------------------------------------------------------------
+// GDBRemoteCommunication constructor
+//----------------------------------------------------------------------
+GDBRemoteCommunication::GDBRemoteCommunication() :
+ Communication("gdb-remote.packets"),
+ m_send_acks (true),
+ m_rx_packet_listener ("gdbremote.rx_packet"),
+ m_sequence_mutex (Mutex::eMutexTypeRecursive),
+ m_is_running (false),
+ m_async_mutex (Mutex::eMutexTypeRecursive),
+ m_async_packet_predicate (false),
+ m_async_packet (),
+ m_async_response (),
+ m_async_timeout (UINT32_MAX),
+ m_async_signal (-1),
+ m_arch(),
+ m_os(),
+ m_vendor(),
+ m_byte_order(eByteOrderHost),
+ m_pointer_byte_size(0)
+{
+ m_rx_packet_listener.StartListeningForEvents(this,
+ Communication::eBroadcastBitPacketAvailable |
+ Communication::eBroadcastBitReadThreadDidExit);
+}
+
+//----------------------------------------------------------------------
+// Destructor
+//----------------------------------------------------------------------
+GDBRemoteCommunication::~GDBRemoteCommunication()
+{
+ m_rx_packet_listener.StopListeningForEvents(this,
+ Communication::eBroadcastBitPacketAvailable |
+ Communication::eBroadcastBitReadThreadDidExit);
+ if (IsConnected())
+ {
+ StopReadThread();
+ Disconnect();
+ }
+}
+
+
+char
+GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
+{
+ int checksum = 0;
+
+ // We only need to compute the checksum if we are sending acks
+ if (m_send_acks)
+ {
+ for (int i = 0; i < payload_length; ++i)
+ checksum += payload[i];
+ }
+ return checksum & 255;
+}
+
+size_t
+GDBRemoteCommunication::SendAck (char ack_char)
+{
+ Mutex::Locker locker(m_sequence_mutex);
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "send packet: %c", ack_char);
+ ConnectionStatus status = eConnectionStatusSuccess;
+ return Write (&ack_char, 1, status, NULL) == 1;
+}
+
+size_t
+GDBRemoteCommunication::SendPacketAndWaitForResponse
+(
+ const char *payload,
+ StringExtractorGDBRemote &response,
+ uint32_t timeout_seconds,
+ bool send_async
+)
+{
+ return SendPacketAndWaitForResponse (payload,
+ ::strlen (payload),
+ response,
+ timeout_seconds,
+ send_async);
+}
+
+size_t
+GDBRemoteCommunication::SendPacketAndWaitForResponse
+(
+ const char *payload,
+ size_t payload_length,
+ StringExtractorGDBRemote &response,
+ uint32_t timeout_seconds,
+ bool send_async
+)
+{
+ Mutex::Locker locker;
+ TimeValue timeout_time;
+ timeout_time = TimeValue::Now();
+ timeout_time.OffsetWithSeconds (timeout_seconds);
+
+ if (locker.TryLock (m_sequence_mutex.GetMutex()))
+ {
+ if (SendPacketNoLock (payload, strlen(payload)))
+ return WaitForPacketNoLock (response, &timeout_time);
+ }
+ else
+ {
+ if (send_async)
+ {
+ Mutex::Locker async_locker (m_async_mutex);
+ m_async_packet.assign(payload, payload_length);
+ m_async_timeout = timeout_seconds;
+ m_async_packet_predicate.SetValue (true, eBroadcastNever);
+
+ bool timed_out = false;
+ if (SendInterrupt(1, &timed_out))
+ {
+ if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
+ {
+ response = m_async_response;
+ return response.GetStringRef().size();
+ }
+ }
+// if (timed_out)
+// m_error.SetErrorString("Timeout.");
+// else
+// m_error.SetErrorString("Unknown error.");
+ }
+ else
+ {
+// m_error.SetErrorString("Sequence mutex is locked.");
+ }
+ }
+ return 0;
+}
+
+//template<typename _Tp>
+//class ScopedValueChanger
+//{
+//public:
+// // Take a value reference and the value to assing it to when this class
+// // instance goes out of scope.
+// ScopedValueChanger (_Tp &value_ref, _Tp value) :
+// m_value_ref (value_ref),
+// m_value (value)
+// {
+// }
+//
+// // This object is going out of scope, change the value pointed to by
+// // m_value_ref to the value we got during construction which was stored in
+// // m_value;
+// ~ScopedValueChanger ()
+// {
+// m_value_ref = m_value;
+// }
+//protected:
+// _Tp &m_value_ref; // A reference to the value we wil change when this object destructs
+// _Tp m_value; // The value to assign to m_value_ref when this goes out of scope.
+//};
+
+StateType
+GDBRemoteCommunication::SendContinuePacketAndWaitForResponse
+(
+ ProcessGDBRemote *process,
+ const char *payload,
+ size_t packet_length,
+ StringExtractorGDBRemote &response
+)
+{
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
+ if (log)
+ log->Printf ("GDBRemoteCommunication::%s ()", __FUNCTION__);
+
+ Mutex::Locker locker(m_sequence_mutex);
+ m_is_running.SetValue (true, eBroadcastNever);
+
+// ScopedValueChanger<bool> restore_running_to_false (m_is_running, false);
+ StateType state = eStateRunning;
+
+ if (SendPacket(payload, packet_length) == 0)
+ state = eStateInvalid;
+
+ while (state == eStateRunning)
+ {
+ if (log)
+ log->Printf ("GDBRemoteCommunication::%s () WaitForPacket(...)", __FUNCTION__);
+
+ if (WaitForPacket (response, (TimeValue*)NULL))
+ {
+ if (response.Empty())
+ state = eStateInvalid;
+ else
+ {
+ const char stop_type = response.GetChar();
+ if (log)
+ log->Printf ("GDBRemoteCommunication::%s () got '%c' packet", __FUNCTION__, stop_type);
+ switch (stop_type)
+ {
+ case 'T':
+ case 'S':
+ if (m_async_signal != -1)
+ {
+ // Save off the async signal we are supposed to send
+ const int async_signal = m_async_signal;
+ // Clear the async signal member so we don't end up
+ // sending the signal multiple times...
+ m_async_signal = -1;
+ // Check which signal we stopped with
+ uint8_t signo = response.GetHexU8(255);
+ if (signo == async_signal)
+ {
+ // We already stopped with a signal that we wanted
+ // to stop with, so we are done
+ response.SetFilePos (0);
+ }
+ else
+ {
+ // We stopped with a different signal that the one
+ // we wanted to stop with, so now we must resume
+ // with the signal we want
+ char signal_packet[32];
+ int signal_packet_len = 0;
+ signal_packet_len = ::snprintf (signal_packet,
+ sizeof (signal_packet),
+ "C%2.2x",
+ async_signal);
+
+ if (SendPacket(signal_packet, signal_packet_len) == 0)
+ {
+ state = eStateInvalid;
+ break;
+ }
+ else
+ continue;
+ }
+ }
+ else if (m_async_packet_predicate.GetValue())
+ {
+ // We are supposed to send an asynchronous packet while
+ // we are running.
+ m_async_response.Clear();
+ if (!m_async_packet.empty())
+ {
+ SendPacketAndWaitForResponse (m_async_packet.data(),
+ m_async_packet.size(),
+ m_async_response,
+ m_async_timeout,
+ false);
+ }
+ // Let the other thread that was trying to send the async
+ // packet know that the packet has been sent.
+ m_async_packet_predicate.SetValue(false, eBroadcastAlways);
+
+ // Continue again
+ if (SendPacket("c", 1) == 0)
+ {
+ state = eStateInvalid;
+ break;
+ }
+ else
+ continue;
+ }
+ // Stop with signal and thread info
+ state = eStateStopped;
+ break;
+
+ case 'W':
+ // process exited
+ state = eStateExited;
+ break;
+
+ case 'O':
+ // STDOUT
+ {
+ std::string inferior_stdout;
+ inferior_stdout.reserve(response.GetBytesLeft () / 2);
+ char ch;
+ while ((ch = response.GetHexU8()) != '\0')
+ inferior_stdout.append(1, ch);
+ process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
+ }
+ break;
+
+ case 'E':
+ // ERROR
+ state = eStateInvalid;
+ break;
+
+ default:
+ if (log)
+ log->Printf ("GDBRemoteCommunication::%s () got unrecognized async packet: '%s'", __FUNCTION__, stop_type);
+ break;
+ }
+ }
+ }
+ else
+ {
+ if (log)
+ log->Printf ("GDBRemoteCommunication::%s () WaitForPacket(...) => false", __FUNCTION__);
+ state = eStateInvalid;
+ }
+ }
+ if (log)
+ log->Printf ("GDBRemoteCommunication::%s () => %s", __FUNCTION__, StateAsCString(state));
+ response.SetFilePos(0);
+ m_is_running.SetValue (false, eBroadcastOnChange);
+ return state;
+}
+
+size_t
+GDBRemoteCommunication::SendPacket (const char *payload)
+{
+ Mutex::Locker locker(m_sequence_mutex);
+ return SendPacketNoLock (payload, ::strlen (payload));
+}
+
+size_t
+GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
+{
+ Mutex::Locker locker(m_sequence_mutex);
+ return SendPacketNoLock (payload, payload_length);
+}
+
+size_t
+GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
+{
+ if (IsConnected())
+ {
+ StreamString packet(0, 4, eByteOrderBig);
+
+ packet.PutChar('$');
+ packet.Write (payload, payload_length);
+ packet.PutChar('#');
+ packet.PutHex8(CalculcateChecksum (payload, payload_length));
+
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "send packet: %s", packet.GetData());
+ ConnectionStatus status = eConnectionStatusSuccess;
+ size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
+ if (bytes_written == packet.GetSize())
+ {
+ if (m_send_acks)
+ GetAck (1) == '+';
+ }
+ return bytes_written;
+ }
+ //m_error.SetErrorString("Not connected.");
+ return 0;
+}
+
+char
+GDBRemoteCommunication::GetAck (uint32_t timeout_seconds)
+{
+ StringExtractorGDBRemote response;
+ if (WaitForPacket (response, timeout_seconds) == 1)
+ return response.GetChar();
+ return 0;
+}
+
+bool
+GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker)
+{
+ return locker.TryLock (m_sequence_mutex.GetMutex());
+}
+
+bool
+GDBRemoteCommunication::SendAsyncSignal (int signo)
+{
+ m_async_signal = signo;
+ bool timed_out = false;
+ if (SendInterrupt(1, &timed_out))
+ return true;
+ m_async_signal = -1;
+ return false;
+}
+
+bool
+GDBRemoteCommunication::SendInterrupt (uint32_t seconds_to_wait_for_stop, bool *timed_out)
+{
+ if (timed_out)
+ *timed_out = false;
+
+ if (IsConnected() && IsRunning())
+ {
+ // Only send an interrupt if our debugserver is running...
+ if (m_sequence_mutex.TryLock() != 0)
+ {
+ // Someone has the mutex locked waiting for a response or for the
+ // inferior to stop, so send the interrupt on the down low...
+ char ctrl_c = '\x03';
+ ConnectionStatus status = eConnectionStatusSuccess;
+ TimeValue timeout;
+ if (seconds_to_wait_for_stop)
+ {
+ timeout = TimeValue::Now();
+ timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
+ }
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "send packet: \\x03");
+ if (Write (&ctrl_c, 1, status, NULL) > 0)
+ {
+ if (seconds_to_wait_for_stop)
+ m_is_running.WaitForValueEqualTo (false, &timeout, timed_out);
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+size_t
+GDBRemoteCommunication::WaitForPacket (StringExtractorGDBRemote &response, uint32_t timeout_seconds)
+{
+ TimeValue timeout_time;
+ timeout_time = TimeValue::Now();
+ timeout_time.OffsetWithSeconds (timeout_seconds);
+ return WaitForPacketNoLock (response, &timeout_time);
+}
+
+size_t
+GDBRemoteCommunication::WaitForPacket (StringExtractorGDBRemote &response, TimeValue* timeout_time_ptr)
+{
+ Mutex::Locker locker(m_sequence_mutex);
+ return WaitForPacketNoLock (response, timeout_time_ptr);
+}
+
+size_t
+GDBRemoteCommunication::WaitForPacketNoLock (StringExtractorGDBRemote &response, TimeValue* timeout_time_ptr)
+{
+ bool checksum_error = false;
+ response.Clear ();
+
+ EventSP event_sp;
+
+ if (m_rx_packet_listener.WaitForEvent (timeout_time_ptr, event_sp))
+ {
+ const uint32_t event_type = event_sp->GetType();
+ if (event_type | Communication::eBroadcastBitPacketAvailable)
+ {
+ const EventDataBytes *event_bytes = EventDataBytes::GetEventDataFromEvent(event_sp.get());
+ if (event_bytes)
+ {
+ const char * packet_data = (const char *)event_bytes->GetBytes();
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "read packet: %s", packet_data);
+ const size_t packet_size = event_bytes->GetByteSize();
+ if (packet_data && packet_size > 0)
+ {
+ std::string &response_str = response.GetStringRef();
+ if (packet_data[0] == '$')
+ {
+ assert (packet_size >= 4); // Must have at least '$#CC' where CC is checksum
+ assert (packet_data[packet_size-3] == '#');
+ assert (::isxdigit (packet_data[packet_size-2])); // Must be checksum hex byte
+ assert (::isxdigit (packet_data[packet_size-1])); // Must be checksum hex byte
+ response_str.assign (packet_data + 1, packet_size - 4);
+ if (m_send_acks)
+ {
+ char packet_checksum = strtol (&packet_data[packet_size-2], NULL, 16);
+ char actual_checksum = CalculcateChecksum (response_str.data(), response_str.size());
+ checksum_error = packet_checksum != actual_checksum;
+ // Send the ack or nack if needed
+ if (checksum_error)
+ SendAck('-');
+ else
+ SendAck('+');
+ }
+ }
+ else
+ {
+ response_str.assign (packet_data, packet_size);
+ }
+ return response_str.size();
+ }
+ }
+ }
+ else if (Communication::eBroadcastBitReadThreadDidExit)
+ {
+ // Our read thread exited on us so just fall through and return zero...
+ }
+ }
+ return 0;
+}
+
+void
+GDBRemoteCommunication::AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast)
+{
+ // Put the packet data into the buffer in a thread safe fashion
+ Mutex::Locker locker(m_bytes_mutex);
+ m_bytes.append ((const char *)src, src_len);
+
+ // Parse up the packets into gdb remote packets
+ while (!m_bytes.empty())
+ {
+ // end_idx must be one past the last valid packet byte. Start
+ // it off with an invalid value that is the same as the current
+ // index.
+ size_t end_idx = 0;
+
+ switch (m_bytes[0])
+ {
+ case '+': // Look for ack
+ case '-': // Look for cancel
+ case '\x03': // ^C to halt target
+ end_idx = 1; // The command is one byte long...
+ break;
+
+ case '$':
+ // Look for a standard gdb packet?
+ end_idx = m_bytes.find('#');
+ if (end_idx != std::string::npos)
+ {
+ if (end_idx + 2 < m_bytes.size())
+ {
+ end_idx += 3;
+ }
+ else
+ {
+ // Checksum bytes aren't all here yet
+ end_idx = std::string::npos;
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ if (end_idx == std::string::npos)
+ {
+ //ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE, "GDBRemoteCommunication::%s packet not yet complete: '%s'",__FUNCTION__, m_bytes.c_str());
+ return;
+ }
+ else if (end_idx > 0)
+ {
+ // We have a valid packet...
+ assert (end_idx <= m_bytes.size());
+ std::auto_ptr<EventDataBytes> event_bytes_ap (new EventDataBytes (&m_bytes[0], end_idx));
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_COMM, "got full packet: %s", event_bytes_ap->GetBytes());
+ BroadcastEvent (eBroadcastBitPacketAvailable, event_bytes_ap.release());
+ m_bytes.erase(0, end_idx);
+ }
+ else
+ {
+ assert (1 <= m_bytes.size());
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_COMM, "GDBRemoteCommunication::%s tossing junk byte at %c",__FUNCTION__, m_bytes[0]);
+ m_bytes.erase(0, 1);
+ }
+ }
+}
+
+lldb::pid_t
+GDBRemoteCommunication::GetCurrentProcessID (uint32_t timeout_seconds)
+{
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, timeout_seconds, false))
+ {
+ if (response.GetChar() == 'Q')
+ if (response.GetChar() == 'C')
+ return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
+ }
+ return LLDB_INVALID_PROCESS_ID;
+}
+
+bool
+GDBRemoteCommunication::GetLaunchSuccess (uint32_t timeout_seconds, std::string &error_str)
+{
+ error_str.clear();
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, timeout_seconds, false))
+ {
+ if (response.IsOKPacket())
+ return true;
+ if (response.GetChar() == 'E')
+ {
+ // A string the describes what failed when launching...
+ error_str = response.GetStringRef().substr(1);
+ }
+ else
+ {
+ error_str.assign ("unknown error occurred launching process");
+ }
+ }
+ else
+ {
+ error_str.assign ("failed to send the qLaunchSuccess packet");
+ }
+ return false;
+}
+
+int
+GDBRemoteCommunication::SendArgumentsPacket (char const *argv[], uint32_t timeout_seconds)
+{
+ if (argv && argv[0])
+ {
+ StreamString packet;
+ packet.PutChar('A');
+ const char *arg;
+ for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
+ {
+ const int arg_len = strlen(arg);
+ if (i > 0)
+ packet.PutChar(',');
+ packet.Printf("%i,%i,", arg_len * 2, i);
+ packet.PutBytesAsRawHex8(arg, arg_len, eByteOrderHost, eByteOrderHost);
+ }
+
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, timeout_seconds, false))
+ {
+ if (response.IsOKPacket())
+ return 0;
+ uint8_t error = response.GetError();
+ if (error)
+ return error;
+ }
+ }
+ return -1;
+}
+
+int
+GDBRemoteCommunication::SendEnvironmentPacket (char const *name_equal_value, uint32_t timeout_seconds)
+{
+ if (name_equal_value && name_equal_value[0])
+ {
+ StreamString packet;
+ packet.Printf("QEnvironment:%s", name_equal_value);
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, timeout_seconds, false))
+ {
+ if (response.IsOKPacket())
+ return 0;
+ uint8_t error = response.GetError();
+ if (error)
+ return error;
+ }
+ }
+ return -1;
+}
+
+bool
+GDBRemoteCommunication::GetHostInfo (uint32_t timeout_seconds)
+{
+ m_arch.Clear();
+ m_os.Clear();
+ m_vendor.Clear();
+ m_byte_order = eByteOrderHost;
+ m_pointer_byte_size = 0;
+
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse ("qHostInfo", response, timeout_seconds, false))
+ {
+ if (response.IsUnsupportedPacket())
+ return false;
+
+
+ std::string name;
+ std::string value;
+ while (response.GetNameColonValue(name, value))
+ {
+ if (name.compare("cputype") == 0)
+ {
+ // exception type in big endian hex
+ m_arch.SetCPUType(Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0));
+ }
+ else if (name.compare("cpusubtype") == 0)
+ {
+ // exception count in big endian hex
+ m_arch.SetCPUSubtype(Args::StringToUInt32 (value.c_str(), 0, 0));
+ }
+ else if (name.compare("ostype") == 0)
+ {
+ // exception data in big endian hex
+ m_os.SetCString(value.c_str());
+ }
+ else if (name.compare("vendor") == 0)
+ {
+ m_vendor.SetCString(value.c_str());
+ }
+ else if (name.compare("endian") == 0)
+ {
+ if (value.compare("little") == 0)
+ m_byte_order = eByteOrderLittle;
+ else if (value.compare("big") == 0)
+ m_byte_order = eByteOrderBig;
+ else if (value.compare("pdp") == 0)
+ m_byte_order = eByteOrderPDP;
+ }
+ else if (name.compare("ptrsize") == 0)
+ {
+ m_pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
+ }
+ }
+ }
+ return HostInfoIsValid();
+}
+
+int
+GDBRemoteCommunication::SendAttach
+(
+ lldb::pid_t pid,
+ uint32_t timeout_seconds,
+ StringExtractorGDBRemote& response
+)
+{
+ if (pid != LLDB_INVALID_PROCESS_ID)
+ {
+ StreamString packet;
+ packet.Printf("vAttach;%x", pid);
+
+ if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, timeout_seconds, false))
+ {
+ if (response.IsErrorPacket())
+ return response.GetError();
+ return 0;
+ }
+ }
+ return -1;
+}
+
+const lldb_private::ArchSpec &
+GDBRemoteCommunication::GetHostArchitecture ()
+{
+ if (!HostInfoIsValid ())
+ GetHostInfo (1);
+ return m_arch;
+}
+
+const lldb_private::ConstString &
+GDBRemoteCommunication::GetOSString ()
+{
+ if (!HostInfoIsValid ())
+ GetHostInfo (1);
+ return m_os;
+}
+
+const lldb_private::ConstString &
+GDBRemoteCommunication::GetVendorString()
+{
+ if (!HostInfoIsValid ())
+ GetHostInfo (1);
+ return m_vendor;
+}
+
+lldb::ByteOrder
+GDBRemoteCommunication::GetByteOrder ()
+{
+ if (!HostInfoIsValid ())
+ GetHostInfo (1);
+ return m_byte_order;
+}
+
+uint32_t
+GDBRemoteCommunication::GetAddressByteSize ()
+{
+ if (!HostInfoIsValid ())
+ GetHostInfo (1);
+ return m_pointer_byte_size;
+}
+
+addr_t
+GDBRemoteCommunication::AllocateMemory (size_t size, uint32_t permissions, uint32_t timeout_seconds)
+{
+ char packet[64];
+ ::snprintf (packet, sizeof(packet), "_M%zx,%s%s%s", size,
+ permissions & lldb::ePermissionsReadable ? "r" : "",
+ permissions & lldb::ePermissionsWritable ? "w" : "",
+ permissions & lldb::ePermissionsExecutable ? "x" : "");
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse (packet, response, timeout_seconds, false))
+ {
+ if (!response.IsErrorPacket())
+ return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
+ }
+ return LLDB_INVALID_ADDRESS;
+}
+
+bool
+GDBRemoteCommunication::DeallocateMemory (addr_t addr, uint32_t timeout_seconds)
+{
+ char packet[64];
+ snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr);
+ StringExtractorGDBRemote response;
+ if (SendPacketAndWaitForResponse (packet, response, timeout_seconds, false))
+ {
+ if (!response.IsOKPacket())
+ return true;
+ }
+ return false;
+}
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h
new file mode 100644
index 00000000000..051fa445ff1
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h
@@ -0,0 +1,270 @@
+//===-- GDBRemoteCommunication.h --------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef liblldb_GDBRemoteCommunication_h_
+#define liblldb_GDBRemoteCommunication_h_
+
+// C Includes
+// C++ Includes
+#include <list>
+#include <string>
+
+// Other libraries and framework includes
+// Project includes
+#include "lldb/lldb-private.h"
+#include "lldb/Core/ArchSpec.h"
+#include "lldb/Core/Communication.h"
+#include "lldb/Core/ConstString.h"
+#include "lldb/Core/Error.h"
+#include "lldb/Core/Listener.h"
+#include "lldb/Host/Mutex.h"
+#include "lldb/Host/Predicate.h"
+
+#include "StringExtractorGDBRemote.h"
+
+class ProcessGDBRemote;
+
+class GDBRemoteCommunication :
+ public lldb_private::Communication
+{
+public:
+ //------------------------------------------------------------------
+ // Constructors and Destructors
+ //------------------------------------------------------------------
+ GDBRemoteCommunication();
+
+ virtual
+ ~GDBRemoteCommunication();
+
+ size_t
+ SendPacket (const char *payload);
+
+ size_t
+ SendPacket (const char *payload,
+ size_t payload_length);
+
+ size_t
+ SendPacketAndWaitForResponse (const char *send_payload,
+ StringExtractorGDBRemote &response,
+ uint32_t timeout_seconds,
+ bool send_async);
+
+ size_t
+ SendPacketAndWaitForResponse (const char *send_payload,
+ size_t send_length,
+ StringExtractorGDBRemote &response,
+ uint32_t timeout_seconds,
+ bool send_async);
+
+ lldb::StateType
+ SendContinuePacketAndWaitForResponse (ProcessGDBRemote *process,
+ const char *packet_payload,
+ size_t packet_length,
+ StringExtractorGDBRemote &response);
+
+ // Wait for a packet within 'nsec' seconds
+ size_t
+ WaitForPacket (StringExtractorGDBRemote &response,
+ uint32_t nsec);
+
+ // Wait for a packet with an absolute timeout time. If 'timeout' is NULL
+ // wait indefinitely.
+ size_t
+ WaitForPacket (StringExtractorGDBRemote &response,
+ lldb_private::TimeValue* timeout);
+
+ char
+ GetAck (uint32_t timeout_seconds);
+
+ size_t
+ SendAck (char ack_char);
+
+ char
+ CalculcateChecksum (const char *payload,
+ size_t payload_length);
+
+ void
+ SetAckMode (bool enabled)
+ {
+ m_send_acks = enabled;
+ }
+
+ bool
+ SendAsyncSignal (int signo);
+
+ bool
+ SendInterrupt (uint32_t seconds_to_wait_for_stop, bool *timed_out = NULL);
+
+ bool
+ GetSequenceMutex(lldb_private::Mutex::Locker& locker);
+
+ //------------------------------------------------------------------
+ // Communication overrides
+ //------------------------------------------------------------------
+ virtual void
+ AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
+
+
+ lldb::pid_t
+ GetCurrentProcessID (uint32_t timeout_seconds);
+
+ bool
+ GetLaunchSuccess (uint32_t timeout_seconds, std::string &error_str);
+
+ //------------------------------------------------------------------
+ /// Sends a GDB remote protocol 'A' packet that delivers program
+ /// arguments to the remote server.
+ ///
+ /// @param[in] argv
+ /// A NULL terminated array of const C strings to use as the
+ /// arguments.
+ ///
+ /// @param[in] timeout_seconds
+ /// The number of seconds to wait for a response from the remote
+ /// server.
+ ///
+ /// @return
+ /// Zero if the response was "OK", a positive value if the
+ /// the response was "Exx" where xx are two hex digits, or
+ /// -1 if the call is unsupported or any other unexpected
+ /// response was received.
+ //------------------------------------------------------------------
+ int
+ SendArgumentsPacket (char const *argv[], uint32_t timeout_seconds);
+
+ //------------------------------------------------------------------
+ /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the
+ /// environment that will get used when launching an application
+ /// in conjunction with the 'A' packet. This function can be called
+ /// multiple times in a row in order to pass on the desired
+ /// environment that the inferior should be launched with.
+ ///
+ /// @param[in] name_equal_value
+ /// A NULL terminated C string that contains a single enironment
+ /// in the format "NAME=VALUE".
+ ///
+ /// @param[in] timeout_seconds
+ /// The number of seconds to wait for a response from the remote
+ /// server.
+ ///
+ /// @return
+ /// Zero if the response was "OK", a positive value if the
+ /// the response was "Exx" where xx are two hex digits, or
+ /// -1 if the call is unsupported or any other unexpected
+ /// response was received.
+ //------------------------------------------------------------------
+ int
+ SendEnvironmentPacket (char const *name_equal_value,
+ uint32_t timeout_seconds);
+
+ //------------------------------------------------------------------
+ /// Sends a "vAttach:PID" where PID is in hex.
+ ///
+ /// @param[in] pid
+ /// A process ID for the remote gdb server to attach to.
+ ///
+ /// @param[in] timeout_seconds
+ /// The number of seconds to wait for a response from the remote
+ /// server.
+ ///
+ /// @param[out] response
+ /// The response received from the gdb server. If the return
+ /// value is zero, \a response will contain a stop reply
+ /// packet.
+ ///
+ /// @return
+ /// Zero if the attach was successful, or an error indicating
+ /// an error code.
+ //------------------------------------------------------------------
+ int
+ SendAttach (lldb::pid_t pid,
+ uint32_t timeout_seconds,
+ StringExtractorGDBRemote& response);
+
+
+ lldb::addr_t
+ AllocateMemory (size_t size, uint32_t permissions, uint32_t timeout_seconds);
+
+ bool
+ DeallocateMemory (lldb::addr_t addr, uint32_t timeout_seconds);
+
+ bool
+ IsRunning() const
+ {
+ return m_is_running.GetValue();
+ }
+
+ bool
+ GetHostInfo (uint32_t timeout_seconds);
+
+ bool
+ HostInfoIsValid () const
+ {
+ return m_pointer_byte_size != 0;
+ }
+
+ const lldb_private::ArchSpec &
+ GetHostArchitecture ();
+
+ const lldb_private::ConstString &
+ GetOSString ();
+
+ const lldb_private::ConstString &
+ GetVendorString();
+
+ lldb::ByteOrder
+ GetByteOrder ();
+
+ uint32_t
+ GetAddressByteSize ();
+
+protected:
+ typedef std::list<std::string> packet_collection;
+
+ size_t
+ SendPacketNoLock (const char *payload,
+ size_t payload_length);
+
+ size_t
+ WaitForPacketNoLock (StringExtractorGDBRemote &response,
+ lldb_private::TimeValue* timeout_time_ptr);
+
+ //------------------------------------------------------------------
+ // Classes that inherit from GDBRemoteCommunication can see and modify these
+ //------------------------------------------------------------------
+ bool m_send_acks;
+ lldb_private::Listener m_rx_packet_listener;
+ lldb_private::Mutex m_sequence_mutex; // Restrict access to sending/receiving packets to a single thread at a time
+ lldb_private::Predicate<bool> m_is_running;
+
+ // If we need to send a packet while the target is running, the m_async_XXX
+ // member variables take care of making this happen.
+ lldb_private::Mutex m_async_mutex;
+ lldb_private::Predicate<bool> m_async_packet_predicate;
+ std::string m_async_packet;
+ StringExtractorGDBRemote m_async_response;
+ uint32_t m_async_timeout;
+ int m_async_signal; // We were asked to deliver a signal to the inferior process.
+
+ lldb_private::ArchSpec m_arch; // Results from the qHostInfo call
+ uint32_t m_cpusubtype; // Results from the qHostInfo call
+ lldb_private::ConstString m_os; // Results from the qHostInfo call
+ lldb_private::ConstString m_vendor; // Results from the qHostInfo call
+ lldb::ByteOrder m_byte_order; // Results from the qHostInfo call
+ uint32_t m_pointer_byte_size; // Results from the qHostInfo call
+
+
+private:
+ //------------------------------------------------------------------
+ // For GDBRemoteCommunication only
+ //------------------------------------------------------------------
+ DISALLOW_COPY_AND_ASSIGN (GDBRemoteCommunication);
+};
+
+#endif // liblldb_GDBRemoteCommunication_h_
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp
new file mode 100644
index 00000000000..a64e74dc963
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp
@@ -0,0 +1,508 @@
+//===-- GDBRemoteRegisterContext.cpp ----------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "GDBRemoteRegisterContext.h"
+
+// C Includes
+// C++ Includes
+// Other libraries and framework includes
+#include "lldb/Core/DataBufferHeap.h"
+#include "lldb/Core/DataExtractor.h"
+#include "lldb/Core/Scalar.h"
+#include "lldb/Core/StreamString.h"
+// Project includes
+#include "StringExtractorGDBRemote.h"
+#include "ProcessGDBRemote.h"
+#include "ThreadGDBRemote.h"
+#include "ARM_GCC_Registers.h"
+#include "ARM_DWARF_Registers.h"
+
+using namespace lldb;
+using namespace lldb_private;
+
+//----------------------------------------------------------------------
+// GDBRemoteRegisterContext constructor
+//----------------------------------------------------------------------
+GDBRemoteRegisterContext::GDBRemoteRegisterContext
+(
+ ThreadGDBRemote &thread,
+ StackFrame *frame,
+ GDBRemoteDynamicRegisterInfo &reg_info,
+ bool read_all_at_once
+) :
+ RegisterContext (thread, frame),
+ m_reg_info (reg_info),
+ m_reg_valid (),
+ m_reg_data (),
+ m_read_all_at_once (read_all_at_once)
+{
+ // Resize our vector of bools to contain one bool for every register.
+ // We will use these boolean values to know when a register value
+ // is valid in m_reg_data.
+ m_reg_valid.resize (reg_info.GetNumRegisters());
+
+ // Make a heap based buffer that is big enough to store all registers
+ DataBufferSP reg_data_sp(new DataBufferHeap (reg_info.GetRegisterDataByteSize(), 0));
+ m_reg_data.SetData (reg_data_sp);
+
+}
+
+//----------------------------------------------------------------------
+// Destructor
+//----------------------------------------------------------------------
+GDBRemoteRegisterContext::~GDBRemoteRegisterContext()
+{
+}
+
+ProcessGDBRemote &
+GDBRemoteRegisterContext::GetGDBProcess()
+{
+ return static_cast<ProcessGDBRemote &>(m_thread.GetProcess());
+}
+
+ThreadGDBRemote &
+GDBRemoteRegisterContext::GetGDBThread()
+{
+ return static_cast<ThreadGDBRemote &>(m_thread);
+}
+
+void
+GDBRemoteRegisterContext::Invalidate ()
+{
+ SetAllRegisterValid (false);
+}
+
+void
+GDBRemoteRegisterContext::SetAllRegisterValid (bool b)
+{
+ std::vector<bool>::iterator pos, end = m_reg_valid.end();
+ for (pos = m_reg_valid.begin(); pos != end; ++pos)
+ *pos = b;
+}
+
+size_t
+GDBRemoteRegisterContext::GetRegisterCount ()
+{
+ return m_reg_info.GetNumRegisters ();
+}
+
+const lldb::RegisterInfo *
+GDBRemoteRegisterContext::GetRegisterInfoAtIndex (uint32_t reg)
+{
+ return m_reg_info.GetRegisterInfoAtIndex (reg);
+}
+
+size_t
+GDBRemoteRegisterContext::GetRegisterSetCount ()
+{
+ return m_reg_info.GetNumRegisterSets ();
+}
+
+
+
+const lldb::RegisterSet *
+GDBRemoteRegisterContext::GetRegisterSet (uint32_t reg_set)
+{
+ return m_reg_info.GetRegisterSet (reg_set);
+}
+
+
+
+bool
+GDBRemoteRegisterContext::ReadRegisterValue (uint32_t reg, Scalar &value)
+{
+ // Read the register
+ if (ReadRegisterBytes (reg, m_reg_data))
+ {
+ const RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg);
+ uint32_t offset = reg_info->byte_offset;
+ switch (reg_info->encoding)
+ {
+ case eEncodingUint:
+ switch (reg_info->byte_size)
+ {
+ case 1:
+ case 2:
+ case 4:
+ value = m_reg_data.GetMaxU32 (&offset, reg_info->byte_size);
+ return true;
+
+ case 8:
+ value = m_reg_data.GetMaxU64 (&offset, reg_info->byte_size);
+ return true;
+ }
+ break;
+
+ case eEncodingSint:
+ switch (reg_info->byte_size)
+ {
+ case 1:
+ case 2:
+ case 4:
+ value = (int32_t)m_reg_data.GetMaxU32 (&offset, reg_info->byte_size);
+ return true;
+
+ case 8:
+ value = m_reg_data.GetMaxS64 (&offset, reg_info->byte_size);
+ return true;
+ }
+ break;
+
+ case eEncodingIEEE754:
+ switch (reg_info->byte_size)
+ {
+ case sizeof (float):
+ value = m_reg_data.GetFloat (&offset);
+ return true;
+
+ case sizeof (double):
+ value = m_reg_data.GetDouble (&offset);
+ return true;
+
+ case sizeof (long double):
+ value = m_reg_data.GetLongDouble (&offset);
+ return true;
+ }
+ break;
+ }
+ }
+ return false;
+}
+
+
+bool
+GDBRemoteRegisterContext::ReadRegisterBytes (uint32_t reg, DataExtractor &data)
+{
+ GDBRemoteCommunication &gdb_comm = GetGDBProcess().GetGDBRemote();
+// FIXME: This check isn't right because IsRunning checks the Public state, but this
+// is work you need to do - for instance in ShouldStop & friends - before the public
+// state has been changed.
+// if (gdb_comm.IsRunning())
+// return false;
+
+ if (m_reg_valid_stop_id != m_thread.GetProcess().GetStopID())
+ {
+ Invalidate();
+ m_reg_valid_stop_id = m_thread.GetProcess().GetStopID();
+ }
+ const RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg);
+ assert (reg_info);
+ if (m_reg_valid[reg] == false)
+ {
+ Mutex::Locker locker;
+ if (gdb_comm.GetSequenceMutex (locker))
+ {
+ if (GetGDBProcess().SetCurrentGDBRemoteThread(m_thread.GetID()))
+ {
+ char packet[32];
+ StringExtractorGDBRemote response;
+ int packet_len;
+ if (m_read_all_at_once)
+ {
+ // Get all registers in one packet
+ packet_len = ::snprintf (packet, sizeof(packet), "g");
+ assert (packet_len < (sizeof(packet) - 1));
+ if (gdb_comm.SendPacketAndWaitForResponse(packet, response, 1, false))
+ {
+ if (response.IsNormalPacket())
+ if (response.GetHexBytes ((void *)m_reg_data.GetDataStart(), m_reg_data.GetByteSize(), '\xcc') == m_reg_data.GetByteSize())
+ SetAllRegisterValid (true);
+ }
+ }
+ else
+ {
+ // Get each register individually
+ packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg, false);
+ assert (packet_len < (sizeof(packet) - 1));
+ if (gdb_comm.SendPacketAndWaitForResponse(packet, response, 1, false))
+ if (response.GetHexBytes ((uint8_t*)m_reg_data.PeekData(reg_info->byte_offset, reg_info->byte_size), reg_info->byte_size, '\xcc') == reg_info->byte_size)
+ m_reg_valid[reg] = true;
+ }
+ }
+ }
+ }
+
+ bool reg_is_valid = m_reg_valid[reg];
+ if (reg_is_valid)
+ {
+ if (&data != &m_reg_data)
+ {
+ // If we aren't extracting into our own buffer (which
+ // only happens when this function is called from
+ // ReadRegisterValue(uint32_t, Scalar&)) then
+ // we transfer bytes from our buffer into the data
+ // buffer that was passed in
+ data.SetByteOrder (m_reg_data.GetByteOrder());
+ data.SetData (m_reg_data, reg_info->byte_offset, reg_info->byte_size);
+ }
+ }
+ return reg_is_valid;
+}
+
+
+bool
+GDBRemoteRegisterContext::WriteRegisterValue (uint32_t reg, const Scalar &value)
+{
+ const RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg);
+ if (reg_info)
+ {
+ DataExtractor data;
+ if (value.GetData (data, reg_info->byte_size))
+ return WriteRegisterBytes (reg, data, 0);
+ }
+ return false;
+}
+
+
+bool
+GDBRemoteRegisterContext::WriteRegisterBytes (uint32_t reg, DataExtractor &data, uint32_t data_offset)
+{
+ GDBRemoteCommunication &gdb_comm = GetGDBProcess().GetGDBRemote();
+// FIXME: This check isn't right because IsRunning checks the Public state, but this
+// is work you need to do - for instance in ShouldStop & friends - before the public
+// state has been changed.
+// if (gdb_comm.IsRunning())
+// return false;
+
+ const RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg);
+
+ if (reg_info)
+ {
+ // Grab a pointer to where we are going to put this register
+ uint8_t *dst = (uint8_t *)m_reg_data.PeekData(reg_info->byte_offset, reg_info->byte_size);
+
+ if (dst == NULL)
+ return false;
+
+ // Grab a pointer to where we are going to grab the new value from
+ const uint8_t *src = data.PeekData(0, reg_info->byte_size);
+
+ if (src == NULL)
+ return false;
+
+ if (data.GetByteOrder() == m_reg_data.GetByteOrder())
+ {
+ // No swapping, just copy the bytes
+ ::memcpy (dst, src, reg_info->byte_size);
+ }
+ else
+ {
+ // Swap the bytes
+ for (uint32_t i=0; i<reg_info->byte_size; ++i)
+ dst[i] = src[reg_info->byte_size - 1 - i];
+ }
+
+ Mutex::Locker locker;
+ if (gdb_comm.GetSequenceMutex (locker))
+ {
+ if (GetGDBProcess().SetCurrentGDBRemoteThread(m_thread.GetID()))
+ {
+ uint32_t offset, end_offset;
+ StreamString packet;
+ StringExtractorGDBRemote response;
+ if (m_read_all_at_once)
+ {
+ // Get all registers in one packet
+ packet.PutChar ('G');
+ offset = 0;
+ end_offset = m_reg_data.GetByteSize();
+
+ packet.PutBytesAsRawHex8 (m_reg_data.GetDataStart(),
+ m_reg_data.GetByteSize(),
+ eByteOrderHost,
+ eByteOrderHost);
+
+ // Invalidate all register values
+ Invalidate ();
+
+ if (gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(),
+ packet.GetString().size(),
+ response,
+ 1,
+ false))
+ {
+ SetAllRegisterValid (false);
+ if (response.IsOKPacket())
+ {
+ return true;
+ }
+ }
+ }
+ else
+ {
+ // Get each register individually
+ packet.Printf ("P%x=", reg);
+ packet.PutBytesAsRawHex8 (m_reg_data.PeekData(reg_info->byte_offset, reg_info->byte_size),
+ reg_info->byte_size,
+ eByteOrderHost,
+ eByteOrderHost);
+
+ // Invalidate just this register
+ m_reg_valid[reg] = false;
+ if (gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(),
+ packet.GetString().size(),
+ response,
+ 1,
+ false))
+ {
+ if (response.IsOKPacket())
+ {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+ return false;
+}
+
+
+bool
+GDBRemoteRegisterContext::ReadAllRegisterValues (lldb::DataBufferSP &data_sp)
+{
+ GDBRemoteCommunication &gdb_comm = GetGDBProcess().GetGDBRemote();
+ StringExtractorGDBRemote response;
+ if (gdb_comm.SendPacketAndWaitForResponse("g", response, 1, false))
+ {
+ if (response.IsErrorPacket())
+ return false;
+
+ response.GetStringRef().insert(0, 1, 'G');
+ data_sp.reset (new DataBufferHeap(response.GetStringRef().data(),
+ response.GetStringRef().size()));
+ return true;
+ }
+ return false;
+}
+
+bool
+GDBRemoteRegisterContext::WriteAllRegisterValues (const lldb::DataBufferSP &data_sp)
+{
+ GDBRemoteCommunication &gdb_comm = GetGDBProcess().GetGDBRemote();
+ StringExtractorGDBRemote response;
+ if (gdb_comm.SendPacketAndWaitForResponse((const char *)data_sp->GetBytes(),
+ data_sp->GetByteSize(),
+ response,
+ 1,
+ false))
+ {
+ if (response.IsOKPacket())
+ return true;
+ }
+ return false;
+}
+
+
+uint32_t
+GDBRemoteRegisterContext::ConvertRegisterKindToRegisterNumber (uint32_t kind, uint32_t num)
+{
+ return m_reg_info.ConvertRegisterKindToRegisterNumber (kind, num);
+}
+
+void
+GDBRemoteDynamicRegisterInfo::HardcodeARMRegisters()
+{
+ static lldb::RegisterInfo
+ g_register_infos[] =
+ {
+ // NAME ALT SZ OFF ENCODING FORMAT NUM COMPILER DWARF GENERIC
+ // ====== ======= == ==== ============= ============ === =============== =============== =========
+ { "r0", NULL, 4, 0, eEncodingUint, eFormatHex, 0, { gcc_r0, dwarf_r0, LLDB_INVALID_REGNUM }},
+ { "r1", NULL, 4, 4, eEncodingUint, eFormatHex, 1, { gcc_r1, dwarf_r1, LLDB_INVALID_REGNUM }},
+ { "r2", NULL, 4, 8, eEncodingUint, eFormatHex, 2, { gcc_r2, dwarf_r2, LLDB_INVALID_REGNUM }},
+ { "r3", NULL, 4, 12, eEncodingUint, eFormatHex, 3, { gcc_r3, dwarf_r3, LLDB_INVALID_REGNUM }},
+ { "r4", NULL, 4, 16, eEncodingUint, eFormatHex, 4, { gcc_r4, dwarf_r4, LLDB_INVALID_REGNUM }},
+ { "r5", NULL, 4, 20, eEncodingUint, eFormatHex, 5, { gcc_r5, dwarf_r5, LLDB_INVALID_REGNUM }},
+ { "r6", NULL, 4, 24, eEncodingUint, eFormatHex, 6, { gcc_r6, dwarf_r6, LLDB_INVALID_REGNUM }},
+ { "r7", NULL, 4, 28, eEncodingUint, eFormatHex, 7, { gcc_r7, dwarf_r7, LLDB_REGNUM_GENERIC_FP }},
+ { "r8", NULL, 4, 32, eEncodingUint, eFormatHex, 8, { gcc_r8, dwarf_r8, LLDB_INVALID_REGNUM }},
+ { "r9", NULL, 4, 36, eEncodingUint, eFormatHex, 9, { gcc_r9, dwarf_r9, LLDB_INVALID_REGNUM }},
+ { "r10", NULL, 4, 40, eEncodingUint, eFormatHex, 10, { gcc_r10, dwarf_r10, LLDB_INVALID_REGNUM }},
+ { "r11", NULL, 4, 44, eEncodingUint, eFormatHex, 11, { gcc_r11, dwarf_r11, LLDB_INVALID_REGNUM }},
+ { "r12", NULL, 4, 48, eEncodingUint, eFormatHex, 12, { gcc_r12, dwarf_r12, LLDB_INVALID_REGNUM }},
+ { "sp", "r13", 4, 52, eEncodingUint, eFormatHex, 13, { gcc_sp, dwarf_sp, LLDB_REGNUM_GENERIC_SP }},
+ { "lr", "r14", 4, 56, eEncodingUint, eFormatHex, 14, { gcc_lr, dwarf_lr, LLDB_REGNUM_GENERIC_RA }},
+ { "pc", "r15", 4, 60, eEncodingUint, eFormatHex, 15, { gcc_pc, dwarf_pc, LLDB_REGNUM_GENERIC_PC }},
+ { NULL, NULL, 12, 64, eEncodingIEEE754, eFormatFloat, 16, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 76, eEncodingIEEE754, eFormatFloat, 17, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 88, eEncodingIEEE754, eFormatFloat, 18, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 100, eEncodingIEEE754, eFormatFloat, 19, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 112, eEncodingIEEE754, eFormatFloat, 20, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 124, eEncodingIEEE754, eFormatFloat, 21, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 136, eEncodingIEEE754, eFormatFloat, 22, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 148, eEncodingIEEE754, eFormatFloat, 23, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { NULL, NULL, 12, 160, eEncodingIEEE754, eFormatFloat, 24, { LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS, LLDB_REGNUM_GENERIC_FLAGS }},
+ { "cpsr", "psr", 4, 172, eEncodingUint, eFormatHex, 25, { gcc_cpsr, dwarf_cpsr, LLDB_REGNUM_GENERIC_FLAGS }},
+ { "s0", NULL, 4, 176, eEncodingIEEE754, eFormatFloat, 26, { LLDB_INVALID_REGNUM, dwarf_s0, LLDB_INVALID_REGNUM }},
+ { "s1", NULL, 4, 180, eEncodingIEEE754, eFormatFloat, 27, { LLDB_INVALID_REGNUM, dwarf_s1, LLDB_INVALID_REGNUM }},
+ { "s2", NULL, 4, 184, eEncodingIEEE754, eFormatFloat, 28, { LLDB_INVALID_REGNUM, dwarf_s2, LLDB_INVALID_REGNUM }},
+ { "s3", NULL, 4, 188, eEncodingIEEE754, eFormatFloat, 29, { LLDB_INVALID_REGNUM, dwarf_s3, LLDB_INVALID_REGNUM }},
+ { "s4", NULL, 4, 192, eEncodingIEEE754, eFormatFloat, 30, { LLDB_INVALID_REGNUM, dwarf_s4, LLDB_INVALID_REGNUM }},
+ { "s5", NULL, 4, 196, eEncodingIEEE754, eFormatFloat, 31, { LLDB_INVALID_REGNUM, dwarf_s5, LLDB_INVALID_REGNUM }},
+ { "s6", NULL, 4, 200, eEncodingIEEE754, eFormatFloat, 32, { LLDB_INVALID_REGNUM, dwarf_s6, LLDB_INVALID_REGNUM }},
+ { "s7", NULL, 4, 204, eEncodingIEEE754, eFormatFloat, 33, { LLDB_INVALID_REGNUM, dwarf_s7, LLDB_INVALID_REGNUM }},
+ { "s8", NULL, 4, 208, eEncodingIEEE754, eFormatFloat, 34, { LLDB_INVALID_REGNUM, dwarf_s8, LLDB_INVALID_REGNUM }},
+ { "s9", NULL, 4, 212, eEncodingIEEE754, eFormatFloat, 35, { LLDB_INVALID_REGNUM, dwarf_s9, LLDB_INVALID_REGNUM }},
+ { "s10", NULL, 4, 216, eEncodingIEEE754, eFormatFloat, 36, { LLDB_INVALID_REGNUM, dwarf_s10, LLDB_INVALID_REGNUM }},
+ { "s11", NULL, 4, 220, eEncodingIEEE754, eFormatFloat, 37, { LLDB_INVALID_REGNUM, dwarf_s11, LLDB_INVALID_REGNUM }},
+ { "s12", NULL, 4, 224, eEncodingIEEE754, eFormatFloat, 38, { LLDB_INVALID_REGNUM, dwarf_s12, LLDB_INVALID_REGNUM }},
+ { "s13", NULL, 4, 228, eEncodingIEEE754, eFormatFloat, 39, { LLDB_INVALID_REGNUM, dwarf_s13, LLDB_INVALID_REGNUM }},
+ { "s14", NULL, 4, 232, eEncodingIEEE754, eFormatFloat, 40, { LLDB_INVALID_REGNUM, dwarf_s14, LLDB_INVALID_REGNUM }},
+ { "s15", NULL, 4, 236, eEncodingIEEE754, eFormatFloat, 41, { LLDB_INVALID_REGNUM, dwarf_s15, LLDB_INVALID_REGNUM }},
+ { "s16", NULL, 4, 240, eEncodingIEEE754, eFormatFloat, 42, { LLDB_INVALID_REGNUM, dwarf_s16, LLDB_INVALID_REGNUM }},
+ { "s17", NULL, 4, 244, eEncodingIEEE754, eFormatFloat, 43, { LLDB_INVALID_REGNUM, dwarf_s17, LLDB_INVALID_REGNUM }},
+ { "s18", NULL, 4, 248, eEncodingIEEE754, eFormatFloat, 44, { LLDB_INVALID_REGNUM, dwarf_s18, LLDB_INVALID_REGNUM }},
+ { "s19", NULL, 4, 252, eEncodingIEEE754, eFormatFloat, 45, { LLDB_INVALID_REGNUM, dwarf_s19, LLDB_INVALID_REGNUM }},
+ { "s20", NULL, 4, 256, eEncodingIEEE754, eFormatFloat, 46, { LLDB_INVALID_REGNUM, dwarf_s20, LLDB_INVALID_REGNUM }},
+ { "s21", NULL, 4, 260, eEncodingIEEE754, eFormatFloat, 47, { LLDB_INVALID_REGNUM, dwarf_s21, LLDB_INVALID_REGNUM }},
+ { "s22", NULL, 4, 264, eEncodingIEEE754, eFormatFloat, 48, { LLDB_INVALID_REGNUM, dwarf_s22, LLDB_INVALID_REGNUM }},
+ { "s23", NULL, 4, 268, eEncodingIEEE754, eFormatFloat, 49, { LLDB_INVALID_REGNUM, dwarf_s23, LLDB_INVALID_REGNUM }},
+ { "s24", NULL, 4, 272, eEncodingIEEE754, eFormatFloat, 50, { LLDB_INVALID_REGNUM, dwarf_s24, LLDB_INVALID_REGNUM }},
+ { "s25", NULL, 4, 276, eEncodingIEEE754, eFormatFloat, 51, { LLDB_INVALID_REGNUM, dwarf_s25, LLDB_INVALID_REGNUM }},
+ { "s26", NULL, 4, 280, eEncodingIEEE754, eFormatFloat, 52, { LLDB_INVALID_REGNUM, dwarf_s26, LLDB_INVALID_REGNUM }},
+ { "s27", NULL, 4, 284, eEncodingIEEE754, eFormatFloat, 53, { LLDB_INVALID_REGNUM, dwarf_s27, LLDB_INVALID_REGNUM }},
+ { "s28", NULL, 4, 288, eEncodingIEEE754, eFormatFloat, 54, { LLDB_INVALID_REGNUM, dwarf_s28, LLDB_INVALID_REGNUM }},
+ { "s29", NULL, 4, 292, eEncodingIEEE754, eFormatFloat, 55, { LLDB_INVALID_REGNUM, dwarf_s29, LLDB_INVALID_REGNUM }},
+ { "s30", NULL, 4, 296, eEncodingIEEE754, eFormatFloat, 56, { LLDB_INVALID_REGNUM, dwarf_s30, LLDB_INVALID_REGNUM }},
+ { "s31", NULL, 4, 300, eEncodingIEEE754, eFormatFloat, 57, { LLDB_INVALID_REGNUM, dwarf_s31, LLDB_INVALID_REGNUM }},
+ { "fpscr", NULL, 4, 304, eEncodingUint, eFormatHex, 58, { LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM,LLDB_INVALID_REGNUM }},
+ { "d16", NULL, 8, 308, eEncodingIEEE754, eFormatFloat, 59, { LLDB_INVALID_REGNUM, dwarf_d16, LLDB_INVALID_REGNUM }},
+ { "d17", NULL, 8, 316, eEncodingIEEE754, eFormatFloat, 60, { LLDB_INVALID_REGNUM, dwarf_d17, LLDB_INVALID_REGNUM }},
+ { "d18", NULL, 8, 324, eEncodingIEEE754, eFormatFloat, 61, { LLDB_INVALID_REGNUM, dwarf_d18, LLDB_INVALID_REGNUM }},
+ { "d19", NULL, 8, 332, eEncodingIEEE754, eFormatFloat, 62, { LLDB_INVALID_REGNUM, dwarf_d19, LLDB_INVALID_REGNUM }},
+ { "d20", NULL, 8, 340, eEncodingIEEE754, eFormatFloat, 63, { LLDB_INVALID_REGNUM, dwarf_d20, LLDB_INVALID_REGNUM }},
+ { "d21", NULL, 8, 348, eEncodingIEEE754, eFormatFloat, 64, { LLDB_INVALID_REGNUM, dwarf_d21, LLDB_INVALID_REGNUM }},
+ { "d22", NULL, 8, 356, eEncodingIEEE754, eFormatFloat, 65, { LLDB_INVALID_REGNUM, dwarf_d22, LLDB_INVALID_REGNUM }},
+ { "d23", NULL, 8, 364, eEncodingIEEE754, eFormatFloat, 66, { LLDB_INVALID_REGNUM, dwarf_d23, LLDB_INVALID_REGNUM }},
+ { "d24", NULL, 8, 372, eEncodingIEEE754, eFormatFloat, 67, { LLDB_INVALID_REGNUM, dwarf_d24, LLDB_INVALID_REGNUM }},
+ { "d25", NULL, 8, 380, eEncodingIEEE754, eFormatFloat, 68, { LLDB_INVALID_REGNUM, dwarf_d25, LLDB_INVALID_REGNUM }},
+ { "d26", NULL, 8, 388, eEncodingIEEE754, eFormatFloat, 69, { LLDB_INVALID_REGNUM, dwarf_d26, LLDB_INVALID_REGNUM }},
+ { "d27", NULL, 8, 396, eEncodingIEEE754, eFormatFloat, 70, { LLDB_INVALID_REGNUM, dwarf_d27, LLDB_INVALID_REGNUM }},
+ { "d28", NULL, 8, 404, eEncodingIEEE754, eFormatFloat, 71, { LLDB_INVALID_REGNUM, dwarf_d28, LLDB_INVALID_REGNUM }},
+ { "d29", NULL, 8, 412, eEncodingIEEE754, eFormatFloat, 72, { LLDB_INVALID_REGNUM, dwarf_d29, LLDB_INVALID_REGNUM }},
+ { "d30", NULL, 8, 420, eEncodingIEEE754, eFormatFloat, 73, { LLDB_INVALID_REGNUM, dwarf_d30, LLDB_INVALID_REGNUM }},
+ { "d31", NULL, 8, 428, eEncodingIEEE754, eFormatFloat, 74, { LLDB_INVALID_REGNUM, dwarf_d31, LLDB_INVALID_REGNUM }},
+ };
+ static const uint32_t num_registers = sizeof (g_register_infos)/sizeof (lldb::RegisterInfo);
+ static ConstString gpr_reg_set ("General Purpose Registers");
+ static ConstString vfp_reg_set ("Floating Point Registers");
+ for (uint32_t i=0; i<num_registers; ++i)
+ {
+ ConstString name;
+ ConstString alt_name;
+ if (g_register_infos[i].name && g_register_infos[i].name[0])
+ name.SetCString(g_register_infos[i].name);
+ if (g_register_infos[i].alt_name && g_register_infos[i].alt_name[0])
+ alt_name.SetCString(g_register_infos[i].alt_name);
+
+ AddRegister (g_register_infos[i], name, alt_name, i < 26 ? gpr_reg_set : vfp_reg_set);
+ }
+}
+
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h
new file mode 100644
index 00000000000..67acdefdce0
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h
@@ -0,0 +1,250 @@
+//===-- GDBRemoteRegisterContext.h ------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef lldb_GDBRemoteRegisterContext_h_
+#define lldb_GDBRemoteRegisterContext_h_
+
+// C Includes
+// C++ Includes
+#include <vector>
+
+// Other libraries and framework includes
+// Project includes
+#include "lldb/lldb-private.h"
+#include "lldb/Core/ConstString.h"
+#include "lldb/Core/DataExtractor.h"
+#include "lldb/Target/RegisterContext.h"
+
+
+class ThreadGDBRemote;
+class ProcessGDBRemote;
+
+class GDBRemoteDynamicRegisterInfo
+{
+public:
+ GDBRemoteDynamicRegisterInfo () :
+ m_regs (),
+ m_sets (),
+ m_set_reg_nums (),
+ m_reg_names (),
+ m_reg_alt_names (),
+ m_set_names (),
+ m_reg_data_byte_size (0)
+ {
+ }
+
+ ~GDBRemoteDynamicRegisterInfo ()
+ {
+ }
+
+ void
+ AddRegister (lldb::RegisterInfo &reg_info, lldb_private::ConstString &reg_name, lldb_private::ConstString &reg_alt_name, lldb_private::ConstString &set_name)
+ {
+ const uint32_t reg_num = m_regs.size();
+ m_reg_names.push_back (reg_name);
+ m_reg_alt_names.push_back (reg_alt_name);
+ reg_info.name = reg_name.AsCString();
+ assert (reg_info.name);
+ reg_info.alt_name = reg_alt_name.AsCString(NULL);
+ m_regs.push_back (reg_info);
+ uint32_t set = GetRegisterSetIndexByName (set_name, true);
+ assert (set < m_sets.size());
+ assert (set < m_set_reg_nums.size());
+ assert (set < m_set_names.size());
+ m_set_reg_nums[set].push_back(reg_num);
+ size_t end_reg_offset = reg_info.byte_offset + reg_info.byte_size;
+ if (m_reg_data_byte_size < end_reg_offset)
+ m_reg_data_byte_size = end_reg_offset;
+ }
+
+ void
+ Finalize ()
+ {
+ for (uint32_t set = 0; set < m_sets.size(); ++set)
+ {
+ assert (m_sets.size() == m_set_reg_nums.size());
+ m_sets[set].num_registers = m_set_reg_nums[set].size();
+ m_sets[set].registers = &m_set_reg_nums[set][0];
+ }
+ }
+
+ size_t
+ GetNumRegisters() const
+ {
+ return m_regs.size();
+ }
+
+ size_t
+ GetNumRegisterSets() const
+ {
+ return m_sets.size();
+ }
+
+ size_t
+ GetRegisterDataByteSize() const
+ {
+ return m_reg_data_byte_size;
+ }
+
+ const lldb::RegisterInfo *
+ GetRegisterInfoAtIndex (uint32_t i) const
+ {
+ if (i < m_regs.size())
+ return &m_regs[i];
+ return NULL;
+ }
+
+ const lldb::RegisterSet *
+ GetRegisterSet (uint32_t i) const
+ {
+ if (i < m_sets.size())
+ return &m_sets[i];
+ return NULL;
+ }
+
+ uint32_t
+ GetRegisterSetIndexByName (lldb_private::ConstString &set_name, bool can_create)
+ {
+ name_collection::iterator pos, end = m_set_names.end();
+ for (pos = m_set_names.begin(); pos != end; ++pos)
+ {
+ if (*pos == set_name)
+ return std::distance (m_set_names.begin(), pos);
+ }
+
+ m_set_names.push_back(set_name);
+ m_set_reg_nums.resize(m_set_reg_nums.size()+1);
+ lldb::RegisterSet new_set = { set_name.AsCString(), NULL, 0, NULL };
+ m_sets.push_back (new_set);
+ return m_sets.size() - 1;
+ }
+
+ uint32_t
+ ConvertRegisterKindToRegisterNumber (uint32_t kind, uint32_t num) const
+ {
+ reg_collection::const_iterator pos, end = m_regs.end();
+ for (pos = m_regs.begin(); pos != end; ++pos)
+ {
+ if (pos->kinds[kind] == num)
+ return std::distance (m_regs.begin(), pos);
+ }
+
+ return LLDB_INVALID_REGNUM;
+ }
+ void
+ Clear()
+ {
+ m_regs.clear();
+ m_sets.clear();
+ m_set_reg_nums.clear();
+ m_reg_names.clear();
+ m_reg_alt_names.clear();
+ m_set_names.clear();
+ }
+
+ void
+ HardcodeARMRegisters();
+
+protected:
+ //------------------------------------------------------------------
+ // Classes that inherit from GDBRemoteRegisterContext can see and modify these
+ //------------------------------------------------------------------
+ typedef std::vector <lldb::RegisterInfo> reg_collection;
+ typedef std::vector <lldb::RegisterSet> set_collection;
+ typedef std::vector <uint32_t> reg_num_collection;
+ typedef std::vector <reg_num_collection> set_reg_num_collection;
+ typedef std::vector <lldb_private::ConstString> name_collection;
+
+ reg_collection m_regs;
+ set_collection m_sets;
+ set_reg_num_collection m_set_reg_nums;
+ name_collection m_reg_names;
+ name_collection m_reg_alt_names;
+ name_collection m_set_names;
+ size_t m_reg_data_byte_size; // The number of bytes required to store all registers
+};
+
+class GDBRemoteRegisterContext : public lldb_private::RegisterContext
+{
+public:
+ //------------------------------------------------------------------
+ // Constructors and Destructors
+ //------------------------------------------------------------------
+ GDBRemoteRegisterContext (ThreadGDBRemote &thread,
+ lldb_private::StackFrame *frame,
+ GDBRemoteDynamicRegisterInfo &reg_info,
+ bool read_all_at_once);
+
+ virtual
+ ~GDBRemoteRegisterContext ();
+
+ //------------------------------------------------------------------
+ // Subclasses must override these functions
+ //------------------------------------------------------------------
+ virtual void
+ Invalidate ();
+
+ virtual size_t
+ GetRegisterCount ();
+
+ virtual const lldb::RegisterInfo *
+ GetRegisterInfoAtIndex (uint32_t reg);
+
+ virtual size_t
+ GetRegisterSetCount ();
+
+ virtual const lldb::RegisterSet *
+ GetRegisterSet (uint32_t reg_set);
+
+ virtual bool
+ ReadRegisterValue (uint32_t reg, lldb_private::Scalar &value);
+
+ virtual bool
+ ReadRegisterBytes (uint32_t reg, lldb_private::DataExtractor &data);
+
+ virtual bool
+ ReadAllRegisterValues (lldb::DataBufferSP &data_sp);
+
+ virtual bool
+ WriteRegisterValue (uint32_t reg, const lldb_private::Scalar &value);
+
+ virtual bool
+ WriteRegisterBytes (uint32_t reg, lldb_private::DataExtractor &data, uint32_t data_offset);
+
+ virtual bool
+ WriteAllRegisterValues (const lldb::DataBufferSP &data_sp);
+
+ virtual uint32_t
+ ConvertRegisterKindToRegisterNumber (uint32_t kind, uint32_t num);
+
+protected:
+
+ void
+ SetAllRegisterValid (bool b);
+
+ ProcessGDBRemote &
+ GetGDBProcess();
+
+ ThreadGDBRemote &
+ GetGDBThread();
+
+ GDBRemoteDynamicRegisterInfo &m_reg_info;
+ std::vector<bool> m_reg_valid;
+ uint32_t m_reg_valid_stop_id;
+ lldb_private::DataExtractor m_reg_data;
+ bool m_read_all_at_once;
+
+private:
+ //------------------------------------------------------------------
+ // For GDBRemoteRegisterContext only
+ //------------------------------------------------------------------
+ DISALLOW_COPY_AND_ASSIGN (GDBRemoteRegisterContext);
+};
+
+#endif // lldb_GDBRemoteRegisterContext_h_
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBServer.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBServer.cpp
new file mode 100644
index 00000000000..a88ec7b09d4
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBServer.cpp
@@ -0,0 +1,1148 @@
+//===-- GDBServer.cpp -------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <errno.h>
+#include <getopt.h>
+#include <netinet/in.h>
+#include <sys/select.h>
+#include <sys/sysctl.h>
+#include <string>
+#include <vector>
+#include <asl.h>
+
+#include "GDBServerLog.h"
+#include "GDBRemoteSession.h"
+
+using namespace lldb;
+
+//----------------------------------------------------------------------
+// Run loop modes which determine which run loop function will be called
+//----------------------------------------------------------------------
+typedef enum
+{
+ eDCGSRunLoopModeInvalid = 0,
+ eDCGSRunLoopModeGetStartModeFromRemoteProtocol,
+ eDCGSRunLoopModeInferiorAttaching,
+ eDCGSRunLoopModeInferiorLaunching,
+ eDCGSRunLoopModeInferiorExecuting,
+ eDCGSRunLoopModeInferiorKillOrDetach,
+ eDCGSRunLoopModeExit
+} GSRunLoopMode;
+
+typedef enum
+{
+ eLaunchFlavorDefault = 0,
+ eLaunchFlavorPosixSpawn,
+#if defined (__arm__)
+ eLaunchFlavorSpringBoard,
+#endif
+ eLaunchFlavorForkExec,
+} GSLaunchFlavor;
+
+typedef lldb::shared_ptr<GDBRemoteSession> GDBRemoteSP;
+
+typedef struct HandleBroadcastEventInfo
+{
+ TargetSP target_sp;
+ GDBRemoteSP remote_sp;
+ GSRunLoopMode mode;
+
+ Target *
+ GetTarget ()
+ {
+ return target_sp.get();
+ }
+
+ Process *
+ GetProcess()
+ {
+ if (target_sp.get())
+ return target_sp->GetProcess().get();
+ return NULL;
+ }
+
+ GDBRemoteSession *
+ GetRemote ()
+ {
+ return remote_sp.get();
+ }
+
+};
+
+
+//----------------------------------------------------------------------
+// Global Variables
+//----------------------------------------------------------------------
+static int g_lockdown_opt = 0;
+static int g_applist_opt = 0;
+static GSLaunchFlavor g_launch_flavor = eLaunchFlavorDefault;
+int g_isatty = 0;
+
+//----------------------------------------------------------------------
+// Run Loop function prototypes
+//----------------------------------------------------------------------
+void GSRunLoopGetStartModeFromRemote (HandleBroadcastEventInfo *info);
+void GSRunLoopInferiorExecuting (HandleBroadcastEventInfo *info);
+
+
+//----------------------------------------------------------------------
+// Get our program path and arguments from the remote connection.
+// We will need to start up the remote connection without a PID, get the
+// arguments, wait for the new process to finish launching and hit its
+// entry point, and then return the run loop mode that should come next.
+//----------------------------------------------------------------------
+void
+GSRunLoopGetStartModeFromRemote (HandleBroadcastEventInfo *info)
+{
+ std::string packet;
+
+ Target *target = info->GetTarget();
+ GDBRemoteSession *remote = info->GetRemote();
+ if (target != NULL && remote != NULL)
+ {
+ // Spin waiting to get the A packet.
+ while (1)
+ {
+ gdb_err_t err = gdb_err;
+ GDBRemoteSession::PacketEnum type;
+
+ err = remote->HandleReceivedPacket (&type);
+
+ // check if we tried to attach to a process
+ if (type == GDBRemoteSession::vattach || type == GDBRemoteSession::vattachwait)
+ {
+ if (err == gdb_success)
+ {
+ info->mode = eDCGSRunLoopModeInferiorExecuting;
+ return;
+ }
+ else
+ {
+ Log::STDERR ("error: attach failed.");
+ info->mode = eDCGSRunLoopModeExit;
+ return;
+ }
+ }
+
+ if (err == gdb_success)
+ {
+ // If we got our arguments we are ready to launch using the arguments
+ // and any environment variables we received.
+ if (type == GDBRemoteSession::set_argv)
+ {
+ info->mode = eDCGSRunLoopModeInferiorLaunching;
+ return;
+ }
+ }
+ else if (err == gdb_not_connected)
+ {
+ Log::STDERR ("error: connection lost.");
+ info->mode = eDCGSRunLoopModeExit;
+ return;
+ }
+ else
+ {
+ // a catch all for any other gdb remote packets that failed
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Error getting packet.",__FUNCTION__);
+ continue;
+ }
+
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "#### %s", __FUNCTION__);
+ }
+ }
+ info->mode = eDCGSRunLoopModeExit;
+}
+
+
+//----------------------------------------------------------------------
+// This run loop mode will wait for the process to launch and hit its
+// entry point. It will currently ignore all events except for the
+// process state changed event, where it watches for the process stopped
+// or crash process state.
+//----------------------------------------------------------------------
+GSRunLoopMode
+GSRunLoopLaunchInferior (HandleBroadcastEventInfo *info)
+{
+ // The Process stuff takes a c array, the GSContext has a vector...
+ // So make up a c array.
+ Target *target = info->GetTarget();
+ GDBRemoteSession *remote = info->GetRemote();
+ Process* process = info->GetProcess();
+
+ if (process == NULL)
+ return eDCGSRunLoopModeExit;
+
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Launching '%s'...", __FUNCTION__, target->GetExecutableModule()->GetFileSpec().GetFilename().AsCString());
+
+ // Our launch type hasn't been set to anything concrete, so we need to
+ // figure our how we are going to launch automatically.
+
+ GSLaunchFlavor launch_flavor = g_launch_flavor;
+ if (launch_flavor == eLaunchFlavorDefault)
+ {
+ // Our default launch method is posix spawn
+ launch_flavor = eLaunchFlavorPosixSpawn;
+
+#if defined (__arm__)
+ // Check if we have an app bundle, if so launch using SpringBoard.
+ if (strstr(inferior_argv[0], ".app"))
+ {
+ launch_flavor = eLaunchFlavorSpringBoard;
+ }
+#endif
+ }
+
+ //ctx.SetLaunchFlavor(launch_flavor);
+
+ const char *stdio_file = NULL;
+ lldb::pid_t pid = process->Launch (remote->GetARGV(), remote->GetENVP(), stdio_file, stdio_file, stdio_file);
+
+ if (pid == LLDB_INVALID_PROCESS_ID)
+ {
+ Log::STDERR ("error: process launch failed: %s", process->GetError().AsCString());
+ }
+ else
+ {
+ if (remote->IsConnected())
+ {
+ // It we are connected already, the next thing gdb will do is ask
+ // whether the launch succeeded, and if not, whether there is an
+ // error code. So we need to fetch one packet from gdb before we wait
+ // on the stop from the target.
+ gdb_err_t err = gdb_err;
+ GDBRemoteSession::PacketEnum type;
+
+ err = remote->HandleReceivedPacket (&type);
+
+ if (err != gdb_success)
+ {
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Error getting packet.", __FUNCTION__);
+ return eDCGSRunLoopModeExit;
+ }
+ if (type != GDBRemoteSession::query_launch_success)
+ {
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Didn't get the expected qLaunchSuccess packet.", __FUNCTION__);
+ }
+ }
+ }
+
+ Listener listener("GSRunLoopLaunchInferior");
+ listener.StartListeningForEvents (process, Process::eBroadcastBitStateChanged);
+ while (process->GetID() != LLDB_INVALID_PROCESS_ID)
+ {
+ uint32_t event_mask = 0;
+ while (listener.WaitForEvent(NULL, &event_mask))
+ {
+ if (event_mask & Process::eBroadcastBitStateChanged)
+ {
+ Event event;
+ StateType event_state;
+ while ((event_state = process->GetNextEvent (&event)))
+ if (StateIsStoppedState(event_state))
+ {
+ GDBServerLog::LogIf (GS_LOG_EVENTS, "%s process %4.4x stopped with state %s", __FUNCTION__, pid, StateAsCString(event_state));
+
+ switch (event_state)
+ {
+ default:
+ case eStateInvalid:
+ case eStateUnloaded:
+ case eStateAttaching:
+ case eStateLaunching:
+ case eStateSuspended:
+ break; // Ignore
+
+ case eStateRunning:
+ case eStateStepping:
+ // Still waiting to stop at entry point...
+ break;
+
+ case eStateStopped:
+ case eStateCrashed:
+ return eDCGSRunLoopModeInferiorExecuting;
+
+ case eStateDetached:
+ case eStateExited:
+ pid = LLDB_INVALID_PROCESS_ID;
+ return eDCGSRunLoopModeExit;
+ }
+ }
+
+ if (event_state = eStateInvalid)
+ break;
+ }
+ }
+ }
+
+ return eDCGSRunLoopModeExit;
+}
+
+
+//----------------------------------------------------------------------
+// This run loop mode will wait for the process to launch and hit its
+// entry point. It will currently ignore all events except for the
+// process state changed event, where it watches for the process stopped
+// or crash process state.
+//----------------------------------------------------------------------
+GSRunLoopMode
+GSRunLoopLaunchAttaching (HandleBroadcastEventInfo *info, lldb::pid_t& pid)
+{
+ Process* process = info->GetProcess();
+
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Attaching to pid %i...", __FUNCTION__, pid);
+ pid = process->Attach(pid);
+
+ if (pid == LLDB_INVALID_PROCESS_ID)
+ return eDCGSRunLoopModeExit;
+ return eDCGSRunLoopModeInferiorExecuting;
+}
+
+//----------------------------------------------------------------------
+// Watch for signals:
+// SIGINT: so we can halt our inferior. (disabled for now)
+// SIGPIPE: in case our child process dies
+//----------------------------------------------------------------------
+lldb::pid_t g_pid;
+int g_sigpipe_received = 0;
+void
+signal_handler(int signo)
+{
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (%s)", __FUNCTION__, Host::GetSignalAsCString(signo));
+
+ switch (signo)
+ {
+// case SIGINT:
+// DNBProcessKill (g_pid, signo);
+// break;
+
+ case SIGPIPE:
+ g_sigpipe_received = 1;
+ break;
+ }
+}
+
+// Return the new run loop mode based off of the current process state
+void
+HandleProcessStateChange (HandleBroadcastEventInfo *info, bool initialize)
+{
+ Process *process = info->GetProcess();
+ if (process == NULL)
+ {
+ info->mode = eDCGSRunLoopModeExit;
+ return;
+ }
+
+ if (process->GetID() == LLDB_INVALID_PROCESS_ID)
+ {
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "#### %s error: pid invalid, exiting...", __FUNCTION__);
+ info->mode = eDCGSRunLoopModeExit;
+ return;
+ }
+ StateType pid_state = process->GetState ();
+
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (info, initialize=%i) pid_state = %s", __FUNCTION__, (int)initialize, StateAsCString(pid_state));
+
+ switch (pid_state)
+ {
+ case eStateInvalid:
+ case eStateUnloaded:
+ // Something bad happened
+ info->mode = eDCGSRunLoopModeExit;
+ return;
+
+ case eStateAttaching:
+ case eStateLaunching:
+ info->mode = eDCGSRunLoopModeInferiorExecuting;
+ return;
+
+ case eStateSuspended:
+ case eStateCrashed:
+ case eStateStopped:
+ if (initialize == false)
+ {
+ // Compare the last stop count to our current notion of a stop count
+ // to make sure we don't notify more than once for a given stop.
+ static uint32_t g_prev_stop_id = 0;
+ uint32_t stop_id = process->GetStopID();
+ bool pid_stop_count_changed = g_prev_stop_id != stop_id;
+ if (pid_stop_count_changed)
+ {
+ info->GetRemote()->FlushSTDIO();
+
+ if (stop_id == 1)
+ {
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s pid_stop_count %u (old %u)) Notify??? no, first stop...", __FUNCTION__, (int)initialize, StateAsCString (pid_state), stop_id, g_prev_stop_id);
+ }
+ else
+ {
+
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s pid_stop_count %u (old %u)) Notify??? YES!!!", __FUNCTION__, (int)initialize, StateAsCString (pid_state), stop_id, g_prev_stop_id);
+ info->GetRemote()->NotifyThatProcessStopped ();
+ }
+ }
+ else
+ {
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s pid_stop_count %u (old %u)) Notify??? skipping...", __FUNCTION__, (int)initialize, StateAsCString (pid_state), stop_id, g_prev_stop_id);
+ }
+ }
+ info->mode = eDCGSRunLoopModeInferiorExecuting;
+ return;
+
+ case eStateStepping:
+ case eStateRunning:
+ info->mode = eDCGSRunLoopModeInferiorExecuting;
+ return;
+
+ case eStateExited:
+ info->GetRemote()->HandlePacket_last_signal (NULL);
+ info->mode = eDCGSRunLoopModeExit;
+ return;
+
+ }
+
+ // Catch all...
+ info->mode = eDCGSRunLoopModeExit;
+}
+
+bool
+CommunicationHandleBroadcastEvent (Broadcaster *broadcaster, uint32_t event_mask, void *baton)
+{
+ HandleBroadcastEventInfo *info = (HandleBroadcastEventInfo *)baton;
+ Process *process = info->GetProcess();
+
+ if (process == NULL)
+ {
+ info->mode = eDCGSRunLoopModeExit;
+ return true;
+ }
+
+ if (event_mask & Communication::eBroadcastBitPacketAvailable)
+ {
+ if (process->IsRunning())
+ {
+ if (info->GetRemote()->HandleAsyncPacket() == gdb_not_connected)
+ info->mode = eDCGSRunLoopModeExit;
+ }
+ else
+ {
+ if (info->GetRemote()->HandleReceivedPacket() == gdb_not_connected)
+ info->mode = eDCGSRunLoopModeExit;
+ }
+ }
+ if (event_mask & Communication::eBroadcastBitReadThreadDidExit)
+ {
+ info->mode = eDCGSRunLoopModeExit;
+ }
+ if (event_mask & Communication::eBroadcastBitDisconnected)
+ {
+ info->mode = eDCGSRunLoopModeExit;
+ }
+
+ return true;
+
+}
+
+bool
+ProcessHandleBroadcastEvent (Broadcaster *broadcaster, uint32_t event_mask, void *baton)
+{
+ HandleBroadcastEventInfo *info = (HandleBroadcastEventInfo *)baton;
+ Process *process = info->GetProcess();
+ if (process == NULL)
+ {
+ info->mode = eDCGSRunLoopModeExit;
+ return true;
+ }
+
+ if (event_mask & Process::eBroadcastBitStateChanged)
+ {
+ // Consume all available process events with no timeout
+ Event event;
+ StateType process_state;
+ while ((process_state = process->GetNextEvent (&event)) != eStateInvalid)
+ {
+ if (StateIsStoppedState(process_state))
+ info->GetRemote()->FlushSTDIO();
+ HandleProcessStateChange (info, false);
+
+ if (info->mode != eDCGSRunLoopModeInferiorExecuting)
+ break;
+ }
+ }
+ else
+ if (event_mask & (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitSTDERR))
+ {
+ info->GetRemote()->FlushSTDIO();
+ }
+ return true;
+}
+
+// This function handles the case where our inferior program is stopped and
+// we are waiting for gdb remote protocol packets. When a packet occurs that
+// makes the inferior run, we need to leave this function with a new state
+// as the return code.
+void
+GSRunLoopInferiorExecuting (HandleBroadcastEventInfo *info)
+{
+ GDBServerLog::LogIf (GS_LOG_MINIMAL, "#### %s", __FUNCTION__);
+
+ // Init our mode and set 'is_running' based on the current process state
+ HandleProcessStateChange (info, true);
+
+ uint32_t desired_mask, acquired_mask;
+ Listener listener("GSRunLoopInferiorExecuting");
+
+ desired_mask = Communication::eBroadcastBitPacketAvailable |
+ Communication::eBroadcastBitReadThreadDidExit |
+ Communication::eBroadcastBitDisconnected;
+
+ acquired_mask = listener.StartListeningForEvents (&(info->GetRemote()->GetPacketComm()),
+ desired_mask,
+ CommunicationHandleBroadcastEvent,
+ info);
+
+ assert (acquired_mask == desired_mask);
+ desired_mask = GDBRemotePacket::eBroadcastBitPacketAvailable;
+
+ acquired_mask = listener.StartListeningForEvents (&(info->GetRemote()->GetPacketComm()),
+ desired_mask,
+ CommunicationHandleBroadcastEvent,
+ info);
+
+ assert (acquired_mask == desired_mask);
+
+ desired_mask = Process::eBroadcastBitStateChanged |
+ Process::eBroadcastBitSTDOUT |
+ Process::eBroadcastBitSTDERR ;
+ acquired_mask = listener.StartListeningForEvents (info->GetProcess (),
+ desired_mask,
+ ProcessHandleBroadcastEvent,
+ info);
+
+ assert (acquired_mask == desired_mask);
+
+ Process *process = info->GetProcess();
+
+ while (process->IsAlive())
+ {
+ if (!info->GetRemote()->IsConnected())
+ {
+ info->mode = eDCGSRunLoopModeInferiorKillOrDetach;
+ break;
+ }
+
+ // We want to make sure we consume all process state changes and have
+ // whomever is notifying us to wait for us to reset the event bit before
+ // continuing.
+ //ctx.Events().SetResetAckMask (GSContext::event_proc_state_changed);
+ uint32_t event_mask = 0;
+ Broadcaster *broadcaster = listener.WaitForEvent(NULL, &event_mask);
+ if (broadcaster)
+ {
+ listener.HandleBroadcastEvent(broadcaster, event_mask);
+ }
+ }
+}
+
+
+//----------------------------------------------------------------------
+// Convenience function to set up the remote listening port
+// Returns 1 for success 0 for failure.
+//----------------------------------------------------------------------
+
+static bool
+StartListening (HandleBroadcastEventInfo *info, int listen_port)
+{
+ if (!info->GetRemote()->IsConnected())
+ {
+ Log::STDOUT ("Listening to port %i...\n", listen_port);
+ char connect_url[256];
+ snprintf(connect_url, sizeof(connect_url), "listen://%i", listen_port);
+
+ Communication &comm = info->remote_sp->GetPacketComm();
+ comm.SetConnection (new ConnectionFileDescriptor);
+
+ if (comm.Connect (connect_url))
+ {
+ if (comm.StartReadThread())
+ return true;
+
+ Log::STDERR ("Failed to start the communication read thread.\n", connect_url);
+ comm.Disconnect();
+ }
+ else
+ {
+ Log::STDERR ("Failed to connection to %s.\n", connect_url);
+ }
+ return false;
+ }
+ return true;
+}
+
+//----------------------------------------------------------------------
+// ASL Logging callback that can be registered with DNBLogSetLogDCScriptInterpreter::Type
+//----------------------------------------------------------------------
+//void
+//ASLLogDCScriptInterpreter::Type(void *baton, uint32_t flags, const char *format, va_list args)
+//{
+// if (format == NULL)
+// return;
+// static aslmsg g_aslmsg = NULL;
+// if (g_aslmsg == NULL)
+// {
+// g_aslmsg = ::asl_new (ASL_TYPE_MSG);
+// char asl_key_sender[PATH_MAX];
+// snprintf(asl_key_sender, sizeof(asl_key_sender), "com.apple.dc-gdbserver-%g", dc_gdbserverVersionNumber);
+// ::asl_set (g_aslmsg, ASL_KEY_SENDER, asl_key_sender);
+// }
+//
+// int asl_level;
+// if (flags & DNBLOG_FLAG_FATAL) asl_level = ASL_LEVEL_CRIT;
+// else if (flags & DNBLOG_FLAG_ERROR) asl_level = ASL_LEVEL_ERR;
+// else if (flags & DNBLOG_FLAG_WARNING) asl_level = ASL_LEVEL_WARNING;
+// else if (flags & DNBLOG_FLAG_VERBOSE) asl_level = ASL_LEVEL_WARNING; //ASL_LEVEL_INFO;
+// else asl_level = ASL_LEVEL_WARNING; //ASL_LEVEL_DEBUG;
+//
+// ::asl_vlog (NULL, g_aslmsg, asl_level, format, args);
+//}
+
+//----------------------------------------------------------------------
+// FILE based Logging callback that can be registered with
+// DNBLogSetLogDCScriptInterpreter::Type
+//----------------------------------------------------------------------
+void
+FileLogDCScriptInterpreter::Type(void *baton, uint32_t flags, const char *format, va_list args)
+{
+ if (baton == NULL || format == NULL)
+ return;
+
+ ::vfprintf ((FILE *)baton, format, args);
+ ::fprintf ((FILE *)baton, "\n");
+}
+
+//----------------------------------------------------------------------
+// option descriptors for getopt_long()
+//----------------------------------------------------------------------
+static struct option g_long_options[] =
+{
+ { "arch", required_argument, NULL, 'c' },
+ { "attach", required_argument, NULL, 'a' },
+ { "debug", no_argument, NULL, 'g' },
+ { "verbose", no_argument, NULL, 'v' },
+ { "lockdown", no_argument, &g_lockdown_opt, 1 }, // short option "-k"
+ { "applist", no_argument, &g_applist_opt, 1 }, // short option "-t"
+ { "log-file", required_argument, NULL, 'l' },
+ { "log-flags", required_argument, NULL, 'f' },
+ { "launch", required_argument, NULL, 'x' }, // Valid values are "auto", "posix-spawn", "fork-exec", "springboard" (arm only)
+ { "waitfor", required_argument, NULL, 'w' }, // Wait for a process whose namet starts with ARG
+ { "waitfor-interval", required_argument, NULL, 'i' }, // Time in usecs to wait between sampling the pid list when waiting for a process by name
+ { "waitfor-duration", required_argument, NULL, 'd' }, // The time in seconds to wait for a process to show up by name
+ { NULL, 0, NULL, 0 }
+};
+
+extern const double dc_gdbserverVersionNumber;
+int
+main (int argc, char *argv[])
+{
+ Initialize();
+ Host::ThreadCreated ("[main]");
+
+ g_isatty = ::isatty (STDIN_FILENO);
+
+// signal (SIGINT, signal_handler);
+ signal (SIGPIPE, signal_handler);
+
+ Log *log = GDBServerLog::GetLogIfAllCategoriesSet(GS_LOG_ALL);
+ const char *this_exe_name = argv[0];
+ int i;
+ int attach_pid = LLDB_INVALID_PROCESS_ID;
+ for (i=0; i<argc; i++)
+ GDBServerLog::LogIf(GS_LOG_DEBUG, "argv[%i] = %s", i, argv[i]);
+
+ FILE* log_file = NULL;
+ uint32_t log_flags = 0;
+ // Parse our options
+ int ch;
+ int long_option_index = 0;
+ int debug = 0;
+ std::string waitfor_pid_name; // Wait for a process that starts with this name
+ std::string attach_pid_name;
+ useconds_t waitfor_interval = 1000; // Time in usecs between process lists polls when waiting for a process by name, default 1 msec.
+ useconds_t waitfor_duration = 0; // Time in seconds to wait for a process by name, 0 means wait forever.
+ ArchSpec arch;
+ GSRunLoopMode start_mode = eDCGSRunLoopModeExit;
+
+ while ((ch = getopt_long(argc, argv, "a:c:d:gi:vktl:f:w:x:", g_long_options, &long_option_index)) != -1)
+ {
+// DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n",
+// ch, (uint8_t)ch,
+// g_long_options[long_option_index].name,
+// g_long_options[long_option_index].has_arg ? '=' : ' ',
+// optarg ? optarg : "");
+ switch (ch)
+ {
+ case 0: // Any optional that auto set themselves will return 0
+ break;
+
+ case 'c':
+ arch.SetArch(optarg);
+ if (!arch.IsValid())
+ {
+ Log::STDERR ("error: invalid arch string '%s'\n", optarg);
+ exit (8);
+ }
+ break;
+
+ case 'a':
+ if (optarg && optarg[0])
+ {
+ if (isdigit(optarg[0]))
+ {
+ char *end = NULL;
+ attach_pid = strtoul(optarg, &end, 0);
+ if (end == NULL || *end != '\0')
+ {
+ Log::STDERR ("error: invalid pid option '%s'\n", optarg);
+ exit (4);
+ }
+ }
+ else
+ {
+ attach_pid_name = optarg;
+ }
+ start_mode = eDCGSRunLoopModeInferiorAttaching;
+ }
+ break;
+
+ // --waitfor=NAME
+ case 'w':
+ if (optarg && optarg[0])
+ {
+ waitfor_pid_name = optarg;
+ start_mode = eDCGSRunLoopModeInferiorAttaching;
+ }
+ break;
+
+ // --waitfor-interval=USEC
+ case 'i':
+ if (optarg && optarg[0])
+ {
+ char *end = NULL;
+ waitfor_interval = strtoul(optarg, &end, 0);
+ if (end == NULL || *end != '\0')
+ {
+ Log::STDERR ("error: invalid waitfor-interval option value '%s'.\n", optarg);
+ exit (6);
+ }
+ }
+ break;
+
+ // --waitfor-duration=SEC
+ case 'd':
+ if (optarg && optarg[0])
+ {
+ char *end = NULL;
+ waitfor_duration = strtoul(optarg, &end, 0);
+ if (end == NULL || *end != '\0')
+ {
+ Log::STDERR ("error: invalid waitfor-duration option value '%s'.\n", optarg);
+ exit (7);
+ }
+ }
+ break;
+
+ case 'x':
+ if (optarg && optarg[0])
+ {
+ if (strcasecmp(optarg, "auto") == 0)
+ g_launch_flavor = eLaunchFlavorDefault;
+ else if (strcasestr(optarg, "posix") == optarg)
+ g_launch_flavor = eLaunchFlavorPosixSpawn;
+ else if (strcasestr(optarg, "fork") == optarg)
+ g_launch_flavor = eLaunchFlavorForkExec;
+#if defined (__arm__)
+ else if (strcasestr(optarg, "spring") == optarg)
+ g_launch_flavor = eLaunchFlavorSpringBoard;
+#endif
+ else
+ {
+ Log::STDERR ("error: invalid TYPE for the --launch=TYPE (-x TYPE) option: '%s'\n", optarg);
+ Log::STDERR ("Valid values TYPE are:\n");
+ Log::STDERR (" auto Auto-detect the best launch method to use.\n");
+ Log::STDERR (" posix Launch the executable using posix_spawn.\n");
+ Log::STDERR (" fork Launch the executable using fork and exec.\n");
+#if defined (__arm__)
+ Log::STDERR (" spring Launch the executable through Springboard.\n");
+#endif
+ exit (5);
+ }
+ }
+ break;
+
+ case 'l': // Set Log File
+ if (optarg && optarg[0])
+ {
+ if (strcasecmp(optarg, "stdout") == 0)
+ log_file = stdout;
+ else if (strcasecmp(optarg, "stderr") == 0)
+ log_file = stderr;
+ else
+ log_file = fopen(optarg, "w+");
+
+ if (log_file == NULL)
+ {
+ const char *errno_str = strerror(errno);
+ Log::STDERR ("Failed to open log file '%s' for writing: errno = %i (%s)", optarg, errno, errno_str ? errno_str : "unknown error");
+ }
+ }
+ break;
+
+ case 'f': // Log Flags
+ if (optarg && optarg[0])
+ log_flags = strtoul(optarg, NULL, 0);
+ break;
+
+ case 'g':
+ debug = 1;
+ //DNBLogSetDebug(1);
+ break;
+
+ case 't':
+ g_applist_opt = 1;
+ break;
+
+ case 'k':
+ g_lockdown_opt = 1;
+ break;
+
+ case 'v':
+ //DNBLogSetVerbose(1);
+ break;
+ }
+ }
+
+ // Skip any options we consumed with getopt_long
+ argc -= optind;
+ argv += optind;
+
+ // It is ok for us to set NULL as the logfile (this will disable any logging)
+
+// if (log_file != NULL)
+// {
+// DNBLogSetLogDCScriptInterpreter::Type(FileLogDCScriptInterpreter::Type, log_file);
+// // If our log file was set, yet we have no log flags, log everything!
+// if (log_flags == 0)
+// log_flags = LOG_ALL | LOG_DCGS_ALL;
+//
+// DNBLogSetLogMask (log_flags);
+// }
+// else
+// {
+// // Enable DNB logging
+// DNBLogSetLogDCScriptInterpreter::Type(ASLLogDCScriptInterpreter::Type, NULL);
+// DNBLogSetLogMask (log_flags);
+//
+// }
+
+ // as long as we're dropping remotenub in as a replacement for gdbserver,
+ // explicitly note that this is not gdbserver.
+
+ Log::STDOUT ("debugserver-%g \n", dc_gdbserverVersionNumber);
+ int listen_port = -1;
+ if (g_lockdown_opt == 0 && g_applist_opt == 0)
+ {
+ // Make sure we at least have port
+ if (argc < 1)
+ {
+ Log::STDERR ("Usage: %s host:port [program-name program-arg1 program-arg2 ...]\n", this_exe_name);
+ exit (1);
+ }
+ // accept 'localhost:' prefix on port number
+
+ std::string host_str;
+ std::string port_str(argv[0]);
+
+ // We just used the host:port arg...
+ argc--;
+ argv++;
+
+ size_t port_idx = port_str.find(':');
+ if (port_idx != std::string::npos)
+ {
+ host_str.assign(port_str, 0, port_idx);
+ port_str.erase(0, port_idx + 1);
+ }
+
+ if (port_str.empty())
+ {
+ Log::STDERR ("error: no port specified\nUsage: %s host:port [program-name program-arg1 program-arg2 ...]\n", this_exe_name);
+ exit (2);
+ }
+ else if (port_str.find_first_not_of("0123456789") != std::string::npos)
+ {
+ Log::STDERR ("error: port must be an integer: %s\nUsage: %s host:port [program-name program-arg1 program-arg2 ...]\n", port_str.c_str(), this_exe_name);
+ exit (3);
+ }
+ //DNBLogDebug("host_str = '%s' port_str = '%s'", host_str.c_str(), port_str.c_str());
+ listen_port = atoi (port_str.c_str());
+ }
+
+
+ // We must set up some communications now.
+
+ FileSpec exe_spec;
+ if (argv[0])
+ exe_spec.SetFile (argv[0]);
+
+ HandleBroadcastEventInfo info;
+ info.target_sp = TargetList::SharedList().CreateTarget(&exe_spec, &arch);
+ ProcessSP process_sp (info.target_sp->CreateProcess ());
+ info.remote_sp.reset (new GDBRemoteSession (process_sp));
+
+ info.remote_sp->SetLog (log);
+ StreamString sstr;
+ sstr.Printf("ConnectionFileDescriptor(%s)", argv[0]);
+
+ if (info.remote_sp.get() == NULL)
+ {
+ Log::STDERR ("error: failed to create a GDBRemoteSession class\n");
+ return -1;
+ }
+
+
+
+ // If we know we're waiting to attach, we don't need any of this other info.
+ if (start_mode != eDCGSRunLoopModeInferiorAttaching)
+ {
+ if (argc == 0 || g_lockdown_opt)
+ {
+ if (g_lockdown_opt != 0)
+ {
+ // Work around for SIGPIPE crashes due to posix_spawn issue. We have to close
+ // STDOUT and STDERR, else the first time we try and do any, we get SIGPIPE and
+ // die as posix_spawn is doing bad things with our file descriptors at the moment.
+ int null = open("/dev/null", O_RDWR);
+ dup2(null, STDOUT_FILENO);
+ dup2(null, STDERR_FILENO);
+ }
+ else if (g_applist_opt != 0)
+ {
+// // List all applications we are able to see
+// std::string applist_plist;
+// int err = ListApplications(applist_plist, false, false);
+// if (err == 0)
+// {
+// fputs (applist_plist.c_str(), stdout);
+// }
+// else
+// {
+// Log::STDERR ("error: ListApplications returned error %i\n", err);
+// }
+// // Exit with appropriate error if we were asked to list the applications
+// // with no other args were given (and we weren't trying to do this over
+// // lockdown)
+// return err;
+ return 0;
+ }
+
+ //DNBLogDebug("Get args from remote protocol...");
+ start_mode = eDCGSRunLoopModeGetStartModeFromRemoteProtocol;
+ }
+ else
+ {
+ start_mode = eDCGSRunLoopModeInferiorLaunching;
+ // Fill in the argv array in the context from the rest of our args.
+ // Skip the name of this executable and the port number
+ info.remote_sp->SetArguments (argc, argv);
+ }
+ }
+
+ if (start_mode == eDCGSRunLoopModeExit)
+ return -1;
+
+ info.mode = start_mode;
+
+ while (info.mode != eDCGSRunLoopModeExit)
+ {
+ switch (info.mode)
+ {
+ case eDCGSRunLoopModeGetStartModeFromRemoteProtocol:
+ #if defined (__arm__)
+ if (g_lockdown_opt)
+ {
+ if (!info.remote_sp->GetCommunication()->IsConnected())
+ {
+ if (info.remote_sp->GetCommunication()->ConnectToService () != gdb_success)
+ {
+ Log::STDERR ("Failed to get connection from a remote gdb process.\n");
+ info.mode = eDCGSRunLoopModeExit;
+ }
+ else if (g_applist_opt != 0)
+ {
+ // List all applications we are able to see
+ std::string applist_plist;
+ if (ListApplications(applist_plist, false, false) == 0)
+ {
+ //DNBLogDebug("Task list: %s", applist_plist.c_str());
+
+ info.remote_sp->GetCommunication()->Write(applist_plist.c_str(), applist_plist.size());
+ // Issue a read that will never yield any data until the other side
+ // closes the socket so this process doesn't just exit and cause the
+ // socket to close prematurely on the other end and cause data loss.
+ std::string buf;
+ info.remote_sp->GetCommunication()->Read(buf);
+ }
+ info.remote_sp->GetCommunication()->Disconnect(false);
+ info.mode = eDCGSRunLoopModeExit;
+ break;
+ }
+ else
+ {
+ // Start watching for remote packets
+ info.remote_sp->StartReadRemoteDataThread();
+ }
+ }
+ }
+ else
+#endif
+ {
+ if (StartListening (&info, listen_port))
+ Log::STDOUT ("Got a connection, waiting for process information for launching or attaching.\n");
+ else
+ info.mode = eDCGSRunLoopModeExit;
+ }
+
+ if (info.mode != eDCGSRunLoopModeExit)
+ GSRunLoopGetStartModeFromRemote (&info);
+ break;
+
+ case eDCGSRunLoopModeInferiorAttaching:
+ if (!waitfor_pid_name.empty())
+ {
+ // Set our end wait time if we are using a waitfor-duration
+ // option that may have been specified
+
+ TimeValue attach_timeout_abstime;
+ if (waitfor_duration != 0)
+ {
+ attach_timeout_abstime = TimeValue::Now();
+ attach_timeout_abstime.OffsetWithSeconds (waitfor_duration);
+ }
+ GSLaunchFlavor launch_flavor = g_launch_flavor;
+ if (launch_flavor == eLaunchFlavorDefault)
+ {
+ // Our default launch method is posix spawn
+ launch_flavor = eLaunchFlavorPosixSpawn;
+
+#if defined (__arm__)
+ // Check if we have an app bundle, if so launch using SpringBoard.
+ if (waitfor_pid_name.find (".app") != std::string::npos)
+ {
+ launch_flavor = eLaunchFlavorSpringBoard;
+ }
+#endif
+ }
+
+ //ctx.SetLaunchFlavor(launch_flavor);
+
+
+ lldb::pid_t pid = info.GetProcess()->Attach (waitfor_pid_name.c_str());
+ if (pid == LLDB_INVALID_PROCESS_ID)
+ {
+ info.GetRemote()->GetLaunchError() = info.GetProcess()->GetError();
+ Log::STDERR ("error: failed to attach to process named: \"%s\" %s", waitfor_pid_name.c_str(), info.GetRemote()->GetLaunchError().AsCString());
+ info.mode = eDCGSRunLoopModeExit;
+ }
+ else
+ {
+ info.mode = eDCGSRunLoopModeInferiorExecuting;
+ }
+ }
+ else if (attach_pid != LLDB_INVALID_PROCESS_ID)
+ {
+ Log::STDOUT ("Attaching to process %i...\n", attach_pid);
+ info.mode = GSRunLoopLaunchAttaching (&info, attach_pid);
+ if (info.mode != eDCGSRunLoopModeInferiorExecuting)
+ {
+ const char *error_str = info.GetRemote()->GetLaunchError().AsCString();
+ Log::STDERR ("error: failed to attach process %i: %s\n", attach_pid, error_str ? error_str : "unknown error.");
+ info.mode = eDCGSRunLoopModeExit;
+ }
+ }
+ else if (!attach_pid_name.empty ())
+ {
+ lldb::pid_t pid = info.GetProcess()->Attach (waitfor_pid_name.c_str());
+ if (pid == LLDB_INVALID_PROCESS_ID)
+ {
+ info.GetRemote()->GetLaunchError() = info.GetProcess()->GetError();
+ Log::STDERR ("error: failed to attach to process named: \"%s\" %s", waitfor_pid_name.c_str(), info.GetRemote()->GetLaunchError().AsCString());
+ info.mode = eDCGSRunLoopModeExit;
+ }
+ else
+ {
+ info.mode = eDCGSRunLoopModeInferiorExecuting;
+ }
+ }
+ else
+ {
+ Log::STDERR ("error: asked to attach with empty name and invalid PID.");
+ info.mode = eDCGSRunLoopModeExit;
+ }
+
+ if (info.mode != eDCGSRunLoopModeExit)
+ {
+ if (StartListening (&info, listen_port))
+ Log::STDOUT ("Got a connection, waiting for debugger instructions for process %d.\n", attach_pid);
+ else
+ info.mode = eDCGSRunLoopModeExit;
+ }
+ break;
+
+ case eDCGSRunLoopModeInferiorLaunching:
+ info.mode = GSRunLoopLaunchInferior (&info);
+
+ if (info.mode == eDCGSRunLoopModeInferiorExecuting)
+ {
+ if (StartListening (&info, listen_port))
+ Log::STDOUT ("Got a connection, waiting for debugger instructions for task \"%s\".\n", argv[0]);
+ else
+ info.mode = eDCGSRunLoopModeExit;
+ }
+ else
+ {
+ Log::STDERR ("error: failed to launch process %s: %s\n", argv[0], info.GetRemote()->GetLaunchError().AsCString());
+ }
+ break;
+
+ case eDCGSRunLoopModeInferiorExecuting:
+ GSRunLoopInferiorExecuting (&info);
+ break;
+
+ case eDCGSRunLoopModeInferiorKillOrDetach:
+ {
+ Process *process = info.GetProcess();
+ if (process && process->IsAlive())
+ {
+ process->Kill(SIGCONT);
+ process->Kill(SIGKILL);
+ }
+ }
+ info.mode = eDCGSRunLoopModeExit;
+ break;
+
+ default:
+ info.mode = eDCGSRunLoopModeExit;
+ case eDCGSRunLoopModeExit:
+ break;
+ }
+ }
+
+ return 0;
+}
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBServerLog.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBServerLog.cpp
new file mode 100644
index 00000000000..2d4116ebe7b
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBServerLog.cpp
@@ -0,0 +1,80 @@
+//===-- GDBServerLog.cpp ----------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//----------------------------------------------------------------------
+//
+// GDBServerLog.cpp
+// liblldb
+//
+// Created by Greg Clayton on 6/19/09.
+//
+//
+//----------------------------------------------------------------------
+
+#include "GDBServerLog.h"
+
+using namespace lldb;
+
+static Log *
+LogAccessor (bool get, Log *log)
+{
+ static Log* g_log = NULL; // Leak for now as auto_ptr was being cleaned up
+ // by global constructors before other threads
+ // were done with it.
+ if (get)
+ {
+// // Debug code below for enabling logging by default
+// if (g_log == NULL)
+// {
+// g_log = new Log("/dev/stdout", false);
+// g_log->GetMask().SetAllFlagBits(GS_LOG_ALL);
+// g_log->GetOptions().Set(LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_THREAD_NAME);
+// }
+ }
+ else
+ {
+ if (g_log)
+ delete g_log;
+ g_log = log;
+ }
+
+ return g_log;
+}
+
+Log *
+GDBServerLog::GetLogIfAllCategoriesSet (uint32_t mask)
+{
+ Log *log = LogAccessor (true, NULL);
+ if (log && mask)
+ {
+ uint32_t log_mask = log->GetMask().GetAllFlagBits();
+ if ((log_mask & mask) != mask)
+ return NULL;
+ }
+ return log;
+}
+
+void
+GDBServerLog::SetLog (Log *log)
+{
+ LogAccessor (false, log);
+}
+
+
+void
+GDBServerLog::LogIf (uint32_t mask, const char *format, ...)
+{
+ Log *log = GDBServerLog::GetLogIfAllCategoriesSet (mask);
+ if (log)
+ {
+ va_list args;
+ va_start (args, format);
+ log->VAPrintf (format, args);
+ va_end (args);
+ }
+}
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBServerLog.h b/lldb/source/Plugins/Process/gdb-remote/GDBServerLog.h
new file mode 100644
index 00000000000..3dec8088cef
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBServerLog.h
@@ -0,0 +1,55 @@
+//===-- GDBServerLog.h ------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//----------------------------------------------------------------------
+//
+// GDBServerLog.h
+// liblldb
+//
+// Created by Greg Clayton on 6/19/09.
+//
+//
+//----------------------------------------------------------------------
+
+#ifndef liblldb_GDBServerLog_h_
+#define liblldb_GDBServerLog_h_
+
+// C Includes
+// C++ Includes
+// Other libraries and framework includes
+
+#include "lldb/Core/Log.h"
+
+// Project includes
+#define GS_LOG_VERBOSE (1u << 0)
+#define GS_LOG_DEBUG (1u << 1)
+#define GS_LOG_PACKETS (1u << 2)
+#define GS_LOG_EVENTS (1u << 3)
+#define GS_LOG_MINIMAL (1u << 4)
+#define GS_LOG_ALL (UINT32_MAX)
+#define GS_LOG_DEFAULT (GS_LOG_VERBOSE |\
+ GS_LOG_PACKETS)
+
+namespace lldb {
+
+class GDBServerLog
+{
+public:
+ static Log *
+ GetLog (uint32_t mask = 0);
+
+ static void
+ SetLog (Log *log);
+
+ static void
+ LogIf (uint32_t mask, const char *format, ...);
+};
+
+} // namespace lldb
+
+#endif // liblldb_GDBServerLog_h_
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
new file mode 100644
index 00000000000..e08679c1e1c
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
@@ -0,0 +1,2272 @@
+//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// C Includes
+#include <errno.h>
+#include <mach/mach.h>
+#include <mach-o/dyld.h>
+#include <spawn.h>
+#include <sys/fcntl.h>
+#include <sys/types.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+
+// C++ Includes
+#include <algorithm>
+#include <map>
+
+// Other libraries and framework includes
+
+#include "lldb/Breakpoint/WatchpointLocation.h"
+#include "lldb/Core/Args.h"
+#include "lldb/Core/ArchSpec.h"
+#include "lldb/Core/Debugger.h"
+#include "lldb/Core/ConnectionFileDescriptor.h"
+#include "lldb/Core/FileSpec.h"
+#include "lldb/Core/InputReader.h"
+#include "lldb/Core/Module.h"
+#include "lldb/Core/PluginManager.h"
+#include "lldb/Core/State.h"
+#include "lldb/Core/StreamString.h"
+#include "lldb/Core/Timer.h"
+#include "lldb/Host/TimeValue.h"
+#include "lldb/Symbol/ObjectFile.h"
+#include "lldb/Target/DynamicLoader.h"
+#include "lldb/Target/Target.h"
+#include "lldb/Target/TargetList.h"
+#include "PseudoTerminal.h"
+
+// Project includes
+#include "lldb/Host/Host.h"
+#include "StringExtractorGDBRemote.h"
+#include "GDBRemoteRegisterContext.h"
+#include "ProcessGDBRemote.h"
+#include "ProcessGDBRemoteLog.h"
+#include "ThreadGDBRemote.h"
+#include "libunwind.h"
+#include "MacOSXLibunwindCallbacks.h"
+
+#if defined (__i386__) || defined (__x86_64__)
+#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_I386_BPT
+#define MACH_EXC_DATA0_TRACE EXC_I386_SGL
+#elif defined (__powerpc__) || defined (__ppc__) || defined (__ppc64__)
+#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_PPC_BREAKPOINT
+#elif defined (__arm__)
+#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_ARM_BREAKPOINT
+#endif
+
+
+#define DEBUGSERVER_BASENAME "debugserver"
+using namespace lldb;
+using namespace lldb_private;
+
+static inline uint16_t
+get_random_port ()
+{
+ return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
+}
+
+
+const char *
+ProcessGDBRemote::GetPluginNameStatic()
+{
+ return "process.gdb-remote";
+}
+
+const char *
+ProcessGDBRemote::GetPluginDescriptionStatic()
+{
+ return "GDB Remote protocol based debugging plug-in.";
+}
+
+void
+ProcessGDBRemote::Terminate()
+{
+ PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
+}
+
+
+Process*
+ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
+{
+ return new ProcessGDBRemote (target, listener);
+}
+
+bool
+ProcessGDBRemote::CanDebug(Target &target)
+{
+ // For now we are just making sure the file exists for a given module
+ ModuleSP exe_module_sp(target.GetExecutableModule());
+ if (exe_module_sp.get())
+ return exe_module_sp->GetFileSpec().Exists();
+ return false;
+}
+
+//----------------------------------------------------------------------
+// ProcessGDBRemote constructor
+//----------------------------------------------------------------------
+ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
+ Process (target, listener),
+ m_dynamic_loader_ap (),
+ m_byte_order (eByteOrderHost),
+ m_flags (0),
+ m_stdio_communication ("gdb-remote.stdio"),
+ m_stdio_mutex (Mutex::eMutexTypeRecursive),
+ m_stdout_data (),
+ m_arch_spec (),
+ m_gdb_comm(),
+ m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
+ m_debugserver_monitor (0),
+ m_register_info (),
+ m_curr_tid (LLDB_INVALID_THREAD_ID),
+ m_curr_tid_run (LLDB_INVALID_THREAD_ID),
+ m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
+ m_async_thread (LLDB_INVALID_HOST_THREAD),
+ m_z0_supported (1),
+ m_continue_packet(),
+ m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
+ m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
+ m_libunwind_addr_space (NULL),
+ m_waiting_for_attach (false),
+ m_packet_timeout (1),
+ m_max_memory_size (512)
+{
+}
+
+//----------------------------------------------------------------------
+// Destructor
+//----------------------------------------------------------------------
+ProcessGDBRemote::~ProcessGDBRemote()
+{
+ // m_mach_process.UnregisterNotificationCallbacks (this);
+ Clear();
+}
+
+//----------------------------------------------------------------------
+// PluginInterface
+//----------------------------------------------------------------------
+const char *
+ProcessGDBRemote::GetPluginName()
+{
+ return "Process debugging plug-in that uses the GDB remote protocol";
+}
+
+const char *
+ProcessGDBRemote::GetShortPluginName()
+{
+ return GetPluginNameStatic();
+}
+
+uint32_t
+ProcessGDBRemote::GetPluginVersion()
+{
+ return 1;
+}
+
+void
+ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
+{
+ strm->Printf("TODO: fill this in\n");
+}
+
+Error
+ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
+{
+ Error error;
+ error.SetErrorString("No plug-in commands are currently supported.");
+ return error;
+}
+
+Log *
+ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
+{
+ return NULL;
+}
+
+void
+ProcessGDBRemote::BuildDynamicRegisterInfo ()
+{
+ char register_info_command[64];
+ m_register_info.Clear();
+ StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
+ uint32_t reg_offset = 0;
+ uint32_t reg_num = 0;
+ for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
+ {
+ ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
+ {
+ packet_type = response.GetType();
+ if (packet_type == StringExtractorGDBRemote::eResponse)
+ {
+ std::string name;
+ std::string value;
+ ConstString reg_name;
+ ConstString alt_name;
+ ConstString set_name;
+ RegisterInfo reg_info = { NULL, // Name
+ NULL, // Alt name
+ 0, // byte size
+ reg_offset, // offset
+ eEncodingUint, // encoding
+ eFormatHex, // formate
+ reg_num, // native register number
+ {
+ LLDB_INVALID_REGNUM, // GCC reg num
+ LLDB_INVALID_REGNUM, // DWARF reg num
+ LLDB_INVALID_REGNUM, // generic reg num
+ reg_num // GDB reg num
+ }
+ };
+
+ while (response.GetNameColonValue(name, value))
+ {
+ if (name.compare("name") == 0)
+ {
+ reg_name.SetCString(value.c_str());
+ }
+ else if (name.compare("alt-name") == 0)
+ {
+ alt_name.SetCString(value.c_str());
+ }
+ else if (name.compare("bitsize") == 0)
+ {
+ reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
+ }
+ else if (name.compare("offset") == 0)
+ {
+ uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
+ if (offset != offset)
+ {
+ reg_offset = offset;
+ reg_info.byte_offset = offset;
+ }
+ }
+ else if (name.compare("encoding") == 0)
+ {
+ if (value.compare("uint") == 0)
+ reg_info.encoding = eEncodingUint;
+ else if (value.compare("sint") == 0)
+ reg_info.encoding = eEncodingSint;
+ else if (value.compare("ieee754") == 0)
+ reg_info.encoding = eEncodingIEEE754;
+ else if (value.compare("vector") == 0)
+ reg_info.encoding = eEncodingVector;
+ }
+ else if (name.compare("format") == 0)
+ {
+ if (value.compare("binary") == 0)
+ reg_info.format = eFormatBinary;
+ else if (value.compare("decimal") == 0)
+ reg_info.format = eFormatDecimal;
+ else if (value.compare("hex") == 0)
+ reg_info.format = eFormatHex;
+ else if (value.compare("float") == 0)
+ reg_info.format = eFormatFloat;
+ else if (value.compare("vector-sint8") == 0)
+ reg_info.format = eFormatVectorOfSInt8;
+ else if (value.compare("vector-uint8") == 0)
+ reg_info.format = eFormatVectorOfUInt8;
+ else if (value.compare("vector-sint16") == 0)
+ reg_info.format = eFormatVectorOfSInt16;
+ else if (value.compare("vector-uint16") == 0)
+ reg_info.format = eFormatVectorOfUInt16;
+ else if (value.compare("vector-sint32") == 0)
+ reg_info.format = eFormatVectorOfSInt32;
+ else if (value.compare("vector-uint32") == 0)
+ reg_info.format = eFormatVectorOfUInt32;
+ else if (value.compare("vector-float32") == 0)
+ reg_info.format = eFormatVectorOfFloat32;
+ else if (value.compare("vector-uint128") == 0)
+ reg_info.format = eFormatVectorOfUInt128;
+ }
+ else if (name.compare("set") == 0)
+ {
+ set_name.SetCString(value.c_str());
+ }
+ else if (name.compare("gcc") == 0)
+ {
+ reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
+ }
+ else if (name.compare("dwarf") == 0)
+ {
+ reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
+ }
+ else if (name.compare("generic") == 0)
+ {
+ if (value.compare("pc") == 0)
+ reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
+ else if (value.compare("sp") == 0)
+ reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
+ else if (value.compare("fp") == 0)
+ reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
+ else if (value.compare("ra") == 0)
+ reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
+ else if (value.compare("flags") == 0)
+ reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
+ }
+ }
+
+ assert (reg_info.byte_size != 0);
+ reg_offset += reg_info.byte_size;
+ m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
+ }
+ }
+ else
+ {
+ packet_type = StringExtractorGDBRemote::eError;
+ }
+ }
+
+ if (reg_num == 0)
+ {
+ // We didn't get anything. See if we are debugging ARM and fill with
+ // a hard coded register set until we can get an updated debugserver
+ // down on the devices.
+ ArchSpec arm_arch ("arm");
+ if (GetTarget().GetArchitecture() == arm_arch)
+ m_register_info.HardcodeARMRegisters();
+ }
+ m_register_info.Finalize ();
+}
+
+Error
+ProcessGDBRemote::WillLaunch (Module* module)
+{
+ return WillLaunchOrAttach ();
+}
+
+Error
+ProcessGDBRemote::WillAttach (lldb::pid_t pid)
+{
+ return WillLaunchOrAttach ();
+}
+
+Error
+ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch)
+{
+ return WillLaunchOrAttach ();
+}
+
+Error
+ProcessGDBRemote::WillLaunchOrAttach ()
+{
+ Error error;
+ // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
+ m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
+
+ if (m_dynamic_loader_ap.get() == NULL)
+ error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
+ m_stdio_communication.Clear ();
+
+ return error;
+}
+
+//----------------------------------------------------------------------
+// Process Control
+//----------------------------------------------------------------------
+Error
+ProcessGDBRemote::DoLaunch
+(
+ Module* module,
+ char const *argv[],
+ char const *envp[],
+ const char *stdin_path,
+ const char *stdout_path,
+ const char *stderr_path
+)
+{
+ // ::LogSetBitMask (GDBR_LOG_DEFAULT);
+ // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
+ // ::LogSetLogFile ("/dev/stdout");
+ Error error;
+
+ ObjectFile * object_file = module->GetObjectFile();
+ if (object_file)
+ {
+ ArchSpec inferior_arch(module->GetArchitecture());
+ char host_port[128];
+ snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
+
+ bool start_debugserver_with_inferior_args = false;
+ if (start_debugserver_with_inferior_args)
+ {
+ // We want to launch debugserver with the inferior program and its
+ // arguments on the command line. We should only do this if we
+ // the GDB server we are talking to doesn't support the 'A' packet.
+ error = StartDebugserverProcess (host_port,
+ argv,
+ envp,
+ NULL, //stdin_path,
+ LLDB_INVALID_PROCESS_ID,
+ NULL, false,
+ inferior_arch);
+ if (error.Fail())
+ return error;
+
+ error = ConnectToDebugserver (host_port);
+ if (error.Success())
+ {
+ SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
+ }
+ }
+ else
+ {
+ error = StartDebugserverProcess (host_port,
+ NULL,
+ NULL,
+ NULL, //stdin_path,
+ LLDB_INVALID_PROCESS_ID,
+ NULL, false,
+ inferior_arch);
+ if (error.Fail())
+ return error;
+
+ error = ConnectToDebugserver (host_port);
+ if (error.Success())
+ {
+ // Send the environment and the program + arguments after we connect
+ if (envp)
+ {
+ const char *env_entry;
+ for (int i=0; (env_entry = envp[i]); ++i)
+ {
+ if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
+ break;
+ }
+ }
+
+ const uint32_t arg_timeout_seconds = 10;
+ int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
+ if (arg_packet_err == 0)
+ {
+ std::string error_str;
+ if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
+ {
+ SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
+ }
+ else
+ {
+ error.SetErrorString (error_str.c_str());
+ }
+ }
+ else
+ {
+ error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
+ }
+
+ SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
+ }
+ }
+
+ if (GetID() == LLDB_INVALID_PROCESS_ID)
+ {
+ KillDebugserverProcess ();
+ return error;
+ }
+
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
+ SetPrivateState (SetThreadStopInfo (response));
+
+ }
+ else
+ {
+ // Set our user ID to an invalid process ID.
+ SetID(LLDB_INVALID_PROCESS_ID);
+ error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
+ }
+
+ // Return the process ID we have
+ return error;
+}
+
+
+Error
+ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
+{
+ Error error;
+ // Sleep and wait a bit for debugserver to start to listen...
+ std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
+ if (conn_ap.get())
+ {
+ std::string connect_url("connect://");
+ connect_url.append (host_port);
+ const uint32_t max_retry_count = 50;
+ uint32_t retry_count = 0;
+ while (!m_gdb_comm.IsConnected())
+ {
+ if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
+ {
+ m_gdb_comm.SetConnection (conn_ap.release());
+ break;
+ }
+ retry_count++;
+
+ if (retry_count >= max_retry_count)
+ break;
+
+ usleep (100000);
+ }
+ }
+
+ if (!m_gdb_comm.IsConnected())
+ {
+ if (error.Success())
+ error.SetErrorString("not connected to remote gdb server");
+ return error;
+ }
+
+ m_gdb_comm.SetAckMode (true);
+ if (m_gdb_comm.StartReadThread(&error))
+ {
+ // Send an initial ack
+ m_gdb_comm.SendAck('+');
+
+ if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
+ m_debugserver_monitor = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
+ (void*)(intptr_t)GetID(), // Pass the inferior pid in the thread argument (which is a void *)
+ m_debugserver_pid,
+ false);
+
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
+ {
+ if (response.IsOKPacket())
+ m_gdb_comm.SetAckMode (false);
+ }
+
+ BuildDynamicRegisterInfo ();
+ }
+ return error;
+}
+
+void
+ProcessGDBRemote::DidLaunchOrAttach ()
+{
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
+ if (GetID() == LLDB_INVALID_PROCESS_ID)
+ {
+ m_dynamic_loader_ap.reset();
+ }
+ else
+ {
+ m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
+
+ Module * exe_module = GetTarget().GetExecutableModule ().get();
+ assert(exe_module);
+
+ m_arch_spec = exe_module->GetArchitecture();
+
+ ObjectFile *exe_objfile = exe_module->GetObjectFile();
+ assert(exe_objfile);
+
+ m_byte_order = exe_objfile->GetByteOrder();
+ assert (m_byte_order != eByteOrderInvalid);
+
+ StreamString strm;
+
+ ArchSpec inferior_arch;
+ // See if the GDB server supports the qHostInfo information
+ const char *vendor = m_gdb_comm.GetVendorString().AsCString();
+ const char *os_type = m_gdb_comm.GetOSString().AsCString();
+
+ if (m_arch_spec.IsValid() && m_arch_spec == ArchSpec ("arm"))
+ {
+ // For ARM we can't trust the arch of the process as it could
+ // have an armv6 object file, but be running on armv7 kernel.
+ inferior_arch = m_gdb_comm.GetHostArchitecture();
+ }
+
+ if (!inferior_arch.IsValid())
+ inferior_arch = m_arch_spec;
+
+ if (vendor == NULL)
+ vendor = Host::GetVendorString().AsCString("apple");
+
+ if (os_type == NULL)
+ os_type = Host::GetOSString().AsCString("darwin");
+
+ strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
+
+ std::transform (strm.GetString().begin(),
+ strm.GetString().end(),
+ strm.GetString().begin(),
+ ::tolower);
+
+ m_target_triple.SetCString(strm.GetString().c_str());
+ }
+}
+
+void
+ProcessGDBRemote::DidLaunch ()
+{
+ DidLaunchOrAttach ();
+ if (m_dynamic_loader_ap.get())
+ m_dynamic_loader_ap->DidLaunch();
+}
+
+Error
+ProcessGDBRemote::DoAttach (pid_t attach_pid)
+{
+ Error error;
+ // Clear out and clean up from any current state
+ Clear();
+ // HACK: require arch be set correctly at the target level until we can
+ // figure out a good way to determine the arch of what we are attaching to
+ m_arch_spec = m_target.GetArchitecture();
+
+ //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
+ if (attach_pid != LLDB_INVALID_PROCESS_ID)
+ {
+ SetPrivateState (eStateAttaching);
+ char host_port[128];
+ snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
+ error = StartDebugserverProcess (host_port,
+ NULL,
+ NULL,
+ NULL,
+ LLDB_INVALID_PROCESS_ID,
+ NULL, false,
+ m_arch_spec);
+
+ if (error.Fail())
+ {
+ const char *error_string = error.AsCString();
+ if (error_string == NULL)
+ error_string = "unable to launch " DEBUGSERVER_BASENAME;
+
+ SetExitStatus (-1, error_string);
+ }
+ else
+ {
+ error = ConnectToDebugserver (host_port);
+ if (error.Success())
+ {
+ char packet[64];
+ const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
+ StringExtractorGDBRemote response;
+ StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
+ packet,
+ packet_len,
+ response);
+ switch (stop_state)
+ {
+ case eStateStopped:
+ case eStateCrashed:
+ case eStateSuspended:
+ SetID (attach_pid);
+ m_last_stop_packet = response;
+ m_last_stop_packet.SetFilePos (0);
+ SetPrivateState (stop_state);
+ break;
+
+ case eStateExited:
+ m_last_stop_packet = response;
+ m_last_stop_packet.SetFilePos (0);
+ response.SetFilePos(1);
+ SetExitStatus(response.GetHexU8(), NULL);
+ break;
+
+ default:
+ SetExitStatus(-1, "unable to attach to process");
+ break;
+ }
+
+ }
+ }
+ }
+
+ lldb::pid_t pid = GetID();
+ if (pid == LLDB_INVALID_PROCESS_ID)
+ {
+ KillDebugserverProcess();
+ }
+ return error;
+}
+
+size_t
+ProcessGDBRemote::AttachInputReaderCallback
+(
+ void *baton,
+ InputReader *reader,
+ lldb::InputReaderAction notification,
+ const char *bytes,
+ size_t bytes_len
+)
+{
+ if (notification == eInputReaderGotToken)
+ {
+ ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
+ if (gdb_process->m_waiting_for_attach)
+ gdb_process->m_waiting_for_attach = false;
+ reader->SetIsDone(true);
+ return 1;
+ }
+ return 0;
+}
+
+Error
+ProcessGDBRemote::DoAttach (const char *process_name, bool wait_for_launch)
+{
+ Error error;
+ // Clear out and clean up from any current state
+ Clear();
+ // HACK: require arch be set correctly at the target level until we can
+ // figure out a good way to determine the arch of what we are attaching to
+ m_arch_spec = m_target.GetArchitecture();
+
+ //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
+ if (process_name && process_name[0])
+ {
+
+ SetPrivateState (eStateAttaching);
+ char host_port[128];
+ snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
+ error = StartDebugserverProcess (host_port,
+ NULL,
+ NULL,
+ NULL,
+ LLDB_INVALID_PROCESS_ID,
+ NULL, false,
+ m_arch_spec);
+ if (error.Fail())
+ {
+ const char *error_string = error.AsCString();
+ if (error_string == NULL)
+ error_string = "unable to launch " DEBUGSERVER_BASENAME;
+
+ SetExitStatus (-1, error_string);
+ }
+ else
+ {
+ error = ConnectToDebugserver (host_port);
+ if (error.Success())
+ {
+ StreamString packet;
+
+ packet.PutCString("vAttach");
+ if (wait_for_launch)
+ packet.PutCString("Wait");
+ packet.PutChar(';');
+ packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
+ StringExtractorGDBRemote response;
+ StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
+ packet.GetData(),
+ packet.GetSize(),
+ response);
+ switch (stop_state)
+ {
+ case eStateStopped:
+ case eStateCrashed:
+ case eStateSuspended:
+ SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
+ m_last_stop_packet = response;
+ m_last_stop_packet.SetFilePos (0);
+ SetPrivateState (stop_state);
+ break;
+
+ case eStateExited:
+ m_last_stop_packet = response;
+ m_last_stop_packet.SetFilePos (0);
+ response.SetFilePos(1);
+ SetExitStatus(response.GetHexU8(), NULL);
+ break;
+
+ default:
+ SetExitStatus(-1, "unable to attach to process");
+ break;
+ }
+ }
+ }
+ }
+
+ lldb::pid_t pid = GetID();
+ if (pid == LLDB_INVALID_PROCESS_ID)
+ {
+ KillDebugserverProcess();
+ }
+ return error;
+}
+
+//
+// if (wait_for_launch)
+// {
+// InputReaderSP reader_sp (new InputReader());
+// StreamString instructions;
+// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
+// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
+// this, // baton
+// eInputReaderGranularityByte,
+// NULL, // End token
+// false);
+//
+// StringExtractorGDBRemote response;
+// m_waiting_for_attach = true;
+// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
+// while (m_waiting_for_attach)
+// {
+// // Wait for one second for the stop reply packet
+// if (m_gdb_comm.WaitForPacket(response, 1))
+// {
+// // Got some sort of packet, see if it is the stop reply packet?
+// char ch = response.GetChar(0);
+// if (ch == 'T')
+// {
+// m_waiting_for_attach = false;
+// }
+// }
+// else
+// {
+// // Put a period character every second
+// fputc('.', reader_out_fh);
+// }
+// }
+// }
+// }
+// return GetID();
+//}
+
+void
+ProcessGDBRemote::DidAttach ()
+{
+ DidLaunchOrAttach ();
+ if (m_dynamic_loader_ap.get())
+ m_dynamic_loader_ap->DidAttach();
+}
+
+Error
+ProcessGDBRemote::WillResume ()
+{
+ m_continue_packet.Clear();
+ // Start the continue packet we will use to run the target. Each thread
+ // will append what it is supposed to be doing to this packet when the
+ // ThreadList::WillResume() is called. If a thread it supposed
+ // to stay stopped, then don't append anything to this string.
+ m_continue_packet.Printf("vCont");
+ return Error();
+}
+
+Error
+ProcessGDBRemote::DoResume ()
+{
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
+ m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
+ return Error();
+}
+
+size_t
+ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
+{
+ const uint8_t *trap_opcode = NULL;
+ uint32_t trap_opcode_size = 0;
+
+ static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
+ //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
+ static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
+ static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
+
+ switch (m_arch_spec.GetCPUType())
+ {
+ case CPU_TYPE_ARM:
+ // TODO: fill this in for ARM. We need to dig up the symbol for
+ // the address in the breakpoint locaiton and figure out if it is
+ // an ARM or Thumb breakpoint.
+ trap_opcode = g_arm_breakpoint_opcode;
+ trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
+ break;
+
+ case CPU_TYPE_POWERPC:
+ case CPU_TYPE_POWERPC64:
+ trap_opcode = g_ppc_breakpoint_opcode;
+ trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
+ break;
+
+ case CPU_TYPE_I386:
+ case CPU_TYPE_X86_64:
+ trap_opcode = g_i386_breakpoint_opcode;
+ trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
+ break;
+
+ default:
+ assert(!"Unhandled architecture in ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode()");
+ return 0;
+ }
+
+ if (trap_opcode && trap_opcode_size)
+ {
+ if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
+ return trap_opcode_size;
+ }
+ return 0;
+}
+
+uint32_t
+ProcessGDBRemote::UpdateThreadListIfNeeded ()
+{
+ // locker will keep a mutex locked until it goes out of scope
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
+ if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE))
+ log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
+
+ const uint32_t stop_id = GetStopID();
+ if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
+ {
+ // Update the thread list's stop id immediately so we don't recurse into this function.
+ ThreadList curr_thread_list (this);
+ curr_thread_list.SetStopID(stop_id);
+
+ Error err;
+ StringExtractorGDBRemote response;
+ for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
+ response.IsNormalPacket();
+ m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
+ {
+ char ch = response.GetChar();
+ if (ch == 'l')
+ break;
+ if (ch == 'm')
+ {
+ do
+ {
+ tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
+
+ if (tid != LLDB_INVALID_THREAD_ID)
+ {
+ ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
+ if (thread_sp)
+ thread_sp->GetRegisterContext()->Invalidate();
+ else
+ thread_sp.reset (new ThreadGDBRemote (*this, tid));
+ curr_thread_list.AddThread(thread_sp);
+ }
+
+ ch = response.GetChar();
+ } while (ch == ',');
+ }
+ }
+
+ m_thread_list = curr_thread_list;
+
+ SetThreadStopInfo (m_last_stop_packet);
+ }
+ return GetThreadList().GetSize(false);
+}
+
+
+StateType
+ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
+{
+ const char stop_type = stop_packet.GetChar();
+ switch (stop_type)
+ {
+ case 'T':
+ case 'S':
+ {
+ // Stop with signal and thread info
+ const uint8_t signo = stop_packet.GetHexU8();
+ std::string name;
+ std::string value;
+ std::string thread_name;
+ uint32_t exc_type = 0;
+ std::vector<uint64_t> exc_data;
+ uint32_t tid = LLDB_INVALID_THREAD_ID;
+ addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
+ uint32_t exc_data_count = 0;
+ while (stop_packet.GetNameColonValue(name, value))
+ {
+ if (name.compare("metype") == 0)
+ {
+ // exception type in big endian hex
+ exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
+ }
+ else if (name.compare("mecount") == 0)
+ {
+ // exception count in big endian hex
+ exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
+ }
+ else if (name.compare("medata") == 0)
+ {
+ // exception data in big endian hex
+ exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
+ }
+ else if (name.compare("thread") == 0)
+ {
+ // thread in big endian hex
+ tid = Args::StringToUInt32 (value.c_str(), 0, 16);
+ }
+ else if (name.compare("name") == 0)
+ {
+ thread_name.swap (value);
+ }
+ else if (name.compare("dispatchqaddr") == 0)
+ {
+ thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
+ }
+ }
+ ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
+
+ if (thread_sp)
+ {
+ ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
+
+ gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
+ gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
+ Thread::StopInfo& stop_info = gdb_thread->GetStopInfoRef();
+ gdb_thread->SetStopInfoStopID (GetStopID());
+ if (exc_type != 0)
+ {
+ if (exc_type == EXC_SOFTWARE && exc_data.size() == 2 && exc_data[0] == EXC_SOFT_SIGNAL)
+ {
+ stop_info.SetStopReasonWithSignal(exc_data[1]);
+ }
+#if defined (MACH_EXC_DATA0_SOFTWARE_BREAKPOINT)
+ else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_SOFTWARE_BREAKPOINT)
+ {
+ addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
+ user_id_t break_id = GetBreakpointSiteList().FindIDByAddress(pc);
+ if (break_id == LLDB_INVALID_BREAK_ID)
+ {
+ //log->Printf("got EXC_BREAKPOINT at 0x%llx but didn't find a breakpoint site.\n", pc);
+ stop_info.SetStopReasonWithException(exc_type, exc_data.size());
+ for (uint32_t i=0; i<exc_data.size(); ++i)
+ stop_info.SetExceptionDataAtIndex(i, exc_data[i]);
+ }
+ else
+ {
+ stop_info.Clear ();
+ stop_info.SetStopReasonWithBreakpointSiteID (break_id);
+ }
+ }
+#endif
+#if defined (MACH_EXC_DATA0_TRACE)
+ else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_TRACE)
+ {
+ stop_info.SetStopReasonToTrace ();
+ }
+#endif
+ else
+ {
+ stop_info.SetStopReasonWithException(exc_type, exc_data.size());
+ for (uint32_t i=0; i<exc_data.size(); ++i)
+ stop_info.SetExceptionDataAtIndex(i, exc_data[i]);
+ }
+ }
+ else if (signo)
+ {
+ stop_info.SetStopReasonWithSignal(signo);
+ }
+ else
+ {
+ stop_info.SetStopReasonToNone();
+ }
+ }
+ return eStateStopped;
+ }
+ break;
+
+ case 'W':
+ // process exited
+ return eStateExited;
+
+ default:
+ break;
+ }
+ return eStateInvalid;
+}
+
+void
+ProcessGDBRemote::RefreshStateAfterStop ()
+{
+ // We must be attaching if we don't already have a valid architecture
+ if (!m_arch_spec.IsValid())
+ {
+ Module *exe_module = GetTarget().GetExecutableModule().get();
+ if (exe_module)
+ m_arch_spec = exe_module->GetArchitecture();
+ }
+ // Let all threads recover from stopping and do any clean up based
+ // on the previous thread state (if any).
+ m_thread_list.RefreshStateAfterStop();
+
+ // Discover new threads:
+ UpdateThreadListIfNeeded ();
+}
+
+Error
+ProcessGDBRemote::DoHalt ()
+{
+ Error error;
+ if (m_gdb_comm.IsRunning())
+ {
+ bool timed_out = false;
+ if (!m_gdb_comm.SendInterrupt (2, &timed_out))
+ {
+ if (timed_out)
+ error.SetErrorString("timed out sending interrupt packet");
+ else
+ error.SetErrorString("unknown error sending interrupt packet");
+ }
+ }
+ return error;
+}
+
+Error
+ProcessGDBRemote::WillDetach ()
+{
+ Error error;
+ const StateType state = m_private_state.GetValue();
+
+ if (IsRunning(state))
+ error.SetErrorString("Process must be stopped in order to detach.");
+
+ return error;
+}
+
+
+Error
+ProcessGDBRemote::DoDestroy ()
+{
+ Error error;
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
+ if (log)
+ log->Printf ("ProcessGDBRemote::DoDestroy()");
+
+ // Interrupt if our inferior is running...
+ m_gdb_comm.SendInterrupt (1);
+ DisableAllBreakpointSites ();
+ SetExitStatus(-1, "process killed");
+
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
+ {
+ if (log)
+ {
+ if (response.IsOKPacket())
+ log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
+ else
+ log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
+ }
+ }
+
+ StopAsyncThread ();
+ m_gdb_comm.StopReadThread();
+ KillDebugserverProcess ();
+ return error;
+}
+
+ByteOrder
+ProcessGDBRemote::GetByteOrder () const
+{
+ return m_byte_order;
+}
+
+//------------------------------------------------------------------
+// Process Queries
+//------------------------------------------------------------------
+
+bool
+ProcessGDBRemote::IsAlive ()
+{
+ return m_gdb_comm.IsConnected();
+}
+
+addr_t
+ProcessGDBRemote::GetImageInfoAddress()
+{
+ if (!m_gdb_comm.IsRunning())
+ {
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
+ {
+ if (response.IsNormalPacket())
+ return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
+ }
+ }
+ return LLDB_INVALID_ADDRESS;
+}
+
+DynamicLoader *
+ProcessGDBRemote::GetDynamicLoader()
+{
+ return m_dynamic_loader_ap.get();
+}
+
+//------------------------------------------------------------------
+// Process Memory
+//------------------------------------------------------------------
+size_t
+ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
+{
+ if (size > m_max_memory_size)
+ {
+ // Keep memory read sizes down to a sane limit. This function will be
+ // called multiple times in order to complete the task by
+ // lldb_private::Process so it is ok to do this.
+ size = m_max_memory_size;
+ }
+
+ char packet[64];
+ const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
+ assert (packet_len + 1 < sizeof(packet));
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
+ {
+ if (response.IsNormalPacket())
+ {
+ error.Clear();
+ return response.GetHexBytes(buf, size, '\xdd');
+ }
+ else if (response.IsErrorPacket())
+ error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
+ else if (response.IsUnsupportedPacket())
+ error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
+ else
+ error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
+ }
+ else
+ {
+ error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
+ }
+ return 0;
+}
+
+size_t
+ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
+{
+ StreamString packet;
+ packet.Printf("M%llx,%zx:", addr, size);
+ packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
+ {
+ if (response.IsOKPacket())
+ {
+ error.Clear();
+ return size;
+ }
+ else if (response.IsErrorPacket())
+ error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
+ else if (response.IsUnsupportedPacket())
+ error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
+ else
+ error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
+ }
+ else
+ {
+ error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
+ }
+ return 0;
+}
+
+lldb::addr_t
+ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
+{
+ addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
+ if (allocated_addr == LLDB_INVALID_ADDRESS)
+ error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
+ else
+ error.Clear();
+ return allocated_addr;
+}
+
+Error
+ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
+{
+ Error error;
+ if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
+ error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
+ return error;
+}
+
+
+//------------------------------------------------------------------
+// Process STDIO
+//------------------------------------------------------------------
+
+size_t
+ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
+{
+ Mutex::Locker locker(m_stdio_mutex);
+ size_t bytes_available = m_stdout_data.size();
+ if (bytes_available > 0)
+ {
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
+ if (bytes_available > buf_size)
+ {
+ memcpy(buf, m_stdout_data.data(), buf_size);
+ m_stdout_data.erase(0, buf_size);
+ bytes_available = buf_size;
+ }
+ else
+ {
+ memcpy(buf, m_stdout_data.data(), bytes_available);
+ m_stdout_data.clear();
+
+ //ResetEventBits(eBroadcastBitSTDOUT);
+ }
+ }
+ return bytes_available;
+}
+
+size_t
+ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
+{
+ // Can we get STDERR through the remote protocol?
+ return 0;
+}
+
+size_t
+ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
+{
+ if (m_stdio_communication.IsConnected())
+ {
+ ConnectionStatus status;
+ m_stdio_communication.Write(src, src_len, status, NULL);
+ }
+ return 0;
+}
+
+Error
+ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
+{
+ Error error;
+ assert (bp_site != NULL);
+
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
+ user_id_t site_id = bp_site->GetID();
+ const addr_t addr = bp_site->GetLoadAddress();
+ if (log)
+ log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
+
+ if (bp_site->IsEnabled())
+ {
+ if (log)
+ log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
+ return error;
+ }
+ else
+ {
+ const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
+
+ if (bp_site->HardwarePreferred())
+ {
+ // Try and set hardware breakpoint, and if that fails, fall through
+ // and set a software breakpoint?
+ }
+
+ if (m_z0_supported)
+ {
+ char packet[64];
+ const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
+ assert (packet_len + 1 < sizeof(packet));
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
+ {
+ if (response.IsUnsupportedPacket())
+ {
+ // Disable z packet support and try again
+ m_z0_supported = 0;
+ return EnableBreakpoint (bp_site);
+ }
+ else if (response.IsOKPacket())
+ {
+ bp_site->SetEnabled(true);
+ bp_site->SetType (BreakpointSite::eExternal);
+ return error;
+ }
+ else
+ {
+ uint8_t error_byte = response.GetError();
+ if (error_byte)
+ error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
+ }
+ }
+ }
+ else
+ {
+ return EnableSoftwareBreakpoint (bp_site);
+ }
+ }
+
+ if (log)
+ {
+ const char *err_string = error.AsCString();
+ log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
+ bp_site->GetLoadAddress(),
+ err_string ? err_string : "NULL");
+ }
+ // We shouldn't reach here on a successful breakpoint enable...
+ if (error.Success())
+ error.SetErrorToGenericError();
+ return error;
+}
+
+Error
+ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
+{
+ Error error;
+ assert (bp_site != NULL);
+ addr_t addr = bp_site->GetLoadAddress();
+ user_id_t site_id = bp_site->GetID();
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
+ if (log)
+ log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
+
+ if (bp_site->IsEnabled())
+ {
+ const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
+
+ if (bp_site->IsHardware())
+ {
+ // TODO: disable hardware breakpoint...
+ }
+ else
+ {
+ if (m_z0_supported)
+ {
+ char packet[64];
+ const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
+ assert (packet_len + 1 < sizeof(packet));
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
+ {
+ if (response.IsUnsupportedPacket())
+ {
+ error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
+ }
+ else if (response.IsOKPacket())
+ {
+ if (log)
+ log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
+ bp_site->SetEnabled(false);
+ return error;
+ }
+ else
+ {
+ uint8_t error_byte = response.GetError();
+ if (error_byte)
+ error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
+ }
+ }
+ }
+ else
+ {
+ return DisableSoftwareBreakpoint (bp_site);
+ }
+ }
+ }
+ else
+ {
+ if (log)
+ log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
+ return error;
+ }
+
+ if (error.Success())
+ error.SetErrorToGenericError();
+ return error;
+}
+
+Error
+ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
+{
+ Error error;
+ if (wp)
+ {
+ user_id_t watchID = wp->GetID();
+ addr_t addr = wp->GetLoadAddress();
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
+ if (log)
+ log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
+ if (wp->IsEnabled())
+ {
+ if (log)
+ log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
+ return error;
+ }
+ else
+ {
+ // Pass down an appropriate z/Z packet...
+ error.SetErrorString("watchpoints not supported");
+ }
+ }
+ else
+ {
+ error.SetErrorString("Watchpoint location argument was NULL.");
+ }
+ if (error.Success())
+ error.SetErrorToGenericError();
+ return error;
+}
+
+Error
+ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
+{
+ Error error;
+ if (wp)
+ {
+ user_id_t watchID = wp->GetID();
+
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
+
+ addr_t addr = wp->GetLoadAddress();
+ if (log)
+ log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
+
+ if (wp->IsHardware())
+ {
+ // Pass down an appropriate z/Z packet...
+ error.SetErrorString("watchpoints not supported");
+ }
+ // TODO: clear software watchpoints if we implement them
+ }
+ else
+ {
+ error.SetErrorString("Watchpoint location argument was NULL.");
+ }
+ if (error.Success())
+ error.SetErrorToGenericError();
+ return error;
+}
+
+void
+ProcessGDBRemote::Clear()
+{
+ m_flags = 0;
+ m_thread_list.Clear();
+ {
+ Mutex::Locker locker(m_stdio_mutex);
+ m_stdout_data.clear();
+ }
+ DestoryLibUnwindAddressSpace();
+}
+
+Error
+ProcessGDBRemote::DoSignal (int signo)
+{
+ Error error;
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
+ if (log)
+ log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
+
+ if (!m_gdb_comm.SendAsyncSignal (signo))
+ error.SetErrorStringWithFormat("failed to send signal %i", signo);
+ return error;
+}
+
+
+Error
+ProcessGDBRemote::DoDetach()
+{
+ Error error;
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
+ if (log)
+ log->Printf ("ProcessGDBRemote::DoDetach()");
+
+ // if (DoSIGSTOP (true))
+ // {
+ // CloseChildFileDescriptors ();
+ //
+ // // Scope for "locker" so we can reply to all of our exceptions (the SIGSTOP
+ // // exception).
+ // {
+ // Mutex::Locker locker(m_exception_messages_mutex);
+ // ReplyToAllExceptions();
+ // }
+ //
+ // // Shut down the exception thread and cleanup our exception remappings
+ // Task().ShutDownExceptionThread();
+ //
+ // pid_t pid = GetID();
+ //
+ // // Detach from our process while we are stopped.
+ // errno = 0;
+ //
+ // // Detach from our process
+ // ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
+ //
+ // error.SetErrorToErrno();
+ //
+ // if (log || error.Fail())
+ // error.PutToLog(log, "::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
+ //
+ // // Resume our task
+ // Task().Resume();
+ //
+ // // NULL our task out as we have already retored all exception ports
+ // Task().Clear();
+ //
+ // // Clear out any notion of the process we once were
+ // Clear();
+ //
+ // SetPrivateState (eStateDetached);
+ // return true;
+ // }
+ return error;
+}
+
+void
+ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
+{
+ ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
+ process->AppendSTDOUT(static_cast<const char *>(src), src_len);
+}
+
+void
+ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
+{
+ ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
+ Mutex::Locker locker(m_stdio_mutex);
+ m_stdout_data.append(s, len);
+
+ // FIXME: Make a real data object for this and put it out.
+ BroadcastEventIfUnique (eBroadcastBitSTDOUT);
+}
+
+
+Error
+ProcessGDBRemote::StartDebugserverProcess
+(
+ const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
+ char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
+ char const *inferior_envp[], // Environment to pass along to the inferior program
+ char const *stdio_path,
+ lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
+ const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
+ bool wait_for_launch, // Wait for the process named "attach_name" to launch
+ ArchSpec& inferior_arch // The arch of the inferior that we will launch
+)
+{
+ Error error;
+ if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
+ {
+ // If we locate debugserver, keep that located version around
+ static FileSpec g_debugserver_file_spec;
+
+ FileSpec debugserver_file_spec;
+ char debugserver_path[PATH_MAX];
+
+ // Always check to see if we have an environment override for the path
+ // to the debugserver to use and use it if we do.
+ const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
+ if (env_debugserver_path)
+ debugserver_file_spec.SetFile (env_debugserver_path);
+ else
+ debugserver_file_spec = g_debugserver_file_spec;
+ bool debugserver_exists = debugserver_file_spec.Exists();
+ if (!debugserver_exists)
+ {
+ // The debugserver binary is in the LLDB.framework/Resources
+ // directory.
+ FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize));
+ const char *framework_dir = framework_file_spec.GetDirectory().AsCString();
+ const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework");
+
+ if (lldb_framework)
+ {
+ int len = lldb_framework - framework_dir + strlen ("/LLDB.framework");
+ ::snprintf (debugserver_path,
+ sizeof(debugserver_path),
+ "%.*s/Resources/%s",
+ len,
+ framework_dir,
+ DEBUGSERVER_BASENAME);
+ debugserver_file_spec.SetFile (debugserver_path);
+ debugserver_exists = debugserver_file_spec.Exists();
+ }
+
+ if (debugserver_exists)
+ {
+ g_debugserver_file_spec = debugserver_file_spec;
+ }
+ else
+ {
+ g_debugserver_file_spec.Clear();
+ debugserver_file_spec.Clear();
+ }
+ }
+
+ if (debugserver_exists)
+ {
+ debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
+
+ m_stdio_communication.Clear();
+ posix_spawnattr_t attr;
+
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
+
+ Error local_err; // Errors that don't affect the spawning.
+ if (log)
+ log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
+ error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
+ if (error.Fail() || log)
+ error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
+ if (error.Fail())
+ return error;;
+
+#if !defined (__arm__)
+
+ // We don't need to do this for ARM, and we really shouldn't now that we
+ // have multiple CPU subtypes and no posix_spawnattr call that allows us
+ // to set which CPU subtype to launch...
+ cpu_type_t cpu = inferior_arch.GetCPUType();
+ if (cpu != 0 && cpu != CPU_TYPE_ANY && cpu != LLDB_INVALID_CPUTYPE)
+ {
+ size_t ocount = 0;
+ error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
+ if (error.Fail() || log)
+ error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
+
+ if (error.Fail() != 0 || ocount != 1)
+ return error;
+ }
+
+#endif
+
+ Args debugserver_args;
+ char arg_cstr[PATH_MAX];
+ bool launch_process = true;
+
+ if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
+ launch_process = false;
+ else if (attach_name)
+ launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
+
+ bool pass_stdio_path_to_debugserver = true;
+ lldb_utility::PseudoTerminal pty;
+ if (stdio_path == NULL)
+ {
+ pass_stdio_path_to_debugserver = false;
+ if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
+ {
+ struct termios stdin_termios;
+ if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
+ {
+ stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
+ stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
+ ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
+ }
+ stdio_path = pty.GetSlaveName (NULL, 0);
+ }
+ }
+
+ // Start args with "debugserver /file/path -r --"
+ debugserver_args.AppendArgument(debugserver_path);
+ debugserver_args.AppendArgument(debugserver_url);
+ debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers
+ debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so
+ // signals generated by special terminal key
+ // sequences (^C) don't affect debugserver
+
+ // Only set the inferior
+ if (launch_process)
+ {
+ if (stdio_path && pass_stdio_path_to_debugserver)
+ {
+ debugserver_args.AppendArgument("-s"); // short for --stdio-path
+ StreamString strm;
+ strm.Printf("'%s'", stdio_path);
+ debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
+ }
+ }
+
+ const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
+ if (env_debugserver_log_file)
+ {
+ ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
+ debugserver_args.AppendArgument(arg_cstr);
+ }
+
+ const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
+ if (env_debugserver_log_flags)
+ {
+ ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
+ debugserver_args.AppendArgument(arg_cstr);
+ }
+// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
+// debugserver_args.AppendArgument("--log-flags=0x800e0e");
+
+ // Now append the program arguments
+ if (launch_process)
+ {
+ if (inferior_argv)
+ {
+ // Terminate the debugserver args so we can now append the inferior args
+ debugserver_args.AppendArgument("--");
+
+ for (int i = 0; inferior_argv[i] != NULL; ++i)
+ debugserver_args.AppendArgument (inferior_argv[i]);
+ }
+ else
+ {
+ // Will send environment entries with the 'QEnvironment:' packet
+ // Will send arguments with the 'A' packet
+ }
+ }
+ else if (attach_pid != LLDB_INVALID_PROCESS_ID)
+ {
+ ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
+ debugserver_args.AppendArgument (arg_cstr);
+ }
+ else if (attach_name && attach_name[0])
+ {
+ if (wait_for_launch)
+ debugserver_args.AppendArgument ("--waitfor");
+ else
+ debugserver_args.AppendArgument ("--attach");
+ debugserver_args.AppendArgument (attach_name);
+ }
+
+ Error file_actions_err;
+ posix_spawn_file_actions_t file_actions;
+#if DONT_CLOSE_DEBUGSERVER_STDIO
+ file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
+#else
+ file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
+ if (file_actions_err.Success())
+ {
+ ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
+ ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
+ ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
+ }
+#endif
+
+ if (log)
+ {
+ StreamString strm;
+ debugserver_args.Dump (&strm);
+ log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
+ }
+
+ error.SetError(::posix_spawnp (&m_debugserver_pid,
+ debugserver_path,
+ file_actions_err.Success() ? &file_actions : NULL,
+ &attr,
+ debugserver_args.GetArgumentVector(),
+ (char * const*)inferior_envp),
+ eErrorTypePOSIX);
+
+ if (file_actions_err.Success())
+ ::posix_spawn_file_actions_destroy (&file_actions);
+
+ // We have seen some cases where posix_spawnp was returning a valid
+ // looking pid even when an error was returned, so clear it out
+ if (error.Fail())
+ m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
+
+ if (error.Fail() || log)
+ error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp);
+
+// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
+// {
+// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
+// if (conn_ap.get())
+// {
+// m_stdio_communication.SetConnection(conn_ap.release());
+// if (m_stdio_communication.IsConnected())
+// {
+// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
+// m_stdio_communication.StartReadThread();
+// }
+// }
+// }
+ }
+ else
+ {
+ error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
+ }
+
+ if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
+ StartAsyncThread ();
+ }
+ return error;
+}
+
+bool
+ProcessGDBRemote::MonitorDebugserverProcess
+(
+ void *callback_baton,
+ lldb::pid_t debugserver_pid,
+ int signo, // Zero for no signal
+ int exit_status // Exit value of process if signal is zero
+)
+{
+ // We pass in the ProcessGDBRemote inferior process it and name it
+ // "gdb_remote_pid". The process ID is passed in the "callback_baton"
+ // pointer value itself, thus we need the double cast...
+
+ // "debugserver_pid" argument passed in is the process ID for
+ // debugserver that we are tracking...
+
+ lldb::pid_t gdb_remote_pid = (lldb::pid_t)(intptr_t)callback_baton;
+ TargetSP target_sp(Debugger::GetSharedInstance().GetTargetList().FindTargetWithProcessID (gdb_remote_pid));
+ if (target_sp)
+ {
+ ProcessSP process_sp (target_sp->GetProcessSP());
+ if (process_sp)
+ {
+ // Sleep for a half a second to make sure our inferior process has
+ // time to set its exit status before we set it incorrectly when
+ // both the debugserver and the inferior process shut down.
+ usleep (500000);
+ // If our process hasn't yet exited, debugserver might have died.
+ // If the process did exit, the we are reaping it.
+ if (process_sp->GetState() != eStateExited)
+ {
+ char error_str[1024];
+ if (signo)
+ {
+ const char *signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
+ if (signal_cstr)
+ ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
+ else
+ ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
+ }
+ else
+ {
+ ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
+ }
+
+ process_sp->SetExitStatus (-1, error_str);
+ }
+ else
+ {
+ ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)process_sp.get();
+ // Debugserver has exited we need to let our ProcessGDBRemote
+ // know that it no longer has a debugserver instance
+ gdb_process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
+ // We are returning true to this function below, so we can
+ // forget about the monitor handle.
+ gdb_process->m_debugserver_monitor = 0;
+ }
+ }
+ }
+ return true;
+}
+
+void
+ProcessGDBRemote::KillDebugserverProcess ()
+{
+ if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
+ {
+ ::kill (m_debugserver_pid, SIGINT);
+ m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
+ }
+}
+
+void
+ProcessGDBRemote::Initialize()
+{
+ static bool g_initialized = false;
+
+ if (g_initialized == false)
+ {
+ g_initialized = true;
+ PluginManager::RegisterPlugin (GetPluginNameStatic(),
+ GetPluginDescriptionStatic(),
+ CreateInstance);
+
+ Log::Callbacks log_callbacks = {
+ ProcessGDBRemoteLog::DisableLog,
+ ProcessGDBRemoteLog::EnableLog,
+ ProcessGDBRemoteLog::ListLogCategories
+ };
+
+ Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
+ }
+}
+
+bool
+ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
+{
+ if (m_curr_tid == tid)
+ return true;
+
+ char packet[32];
+ const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
+ assert (packet_len + 1 < sizeof(packet));
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
+ {
+ if (response.IsOKPacket())
+ {
+ m_curr_tid = tid;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool
+ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
+{
+ if (m_curr_tid_run == tid)
+ return true;
+
+ char packet[32];
+ const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
+ assert (packet_len + 1 < sizeof(packet));
+ StringExtractorGDBRemote response;
+ if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
+ {
+ if (response.IsOKPacket())
+ {
+ m_curr_tid_run = tid;
+ return true;
+ }
+ }
+ return false;
+}
+
+void
+ProcessGDBRemote::ResetGDBRemoteState ()
+{
+ // Reset and GDB remote state
+ m_curr_tid = LLDB_INVALID_THREAD_ID;
+ m_curr_tid_run = LLDB_INVALID_THREAD_ID;
+ m_z0_supported = 1;
+}
+
+
+bool
+ProcessGDBRemote::StartAsyncThread ()
+{
+ ResetGDBRemoteState ();
+
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
+
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
+
+ // Create a thread that watches our internal state and controls which
+ // events make it to clients (into the DCProcess event queue).
+ m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
+ return m_async_thread != LLDB_INVALID_HOST_THREAD;
+}
+
+void
+ProcessGDBRemote::StopAsyncThread ()
+{
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
+
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
+
+ m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
+
+ // Stop the stdio thread
+ if (m_async_thread != LLDB_INVALID_HOST_THREAD)
+ {
+ Host::ThreadJoin (m_async_thread, NULL, NULL);
+ }
+}
+
+
+void *
+ProcessGDBRemote::AsyncThread (void *arg)
+{
+ ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
+
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
+
+ Listener listener ("ProcessGDBRemote::AsyncThread");
+ EventSP event_sp;
+ const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
+ eBroadcastBitAsyncThreadShouldExit;
+
+ if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
+ {
+ bool done = false;
+ while (!done)
+ {
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
+ if (listener.WaitForEvent (NULL, event_sp))
+ {
+ const uint32_t event_type = event_sp->GetType();
+ switch (event_type)
+ {
+ case eBroadcastBitAsyncContinue:
+ {
+ const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
+
+ if (continue_packet)
+ {
+ const char *continue_cstr = (const char *)continue_packet->GetBytes ();
+ const size_t continue_cstr_len = continue_packet->GetByteSize ();
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
+
+ process->SetPrivateState(eStateRunning);
+ StringExtractorGDBRemote response;
+ StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
+
+ switch (stop_state)
+ {
+ case eStateStopped:
+ case eStateCrashed:
+ case eStateSuspended:
+ process->m_last_stop_packet = response;
+ process->m_last_stop_packet.SetFilePos (0);
+ process->SetPrivateState (stop_state);
+ break;
+
+ case eStateExited:
+ process->m_last_stop_packet = response;
+ process->m_last_stop_packet.SetFilePos (0);
+ response.SetFilePos(1);
+ process->SetExitStatus(response.GetHexU8(), NULL);
+ done = true;
+ break;
+
+ case eStateInvalid:
+ break;
+
+ default:
+ process->SetPrivateState (stop_state);
+ break;
+ }
+ }
+ }
+ break;
+
+ case eBroadcastBitAsyncThreadShouldExit:
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
+ done = true;
+ break;
+
+ default:
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
+ done = true;
+ break;
+ }
+ }
+ else
+ {
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
+ done = true;
+ }
+ }
+ }
+
+ if (log)
+ log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
+
+ process->m_async_thread = LLDB_INVALID_HOST_THREAD;
+ return NULL;
+}
+
+lldb_private::unw_addr_space_t
+ProcessGDBRemote::GetLibUnwindAddressSpace ()
+{
+ unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
+ if (m_target.GetArchitecture().GetCPUType() == CPU_TYPE_I386)
+ target_type = UNW_TARGET_I386;
+ if (m_target.GetArchitecture().GetCPUType() == CPU_TYPE_X86_64)
+ target_type = UNW_TARGET_X86_64;
+
+ if (m_libunwind_addr_space)
+ {
+ if (m_libunwind_target_type != target_type)
+ DestoryLibUnwindAddressSpace();
+ else
+ return m_libunwind_addr_space;
+ }
+ unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
+ m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
+ if (m_libunwind_addr_space)
+ m_libunwind_target_type = target_type;
+ else
+ m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
+ return m_libunwind_addr_space;
+}
+
+void
+ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
+{
+ if (m_libunwind_addr_space)
+ {
+ unw_destroy_addr_space (m_libunwind_addr_space);
+ m_libunwind_addr_space = NULL;
+ }
+ m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
+}
+
+
+const char *
+ProcessGDBRemote::GetDispatchQueueNameForThread
+(
+ addr_t thread_dispatch_qaddr,
+ std::string &dispatch_queue_name
+)
+{
+ dispatch_queue_name.clear();
+ if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
+ {
+ // Cache the dispatch_queue_offsets_addr value so we don't always have
+ // to look it up
+ if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
+ {
+ ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib")));
+ if (module_sp.get() == NULL)
+ return NULL;
+
+ const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData);
+ if (dispatch_queue_offsets_symbol)
+ m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(this);
+
+ if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
+ return NULL;
+ }
+
+ uint8_t memory_buffer[8];
+ DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
+
+ // Excerpt from src/queue_private.h
+ struct dispatch_queue_offsets_s
+ {
+ uint16_t dqo_version;
+ uint16_t dqo_label;
+ uint16_t dqo_label_size;
+ } dispatch_queue_offsets;
+
+
+ Error error;
+ if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
+ {
+ uint32_t data_offset = 0;
+ if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
+ {
+ if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
+ {
+ data_offset = 0;
+ lldb::addr_t queue_addr = data.GetAddress(&data_offset);
+ lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
+ dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
+ size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
+ if (bytes_read < dispatch_queue_offsets.dqo_label_size)
+ dispatch_queue_name.erase (bytes_read);
+ }
+ }
+ }
+ }
+ if (dispatch_queue_name.empty())
+ return NULL;
+ return dispatch_queue_name.c_str();
+}
+
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
new file mode 100644
index 00000000000..cd5bab0194f
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
@@ -0,0 +1,404 @@
+//===-- ProcessGDBRemote.h --------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef liblldb_ProcessGDBRemote_h_
+#define liblldb_ProcessGDBRemote_h_
+
+// C Includes
+
+// C++ Includes
+#include <list>
+
+// Other libraries and framework includes
+#include "lldb/Core/ArchSpec.h"
+#include "lldb/Core/Broadcaster.h"
+#include "lldb/Core/Error.h"
+#include "lldb/Core/InputReader.h"
+#include "lldb/Core/StreamString.h"
+#include "lldb/Core/ThreadSafeValue.h"
+#include "lldb/Target/Process.h"
+#include "lldb/Target/Thread.h"
+
+#include "GDBRemoteCommunication.h"
+#include "StringExtractor.h"
+#include "GDBRemoteRegisterContext.h"
+#include "libunwind.h"
+
+class ThreadGDBRemote;
+
+class ProcessGDBRemote : public lldb_private::Process
+{
+public:
+ //------------------------------------------------------------------
+ // Constructors and Destructors
+ //------------------------------------------------------------------
+ static Process*
+ CreateInstance (lldb_private::Target& target, lldb_private::Listener &listener);
+
+ static void
+ Initialize();
+
+ static void
+ Terminate();
+
+ static const char *
+ GetPluginNameStatic();
+
+ static const char *
+ GetPluginDescriptionStatic();
+
+ //------------------------------------------------------------------
+ // Constructors and Destructors
+ //------------------------------------------------------------------
+ ProcessGDBRemote(lldb_private::Target& target, lldb_private::Listener &listener);
+
+ virtual
+ ~ProcessGDBRemote();
+
+ //------------------------------------------------------------------
+ // Check if a given Process
+ //------------------------------------------------------------------
+ virtual bool
+ CanDebug (lldb_private::Target &target);
+
+ //------------------------------------------------------------------
+ // Creating a new process, or attaching to an existing one
+ //------------------------------------------------------------------
+ virtual lldb_private::Error
+ WillLaunch (lldb_private::Module* module);
+
+ virtual lldb_private::Error
+ DoLaunch (lldb_private::Module* module,
+ char const *argv[], // Can be NULL
+ char const *envp[], // Can be NULL
+ const char *stdin_path, // Can be NULL
+ const char *stdout_path, // Can be NULL
+ const char *stderr_path); // Can be NULL
+
+ virtual void
+ DidLaunch ();
+
+ virtual lldb_private::Error
+ WillAttach (lldb::pid_t pid);
+
+ virtual lldb_private::Error
+ WillAttach (const char *process_name, bool wait_for_launch);
+
+ lldb_private::Error
+ WillLaunchOrAttach ();
+
+ virtual lldb_private::Error
+ DoAttach (lldb::pid_t pid);
+
+ virtual lldb_private::Error
+ DoAttach (const char *process_name, bool wait_for_launch);
+
+ virtual void
+ DidAttach ();
+
+ //------------------------------------------------------------------
+ // PluginInterface protocol
+ //------------------------------------------------------------------
+ virtual const char *
+ GetPluginName();
+
+ virtual const char *
+ GetShortPluginName();
+
+ virtual uint32_t
+ GetPluginVersion();
+
+ virtual void
+ GetPluginCommandHelp (const char *command, lldb_private::Stream *strm);
+
+ virtual lldb_private::Error
+ ExecutePluginCommand (lldb_private::Args &command, lldb_private::Stream *strm);
+
+ virtual lldb_private::Log *
+ EnablePluginLogging (lldb_private::Stream *strm, lldb_private::Args &command);
+
+ //------------------------------------------------------------------
+ // Process Control
+ //------------------------------------------------------------------
+ virtual lldb_private::Error
+ WillResume ();
+
+ virtual lldb_private::Error
+ DoResume ();
+
+ virtual lldb_private::Error
+ DoHalt ();
+
+ virtual lldb_private::Error
+ WillDetach ();
+
+ virtual lldb_private::Error
+ DoDetach ();
+
+ virtual lldb_private::Error
+ DoSignal (int signal);
+
+ virtual lldb_private::Error
+ DoDestroy ();
+
+ virtual void
+ RefreshStateAfterStop();
+
+ //------------------------------------------------------------------
+ // Process Queries
+ //------------------------------------------------------------------
+ virtual bool
+ IsAlive ();
+
+ virtual lldb::addr_t
+ GetImageInfoAddress();
+
+ //------------------------------------------------------------------
+ // Process Memory
+ //------------------------------------------------------------------
+ virtual size_t
+ DoReadMemory (lldb::addr_t addr, void *buf, size_t size, lldb_private::Error &error);
+
+ virtual size_t
+ DoWriteMemory (lldb::addr_t addr, const void *buf, size_t size, lldb_private::Error &error);
+
+ virtual lldb::addr_t
+ DoAllocateMemory (size_t size, uint32_t permissions, lldb_private::Error &error);
+
+ virtual lldb_private::Error
+ DoDeallocateMemory (lldb::addr_t ptr);
+
+ //------------------------------------------------------------------
+ // Process STDIO
+ //------------------------------------------------------------------
+ virtual size_t
+ GetSTDOUT (char *buf, size_t buf_size, lldb_private::Error &error);
+
+ virtual size_t
+ GetSTDERR (char *buf, size_t buf_size, lldb_private::Error &error);
+
+ virtual size_t
+ PutSTDIN (const char *buf, size_t buf_size, lldb_private::Error &error);
+
+ //----------------------------------------------------------------------
+ // Process Breakpoints
+ //----------------------------------------------------------------------
+ virtual size_t
+ GetSoftwareBreakpointTrapOpcode (lldb_private::BreakpointSite *bp_site);
+
+ //----------------------------------------------------------------------
+ // Process Breakpoints
+ //----------------------------------------------------------------------
+ virtual lldb_private::Error
+ EnableBreakpoint (lldb_private::BreakpointSite *bp_site);
+
+ virtual lldb_private::Error
+ DisableBreakpoint (lldb_private::BreakpointSite *bp_site);
+
+ //----------------------------------------------------------------------
+ // Process Watchpoints
+ //----------------------------------------------------------------------
+ virtual lldb_private::Error
+ EnableWatchpoint (lldb_private::WatchpointLocation *wp_loc);
+
+ virtual lldb_private::Error
+ DisableWatchpoint (lldb_private::WatchpointLocation *wp_loc);
+
+ virtual lldb::ByteOrder
+ GetByteOrder () const;
+
+ virtual lldb_private::DynamicLoader *
+ GetDynamicLoader ();
+
+protected:
+ friend class ThreadGDBRemote;
+ friend class GDBRemoteCommunication;
+ friend class GDBRemoteRegisterContext;
+
+ bool
+ SetCurrentGDBRemoteThread (int tid);
+
+ bool
+ SetCurrentGDBRemoteThreadForRun (int tid);
+
+ //----------------------------------------------------------------------
+ // Accessors
+ //----------------------------------------------------------------------
+ bool
+ IsRunning ( lldb::StateType state )
+ {
+ return state == lldb::eStateRunning || IsStepping(state);
+ }
+
+ bool
+ IsStepping ( lldb::StateType state)
+ {
+ return state == lldb::eStateStepping;
+ }
+ bool
+ CanResume ( lldb::StateType state)
+ {
+ return state == lldb::eStateStopped;
+ }
+
+ bool
+ HasExited (lldb::StateType state)
+ {
+ return state == lldb::eStateExited;
+ }
+
+ bool
+ ProcessIDIsValid ( ) const;
+
+ static void
+ STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
+
+ void
+ AppendSTDOUT (const char* s, size_t len);
+
+ lldb_private::ArchSpec&
+ GetArchSpec()
+ {
+ return m_arch_spec;
+ }
+ const lldb_private::ArchSpec&
+ GetArchSpec() const
+ {
+ return m_arch_spec;
+ }
+
+ void
+ Clear ( );
+
+ lldb_private::Flags &
+ GetFlags ()
+ {
+ return m_flags;
+ }
+
+ const lldb_private::Flags &
+ GetFlags () const
+ {
+ return m_flags;
+ }
+
+ uint32_t
+ UpdateThreadListIfNeeded ();
+
+ lldb_private::Error
+ StartDebugserverProcess (const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
+ char const *inferior_argv[],
+ char const *inferior_envp[],
+ const char *stdin_path,
+ lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, then attach to this pid
+ const char *attach_pid_name, // Wait for the next process to launch whose basename matches "attach_wait_name"
+ bool wait_for_launch, // Wait for the process named "attach_wait_name" to launch
+ lldb_private::ArchSpec& arch_spec);
+
+ void
+ KillDebugserverProcess ();
+
+ void
+ BuildDynamicRegisterInfo ();
+
+ GDBRemoteCommunication &
+ GetGDBRemote()
+ {
+ return m_gdb_comm;
+ }
+
+ //------------------------------------------------------------------
+ /// Broadcaster event bits definitions.
+ //------------------------------------------------------------------
+ enum
+ {
+ eBroadcastBitAsyncContinue = (1 << 0),
+ eBroadcastBitAsyncThreadShouldExit = (1 << 1)
+ };
+
+
+ std::auto_ptr<lldb_private::DynamicLoader> m_dynamic_loader_ap;
+ lldb_private::Flags m_flags; // Process specific flags (see eFlags enums)
+ lldb_private::Communication m_stdio_communication;
+ lldb_private::Mutex m_stdio_mutex; // Multithreaded protection for stdio
+ std::string m_stdout_data;
+ lldb_private::ArchSpec m_arch_spec;
+ lldb::ByteOrder m_byte_order;
+ GDBRemoteCommunication m_gdb_comm;
+ lldb::pid_t m_debugserver_pid;
+ uint32_t m_debugserver_monitor;
+ StringExtractor m_last_stop_packet;
+ GDBRemoteDynamicRegisterInfo m_register_info;
+ lldb_private::Broadcaster m_async_broadcaster;
+ lldb::thread_t m_async_thread;
+ // Current GDB remote state. Any members added here need to be reset to
+ // proper default values in ResetGDBRemoteState ().
+ lldb::tid_t m_curr_tid; // Current gdb remote protocol thread index for all other operations
+ lldb::tid_t m_curr_tid_run; // Current gdb remote protocol thread index for continue, step, etc
+ uint32_t m_z0_supported:1; // Set to non-zero if Z0 and z0 packets are supported
+ lldb_private::StreamString m_continue_packet;
+ lldb::addr_t m_dispatch_queue_offsets_addr;
+ uint32_t m_packet_timeout;
+ size_t m_max_memory_size; // The maximum number of bytes to read/write when reading and writing memory
+ lldb_private::unw_targettype_t m_libunwind_target_type;
+ lldb_private::unw_addr_space_t m_libunwind_addr_space; // libunwind address space object for this process.
+ bool m_waiting_for_attach;
+
+ void
+ ResetGDBRemoteState ();
+
+ bool
+ StartAsyncThread ();
+
+ void
+ StopAsyncThread ();
+
+ static void *
+ AsyncThread (void *arg);
+
+ static bool
+ MonitorDebugserverProcess (void *callback_baton,
+ lldb::pid_t pid,
+ int signo, // Zero for no signal
+ int exit_status); // Exit value of process if signal is zero
+
+ lldb::StateType
+ SetThreadStopInfo (StringExtractor& stop_packet);
+
+ void
+ DidLaunchOrAttach ();
+
+ lldb_private::Error
+ ConnectToDebugserver (const char *host_port);
+
+ const char *
+ GetDispatchQueueNameForThread (lldb::addr_t thread_dispatch_qaddr,
+ std::string &dispatch_queue_name);
+
+ static size_t
+ AttachInputReaderCallback (void *baton,
+ lldb_private::InputReader *reader,
+ lldb::InputReaderAction notification,
+ const char *bytes,
+ size_t bytes_len);
+
+private:
+ //------------------------------------------------------------------
+ // For ProcessGDBRemote only
+ //------------------------------------------------------------------
+ DISALLOW_COPY_AND_ASSIGN (ProcessGDBRemote);
+
+ lldb_private::unw_addr_space_t
+ GetLibUnwindAddressSpace ();
+
+ void
+ DestoryLibUnwindAddressSpace ();
+};
+
+#endif // liblldb_ProcessGDBRemote_h_
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp
new file mode 100644
index 00000000000..051ce8f20f4
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp
@@ -0,0 +1,121 @@
+//===-- ProcessGDBRemoteLog.cpp ---------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ProcessGDBRemoteLog.h"
+
+#include "lldb/Core/Args.h"
+#include "lldb/Core/StreamFile.h"
+
+#include "ProcessGDBRemote.h"
+
+using namespace lldb;
+using namespace lldb_private;
+
+
+static Log* g_log = NULL; // Leak for now as auto_ptr was being cleaned up
+ // by global constructors before other threads
+ // were done with it.
+Log *
+ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (uint32_t mask)
+{
+ Log *log = g_log;
+ if (log && mask)
+ {
+ uint32_t log_mask = log->GetMask().GetAllFlagBits();
+ if ((log_mask & mask) != mask)
+ return NULL;
+ }
+ return log;
+}
+
+void
+ProcessGDBRemoteLog::DisableLog ()
+{
+ if (g_log)
+ {
+ delete g_log;
+ g_log = NULL;
+ }
+}
+
+Log *
+ProcessGDBRemoteLog::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, Args &args, Stream *feedback_strm)
+{
+ DisableLog ();
+ g_log = new Log (log_stream_sp);
+ if (g_log)
+ {
+ uint32_t flag_bits = 0;
+ bool got_unknown_category = false;
+ const size_t argc = args.GetArgumentCount();
+ for (size_t i=0; i<argc; ++i)
+ {
+ const char *arg = args.GetArgumentAtIndex(i);
+
+ if (::strcasecmp (arg, "all") == 0 ) flag_bits |= GDBR_LOG_ALL;
+ else if (::strcasestr (arg, "break") == arg ) flag_bits |= GDBR_LOG_BREAKPOINTS;
+ else if (::strcasecmp (arg, "default") == 0 ) flag_bits |= GDBR_LOG_DEFAULT;
+ else if (::strcasecmp (arg, "packets") == 0 ) flag_bits |= GDBR_LOG_PACKETS;
+ else if (::strcasecmp (arg, "memory") == 0 ) flag_bits |= GDBR_LOG_MEMORY;
+ else if (::strcasecmp (arg, "data-short") == 0 ) flag_bits |= GDBR_LOG_MEMORY_DATA_SHORT;
+ else if (::strcasecmp (arg, "data-long") == 0 ) flag_bits |= GDBR_LOG_MEMORY_DATA_LONG;
+ else if (::strcasecmp (arg, "process") == 0 ) flag_bits |= GDBR_LOG_PROCESS;
+ else if (::strcasecmp (arg, "step") == 0 ) flag_bits |= GDBR_LOG_STEP;
+ else if (::strcasecmp (arg, "thread") == 0 ) flag_bits |= GDBR_LOG_THREAD;
+ else if (::strcasecmp (arg, "verbose") == 0 ) flag_bits |= GDBR_LOG_VERBOSE;
+ else if (::strcasestr (arg, "watch") == arg ) flag_bits |= GDBR_LOG_WATCHPOINTS;
+ else
+ {
+ feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
+ if (got_unknown_category == false)
+ {
+ got_unknown_category = true;
+ ListLogCategories (feedback_strm);
+ }
+ }
+ }
+ if (flag_bits == 0)
+ flag_bits = GDBR_LOG_DEFAULT;
+ g_log->GetMask().SetAllFlagBits(flag_bits);
+ g_log->GetOptions().SetAllFlagBits(log_options);
+ }
+ return g_log;
+}
+
+void
+ProcessGDBRemoteLog::ListLogCategories (Stream *strm)
+{
+ strm->Printf("Logging categories for '%s':\n"
+ "\tall - turn on all available logging categories\n"
+ "\tbreak - log breakpoints\n"
+ "\tdefault - enable the default set of logging categories for liblldb\n"
+ "\tpackets - log gdb remote packets\n"
+ "\tmemory - log memory reads and writes\n"
+ "\tdata-short - log memory bytes for memory reads and writes for short transactions only\n"
+ "\tdata-long - log memory bytes for memory reads and writes for all transactions\n"
+ "\tprocess - log process events and activities\n"
+ "\tthread - log thread events and activities\n"
+ "\tstep - log step related activities\n"
+ "\tverbose - enable verbose loggging\n"
+ "\twatch - log watchpoint related activities\n", ProcessGDBRemote::GetPluginNameStatic());
+}
+
+
+void
+ProcessGDBRemoteLog::LogIf (uint32_t mask, const char *format, ...)
+{
+ Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (mask);
+ if (log)
+ {
+ va_list args;
+ va_start (args, format);
+ log->VAPrintf (format, args);
+ va_end (args);
+ }
+}
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h
new file mode 100644
index 00000000000..97580d38674
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h
@@ -0,0 +1,53 @@
+//===-- ProcessGDBRemoteLog.h -----------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef liblldb_ProcessGDBRemoteLog_h_
+#define liblldb_ProcessGDBRemoteLog_h_
+
+// C Includes
+// C++ Includes
+// Other libraries and framework includes
+
+// Project includes
+#include "lldb/Core/Log.h"
+
+#define GDBR_LOG_VERBOSE (1u << 0)
+#define GDBR_LOG_PROCESS (1u << 1)
+#define GDBR_LOG_THREAD (1u << 2)
+#define GDBR_LOG_PACKETS (1u << 3)
+#define GDBR_LOG_MEMORY (1u << 4) // Log memory reads/writes calls
+#define GDBR_LOG_MEMORY_DATA_SHORT (1u << 5) // Log short memory reads/writes bytes
+#define GDBR_LOG_MEMORY_DATA_LONG (1u << 6) // Log all memory reads/writes bytes
+#define GDBR_LOG_BREAKPOINTS (1u << 7)
+#define GDBR_LOG_WATCHPOINTS (1u << 8)
+#define GDBR_LOG_STEP (1u << 9)
+#define GDBR_LOG_COMM (1u << 10)
+#define GDBR_LOG_ALL (UINT32_MAX)
+#define GDBR_LOG_DEFAULT GDBR_LOG_PACKETS
+
+class ProcessGDBRemoteLog
+{
+public:
+ static lldb_private::Log *
+ GetLogIfAllCategoriesSet(uint32_t mask = 0);
+
+ static void
+ DisableLog ();
+
+ static lldb_private::Log *
+ EnableLog (lldb::StreamSP &log_stream_sp, uint32_t log_options, lldb_private::Args &args, lldb_private::Stream *feedback_strm);
+
+ static void
+ ListLogCategories (lldb_private::Stream *strm);
+
+ static void
+ LogIf (uint32_t mask, const char *format, ...);
+};
+
+#endif // liblldb_ProcessGDBRemoteLog_h_
diff --git a/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp b/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp
new file mode 100644
index 00000000000..37485edf4e5
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp
@@ -0,0 +1,296 @@
+//===-- ThreadGDBRemote.cpp -------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+
+#include "ThreadGDBRemote.h"
+
+#include "lldb/Core/ArchSpec.h"
+#include "lldb/Core/DataExtractor.h"
+#include "lldb/Core/StreamString.h"
+#include "lldb/Target/Process.h"
+#include "lldb/Target/RegisterContext.h"
+#include "lldb/Target/Target.h"
+#include "lldb/Target/Unwind.h"
+#include "lldb/Breakpoint/WatchpointLocation.h"
+
+#include "LibUnwindRegisterContext.h"
+#include "ProcessGDBRemote.h"
+#include "ProcessGDBRemoteLog.h"
+#include "StringExtractorGDBRemote.h"
+#include "UnwindLibUnwind.h"
+#include "UnwindMacOSXFrameBackchain.h"
+
+using namespace lldb;
+using namespace lldb_private;
+
+//----------------------------------------------------------------------
+// Thread Registers
+//----------------------------------------------------------------------
+
+ThreadGDBRemote::ThreadGDBRemote (ProcessGDBRemote &process, lldb::tid_t tid) :
+ Thread(process, tid),
+ m_stop_info_stop_id (0),
+ m_stop_info (this),
+ m_thread_name (),
+ m_dispatch_queue_name (),
+ m_thread_dispatch_qaddr (LLDB_INVALID_ADDRESS),
+ m_unwinder_ap ()
+{
+// ProcessGDBRemoteLog::LogIf(GDBR_LOG_THREAD | GDBR_LOG_VERBOSE, "ThreadGDBRemote::ThreadGDBRemote ( pid = %i, tid = 0x%4.4x, )", m_process.GetID(), GetID());
+ ProcessGDBRemoteLog::LogIf(GDBR_LOG_THREAD, "%p: ThreadGDBRemote::ThreadGDBRemote (pid = %i, tid = 0x%4.4x)", this, m_process.GetID(), GetID());
+}
+
+ThreadGDBRemote::~ThreadGDBRemote ()
+{
+ ProcessGDBRemoteLog::LogIf(GDBR_LOG_THREAD, "%p: ThreadGDBRemote::~ThreadGDBRemote (pid = %i, tid = 0x%4.4x)", this, m_process.GetID(), GetID());
+}
+
+
+const char *
+ThreadGDBRemote::GetInfo ()
+{
+ return NULL;
+}
+
+
+const char *
+ThreadGDBRemote::GetName ()
+{
+ if (m_thread_name.empty())
+ return NULL;
+ return m_thread_name.c_str();
+}
+
+
+const char *
+ThreadGDBRemote::GetQueueName ()
+{
+ // Always re-fetch the dispatch queue name since it can change
+ if (m_thread_dispatch_qaddr != 0 || m_thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
+ return GetGDBProcess().GetDispatchQueueNameForThread (m_thread_dispatch_qaddr, m_dispatch_queue_name);
+ return NULL;
+}
+
+bool
+ThreadGDBRemote::WillResume (StateType resume_state)
+{
+ // TODO: cache for next time in case we can match things up??
+ ClearStackFrames();
+ int signo = GetResumeSignal();
+ m_stop_info.Clear();
+ switch (resume_state)
+ {
+ case eStateSuspended:
+ case eStateStopped:
+ // Don't append anything for threads that should stay stopped.
+ break;
+
+ case eStateRunning:
+ if (m_process.GetUnixSignals().SignalIsValid (signo))
+ GetGDBProcess().m_continue_packet.Printf(";C%2.2x:%4.4x", signo, GetID());
+ else
+ GetGDBProcess().m_continue_packet.Printf(";c:%4.4x", GetID());
+ break;
+
+ case eStateStepping:
+ if (m_process.GetUnixSignals().SignalIsValid (signo))
+ GetGDBProcess().m_continue_packet.Printf(";S%2.2x:%4.4x", signo, GetID());
+ else
+ GetGDBProcess().m_continue_packet.Printf(";s:%4.4x", GetID());
+ break;
+ }
+ Thread::WillResume(resume_state);
+ return true;
+}
+
+void
+ThreadGDBRemote::RefreshStateAfterStop()
+{
+ // Invalidate all registers in our register context
+ GetRegisterContext()->Invalidate();
+}
+
+Unwind *
+ThreadGDBRemote::GetUnwinder ()
+{
+ if (m_unwinder_ap.get() == NULL)
+ {
+ const ArchSpec target_arch (GetProcess().GetTarget().GetArchitecture ());
+ if (target_arch == ArchSpec("x86_64") || target_arch == ArchSpec("i386"))
+ {
+ m_unwinder_ap.reset (new UnwindLibUnwind (*this, GetGDBProcess().GetLibUnwindAddressSpace()));
+ }
+ else
+ {
+ m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
+ }
+ }
+ return m_unwinder_ap.get();
+}
+
+uint32_t
+ThreadGDBRemote::GetStackFrameCount()
+{
+ Unwind *unwinder = GetUnwinder ();
+ if (unwinder)
+ return unwinder->GetFrameCount();
+ return 0;
+}
+
+// Make sure that GetStackFrameAtIndex() does NOT call GetStackFrameCount() when
+// getting the stack frame at index zero! This way GetStackFrameCount() (via
+// GetStackFRameData()) can call this function to get the first frame in order
+// to provide the first frame to a lower call for efficiency sake (avoid
+// redundant lookups in the frame symbol context).
+lldb::StackFrameSP
+ThreadGDBRemote::GetStackFrameAtIndex (uint32_t idx)
+{
+
+ StackFrameSP frame_sp (m_frames.GetFrameAtIndex(idx));
+
+ if (frame_sp.get())
+ return frame_sp;
+
+ // Don't try and fetch a frame while process is running
+// FIXME: This check isn't right because IsRunning checks the Public state, but this
+// is work you need to do - for instance in ShouldStop & friends - before the public
+// state has been changed.
+// if (m_process.IsRunning())
+// return frame_sp;
+
+ // Special case the first frame (idx == 0) so that we don't need to
+ // know how many stack frames there are to get it. If we need any other
+ // frames, then we do need to know if "idx" is a valid index.
+ if (idx == 0)
+ {
+ // If this is the first frame, we want to share the thread register
+ // context with the stack frame at index zero.
+ GetRegisterContext();
+ assert (m_reg_context_sp.get());
+ frame_sp.reset (new StackFrame (idx, *this, m_reg_context_sp, m_reg_context_sp->GetSP(), m_reg_context_sp->GetPC()));
+ }
+ else if (idx < GetStackFrameCount())
+ {
+ Unwind *unwinder = GetUnwinder ();
+ if (unwinder)
+ {
+ addr_t pc, cfa;
+ if (unwinder->GetFrameInfoAtIndex(idx, cfa, pc))
+ frame_sp.reset (new StackFrame (idx, *this, cfa, pc));
+ }
+ }
+ m_frames.SetFrameAtIndex(idx, frame_sp);
+ return frame_sp;
+}
+
+void
+ThreadGDBRemote::ClearStackFrames ()
+{
+ Unwind *unwinder = GetUnwinder ();
+ if (unwinder)
+ unwinder->Clear();
+ Thread::ClearStackFrames();
+}
+
+
+bool
+ThreadGDBRemote::ThreadIDIsValid (lldb::tid_t thread)
+{
+ return thread != 0;
+}
+
+void
+ThreadGDBRemote::Dump(Log *log, uint32_t index)
+{
+}
+
+
+bool
+ThreadGDBRemote::ShouldStop (bool &step_more)
+{
+ return true;
+}
+RegisterContext *
+ThreadGDBRemote::GetRegisterContext ()
+{
+ if (m_reg_context_sp.get() == NULL)
+ m_reg_context_sp.reset (CreateRegisterContextForFrame (NULL));
+ return m_reg_context_sp.get();
+}
+
+RegisterContext *
+ThreadGDBRemote::CreateRegisterContextForFrame (StackFrame *frame)
+{
+ const bool read_all_registers_at_once = false;
+ uint32_t frame_idx = 0;
+
+ if (frame)
+ frame_idx = frame->GetID();
+
+ if (frame_idx == 0)
+ return new GDBRemoteRegisterContext (*this, frame, GetGDBProcess().m_register_info, read_all_registers_at_once);
+ else if (m_unwinder_ap.get() && frame_idx < m_unwinder_ap->GetFrameCount())
+ return m_unwinder_ap->CreateRegisterContextForFrame (frame);
+ return NULL;
+}
+
+bool
+ThreadGDBRemote::SaveFrameZeroState (RegisterCheckpoint &checkpoint)
+{
+ lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
+ if (frame_sp)
+ {
+ checkpoint.SetStackID(frame_sp->GetStackID());
+ return frame_sp->GetRegisterContext()->ReadAllRegisterValues (checkpoint.GetData());
+ }
+ return false;
+}
+
+bool
+ThreadGDBRemote::RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint)
+{
+ lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
+ if (frame_sp)
+ {
+ bool ret = frame_sp->GetRegisterContext()->WriteAllRegisterValues (checkpoint.GetData());
+ frame_sp->GetRegisterContext()->Invalidate();
+ ClearStackFrames();
+ return ret;
+ }
+ return false;
+}
+
+bool
+ThreadGDBRemote::GetRawStopReason (StopInfo *stop_info)
+{
+ if (m_stop_info_stop_id != m_process.GetStopID())
+ {
+ char packet[256];
+ const int packet_len = snprintf(packet, sizeof(packet), "qThreadStopInfo%x", GetID());
+ assert (packet_len < (sizeof(packet) - 1));
+ StringExtractorGDBRemote stop_packet;
+ if (GetGDBProcess().GetGDBRemote().SendPacketAndWaitForResponse(packet, stop_packet, 1, false))
+ {
+ std::string copy(stop_packet.GetStringRef());
+ GetGDBProcess().SetThreadStopInfo (stop_packet);
+ // The process should have set the stop info stop ID and also
+ // filled this thread in with valid stop info
+ if (m_stop_info_stop_id != m_process.GetStopID())
+ {
+ //ProcessGDBRemoteLog::LogIf(GDBR_LOG_THREAD, "warning: qThreadStopInfo problem: '%s' => '%s'", packet, stop_packet.GetStringRef().c_str());
+ printf("warning: qThreadStopInfo problem: '%s' => '%s'\n\torig '%s'\n", packet, stop_packet.GetStringRef().c_str(), copy.c_str()); /// REMOVE THIS
+ return false;
+ }
+ }
+ }
+ *stop_info = m_stop_info;
+ return true;
+}
+
+
diff --git a/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h b/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h
new file mode 100644
index 00000000000..3fa4ae09a2a
--- /dev/null
+++ b/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h
@@ -0,0 +1,156 @@
+//===-- ThreadGDBRemote.h ---------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef liblldb_ThreadGDBRemote_h_
+#define liblldb_ThreadGDBRemote_h_
+
+#include <string>
+
+#include "lldb/Target/Process.h"
+#include "lldb/Target/Thread.h"
+#include "MachException.h"
+#include "libunwind.h"
+
+class StringExtractor;
+class ProcessGDBRemote;
+
+class ThreadGDBRemote : public lldb_private::Thread
+{
+public:
+ ThreadGDBRemote (ProcessGDBRemote &process, lldb::tid_t tid);
+
+ virtual
+ ~ThreadGDBRemote ();
+
+ virtual bool
+ WillResume (lldb::StateType resume_state);
+
+ virtual void
+ RefreshStateAfterStop();
+
+ virtual const char *
+ GetInfo ();
+
+ virtual const char *
+ GetName ();
+
+ virtual const char *
+ GetQueueName ();
+
+ virtual lldb_private::RegisterContext *
+ GetRegisterContext ();
+
+ virtual lldb_private::RegisterContext *
+ CreateRegisterContextForFrame (lldb_private::StackFrame *frame);
+
+ virtual bool
+ SaveFrameZeroState (RegisterCheckpoint &checkpoint);
+
+ virtual bool
+ RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint);
+
+ virtual uint32_t
+ GetStackFrameCount();
+
+ virtual lldb::StackFrameSP
+ GetStackFrameAtIndex (uint32_t idx);
+
+ virtual void
+ ClearStackFrames ();
+
+ ProcessGDBRemote &
+ GetGDBProcess ()
+ {
+ return (ProcessGDBRemote &)m_process;
+ }
+
+ const ProcessGDBRemote &
+ GetGDBProcess () const
+ {
+ return (ProcessGDBRemote &)m_process;
+ }
+
+ void
+ Dump (lldb_private::Log *log, uint32_t index);
+
+ static bool
+ ThreadIDIsValid (lldb::tid_t thread);
+
+ bool
+ ShouldStop (bool &step_more);
+
+ const char *
+ GetBasicInfoAsString ();
+
+ lldb_private::Thread::StopInfo &
+ GetStopInfoRef ()
+ {
+ return m_stop_info;
+ }
+
+ uint32_t
+ GetStopInfoStopID()
+ {
+ return m_stop_info_stop_id;
+ }
+
+ void
+ SetStopInfoStopID (uint32_t stop_id)
+ {
+ m_stop_info_stop_id = stop_id;
+ }
+
+ void
+ SetName (const char *name)
+ {
+ if (name && name[0])
+ m_thread_name.assign (name);
+ else
+ m_thread_name.clear();
+ }
+
+ lldb::addr_t
+ GetThreadDispatchQAddr ()
+ {
+ return m_thread_dispatch_qaddr;
+ }
+
+ void
+ SetThreadDispatchQAddr (lldb::addr_t thread_dispatch_qaddr)
+ {
+ m_thread_dispatch_qaddr = thread_dispatch_qaddr;
+ }
+
+protected:
+ //------------------------------------------------------------------
+ // Member variables.
+ //------------------------------------------------------------------
+ uint32_t m_stop_info_stop_id;
+ lldb_private::Thread::StopInfo m_stop_info;
+ std::string m_thread_name;
+ std::string m_dispatch_queue_name;
+ lldb::addr_t m_thread_dispatch_qaddr;
+ std::auto_ptr<lldb_private::Unwind> m_unwinder_ap;
+ //------------------------------------------------------------------
+ // Member variables.
+ //------------------------------------------------------------------
+
+ lldb_private::Unwind *
+ GetUnwinder ();
+
+ void
+ SetStopInfoFromPacket (StringExtractor &stop_packet, uint32_t stop_id);
+
+ virtual bool
+ GetRawStopReason (StopInfo *stop_info);
+
+
+};
+
+#endif // liblldb_ThreadGDBRemote_h_
OpenPOWER on IntegriCloud