summaryrefslogtreecommitdiffstats
path: root/src/declarative/debugger/qjsdebuggeragent.cpp
blob: 9b76592c485918421a1c1e6b375a6edc231e39f1 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 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 the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "private/qjsdebuggeragent_p.h"
#include "private/qdeclarativedebughelper_p.h"

#include <QtCore/qdatetime.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qset.h>
#include <QtCore/qurl.h>
#include <QtScript/qscriptcontextinfo.h>
#include <QtScript/qscriptengine.h>
#include <QtScript/qscriptvalueiterator.h>

QT_BEGIN_NAMESPACE

class QJSDebuggerAgentPrivate
{
public:
    QJSDebuggerAgentPrivate(QJSDebuggerAgent *q)
        : q(q), state(NoState)
    {}

    void continueExec();
    void recordKnownObjects(const QList<JSAgentWatchData> &);
    QList<JSAgentWatchData> getLocals(QScriptContext *);
    void positionChange(qint64 scriptId, int lineNumber, int columnNumber);
    QScriptEngine *engine() { return q->engine(); }
    void stopped();

public:
    QJSDebuggerAgent *q;
    JSDebuggerState state;
    int stepDepth;
    int stepCount;

    QEventLoop loop;
    QHash<qint64, QString> filenames;
    JSAgentBreakpoints breakpoints;
    // breakpoints by filename (without path)
    QHash<QString, JSAgentBreakpointData> fileNameToBreakpoints;
    QStringList watchExpressions;
    QSet<qint64> knownObjectIds;
};

namespace {

class SetupExecEnv
{
public:
    SetupExecEnv(QJSDebuggerAgentPrivate *a)
        : agent(a),
          previousState(a->state),
          hadException(a->engine()->hasUncaughtException())
    {
        agent->state = StoppedState;
    }

    ~SetupExecEnv()
    {
        if (!hadException && agent->engine()->hasUncaughtException())
            agent->engine()->clearExceptions();
        agent->state = previousState;
    }

private:
    QJSDebuggerAgentPrivate *agent;
    JSDebuggerState previousState;
    bool hadException;
};

} // anonymous namespace

static JSAgentWatchData fromScriptValue(const QString &expression,
                                        const QScriptValue &value)
{
    static const QString arrayStr = QCoreApplication::translate
            ("Debugger::JSAgentWatchData", "[Array of length %1]");
    static const QString undefinedStr = QCoreApplication::translate
            ("Debugger::JSAgentWatchData", "<undefined>");

    JSAgentWatchData data;
    data.exp = expression.toUtf8();
    data.name = data.exp;
    data.hasChildren = false;
    data.value = value.toString().toUtf8();
    data.objectId = value.objectId();
    if (value.isArray()) {
        data.type = "Array";
        data.value = arrayStr.arg(value.property(QLatin1String("length")).toString()).toUtf8();
        data.hasChildren = true;
    } else if (value.isBool()) {
        data.type = "Bool";
        // data.value = value.toBool() ? "true" : "false";
    } else if (value.isDate()) {
        data.type = "Date";
        data.value = value.toDateTime().toString().toUtf8();
    } else if (value.isError()) {
        data.type = "Error";
    } else if (value.isFunction()) {
        data.type = "Function";
    } else if (value.isUndefined()) {
        data.type = undefinedStr.toUtf8();
    } else if (value.isNumber()) {
        data.type = "Number";
    } else if (value.isRegExp()) {
        data.type = "RegExp";
    } else if (value.isString()) {
        data.type = "String";
    } else if (value.isVariant()) {
        data.type = "Variant";
    } else if (value.isQObject()) {
        const QObject *obj = value.toQObject();
        data.type = "Object";
        data.value += '[';
        data.value += obj->metaObject()->className();
        data.value += ']';
        data.hasChildren = true;
    } else if (value.isObject()) {
        data.type = "Object";
        data.hasChildren = true;
        data.value = "[Object]";
    } else if (value.isNull()) {
        data.type = "<null>";
    } else {
        data.type = "<unknown>";
    }
    return data;
}

