summaryrefslogtreecommitdiffstats
path: root/src/qscriptdebuggerconnector.cpp
blob: b677d27fbf0816b2e7d60d38d7db2bdfebe1c97b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "qscriptdebuggerconnector.h"
#include <QtCore/qeventloop.h>
#include <QtNetwork/qtcpserver.h>
#include <QtNetwork/qtcpsocket.h>
#include <QtScript/qscriptengine.h>
#include <private/qscriptdebuggerbackend_p.h>
#include <private/qscriptdebuggercommand_p.h>
#include <private/qscriptdebuggerevent_p.h>
#include <private/qscriptdebuggerresponse_p.h>
#include <private/qscriptdebuggercommandexecutor_p.h>
#include <private/qscriptbreakpointdata_p.h>
#include <private/qscriptdebuggerobjectsnapshotdelta_p.h>

// #define DEBUGGERCONNECTOR_DEBUG

class QScriptRemoteTargetDebuggerBackend : public QObject,
                                           public QScriptDebuggerBackend
{
    Q_OBJECT
public:
    enum Error {
        NoError,
        HostNotFoundError,
        ConnectionRefusedError,
        HandshakeError,
        SocketError
    };

    QScriptRemoteTargetDebuggerBackend();
    ~QScriptRemoteTargetDebuggerBackend();

    void connectToDebugger(const QHostAddress &address, quint16 port);
    void disconnectFromDebugger();

    bool listen(const QHostAddress &address, quint16 port);

    void resume();

Q_SIGNALS:
    void connected();
    void disconnected();
    void error(Error error);

protected:
    void event(const QScriptDebuggerEvent &event);

private Q_SLOTS:
    void onSocketStateChanged(QAbstractSocket::SocketState);
    void onSocketError(QAbstractSocket::SocketError);
    void onReadyRead();
    void onNewConnection();

private:
    enum State {
        UnconnectedState,
        HandshakingState,
        ConnectedState
    };

private:
    State m_state;
    QTcpSocket *m_socket;
    int m_blockSize;
    QTcpServer *m_server;
    QList<QEventLoop*> m_eventLoopPool;
    QList<QEventLoop*> m_eventLoopStack;

private:
    Q_DISABLE_COPY(QScriptRemoteTargetDebuggerBackend)
};

QScriptRemoteTargetDebuggerBackend::QScriptRemoteTargetDebuggerBackend()
    : m_state(UnconnectedState), m_socket(0), m_blockSize(0), m_server(0)
{
}

QScriptRemoteTargetDebuggerBackend::~QScriptRemoteTargetDebuggerBackend()
{
}

void QScriptRemoteTargetDebuggerBackend::connectToDebugger(const QHostAddress &address, quint16 port)
{
    Q_ASSERT(m_state == UnconnectedState);
    if (!m_socket) {
        m_socket = new QTcpSocket(this);
        QObject::connect(m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                         this, SLOT(onSocketSateChanged(QAbstractSocket::SocketState)));
        QObject::connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),
                         this, SLOT(onSocketError(QAbstractSocket::SocketError)));
        QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    }
    m_socket->connectToHost(address, port);
}

void QScriptRemoteTargetDebuggerBackend::disconnectFromDebugger()
{
    if (!m_socket)
        return;
    m_socket->disconnectFromHost();
}

bool QScriptRemoteTargetDebuggerBackend::listen(const QHostAddress &address, quint16 port)
{
    if (m_socket)
        return false;
    if (!m_server) {
        m_server = new QTcpServer();
        QObject::connect(m_server, SIGNAL(newConnection()),
                         this, SLOT(onNewConnection()));
    }
    return m_server->listen(address, port);
}

void QScriptRemoteTargetDebuggerBackend::onSocketStateChanged(QAbstractSocket::SocketState s)
{
    if (s == QAbstractSocket::ConnectedState) {
        m_state = HandshakingState;
    } else if (s == QAbstractSocket::UnconnectedState) {
        engine()->setAgent(0);
        m_state = UnconnectedState;
        emit disconnected();
    }
}

