tst_gdb.cpp 105 KB
Newer Older
hjk's avatar
hjk committed
1

hjk's avatar
hjk committed
2
3
//bool checkUninitialized = true;
bool checkUninitialized = false;
hjk's avatar
hjk committed
4
5
//#define DO_DEBUG 1

hjk's avatar
hjk committed
6
7
8
9
10
11
#include <QtCore/QThread>
#include <QtCore/QMutex>
#include <QtCore/QWaitCondition>

#include <QtCore/private/qobject_p.h>

hjk's avatar
hjk committed
12
13
//#include <QtGui/QStandardItemModel>
//#include <QtGui/QStringListModel>
hjk's avatar
hjk committed
14
15
16
17
18
19

#include <QtTest/QtTest>

#include "gdb/gdbmi.h"

#include <sys/types.h>
Friedemann Kleint's avatar
Friedemann Kleint committed
20
21
22
23
24
25

#ifdef Q_OS_WIN
#    include <windows.h>
#else
#    include <unistd.h>
#endif
hjk's avatar
hjk committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40


#undef NS
#ifdef QT_NAMESPACE
#   define STRINGIFY0(s) #s
#   define STRINGIFY1(s) STRINGIFY0(s)
#   define NS STRINGIFY1(QT_NAMESPACE) "::"
#   define NSX "'" STRINGIFY1(QT_NAMESPACE) "::"
#   define NSY "'"
#else
#   define NS ""
#   define NSX ""
#   define NSY ""
#endif

hjk's avatar
hjk committed
41
42
43
44
45
46
47
48
#undef DEBUG
#if DO_DEBUG
#   define DEBUG(s) qDebug() << s
#else
#   define DEBUG(s)
#endif
#define DEBUGX(s) qDebug() << s

hjk's avatar
hjk committed
49
50
#define gettid()  QString("0x%1").arg((qulonglong)(void *)currentThread(), 0, 16)

Friedemann Kleint's avatar
Friedemann Kleint committed
51
52
53
54
55
#ifdef Q_OS_WIN
QString gdbBinary = "c:\\MinGw\\bin\\gdb.exe";
#else
QString gdbBinary = "./gdb";
#endif
56

hjk's avatar
hjk committed
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
class Foo
{
public:
    Foo(int i = 0)
        : a(i), b(2)
    {}

    ~Foo()
    {
    } 
    void doit()
    {
        static QObject ob;
        m["1"] = "2";
        h[&ob] = m.begin();

        a += 1;
        --b;
        //s += 'x';
    }


    struct Bar {
        Bar() : ob(0) {}
        QObject *ob;
    };

public:
    int a, b;
    char x[6];

private:
    //QString s;
    typedef QMap<QString, QString> Map;
    Map m;
    QHash<QObject *, Map::iterator> h;
};



97
98
/////////////////////////////////////////////////////////////////////////
//
Friedemann Kleint's avatar
Friedemann Kleint committed
99
//
100
101
102
103
// Helper stuff
//
/////////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
104
105
typedef QList<QByteArray> QByteArrayList;

hjk's avatar
hjk committed
106
#if 0
hjk's avatar
hjk committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
static QByteArray operator<<(QByteArray ba, const QByteArray &replacement)
{
    int pos = ba.indexOf('%');
    Q_ASSERT(pos != -1);
    return ba.replace(pos, 1, replacement);
}

static QByteArray &operator<<=(QByteArray &ba, const QByteArray &replacement)
{
    int pos = ba.indexOf('%');
    Q_ASSERT(pos != -1);
    return ba.replace(pos, 1, replacement);
}


template <typename T> 
inline QByteArray N(T t) { return QByteArray::number(t); }
hjk's avatar
hjk committed
124
#endif
hjk's avatar
hjk committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145



struct Int3 {
    Int3() { i1 = 42; i2 = 43; i3 = 44; }
    int i1, i2, i3;
};

struct QString3 {
    QString3() { s1 = "a"; s2 = "b"; s3 = "c"; }
    QString s1, s2, s3;
};

class tst_Gdb;