static QList<JSAgentWatchData> expandObject(const QScriptValue &object)
{
    QList<JSAgentWatchData> result;
    QScriptValueIterator it(object);
    while (it.hasNext()) {
        it.next();
        if (it.flags() & QScriptValue::SkipInEnumeration)
            continue;
        if (/*object.isQObject() &&*/ it.value().isFunction()) {
            // Cosmetics: skip all functions and slot, there are too many of them,
            // and it is not useful information in the debugger.
            continue;
        }
        JSAgentWatchData data = fromScriptValue(it.name(), it.value());
        result.append(data);
    }
    if (result.isEmpty()) {
        JSAgentWatchData data;
        data.name = "<no initialized data>";
        data.hasChildren = false;
        data.value = " ";
        data.objectId = 0;
        result.append(data);
    }
    return result;
}

static QString fileName(const QString &fileUrl)
{
    int lastDelimiterPos = fileUrl.lastIndexOf(QLatin1Char('/'));
    return fileUrl.mid(lastDelimiterPos, fileUrl.size() - lastDelimiterPos);
}

void QJSDebuggerAgentPrivate::recordKnownObjects(const QList<JSAgentWatchData>& list)
{
    foreach (const JSAgentWatchData &data, list)
        knownObjectIds << data.objectId;
}

QList<JSAgentWatchData> QJSDebuggerAgentPrivate::getLocals(QScriptContext *ctx)
{
    QList<JSAgentWatchData> locals;
    if (ctx) {
        QScriptValue activationObject = ctx->activationObject();
        QScriptValue thisObject = ctx->thisObject();
        locals = expandObject(activationObject);
        if (thisObject.isObject()
                && thisObject.objectId() != engine()->globalObject().objectId()
                && QScriptValueIterator(thisObject).hasNext())
            locals.prepend(fromScriptValue(QLatin1String("this"), thisObject));
        recordKnownObjects(locals);
        knownObjectIds << activationObject.objectId();
    }
    return locals;
}

/*!
  Constructs a new agent for the given \a engine. The agent will
  report debugging-related events (e.g. step completion) to the given
  \a backend.
*/
QJSDebuggerAgent::QJSDebuggerAgent(QScriptEngine *engine, QObject *parent)
    : QObject(parent)
    , QScriptEngineAgent(engine)
    , d(new QJSDebuggerAgentPrivate(this))
{
    QJSDebuggerAgent::engine()->setAgent(this);
}

QJSDebuggerAgent::QJSDebuggerAgent(QDeclarativeEngine *engine, QObject *parent)
    : QObject(parent)
    , QScriptEngineAgent(QDeclarativeDebugHelper::getScriptEngine(engine))
    , d(new QJSDebuggerAgentPrivate(this))
{
    QJSDebuggerAgent::engine()->setAgent(this);
}

/*!
  Destroys this QJSDebuggerAgent.
*/
QJSDebuggerAgent::~QJSDebuggerAgent()
{
    engine()->setAgent(0);
    delete d;
}

void QJSDebuggerAgent::setBreakpoints(const JSAgentBreakpoints &breakpoints)
{
    d->breakpoints = breakpoints;

    d->fileNameToBreakpoints.clear();
    foreach (const JSAgentBreakpointData &bp, breakpoints)
        d->fileNameToBreakpoints.insertMulti(fileName(QString::fromUtf8(bp.fileUrl)), bp);
}

void QJSDebuggerAgent::setWatchExpressions(const QStringList &watchExpressions)
{
    d->watchExpressions = watchExpressions;
}

void QJSDebuggerAgent::stepOver()
{
    d->stepDepth = 0;
    d->state = SteppingOverState;
    d->continueExec();
}

void QJSDebuggerAgent::stepInto()
{
    d->stepDepth = 0;
    d->state = SteppingIntoState;
    d->continueExec();
}