void QScriptRemoteTargetDebuggerBackend::onSocketError(QAbstractSocket::SocketError err)
{
    qDebug("%s", qPrintable(m_socket->errorString()));
}

void QScriptRemoteTargetDebuggerBackend::onNewConnection()
{
    m_socket = m_server->nextPendingConnection();
    m_server->close();
    QObject::connect(m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                     this, SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
    QObject::connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),
                     this, SLOT(onSocketError(QAbstractSocket::SocketError)));
    QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    // the handshake is initiated by the debugger side, so wait for it
    m_state = HandshakingState;
}

void QScriptRemoteTargetDebuggerBackend::onReadyRead()
{
    switch (m_state) {
    case UnconnectedState:
        Q_ASSERT(0);
        break;

    case HandshakingState: {
        QByteArray handshakeData("QtScriptDebug-Handshake");
        if (m_socket->bytesAvailable() == handshakeData.size()) {
            QByteArray ba = m_socket->read(handshakeData.size());
            if (ba == handshakeData) {
#ifdef DEBUGGERCONNECTOR_DEBUG
                qDebug() << "sending handshake reply (" << handshakeData.size() << "bytes )";
#endif
                m_socket->write(handshakeData);
                // handshaking complete
                // ### a way to specify if a break should be triggered immediately,
                // or only if an uncaught exception is triggered
                interruptEvaluation();
                m_state = ConnectedState;
                emit connected();
            } else {
//                d->error = QScriptDebuggerConnector::HandshakeError;
//                d->errorString = QString::fromLatin1("Incorrect handshake data received");
                m_state = UnconnectedState;
                emit error(HandshakeError);
                m_socket->close();
            }
        }
    }   break;

    case ConnectedState: {
#ifdef DEBUGGERCONNECTOR_DEBUG
        qDebug() << "received data. bytesAvailable:" << m_socket->bytesAvailable();
#endif
        QDataStream in(m_socket);
        in.setVersion(QDataStream::Qt_4_5);
        if (m_blockSize == 0) {
            if (m_socket->bytesAvailable() < (int)sizeof(quint32))
                return;
            in >> m_blockSize;
#ifdef DEBUGGERCONNECTOR_DEBUG
            qDebug() << "  blockSize:" << m_blockSize;
#endif
        }
        if (m_socket->bytesAvailable() < m_blockSize)
            return;

#ifdef DEBUGGERCONNECTOR_DEBUG
        qDebug() << "deserializing command";
#endif
        int wasAvailable = m_socket->bytesAvailable();
        qint32 id;
        in >> id;
        QScriptDebuggerCommand command(QScriptDebuggerCommand::None);
        in >> command;
        Q_ASSERT(m_socket->bytesAvailable() == wasAvailable - m_blockSize);

#ifdef DEBUGGERCONNECTOR_DEBUG
        qDebug("executing command (id=%d, type=%d)", id, command.type());
#endif
        QScriptDebuggerResponse response = commandExecutor()->execute(this, command);

#ifdef DEBUGGERCONNECTOR_DEBUG
        qDebug() << "serializing response";
#endif
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_5);
        out << (quint32)0; // reserve 4 bytes for block size
        out << (quint8)1;  // type = command response
        out << id;
        out << response;
        out.device()->seek(0);
        out << (quint32)(block.size() - sizeof(quint32));
#ifdef DEBUGGERCONNECTOR_DEBUG
        qDebug() << "writing response (" << block.size() << "bytes )" << block.toHex();
#endif
        m_socket->write(block);
        m_blockSize = 0;

#ifdef DEBUGGERCONNECTOR_DEBUG
        qDebug() << "bytes available is now" << m_socket->bytesAvailable();
#endif
        if (m_socket->bytesAvailable() != 0)
            QMetaObject::invokeMethod(this, "onReadyRead", Qt::QueuedConnection);
    }   break;

    }
}