class Thread : public QThread
{
    Q_OBJECT

public:
    Thread(tst_Gdb *test);
Friedemann Kleint's avatar
Friedemann Kleint committed
146
    void startup(QProcess *proc);
hjk's avatar
hjk committed
147
148
    void run();

Friedemann Kleint's avatar
Friedemann Kleint committed
149
150
    QString errorString() const { return  m_errorString; }

hjk's avatar
hjk committed
151
152
153
154
155
156
157
158
public slots:
    void readStandardOutput();
    void readStandardError();
    void handleGdbStarted();
    void handleGdbError(QProcess::ProcessError);
    void handleGdbFinished(int, QProcess::ExitStatus);
    void writeToGdbRequested(const QByteArray &ba)
    {
hjk's avatar
hjk committed
159
        DEBUG("THREAD GDB IN: " << ba);
hjk's avatar
hjk committed
160
161
162
163
164
165
166
        m_proc->write(ba);
        m_proc->write("\n");
    }


public:
    QByteArray m_output;
hjk's avatar
hjk committed
167
168
    QByteArray m_lastStopped; // last seen "*stopped" message
    int m_line; // line extracted from last "*stopped" message
hjk's avatar
hjk committed
169
170
    QProcess *m_proc; // owned
    tst_Gdb *m_test; // not owned
Friedemann Kleint's avatar
Friedemann Kleint committed
171
    QString m_errorString;
hjk's avatar
hjk committed
172
173
174
175
176
177
178
};

class tst_Gdb : public QObject
{
    Q_OBJECT

public:
hjk's avatar
hjk committed
179
180
181
182
183
    tst_Gdb();

    void cleanupTestCase();
    void prepare(const QByteArray &function);
    void run(const QByteArray &label, const QByteArray &expected,
hjk's avatar
hjk committed
184
        const QByteArray &expanded = QByteArray(), bool fancy = true);
hjk's avatar
hjk committed
185
186
187
188
189
190
    void next(int n = 1);

signals:
    void writeToGdb(const QByteArray &ba);

private slots:
Friedemann Kleint's avatar
Friedemann Kleint committed
191
    void initTestCase();
hjk's avatar
hjk committed
192
    void dumpArray();
hjk's avatar
hjk committed
193
    void dumpMisc();
hjk's avatar
hjk committed
194
    void dumpFoo();
hjk's avatar
hjk committed
195
196
    void dumpQByteArray();
    void dumpQChar();
hjk's avatar
hjk committed
197
    void dumpQList_char_star();
hjk's avatar
hjk committed
198
    void dumpQList_char();
199
    void dumpQList_int();
hjk's avatar
hjk committed
200
201
202
    void dumpQList_QString();
    void dumpQList_QString3();
    void dumpQList_Int3();
hjk's avatar
hjk committed
203
    void dumpQStack();
hjk's avatar
hjk committed
204
205
    void dumpQString();
    void dumpQStringList();
hjk's avatar
hjk committed
206
207
    void dumpQWeakPointer();
    void dumpQVector();
hjk's avatar
hjk committed
208

hjk's avatar
hjk committed
209
210
    void dumpQHash();

hjk's avatar
hjk committed
211
212
public slots:
    void dumperCompatibility();
hjk's avatar
hjk committed
213
#if 0
hjk's avatar
hjk committed
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
    void dumpQAbstractItemAndModelIndex();
    void dumpQAbstractItemModel();
    void dumpQDateTime();
    void dumpQDir();
    void dumpQFile();
    void dumpQFileInfo();
    void dumpQHashNode();
    void dumpQImage();
    void dumpQImageData();
    void dumpQLinkedList();
    void dumpQLocale();
    void dumpQMap();
    void dumpQMapNode();
    void dumpQObject();
    void dumpQObjectChildList();
    void dumpQObjectMethodList();
    void dumpQObjectPropertyList();
    void dumpQObjectSignal();
    void dumpQObjectSignalList();
    void dumpQObjectSlot();
    void dumpQObjectSlotList();
    void dumpQPixmap();
    void dumpQSharedPointer();
    void dumpQTextCodec();
    void dumpQVariant_invalid();
    void dumpQVariant_QString();
    void dumpQVariant_QStringList();
    void dumpStdVector();
hjk's avatar
hjk committed
242
#endif
hjk's avatar
hjk committed
243
244

private:
hjk's avatar
hjk committed
245
#if 0
hjk's avatar
hjk committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    void dumpQAbstractItemHelper(QModelIndex &index);
    void dumpQAbstractItemModelHelper(QAbstractItemModel &m);
    void dumpQDateTimeHelper(const QDateTime &d);
    void dumpQFileHelper(const QString &name, bool exists);
    template <typename K, typename V> void dumpQHashNodeHelper(QHash<K, V> &hash);
    void dumpQImageHelper(const QImage &img);
    void dumpQImageDataHelper(QImage &img);
    template <typename T> void dumpQLinkedListHelper(QLinkedList<T> &l);
    void dumpQLocaleHelper(QLocale &loc);
    template <typename K, typename V> void dumpQMapHelper(QMap<K, V> &m);
    template <typename K, typename V> void dumpQMapNodeHelper(QMap<K, V> &m);
    void dumpQObjectChildListHelper(QObject &o);
    void dumpQObjectSignalHelper(QObject &o, int sigNum);
#if QT_VERSION >= 0x040500
    template <typename T>
    void dumpQSharedPointerHelper(QSharedPointer<T> &ptr);
    template <typename T>
    void dumpQWeakPointerHelper(QWeakPointer<T> &ptr);
#endif
    void dumpQTextCodecHelper(QTextCodec *codec);
hjk's avatar
hjk committed
266
#endif
hjk's avatar
hjk committed
267
268

private:
hjk's avatar
hjk committed
269
270
    QHash<QByteArray, int> m_lineForLabel;
    QByteArray m_function;
hjk's avatar
hjk committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    Thread m_thread;
};