void QJSDebuggerAgent::stepOut()
{
    d->stepDepth = 0;
    d->state = SteppingOutState;
    d->continueExec();
}

void QJSDebuggerAgent::continueExecution()
{
    d->state = NoState;
    d->continueExec();
}

JSAgentWatchData QJSDebuggerAgent::executeExpression(const QString &expr)
{
    SetupExecEnv execEnv(d);

    JSAgentWatchData data = fromScriptValue(expr, engine()->evaluate(expr));
    d->knownObjectIds << data.objectId;
    return data;
}

QList<JSAgentWatchData> QJSDebuggerAgent::expandObjectById(quint64 objectId)
{
    SetupExecEnv execEnv(d);

    QScriptValue v;
    if (d->knownObjectIds.contains(objectId))
        v = engine()->objectById(objectId);

    QList<JSAgentWatchData> result = expandObject(v);
    d->recordKnownObjects(result);
    return result;
}

QList<JSAgentWatchData> QJSDebuggerAgent::locals()
{
    SetupExecEnv execEnv(d);
    return d->getLocals(engine()->currentContext());
}

QList<JSAgentWatchData> QJSDebuggerAgent::localsAtFrame(int frameId)
{
    SetupExecEnv execEnv(d);

    int deep = 0;
    QScriptContext *ctx = engine()->currentContext();
    while (ctx && deep < frameId) {
        ctx = ctx->parentContext();
        deep++;
    }

    return d->getLocals(ctx);
}

QList<JSAgentStackData> QJSDebuggerAgent::backtrace()
{
    SetupExecEnv execEnv(d);

    QList<JSAgentStackData> backtrace;

    for (QScriptContext *ctx = engine()->currentContext(); ctx; ctx = ctx->parentContext()) {
        QScriptContextInfo info(ctx);

        JSAgentStackData frame;
        frame.functionName = info.functionName().toUtf8();
        if (frame.functionName.isEmpty()) {
            if (ctx->parentContext()) {
                switch (info.functionType()) {
                case QScriptContextInfo::ScriptFunction:
                    frame.functionName = "<anonymous>";
                    break;
                case QScriptContextInfo::NativeFunction:
                    frame.functionName = "<native>";
                    break;
                case QScriptContextInfo::QtFunction:
                case QScriptContextInfo::QtPropertyFunction:
                    frame.functionName = "<native slot>";
                    break;
                }
            } else {
                frame.functionName = "<global>";
            }
        }
        frame.lineNumber = info.lineNumber();
        // if the line number is unknown, fallback to the function line number
        if (frame.lineNumber == -1)
            frame.lineNumber = info.functionStartLineNumber();

        frame.fileUrl = info.fileName().toUtf8();
        backtrace.append(frame);
    }

    return backtrace;
}

QList<JSAgentWatchData> QJSDebuggerAgent::watches()
{
    SetupExecEnv execEnv(d);

    QList<JSAgentWatchData> watches;
    foreach (const QString &expr, d->watchExpressions)
        watches << fromScriptValue(expr, engine()->evaluate(expr));
    d->recordKnownObjects(watches);
    return watches;
}

void QJSDebuggerAgent::setProperty(qint64 objectId,
                                   const QString &property,
                                   const QString &value)
{
    SetupExecEnv execEnv(d);

    if (d->knownObjectIds.contains(objectId)) {
        QScriptValue object = engine()->objectById(objectId);
        if (object.isObject()) {
            QScriptValue result = engine()->evaluate(value);
            object.setProperty(property, result);
        }
    }
}

/*!
  \reimp
*/
void QJSDebuggerAgent::scriptLoad(qint64 id, const QString &program,
                                  const QString &fileName, int)
{
    Q_UNUSED(program);
    d->filenames.insert(id, fileName);
}

/*!
  \reimp
*/
void QJSDebuggerAgent::scriptUnload(qint64 id)
{
    d->filenames.remove(id);
}