/*!
  \reimp
*/
void QScriptRemoteTargetDebuggerBackend::event(const QScriptDebuggerEvent &event)
{
    if (m_state != ConnectedState)
        return;
    if (m_eventLoopPool.isEmpty())
        m_eventLoopPool.append(new QEventLoop());
    QEventLoop *eventLoop = m_eventLoopPool.takeFirst();
    Q_ASSERT(!eventLoop->isRunning());
    m_eventLoopStack.prepend(eventLoop);

#ifdef DEBUGGERCONNECTOR_DEBUG
    qDebug() << "serializing event of type" << event.type();
#endif
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_5);
    out << (quint32)0; // reserve 4 bytes for block size
    out << (quint8)0;  // type = event
    out << event;
    out.device()->seek(0);
    out << (quint32)(block.size() - sizeof(quint32));

#ifdef DEBUGGERCONNECTOR_DEBUG
    qDebug() << "writing event (" << block.size() << " bytes )";
#endif
    m_socket->write(block);

    // run an event loop until the debugger triggers a resume
#ifdef DEBUGGERCONNECTOR_DEBUG
    qDebug("entering event loop");
#endif
    eventLoop->exec();
#ifdef DEBUGGERCONNECTOR_DEBUG
    qDebug("returned from event loop");
#endif

    if (!m_eventLoopStack.isEmpty()) {
        // the event loop was quit directly (i.e. not via resume())
        m_eventLoopStack.takeFirst();
    }
    m_eventLoopPool.append(eventLoop);
    doPendingEvaluate(/*postEvent=*/false);
}

/*!
  \reimp
*/
void QScriptRemoteTargetDebuggerBackend::resume()
{
    // quitting the event loops will cause event() to return (see above)
    while (!m_eventLoopStack.isEmpty()) {
        QEventLoop *eventLoop = m_eventLoopStack.takeFirst();
        if (eventLoop->isRunning())
            eventLoop->quit();
    }
}

/*!
  Constructs a new QScriptDebuggerConnector object with the given \a
  parent.
*/
QScriptDebuggerConnector::QScriptDebuggerConnector(QObject *parent)
    : QObject(parent), m_backend(0)
{
}

/*!
  Destroys this QScriptDebuggerConnector.
*/
QScriptDebuggerConnector::~QScriptDebuggerConnector()
{
    delete m_backend;
}

/*!
  Sets the \a engine that this connector will manage a connection to.
*/
void QScriptDebuggerConnector::setEngine(QScriptEngine *engine)
{
    if (m_backend) {
        m_backend->detach();
    } else {
        m_backend = new QScriptRemoteTargetDebuggerBackend();
        QObject::connect(m_backend, SIGNAL(connected()),
                         this, SIGNAL(connected()));
        QObject::connect(m_backend, SIGNAL(disconnected()),
                         this, SIGNAL(disconnected()));
    }
    m_backend->attachTo(engine);
}

/*!
  Returns the \a engine that this connector manages a connection to,
  or 0 if no engine has been set.
*/
QScriptEngine *QScriptDebuggerConnector::engine() const
{
    if (!m_backend)
        return 0;
    return m_backend->engine();
}

/*!
  Attempts to make a connection to the given \a address on the given
  \a port.

  The connected() signal is emitted when the connection has been
  established.

  \sa disconnectFromDebugger(), listen()
*/
void QScriptDebuggerConnector::connectToDebugger(const QHostAddress &address, quint16 port)
{
    if (!m_backend) {
        qWarning("QScriptDebuggerConnector::connectToDebugger(): no engine has been set (call setEngine() first)");
        return;
    }
    m_backend->connectToDebugger(address, port);
}

/*!
  Attempts to close the connection.

  The disconnected() signal is emitted when the connection has been
  closed.

  \sa connectToDebugger()
*/
void QScriptDebuggerConnector::disconnectFromDebugger()
{
    if (m_backend)
        m_backend->disconnectFromDebugger();
}

/*!
  Listens for an incoming connection on the given \a address and \a
  port.

  Returns true on success; otherwise returns false.

  The connected() signal is emitted when a connection has been
  established.

  \sa connectToDebugger()
*/
bool QScriptDebuggerConnector::listen(const QHostAddress &address, quint16 port)
{
    if (!m_backend) {
        qWarning("QScriptDebuggerConnector::listen(): no engine has been set (call setEngine() first)");
        return false;
    }
    return m_backend->listen(address, port);
}

#include "qscriptdebuggerconnector.moc"