QMutex m_mutex;
QWaitCondition m_waitCondition;

//
// Dumpers
//

QByteArray str(const void *p)
{
    char buf[100];
    sprintf(buf, "%p", p);
    return buf;
}

hjk's avatar
hjk committed
288
#if 0
hjk's avatar
hjk committed
289
290
291
292
static const void *deref(const void *p)
{
    return *reinterpret_cast<const char* const*>(p);
}
hjk's avatar
hjk committed
293
#endif
hjk's avatar
hjk committed
294
295
296
297
298
299
300
301
302
303

void tst_Gdb::dumperCompatibility()
{
    // Ensure that no arbitrary padding is introduced by QVectorTypedData.
    const size_t qVectorDataSize = 16;
    QCOMPARE(sizeof(QVectorData), qVectorDataSize);
    QVectorTypedData<int> *v = 0;
    QCOMPARE(size_t(&v->array), qVectorDataSize);
}

hjk's avatar
hjk committed
304
#if 0
hjk's avatar
hjk committed
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
static const QByteArray utfToBase64(const QString &string)
{
    return QByteArray(reinterpret_cast<const char *>(string.utf16()), 2 * string.size()).toBase64();
}

static const char *boolToVal(bool b)
{
    return b ? "'true'" : "'false'";
}

static const QByteArray ptrToBa(const void *p, bool symbolicNull = true)
{
    return QByteArray().append(p == 0 && symbolicNull ?
        "<null>" :
        QByteArray("0x") + QByteArray::number((quintptr) p, 16));
}

static const QByteArray generateQStringSpec(const QString &str)
{
    return QByteArray("value='%',type='"NS"QString',numchild='0',valueencoded='2'")
        << utfToBase64(str);
}

static const QByteArray generateQCharSpec(const QChar& ch)
{
    return QByteArray("value='%',valueencoded='2',type='"NS"QChar',numchild='0'")
        << utfToBase64(QString(QLatin1String("'%1' (%2, 0x%3)")).
                   arg(ch).arg(ch.unicode()).arg(ch.unicode(), 0, 16));
}

static const QByteArray generateBoolSpec(bool b)
{
    return QByteArray("value=%,type='bool',numchild='0'")
        << boolToVal(b);
}

static const QByteArray generateLongSpec(long n)
{
    return QByteArray("value='%',type='long',numchild='0'")
        << N(qlonglong(n));
}

static const QByteArray generateIntSpec(int n)
{
    return QByteArray("value='%',type='int',numchild='0'")
        << N(n);
}

const QByteArray createExp(const void *ptr,
    const QByteArray &type, const QByteArray &method)
{
    return QByteArray("exp='(("NSX"%"NSY"*)%)->%'")
        << type << ptrToBa(ptr) << method;
}

// Helper functions.

#ifdef Q_CC_MSVC
#  define MAP_NODE_TYPE_END ">"
#else
#  define MAP_NODE_TYPE_END " >"
#endif

template <typename T> static const char *typeToString()
{
    return "<unknown type>";
}
template <typename T> const QByteArray valToString(const T &)
{
    return "<unknown value>";
}
template <> const QByteArray valToString(const int &n)
{
    return QByteArray().append(N(n));
}
template <> const QByteArray valToString(const QString &s)
{
    return QByteArray(utfToBase64(s)).append("',valueencoded='2");
}
template <> const QByteArray valToString(int * const &p)
{
    return ptrToBa(p);
}
template <typename T> const QByteArray derefValToString(const T &v)
{
    return valToString(v);
}
template <> const QByteArray derefValToString(int * const &ptr)
{
    return valToString(*ptr);
}
const QString stripPtrType(const QString &ptrTypeStr)
{
    return ptrTypeStr.mid(0, ptrTypeStr.size() - 2);
}
template <> const char *typeToString<int>()
{
    return "int";
}
template <> const char *typeToString<QString>()
{
    return NS"QString";
}
template <> const char *typeToString<int *>()
{
    return "int *";
}
template <typename T> bool isSimpleType()
{
    return false;
}
template <> bool isSimpleType<int>()
{
    return true;
}
template <typename T> bool isPointer()
{
    return false;
}
template <> bool isPointer<int *>()
{
    return true;
}