/*!
  \reimp
*/
void QJSDebuggerAgent::contextPush()
{
}

/*!
  \reimp
*/
void QJSDebuggerAgent::contextPop()
{
}

/*!
  \reimp
*/
void QJSDebuggerAgent::functionEntry(qint64 scriptId)
{
    Q_UNUSED(scriptId);
    d->stepDepth++;
}

/*!
  \reimp
*/
void QJSDebuggerAgent::functionExit(qint64 scriptId, const QScriptValue &returnValue)
{
    Q_UNUSED(scriptId);
    Q_UNUSED(returnValue);
    d->stepDepth--;
}

/*!
  \reimp
*/
void QJSDebuggerAgent::positionChange(qint64 scriptId, int lineNumber, int columnNumber)
{
    d->positionChange(scriptId, lineNumber, columnNumber);
}

void QJSDebuggerAgentPrivate::positionChange(qint64 scriptId, int lineNumber, int columnNumber)
{
    Q_UNUSED(columnNumber);

    if (state == StoppedState)
        return; //no re-entrency

    // check breakpoints
    if (!breakpoints.isEmpty()) {
        QHash<qint64, QString>::const_iterator it = filenames.constFind(scriptId);
        QScriptContext *ctx = engine()->currentContext();
        QScriptContextInfo info(ctx);
        if (it == filenames.constEnd()) {
            // It is possible that the scripts are loaded before the agent is attached
            QString filename = info.fileName();

            JSAgentStackData frame;
            frame.functionName = info.functionName().toUtf8();

            QPair<QString, qint32> key = qMakePair(filename, lineNumber);
            it = filenames.insert(scriptId, filename);
        }

        const QString filePath = it.value();
        JSAgentBreakpoints bps = fileNameToBreakpoints.values(fileName(filePath)).toSet();

        foreach (const JSAgentBreakpointData &bp, bps) {
            if (bp.lineNumber == lineNumber) {
                stopped();
                return;
            }
        }
    }

    switch (state) {
    case NoState:
    case StoppedState:
        // Do nothing
        break;
    case SteppingOutState:
        if (stepDepth >= 0)
            break;
        //fallthough
    case SteppingOverState:
        if (stepDepth > 0)
            break;
        //fallthough
    case SteppingIntoState:
        stopped();
        break;
    }

}

/*!
  \reimp
*/
void QJSDebuggerAgent::exceptionThrow(qint64 scriptId,
                                     const QScriptValue &exception,
                                     bool hasHandler)
{
    Q_UNUSED(scriptId);
    Q_UNUSED(exception);
    Q_UNUSED(hasHandler);
//    qDebug() << Q_FUNC_INFO << exception.toString() << hasHandler;
#if 0 //sometimes, we get exceptions that we should just ignore.
    if (!hasHandler && state != StoppedState)
        stopped(true, exception);
#endif
}

/*!
  \reimp
*/
void QJSDebuggerAgent::exceptionCatch(qint64 scriptId, const QScriptValue &exception)
{
    Q_UNUSED(scriptId);
    Q_UNUSED(exception);
}

bool QJSDebuggerAgent::supportsExtension(Extension extension) const
{
    return extension == QScriptEngineAgent::DebuggerInvocationRequest;
}

QVariant QJSDebuggerAgent::extension(Extension extension, const QVariant &argument)
{
    if (extension == QScriptEngineAgent::DebuggerInvocationRequest) {
        d->stopped();
        return QVariant();
    }
    return QScriptEngineAgent::extension(extension, argument);
}

void QJSDebuggerAgentPrivate::stopped()
{
    bool becauseOfException = false;
    const QScriptValue &exception = QScriptValue();

    knownObjectIds.clear();
    state = StoppedState;

    emit q->stopped(becauseOfException, exception.toString());

    loop.exec(QEventLoop::ExcludeUserInputEvents);
}

void QJSDebuggerAgentPrivate::continueExec()
{
    loop.quit();
}

QT_END_NAMESPACE