template <typename T> static const char *typeToNumchild()
{
    return "1";
}
template <> const char *typeToNumchild<int>()
{
    return "0";
}
template <> const char *typeToNumchild<QString>()
{
    return "0";
}
template <typename K, typename V>
QByteArray getMapType()
{
    return QByteArray(typeToString<K>()) + "@" + QByteArray(typeToString<V>());
}
template <typename K, typename V>
void getMapNodeParams(size_t &nodeSize, size_t &valOffset)
{
#if QT_VERSION >= 0x040500
    typedef QMapNode<K, V> NodeType;
    NodeType *node = 0;
    nodeSize = sizeof(NodeType);
    valOffset = size_t(&node->value);
#else
    nodeSize = sizeof(K) + sizeof(V) + 2*sizeof(void *);
    valOffset = sizeof(K);
#endif
}

hjk's avatar
hjk committed
460
#endif
hjk's avatar
hjk committed
461
462
463
464
465
466
467
468


/////////////////////////////////////////////////////////////////////////
//
// Gdb Thread
//
/////////////////////////////////////////////////////////////////////////

Friedemann Kleint's avatar
Friedemann Kleint committed
469
Thread::Thread(tst_Gdb *test) : m_proc(0), m_test(test)
hjk's avatar
hjk committed
470
{
Friedemann Kleint's avatar
Friedemann Kleint committed
471
472
473
#ifdef Q_OS_WIN
    qDebug() << "\nTHREAD CREATED" << GetCurrentProcessId() << GetCurrentThreadId();
#else
hjk's avatar
hjk committed
474
    qDebug() << "\nTHREAD CREATED" << getpid() << gettid();
Friedemann Kleint's avatar
Friedemann Kleint committed
475
#endif
hjk's avatar
hjk committed
476
    connect(m_test, SIGNAL(writeToGdb(QByteArray)),
Friedemann Kleint's avatar
Friedemann Kleint committed
477
478
479
480
481
482
483
            this, SLOT(writeToGdbRequested(QByteArray)), Qt::QueuedConnection);
}

void Thread::startup(QProcess *proc)
{
    m_proc = proc;
    m_proc->moveToThread(this);
hjk's avatar
hjk committed
484
485
486
487
488
489
490
491
492
493
494
    connect(m_proc, SIGNAL(error(QProcess::ProcessError)),
        this, SLOT(handleGdbError(QProcess::ProcessError)));
    connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)),
        this, SLOT(handleGdbFinished(int, QProcess::ExitStatus)));
    connect(m_proc, SIGNAL(started()),
        this, SLOT(handleGdbStarted()));
    connect(m_proc, SIGNAL(readyReadStandardOutput()),
        this, SLOT(readStandardOutput()));
    connect(m_proc, SIGNAL(readyReadStandardError()),
        this, SLOT(readStandardError()));
    start();
hjk's avatar
hjk committed
495
496
}

hjk's avatar
hjk committed
497
void Thread::handleGdbError(QProcess::ProcessError error)
hjk's avatar
hjk committed
498
{
hjk's avatar
hjk committed
499
500
501
    qDebug() << "GDB ERROR: " << error;
    //this->exit();
}
hjk's avatar
hjk committed
502

hjk's avatar
hjk committed
503
504
505
506
507
508
509
void Thread::handleGdbFinished(int code, QProcess::ExitStatus st)
{
    qDebug() << "GDB FINISHED: " << code << st;
    //m_waitCondition.wakeAll();
    //this->exit();
    throw 42;
}
hjk's avatar
hjk committed
510

hjk's avatar
hjk committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
void Thread::readStandardOutput()
{
    QByteArray ba = m_proc->readAllStandardOutput();
    DEBUG("THREAD GDB OUT: " << ba);
    // =library-loaded...
    if (ba.startsWith("=")) 
        return;
    if (ba.startsWith("*stopped")) {
        m_lastStopped = ba;
        //qDebug() << "THREAD GDB OUT: " << ba;
        if (!ba.contains("func=\"main\"")) {
            int pos1 = ba.indexOf(",line=\"") + 7;
            int pos2 = ba.indexOf("\"", pos1);
            m_line = ba.mid(pos1, pos2 - pos1).toInt();
            DEBUG(" LINE 1: " << m_line);
hjk's avatar
hjk committed
526
        }
hjk's avatar
hjk committed
527
    }
hjk's avatar
hjk committed
528

hjk's avatar
hjk committed
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    // The "call" is always aborted with a message like:
    //  "~"2321\t    /* A */ QString s;\n" " 
    //  "&"The program being debugged stopped while in a function called ..."
    //  "^error,msg="The program being debugged stopped ..."
    // Extract the "2321" from this
    static QByteArray lastText;
    if (ba.startsWith("~")) {
        lastText = ba;
        if (ba.size() > 8
                && (ba.at(2) < 'a' || ba.at(2) > 'z')
                && (ba.at(2) < '0' || ba.at(2) > '9')
                && !ba.startsWith("~\"Breakpoint ")
                && !ba.startsWith("~\"    at ")
                && !ba.startsWith("~\"    locals=")
                && !ba.startsWith("~\"XXX:")) {
            QByteArray ba1 = ba.mid(2, ba.size() - 6);
            if (ba1.startsWith("  File "))
                ba1 = ba1.replace(2, ba1.indexOf(','), "");
            qWarning() << "OUT: " << ba1;
hjk's avatar
hjk committed
548
        }
hjk's avatar
hjk committed
549
550
551
552
553
554
555
556
557
558
559
    }
    if (ba.startsWith("&\"The program being debugged")) {
        int pos1 = 2;
        int pos2 = lastText.indexOf("\\", pos1);
        m_line = lastText.mid(pos1, pos2 - pos1).toInt();
        DEBUG(" LINE 2: " << m_line);
    }
    if (ba.startsWith("^error,msg=")) {
        if (!ba.startsWith("^error,msg=\"The program being debugged stopped"))
            qWarning() << "ERROR: " << ba.mid(1, ba.size() - 3);
    }
hjk's avatar
hjk committed
560

hjk's avatar
hjk committed
561
562
563
564
565
566
567
568
569
570
571
572
    if (ba.startsWith("~\"XXX: ")) {
        QByteArray ba1 = ba.mid(7, ba.size() - 11);
        qWarning() << "MESSAGE: " << ba.mid(7, ba.size() - 12);
    }
    if (!ba.contains("locals={iname="))
        return;
    //m_output += ba;
    ba = ba.mid(2, ba.size() - 4);
    ba = ba.replace("\\\"", "\"");
    m_output = ba;
    m_waitCondition.wakeAll();
}
hjk's avatar
hjk committed
573

hjk's avatar
hjk committed
574
575
576
577
578
void Thread::readStandardError()
{
    QByteArray ba = m_proc->readAllStandardOutput();
    qDebug() << "THREAD GDB ERR: " << ba;
}
hjk's avatar
hjk committed
579

hjk's avatar
hjk committed
580
581
582
583
void Thread::handleGdbStarted()
{
    //qDebug() << "\n\nGDB STARTED" << getpid() << gettid() << "\n\n";
}
hjk's avatar
hjk committed
584

hjk's avatar
hjk committed
585
586
587
588
589
590
591
592
void Thread::run()
{
    m_proc->write("break main\n");
    m_proc->write("run\n");
    m_proc->write("handle SIGSTOP stop pass\n");
    //qDebug() << "\nTHREAD RUNNING";
    exec();
}
hjk's avatar
hjk committed
593
594


hjk's avatar
hjk committed
595
596
597
598
599
/////////////////////////////////////////////////////////////////////////
//
// Test Class Framework Implementation
//
/////////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
600

hjk's avatar
hjk committed
601
602
603
604
tst_Gdb::tst_Gdb()
    : m_thread(this)
{

Friedemann Kleint's avatar
Friedemann Kleint committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
}

void tst_Gdb::initTestCase()
{
    //qDebug() << "\nTHREAD RUN" << getpid() << gettid();
    QProcess *gdbProc = new QProcess;
    QStringList args;
    args << QLatin1String("-i")
            << QLatin1String("mi") << QLatin1String("--args")
            << qApp->applicationFilePath();
    qDebug() << "Starting" << gdbBinary << args;
    gdbProc->start(gdbBinary, args);
    if (!gdbProc->waitForStarted()) {
        const QString msg = QString::fromLatin1("Unable to run %1: %2").arg(gdbBinary, gdbProc->errorString());
        delete gdbProc;
        QSKIP(msg.toLatin1().constData(), SkipAll);
    }

    const QString fileName = "tst_gdb.cpp";
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        const QString msg = QString::fromLatin1("Unable to open %1: %2").arg(fileName, file.errorString());
        QSKIP(msg.toLatin1().constData(), SkipAll);
    }

hjk's avatar
hjk committed
630
631
632
633
634
635
636
637
638
639
640
641
642
    QByteArray funcName;
    const QByteArrayList bal = file.readAll().split('\n');
    Q_ASSERT(bal.size() > 100);
    for (int i = 0; i != bal.size(); ++i) {
        const QByteArray &ba = bal.at(i);
        if (ba.startsWith("void dump")) {
            int pos = ba.indexOf('(');
            funcName = ba.mid(5, pos - 5) + '@';
        } else if (ba.startsWith("    /*")) {
            int pos = ba.indexOf('*', 7);
            m_lineForLabel[funcName + ba.mid(7, pos - 8)] = i + 1;
        }
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
643
    m_thread.startup(gdbProc);
hjk's avatar
hjk committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
}

void tst_Gdb::prepare(const QByteArray &function)
{
    m_function = function;
    writeToGdb("b " + function);
    writeToGdb("call " + function + "()");
}

static bool isJoker(const QByteArray &ba)
{
    return ba.endsWith("'-'") || ba.contains("'-'}");
}

void tst_Gdb::run(const QByteArray &label, const QByteArray &expected0,
    const QByteArray &expanded, bool fancy)
{
    //qDebug() << "\nABOUT TO RUN TEST: " << expanded;
    qWarning() << label << "...";
    writeToGdb("bb " + QByteArray::number(int(fancy)) + " " + expanded);
    m_mutex.lock();
    m_waitCondition.wait(&m_mutex);
    QByteArray ba = m_thread.m_output;
    m_mutex.unlock();
    //GdbMi locals;
    //locals.fromString("{" + ba + "}");
    QByteArray received = ba.replace("\"", "'");
    //qDebug() << "OUTPUT: " << ba << "\n\n";
    //qDebug() << "OUTPUT: " << locals.toString() << "\n\n";

    QByteArray actual = received.trimmed();
    if (actual.endsWith("\\n"))
        actual.chop(2);
    QByteArray expected = "locals={iname='local',name='Locals',value=' ',type=' ',"
        "children=[" + expected0 + "]}";
    int line = m_thread.m_line;

    QByteArrayList l1 = actual.split(',');
    QByteArrayList l2 = expected.split(',');

    bool ok = l1.size() == l2.size();
    if (ok) {
        for (int i = 0 ; i < l1.size(); ++i) {
            // Use "-" as joker.
            if (l1.at(i) != l2.at(i) && !isJoker(l2.at(i)))
                ok = false;
        }
    } else {
        qWarning() << "!= size: " << l1.size() << l2.size();
    }
    
    if (!ok) {
        int i = 0;
        for ( ; i < l1.size() && i < l2.size(); ++i) {
            if (l1.at(i) == l2.at(i) || isJoker(l2.at(i))) {
                qWarning() << "== " << l1.at(i);
            } else {
                //qWarning() << "!= " << l1.at(i).right(30) << l2.at(i).right(30);
                qWarning() << "!= " << l1.at(i) << l2.at(i);
                ok = false;
            }
        }
        for ( ; i < l2.size(); ++i) 
            qWarning() << "!= " << "-----" << l2.at(i);
        for ( ; i < l1.size(); ++i) 
            qWarning() << "!= " << l1.at(i) << "-----";
        if (l1.size() != l2.size()) {
            ok = false;
            qWarning() << "!= size: " << l1.size() << l2.size();
        }
        qWarning() << "RECEIVED: " << received;
    }
    QCOMPARE(ok, true);
    //qWarning() << "LINE: " << line << "ACT/EXP" << m_function + '@' + label;
    //QCOMPARE(actual, expected);


    int expline = m_lineForLabel.value(m_function + '@' + label);
    int actline = line;
    if (actline != expline) {
        qWarning() << "LAST STOPPED: " << m_thread.m_lastStopped;
    }
    QCOMPARE(actline, expline);
}

void tst_Gdb::next(int n)
{
    for (int i = 0; i != n; ++i)
        writeToGdb("next");
}

void tst_Gdb::cleanupTestCase()
{
    writeToGdb("kill");
    writeToGdb("quit");
    //m_thread.m_proc->waitForFinished();
}


/////////////////////////////////////////////////////////////////////////
//
// Dumper Tests
//
/////////////////////////////////////////////////////////////////////////

///////////////////////////// Foo structure /////////////////////////////////

void dumpFoo()
{
    /* A */ Foo f;
    /* B */ f.doit();
    /* D */ (void) 0;
}

void tst_Gdb::dumpFoo()
{
    prepare("dumpFoo");
    next();
    run("B","{iname='local.f',addr='-',name='f',type='Foo',"
            "value='-',numchild='5'}", "", 0);
    run("B","{iname='local.f',addr='-',name='f',type='Foo',"
            "value='-',numchild='5',children=["
            "{iname='local.f.a',name='a',type='int',value='0',numchild='0'},"
            "{iname='local.f.b',name='b',type='int',value='2',numchild='0'},"
            "{iname='local.f.x',name='x',type='char [6]',"
                "value='{...}',numchild='1'},"
            "{iname='local.f.m',name='m',type='"NS"QMap<"NS"QString, "NS"QString>',"
                "value='{...}',numchild='1'},"
            "{iname='local.f.h',name='h',type='"NS"QHash<"NS"QObject*, "
                ""NS"QMap<"NS"QString, "NS"QString>::iterator>',"
                "value='{...}',numchild='1'}]}",
            "local.f", 0);
}


///////////////////////////// Array ///////////////////////////////////////

void dumpArray_char()
{
    /* A */ const char s[] = "XYZ";
    /* B */ (void) &s; }

void dumpArray_int()
{
    /* A */ int s[] = {1, 2, 3};
    /* B */ (void) s; }

void tst_Gdb::dumpArray()
{
    prepare("dumpArray_char");
    next();
    // FIXME: numchild should be '4', not '1'
    run("B","{iname='local.s',addr='-',name='s',type='char [4]',"
            "value='-',numchild='1'}", "");
    run("B","{iname='local.s',addr='-',name='s',type='char [4]',"
            "value='-',numchild='1',childtype='char',childnumchild='0',"
            "children=[{value='88 'X''},{value='89 'Y''},{value='90 'Z''},"
            "{value='0 '\\\\000''}]}",
            "local.s");

    prepare("dumpArray_int");
    next();
    // FIXME: numchild should be '3', not '1'
    run("B","{iname='local.s',addr='-',name='s',type='int [3]',"
            "value='-',numchild='1'}", "");
    run("B","{iname='local.s',addr='-',name='s',type='int [3]',"
            "value='-',numchild='1',childtype='int',childnumchild='0',"
            "children=[{value='1'},{value='2'},{value='3'}]}",
            "local.s");
}


///////////////////////////// Misc stuff /////////////////////////////////

void dumpMisc()
{
    /* A */ int *s = new int(1);
    /* B */ *s += 1;
    /* D */ (void) 0;
}

void tst_Gdb::dumpMisc()
{
    prepare("dumpMisc");
    next();
    run("B","{iname='local.s',addr='-',name='s',type='int *',"
            "value='-',numchild='1'}", "", 0);
    run("B","{iname='local.s',addr='-',name='s',type='int *',"
            "value='-',numchild='1',children=[{iname='local.s.*',"
            "name='*s',type='int',value='1',numchild='0'}]}", "local.s", 0);
}

#if 0
void tst_Gdb::dumpQAbstractItemHelper(QModelIndex &index)
{
    const QAbstractItemModel *model = index.model();
    const QString &rowStr = N(index.row());
    const QString &colStr = N(index.column());
    const QByteArray &internalPtrStrSymbolic = ptrToBa(index.internalPointer());
    const QByteArray &internalPtrStrValue = ptrToBa(index.internalPointer(), false);
    const QByteArray &modelPtrStr = ptrToBa(model);
    QByteArray indexSpecSymbolic = QByteArray().append(rowStr + "," + colStr + ",").
        append(internalPtrStrSymbolic + "," + modelPtrStr);
    QByteArray indexSpecValue = QByteArray().append(rowStr + "," + colStr + ",").
        append(internalPtrStrValue + "," + modelPtrStr);
    QByteArray expected = QByteArray("tiname='iname',addr='").append(ptrToBa(&index)).
        append("',type='"NS"QAbstractItem',addr='$").append(indexSpecSymbolic).
        append("',value='").append(valToString(model->data(index).toString())).
        append("',numchild='1',children=[");
    int rowCount = model->rowCount(index);
    int columnCount = model->columnCount(index);
    for (int row = 0; row < rowCount; ++row) {
        for (int col = 0; col < columnCount; ++col) {
            const QModelIndex &childIndex = model->index(row, col, index);
            expected.append("{name='[").append(valToString(row)).append(",").
                append(N(col)).append("]',numchild='1',addr='$").
                append(N(childIndex.row())).append(",").
                append(N(childIndex.column())).append(",").
                append(ptrToBa(childIndex.internalPointer())).append(",").
                append(modelPtrStr).append("',type='"NS"QAbstractItem',value='").
                append(valToString(model->data(childIndex).toString())).append("'}");
            if (col < columnCount - 1 || row < rowCount - 1)
                expected.append(",");
        }
    }
    expected.append("]");
    testDumper(expected, &index, NS"QAbstractItem", true, indexSpecValue);
}

void tst_Gdb::dumpQAbstractItemAndModelIndex()
{
    class PseudoTreeItemModel : public QAbstractItemModel
    {
    public:
        PseudoTreeItemModel() : QAbstractItemModel(), parent1(0),
            parent1Child(1), parent2(10), parent2Child1(11), parent2Child2(12)
        {}

        int columnCount(const QModelIndex &parent = QModelIndex()) const
        {
            Q_UNUSED(parent);
            return 1;
        }

        QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
        {
            return !index.isValid() || role != Qt::DisplayRole ?
                    QVariant() : *static_cast<int *>(index.internalPointer());
        }

        QModelIndex index(int row, int column,
                          const QModelIndex & parent = QModelIndex()) const
        {
            QModelIndex index;
            if (column == 0) {
                if (!parent.isValid()) {
                    if (row == 0)
                        index = createIndex(row, column, &parent1);
                    else if (row == 1)
                        index = createIndex(row, column, &parent2);
                } else if (parent.internalPointer() == &parent1 && row == 0) {
                    index = createIndex(row, column, &parent1Child);
                } else if (parent.internalPointer() == &parent2) {
                    index = createIndex(row, column,
                                row == 0 ? &parent2Child1 : &parent2Child2);
                }
            }
            return index;
        }

        QModelIndex parent(const QModelIndex & index) const
        {
            QModelIndex parent;
            if (index.isValid()) {
                if (index.internalPointer() == &parent1Child)
                    parent = createIndex(0, 0, &parent1);
                else if (index.internalPointer() == &parent2Child1 ||
                         index.internalPointer() == &parent2Child2)
                    parent = createIndex(1, 0, &parent2);
            }
            return parent;
        }

        int rowCount(const QModelIndex &parent = QModelIndex()) const
        {
            int rowCount;
            if (!parent.isValid() || parent.internalPointer() == &parent2)
                rowCount = 2;
            else if (parent.internalPointer() == &parent1)
                rowCount = 1;
            else
                rowCount = 0;
            return rowCount;
        }

    private:
        mutable int parent1;
        mutable int parent1Child;
        mutable int parent2;
        mutable int parent2Child1;
        mutable int parent2Child2;
    };

    PseudoTreeItemModel m2;

    // Case 1: ModelIndex with no children.
    QStringListModel m(QStringList() << "item1" << "item2" << "item3");
    QModelIndex index = m.index(2, 0);

    testDumper(QByteArray("type='$T',value='(2, 0)',numchild='5',children=["
        "{name='row',value='2',type='int',numchild='0'},"
        "{name='column',value='0',type='int',numchild='0'},"
        "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
            "type='$T',numchild='1'},"
        "{name='internalId',%},"
        "{name='model',value='%',type='"NS"QAbstractItemModel*',"
            "numchild='1'}]")
         << generateQStringSpec(N(index.internalId()))
         << ptrToBa(&m),
        &index, NS"QModelIndex", true);

    // Case 2: ModelIndex with one child.
hjk's avatar
hjk committed
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    QModelIndex index2 = m2.index(0, 0);
    dumpQAbstractItemHelper(index2);

    qDebug() << "FIXME: invalid indices should not have children";
    testDumper(QByteArray("type='$T',value='(0, 0)',numchild='5',children=["
        "{name='row',value='0',type='int',numchild='0'},"
        "{name='column',value='0',type='int',numchild='0'},"
        "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
            "type='$T',numchild='1'},"
        "{name='internalId',%},"
        "{name='model',value='%',type='"NS"QAbstractItemModel*',"
            "numchild='1'}]")
         << generateQStringSpec(N(index2.internalId()))
         << ptrToBa(&m2),
        &index2, NS"QModelIndex", true);


    // Case 3: ModelIndex with two children.
    QModelIndex index3 = m2.index(1, 0);
    dumpQAbstractItemHelper(index3);

    testDumper(QByteArray("type='$T',value='(1, 0)',numchild='5',children=["
        "{name='row',value='1',type='int',numchild='0'},"
        "{name='column',value='0',type='int',numchild='0'},"
        "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
            "type='$T',numchild='1'},"
        "{name='internalId',%},"
        "{name='model',value='%',type='"NS"QAbstractItemModel*',"
            "numchild='1'}]")
         << generateQStringSpec(N(index3.internalId()))
         << ptrToBa(&m2),
        &index3, NS"QModelIndex", true);


    // Case 4: ModelIndex with a parent.