tst_dumpers.cpp 207 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Bill King's avatar
Bill King committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Bill King's avatar
Bill King committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Bill King's avatar
Bill King committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
Bill King's avatar
Bill King committed
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
** Alternatively, 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.
Bill King's avatar
Bill King committed
23
**
hjk's avatar
hjk committed
24
25
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
Bill King's avatar
Bill King committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
Bill King's avatar
Bill King committed
29

hjk's avatar
hjk committed
30
#include "debuggerprotocol.h"
31
32
#include "watchdata.h"
#include "watchutils.h"
33

34
#include <cplusplus/CppRewriter.h>
35
#include <utils/environment.h>
36
37
38
#include <utils/qtcprocess.h>
#include <utils/fileutils.h>
#include <utils/synchronousprocess.h>
39

40
#include "temporarydir.h"
41

42
#include <QtTest>
43
#include <math.h>
44

45
46
47
48
49
50
#if  QT_VERSION >= 0x050000
#define MSKIP_SINGLE(x) QSKIP(x)
#else
#define MSKIP_SINGLE(x) QSKIP(x, SkipSingle)
#endif

51
using namespace Debugger;
52
using namespace Utils;
hjk's avatar
hjk committed
53
using namespace Internal;
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
// Copied from abstractmsvctoolchain.cpp to avoid plugin dependency.

static bool generateEnvironmentSettings(Utils::Environment &env,
                                        const QString &batchFile,
                                        const QString &batchArgs,
                                        QMap<QString, QString> &envPairs)
{
    // Create a temporary file name for the output. Use a temporary file here
    // as I don't know another way to do this in Qt...
    // Note, can't just use a QTemporaryFile all the way through as it remains open
    // internally so it can't be streamed to later.
    QString tempOutFile;
    QTemporaryFile* pVarsTempFile = new QTemporaryFile(QDir::tempPath() + QLatin1String("/XXXXXX.txt"));
    pVarsTempFile->setAutoRemove(false);
    pVarsTempFile->open();
    pVarsTempFile->close();
    tempOutFile = pVarsTempFile->fileName();
    delete pVarsTempFile;

    // Create a batch file to create and save the env settings
    Utils::TempFileSaver saver(QDir::tempPath() + QLatin1String("/XXXXXX.bat"));

    QByteArray call = "call ";
    call += Utils::QtcProcess::quoteArg(batchFile).toLocal8Bit();
    if (!batchArgs.isEmpty()) {
        call += ' ';
        call += batchArgs.toLocal8Bit();
    }
    saver.write(call + "\r\n");

    const QByteArray redirect = "set > " + Utils::QtcProcess::quoteArg(
                                    QDir::toNativeSeparators(tempOutFile)).toLocal8Bit() + "\r\n";
    saver.write(redirect);
    if (!saver.finalize()) {
        qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString()));
        return false;
    }

    Utils::QtcProcess run;
    // As of WinSDK 7.1, there is logic preventing the path from being set
    // correctly if "ORIGINALPATH" is already set. That can cause problems
    // if Creator is launched within a session set up by setenv.cmd.
    env.unset(QLatin1String("ORIGINALPATH"));
    run.setEnvironment(env);
    const QString cmdPath = QString::fromLocal8Bit(qgetenv("COMSPEC"));
    // Windows SDK setup scripts require command line switches for environment expansion.
    QString cmdArguments = QLatin1String(" /E:ON /V:ON /c \"");
    cmdArguments += QDir::toNativeSeparators(saver.fileName());
    cmdArguments += QLatin1Char('"');
    run.setCommand(cmdPath, cmdArguments);
    run.start();

    if (!run.waitForStarted()) {
        qWarning("%s: Unable to run '%s': %s", Q_FUNC_INFO, qPrintable(batchFile),
                 qPrintable(run.errorString()));
        return false;
    }
    if (!run.waitForFinished()) {
        qWarning("%s: Timeout running '%s'", Q_FUNC_INFO, qPrintable(batchFile));
        Utils::SynchronousProcess::stopProcess(run);
        return false;
    }
    // The SDK/MSVC scripts do not return exit codes != 0. Check on stdout.
    const QByteArray stdOut = run.readAllStandardOutput();
    if (!stdOut.isEmpty() && (stdOut.contains("Unknown") || stdOut.contains("Error")))
        qWarning("%s: '%s' reports:\n%s", Q_FUNC_INFO, call.constData(), stdOut.constData());

    //
    // Now parse the file to get the environment settings
    QFile varsFile(tempOutFile);
    if (!varsFile.open(QIODevice::ReadOnly))
        return false;

    QRegExp regexp(QLatin1String("(\\w*)=(.*)"));
    while (!varsFile.atEnd()) {
        const QString line = QString::fromLocal8Bit(varsFile.readLine()).trimmed();
        if (regexp.exactMatch(line)) {
            const QString varName = regexp.cap(1);
            const QString varValue = regexp.cap(2);

            if (!varValue.isEmpty())
                envPairs.insert(varName, varValue);
        }
    }

    // Tidy up and remove the file
    varsFile.close();
    varsFile.remove();

    return true;
}

147
148
static QByteArray noValue = "\001";

149
150
151
152
153
154
155
156
157
158
static QString toHex(const QString &str)
{
    QString encoded;
    foreach (const QChar c, str) {
        encoded += QString::fromLatin1("%1")
            .arg(c.unicode(), 2, 16, QLatin1Char('0'));
    }
    return encoded;
}

hjk's avatar
hjk committed
159
160
struct Context
{
hjk's avatar
hjk committed
161
    Context() : qtVersion(0), gccVersion(0) {}
hjk's avatar
hjk committed
162
163
164

    QByteArray nameSpace;
    int qtVersion;
hjk's avatar
hjk committed
165
    int gccVersion;
hjk's avatar
hjk committed
166
167
};

hjk's avatar
hjk committed
168
169
struct Name
{
hjk's avatar
hjk committed
170
171
172
173
174
    Name() : name(noValue) {}
    Name(const char *str) : name(str) {}
    Name(const QByteArray &ba) : name(ba) {}

    bool matches(const QByteArray &actualName0, const Context &context) const
hjk's avatar
hjk committed
175
176
177
    {
        QByteArray actualName = actualName0;
        QByteArray expectedName = name;
hjk's avatar
hjk committed
178
        expectedName.replace("@Q", context.nameSpace + 'Q');
hjk's avatar
hjk committed
179
180
181
182
183
184
185
        return actualName == expectedName;
    }

    QByteArray name;
};

static Name nameFromIName(const QByteArray &iname)
hjk's avatar
hjk committed
186
187
{
    int pos = iname.lastIndexOf('.');
hjk's avatar
hjk committed
188
    return Name(pos == -1 ? iname : iname.mid(pos + 1));
hjk's avatar
hjk committed
189
190
191
192
193
194
195
196
}

static QByteArray parentIName(const QByteArray &iname)
{
    int pos = iname.lastIndexOf('.');
    return pos == -1 ? QByteArray() : iname.left(pos);
}

hjk's avatar
hjk committed
197
struct ValueBase
198
{
hjk's avatar
hjk committed
199
200
201
202
    ValueBase()
      : hasPtrSuffix(false), isFloatValue(false), substituteNamespace(true),
        qtVersion(0), minimalGccVersion(0)
    {}
hjk's avatar
hjk committed
203
204

    bool hasPtrSuffix;
205
    bool isFloatValue;
206
    bool substituteNamespace;
hjk's avatar
hjk committed
207
208
    int qtVersion;
    int minimalGccVersion;
hjk's avatar
hjk committed
209
210
211
212
};

struct Value : public ValueBase
{
213
214
215
216
    Value() : value(QString::fromLatin1(noValue)) {}
    Value(const char *str) : value(QLatin1String(str)) {}
    Value(const QByteArray &ba) : value(QString::fromLatin1(ba.data(), ba.size())) {}
    Value(const QString &str) : value(str) {}
217

hjk's avatar
hjk committed
218
    bool matches(const QString &actualValue0, const Context &context) const
219
    {
220
        if (value == QString::fromLatin1(noValue))
221
            return true;
hjk's avatar
hjk committed
222
223

        if (context.qtVersion) {
hjk's avatar
hjk committed
224
            if (qtVersion == 4) {
hjk's avatar
hjk committed
225
226
227
228
                if (context.qtVersion < 0x40000 || context.qtVersion >= 0x50000) {
                    //QWARN("Qt 4 specific case skipped");
                    return true;
                }
hjk's avatar
hjk committed
229
            } else if (qtVersion == 5) {
hjk's avatar
hjk committed
230
231
232
233
234
235
                if (context.qtVersion < 0x50000 || context.qtVersion >= 0x60000) {
                    //QWARN("Qt 5 specific case skipped");
                    return true;
                }
            }
        }
hjk's avatar
hjk committed
236
237
238
239
240
241
        if (minimalGccVersion && context.gccVersion) {
            if (minimalGccVersion >= context.gccVersion) {
                //QWARN("Current GCC is too old for this test.")
                return true;
            }
        }
242
243
244
        QString actualValue = actualValue0;
        if (actualValue == QLatin1String(" "))
            actualValue.clear(); // FIXME: Remove later.
245
        QString expectedValue = value;
246
247
        if (substituteNamespace)
            expectedValue.replace(QLatin1Char('@'), QString::fromLatin1(context.nameSpace));
hjk's avatar
hjk committed
248

249
        if (hasPtrSuffix)
250
251
            return actualValue.startsWith(expectedValue + QLatin1String(" @0x"))
                || actualValue.startsWith(expectedValue + QLatin1String("@0x"));
252
253
254
255
256
257
258
259
260
261
262
263

        if (isFloatValue) {
            double f1 = fabs(expectedValue.toDouble());
            double f2 = fabs(actualValue.toDouble());
            //qDebug() << "expected float: " << qPrintable(expectedValue) << f1;
            //qDebug() << "actual   float: " << qPrintable(actualValue) << f2;
            if (f1 < f2)
                std::swap(f1, f2);
            return f1 - f2 <= 0.01 * f2;
        }


264
        return actualValue == expectedValue;
265
266
    }

hjk's avatar
hjk committed
267
268
    void setMinimalGccVersion(int version) { minimalGccVersion = version; }

269
    QString value;
270
271
272
273
274
275
276
277
};

struct Pointer : Value
{
    Pointer() { hasPtrSuffix = true; }
    Pointer(const QByteArray &value) : Value(value) { hasPtrSuffix = true; }
};

278
279
280
281
282
283
struct FloatValue : Value
{
    FloatValue() { isFloatValue = true; }
    FloatValue(const QByteArray &value) : Value(value) { isFloatValue = true; }
};

hjk's avatar
hjk committed
284
285
struct Value4 : Value
{
hjk's avatar
hjk committed
286
    Value4(const QByteArray &value) : Value(value) { qtVersion = 4; }
hjk's avatar
hjk committed
287
288
289
290
};

struct Value5 : Value
{
hjk's avatar
hjk committed
291
    Value5(const QByteArray &value) : Value(value) { qtVersion = 5; }
hjk's avatar
hjk committed
292
293
};

294
295
296
297
298
struct UnsubstitutedValue : Value
{
    UnsubstitutedValue(const QByteArray &value) : Value(value) { substituteNamespace = false; }
};

299
300
struct Type
{
301
302
303
    Type() : qtVersion(0), isPattern(false) {}
    Type(const char *str) : type(str), qtVersion(0), isPattern(false) {}
    Type(const QByteArray &ba) : type(ba), qtVersion(0), isPattern(false) {}
hjk's avatar
hjk committed
304
305

    bool matches(const QByteArray &actualType0, const Context &context) const
306
    {
307
        if (context.qtVersion) {
hjk's avatar
hjk committed
308
            if (qtVersion == 4) {
309
310
311
312
                if (context.qtVersion < 0x40000 || context.qtVersion >= 0x50000) {
                    //QWARN("Qt 4 specific case skipped");
                    return true;
                }
hjk's avatar
hjk committed
313
            } else if (qtVersion == 5) {
314
315
316
317
318
319
                if (context.qtVersion < 0x50000 || context.qtVersion >= 0x60000) {
                    //QWARN("Qt 5 specific case skipped");
                    return true;
                }
            }
        }
320
321
        QByteArray actualType =
            CPlusPlus::simplifySTLType(QString::fromLatin1(actualType0)).toLatin1();
322
        actualType.replace(' ', "");
hjk's avatar
hjk committed
323
        actualType.replace("const", "");
324
325
        QByteArray expectedType = type;
        expectedType.replace(' ', "");
326
        expectedType.replace("const", "");
hjk's avatar
hjk committed
327
        expectedType.replace('@', context.nameSpace);
328
329
330
331
332
        if (isPattern) {
            QString actual = QString::fromLatin1(actualType);
            QString expected = QString::fromLatin1(expectedType);
            return QRegExp(expected).exactMatch(actual);
        }
333
334
335
        return actualType == expectedType;
    }
    QByteArray type;
hjk's avatar
hjk committed
336
    int qtVersion;
337
    bool isPattern;
338
339
340
341
};

struct Type4 : Type
{
hjk's avatar
hjk committed
342
    Type4(const QByteArray &ba) : Type(ba) { qtVersion = 4; }
343
344
345
346
};

struct Type5 : Type
{
hjk's avatar
hjk committed
347
    Type5(const QByteArray &ba) : Type(ba) { qtVersion = 5; }
348
349
};

350
351
352
353
354
struct Pattern : Type
{
    Pattern(const QByteArray &ba) : Type(ba) { isPattern = true; }
};

355
356
enum DebuggerEngine
{
357
358
359
    DumpTestGdbEngine = 0x01,
    DumpTestCdbEngine = 0x02,
    DumpTestLldbEngine = 0x04,
360
361
362
363
};

struct CheckBase
{
364
365
    CheckBase() : enginesForCheck(DumpTestGdbEngine | DumpTestCdbEngine | DumpTestLldbEngine) {}
    mutable int enginesForCheck;
366
367
368
};

struct Check : CheckBase
369
370
371
{
    Check() {}

hjk's avatar
hjk committed
372
    Check(const QByteArray &iname, const Value &value, const Type &type)
hjk's avatar
hjk committed
373
374
375
376
        : iname(iname), expectedName(nameFromIName(iname)),
          expectedValue(value), expectedType(type)
    {}

hjk's avatar
hjk committed
377
    Check(const QByteArray &iname, const Name &name,
378
         const Value &value, const Type &type)
379
380
381
382
        : iname(iname), expectedName(name),
          expectedValue(value), expectedType(type)
    {}

383
384
    bool matchesEngine(DebuggerEngine engine) const
    {
385
386
387
388
389
390
391
        return (engine & enginesForCheck);
    }

    const Check &setEngines(int debuggerEngine)
    {
        enginesForCheck = debuggerEngine;
        return *this;
392
393
394
395
    }

    const Check &setForLldbOnly() const
    {
396
        enginesForCheck = DumpTestLldbEngine;
397
398
399
400
401
        return *this;
    }

    const Check &setForGdbOnly() const
    {
402
        enginesForCheck = DumpTestGdbEngine;
403
404
405
        return *this;
    }

406
    const Check &setForCdbOnly()
407
    {
408
409
        enginesForCheck = DumpTestCdbEngine;
        return *this;
410
    }
411

412
    QByteArray iname;
hjk's avatar
hjk committed
413
    Name expectedName;
414
    Value expectedValue;
415
    Type expectedType;
416
417
};

hjk's avatar
hjk committed
418
struct CheckType : public Check
419
{
hjk's avatar
hjk committed
420
    CheckType(const QByteArray &iname, const Name &name,
421
         const Type &type)
422
423
        : Check(iname, name, noValue, type)
    {}
424

425
    CheckType(const QByteArray &iname, const Type &type)
hjk's avatar
hjk committed
426
427
428
429
        : Check(iname, noValue, type)
    {}
};

hjk's avatar
hjk committed
430
struct Profile
hjk's avatar
hjk committed
431
432
433
434
{
    Profile(const QByteArray &contents) : contents(contents) {}

    QByteArray contents;
435
436
};

hjk's avatar
hjk committed
437

hjk's avatar
hjk committed
438
439
struct Cxx11Profile : public Profile
{
440
441
442
443
444
445
    Cxx11Profile()
      : Profile("greaterThan(QT_MAJOR_VERSION,4): CONFIG += c++11\n"
                "else: QMAKE_CXXFLAGS += -std=c++0x\n")
    {}
};

446
447
448
449
450
451
452
struct BoostProfile : public Profile
{
    BoostProfile()
      : Profile("macx:INCLUDEPATH += /usr/local/include")
    {}
};

453
struct MacLibCppProfile : public Profile
454
{
455
    MacLibCppProfile()
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
      : Profile("macx {\n"
                "QMAKE_CXXFLAGS += -stdlib=libc++\n"
                "LIBS += -stdlib=libc++\n"
                "QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.7\n"
                "QMAKE_IOS_DEPLOYMENT_TARGET = 10.7\n"
                "QMAKE_CFLAGS -= -mmacosx-version-min=10.6\n"
                "QMAKE_CFLAGS += -mmacosx-version-min=10.7\n"
                "QMAKE_CXXFLAGS -= -mmacosx-version-min=10.6\n"
                "QMAKE_CXXFLAGS += -mmacosx-version-min=10.7\n"
                "QMAKE_OBJECTIVE_CFLAGS -= -mmacosx-version-min=10.6\n"
                "QMAKE_OBJECTIVE_CFLAGS += -mmacosx-version-min=10.7\n"
                "QMAKE_LFLAGS -= -mmacosx-version-min=10.6\n"
                "QMAKE_LFLAGS += -mmacosx-version-min=10.7\n"
                "}")
    {}
hjk's avatar
hjk committed
471
472
};

473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
struct GdbVersion
{
    // Minimum and maximum are inclusive.
    GdbVersion(int minimum = 0, int maximum = 0)
    {
        if (minimum && !maximum)
            maximum = minimum;
        if (maximum == 0)
            maximum = INT_MAX;

        max = maximum;
        min = minimum;
    }
    int min;
    int max;
};

hjk's avatar
hjk committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
struct LldbVersion
{
    // Minimum and maximum are inclusive.
    LldbVersion(int minimum = 0, int maximum = 0)
    {
        if (minimum && !maximum)
            maximum = minimum;
        if (maximum == 0)
            maximum = INT_MAX;

        max = maximum;
        min = minimum;
    }
    int min;
    int max;
};

507
508
struct ForceC {};

hjk's avatar
hjk committed
509
510
511
512
513
514
struct CoreProfile {};
struct CorePrivateProfile {};
struct GuiProfile {};

struct DataBase
{
515
516
    DataBase()
      : useQt(false), useQHash(false),
517
        forceC(false), engines(DumpTestGdbEngine | DumpTestCdbEngine | DumpTestLldbEngine),
518
        glibcxxDebug(false)
519
    {}
hjk's avatar
hjk committed
520
521

    mutable bool useQt;
522
    mutable bool useQHash;
hjk's avatar
hjk committed
523
    mutable bool forceC;
524
    mutable int engines;
525
    mutable bool glibcxxDebug;
526
    mutable GdbVersion neededGdbVersion;
hjk's avatar
hjk committed
527
    mutable LldbVersion neededLldbVersion;
hjk's avatar
hjk committed
528
529
530
};

class Data : public DataBase
531
{
hjk's avatar
hjk committed
532
533
public:
    Data() {}
hjk's avatar
hjk committed
534
    Data(const QByteArray &code) : code(code) {}
535

536
    Data(const QByteArray &includes, const QByteArray &code)
hjk's avatar
hjk committed
537
        : includes(includes), code(code)
hjk's avatar
hjk committed
538
    {}
539

540
541
    const Data &operator%(const Check &check) const
    {
542
        checks.append(check);
543
544
545
        return *this;
    }

hjk's avatar
hjk committed
546
547
548
549
550
551
    const Data &operator%(const Profile &profile) const
    {
        profileExtra += profile.contents;
        return *this;
    }

552
553
554
555
556
557
    const Data &operator%(const GdbVersion &gdbVersion) const
    {
        neededGdbVersion = gdbVersion;
        return *this;
    }

hjk's avatar
hjk committed
558
559
560
561
562
563
    const Data &operator%(const LldbVersion &lldbVersion) const
    {
        neededLldbVersion = lldbVersion;
        return *this;
    }

564
    const Data &operator%(const DebuggerEngine &enginesForTest) const
hjk's avatar
hjk committed
565
    {
566
        engines = enginesForTest;
hjk's avatar
hjk committed
567
568
569
        return *this;
    }

hjk's avatar
hjk committed
570
571
572
573
    const Data &operator%(const CoreProfile &) const
    {
        profileExtra +=
            "CONFIG += QT\n"
574
            "QT += core\n";
hjk's avatar
hjk committed
575
576

        useQt = true;
577
578
        useQHash = true;

hjk's avatar
hjk committed
579
580
581
582
583
        return *this;
    }

    const Data &operator%(const GuiProfile &) const
    {
584
        this->operator%(CoreProfile());
hjk's avatar
hjk committed
585
586
587
588
589
590
591
592
593
        profileExtra +=
            "QT += gui\n"
            "greaterThan(QT_MAJOR_VERSION, 4):QT *= widgets\n";

        return *this;
    }

    const Data &operator%(const CorePrivateProfile &) const
    {
594
        this->operator%(CoreProfile());
hjk's avatar
hjk committed
595
596
        profileExtra +=
            "greaterThan(QT_MAJOR_VERSION, 4) {\n"
597
            "  QT += core-private\n"
hjk's avatar
hjk committed
598
599
600
601
602
603
            "  CONFIG += no_private_qt_headers_warning\n"
            "}";

        return *this;
    }

604
605
606
607
608
609
    const Data &operator%(const ForceC &) const
    {
        forceC = true;
        return *this;
    }

hjk's avatar
hjk committed
610
public:
hjk's avatar
hjk committed
611
    mutable QByteArray profileExtra;
612
613
    mutable QByteArray includes;
    mutable QByteArray code;
614
    mutable QList<Check> checks;
hjk's avatar
hjk committed
615
616
};

617
618
619
620
struct TempStuff
{
    TempStuff() : buildTemp(QLatin1String("qt_tst_dumpers_"))
    {
621
        buildPath = QDir::currentPath() + QLatin1Char('/')  + buildTemp.path();
622
623
624
625
626
627
628
629
630
        buildTemp.setAutoRemove(false);
        QVERIFY(!buildPath.isEmpty());
    }

    QByteArray input;
    QTemporaryDir buildTemp;
    QString buildPath;
};

hjk's avatar
hjk committed
631
Q_DECLARE_METATYPE(Data)
hjk's avatar
hjk committed
632

633
class tst_Dumpers : public QObject
634
635
636
637
{
    Q_OBJECT

public:
638
639
640
    tst_Dumpers()
    {
        t = 0;
641
        m_keepTemp = true;
642
        m_forceKeepTemp = false;
643
644
645
646
647
        m_gdbVersion = 0;
        m_gdbBuildVersion = 0;
        m_lldbVersion = 0;
        m_isMacGdb = false;
        m_isQnxGdb = false;
648
        m_useGLibCxxDebug = false;
649
    }
650
651

private slots:
hjk's avatar
hjk committed
652
    void initTestCase();
hjk's avatar
hjk committed
653
654
    void dumper();
    void dumper_data();
655
656
    void init();
    void cleanup();
hjk's avatar
hjk committed
657
658

private:
659
    bool keepTemp() const { return m_keepTemp || m_forceKeepTemp; }
660
    TempStuff *t;
hjk's avatar
hjk committed
661
662
    QByteArray m_debuggerBinary;
    QByteArray m_qmakeBinary;
663
    Environment m_env;
hjk's avatar
hjk committed
664
    bool m_usePython;
665
    DebuggerEngine m_debuggerEngine;
hjk's avatar
hjk committed
666
    bool m_keepTemp;
667
    bool m_forceKeepTemp;
668
669
    int m_gdbVersion; // 7.5.1 -> 70501
    int m_gdbBuildVersion;
670
    int m_lldbVersion;
671
672
    bool m_isMacGdb;
    bool m_isQnxGdb;
673
    bool m_useGLibCxxDebug;
hjk's avatar
hjk committed
674
675
676
677
};

void tst_Dumpers::initTestCase()
{
678
    m_debuggerBinary = qgetenv("QTC_DEBUGGER_PATH_FOR_TEST");
hjk's avatar
hjk committed
679
680
    if (m_debuggerBinary.isEmpty())
        m_debuggerBinary = "gdb";
681
    qDebug() << "Debugger           : " << m_debuggerBinary.constData();
682

683
    m_debuggerEngine = DumpTestGdbEngine;
684
    if (m_debuggerBinary.endsWith("cdb.exe"))
685
        m_debuggerEngine = DumpTestCdbEngine;
686

687
    if (m_debuggerBinary.endsWith("lldb"))
688
        m_debuggerEngine = DumpTestLldbEngine;
hjk's avatar
hjk committed
689

hjk's avatar
hjk committed
690
    m_qmakeBinary = qgetenv("QTC_QMAKE_PATH_FOR_TEST");
hjk's avatar
hjk committed
691
692
    if (m_qmakeBinary.isEmpty())
        m_qmakeBinary = "qmake";
693
694
695
696
697
698
699
    qDebug() << "QMake              : " << m_qmakeBinary.constData();

    m_useGLibCxxDebug = qgetenv("QTC_USE_GLIBCXXDEBUG_FOR_TEST").toInt();
    qDebug() << "Use _GLIBCXX_DEBUG : " << m_useGLibCxxDebug;

    m_forceKeepTemp = qgetenv("QTC_KEEP_TEMP_FOR_TEST").toInt();
    qDebug() << "Force keep temp    : " << m_forceKeepTemp;
hjk's avatar
hjk committed
700

701
    m_env = Environment::systemEnvironment();
702

703
    if (m_debuggerEngine == DumpTestGdbEngine) {
704
705
706
707
708
709
710
711
712
713
        QProcess debugger;
        debugger.start(QString::fromLatin1(m_debuggerBinary)
                       + QLatin1String(" -i mi -quiet -nx"));
        bool ok = debugger.waitForStarted();
        debugger.write("set confirm off\npython print 43\nshow version\nquit\n");
        ok = debugger.waitForFinished();
        QVERIFY(ok);
        QByteArray output = debugger.readAllStandardOutput();
        //qDebug() << "stdout: " << output;
        m_usePython = !output.contains("Python scripting is not supported in this copy of GDB");
714
715
        qDebug() << "Python             : " << (m_usePython ? "ok" : "*** not ok ***");
        qDebug() << "Dumper dir         : " << DUMPERDIR;
716
717
718
719
720
721
722
723
724

        QString version = QString::fromLocal8Bit(output);
        int pos1 = version.indexOf(QLatin1String("&\"show version\\n"));
        QVERIFY(pos1 != -1);
        pos1 += 20;
        int pos2 = version.indexOf(QLatin1String("~\"Copyright (C) "), pos1);
        QVERIFY(pos2 != -1);
        pos2 -= 4;
        version = version.mid(pos1, pos2 - pos1);
725
        extractGdbVersion(version, &m_gdbVersion,
726
            &m_gdbBuildVersion, &m_isMacGdb, &m_isQnxGdb);
727
        qDebug() << "Gdb version        : " << m_gdbVersion;
728
    } else if (m_debuggerEngine == DumpTestCdbEngine) {
729
730
        QByteArray envBat = qgetenv("QTC_MSVC_ENV_BAT");
        QMap <QString, QString> envPairs;
731
        QVERIFY(generateEnvironmentSettings(m_env, QString::fromLatin1(envBat), QString(), envPairs));
732
        for (QMap<QString,QString>::const_iterator envIt = envPairs.begin(); envIt!=envPairs.end(); ++envIt)
733
                m_env.set(envIt.key(), envIt.value());
734
735
        const QByteArray cdbextPath = QByteArray(CDBEXT_PATH) + QByteArray("\\qtcreatorcdbext64");
        QVERIFY(QFile::exists(QString::fromLatin1(cdbextPath + QByteArray("\\qtcreatorcdbext.dll"))));
736
        m_env.appendOrSet(QLatin1String("_NT_DEBUGGER_EXTENSION_PATH"),
737
738
                             QString::fromLatin1(cdbextPath),
                             QLatin1String(";"));
739
    } else if (m_debuggerEngine == DumpTestLldbEngine) {
740
741
        m_usePython = true;
        QProcess debugger;
742
743
        QString cmd = QString::fromUtf8(m_debuggerBinary + " -v");
        debugger.start(cmd);
744
745
746
747
748
749
        bool ok = debugger.waitForFinished(2000);
        QVERIFY(ok);
        QByteArray output = debugger.readAllStandardOutput();
        output += debugger.readAllStandardError();
        output = output.trimmed();
        // Should be something like LLDB-178
750
751
752
753
754
        QByteArray ba = output.mid(output.indexOf('-') + 1);
        int pos = ba.indexOf('.');
        if (pos >= 0)
            ba = ba.left(pos);
        m_lldbVersion = ba.toInt();
755
        qDebug() << "Lldb version       :" << output << ba << m_lldbVersion;
756
        QVERIFY(m_lldbVersion);
757
    }
hjk's avatar
hjk committed
758
759
}

760
void tst_Dumpers::init()
hjk's avatar
hjk committed
761
{
762
    t = new TempStuff();
hjk's avatar
hjk committed
763
764
}

765
void tst_Dumpers::cleanup()
hjk's avatar
hjk committed
766
{
767
768
    if (!t->buildTemp.autoRemove()) {
        QFile logger(t->buildPath + QLatin1String("/input.txt"));
hjk's avatar
hjk committed
769
        logger.open(QIODevice::ReadWrite);
770
        logger.write(t->input);
hjk's avatar
hjk committed
771
    }
772
773
    delete t;
}
774

hjk's avatar
hjk committed
775
776
777
778
void tst_Dumpers::dumper()
{
    QFETCH(Data, data);

779
780
781
    if (!(data.engines & m_debuggerEngine))
        MSKIP_SINGLE("The test is excluded for this debugger engine.");

782
    if (m_debuggerEngine == DumpTestGdbEngine) {
783
        if (data.neededGdbVersion.min > m_gdbVersion)
hjk's avatar
hjk committed
784
785
            MSKIP_SINGLE("Need minimum GDB version "
                + QByteArray::number(data.neededGdbVersion.min));
786
        if (data.neededGdbVersion.max < m_gdbVersion)
hjk's avatar
hjk committed
787
788
789
790
791
792
793
794
795
796
797
            MSKIP_SINGLE("Need maximum GDB version "
                + QByteArray::number(data.neededGdbVersion.max));
    }

    if (m_debuggerEngine == DumpTestLldbEngine) {
        if (data.neededLldbVersion.min > m_gdbVersion)
            MSKIP_SINGLE("Need minimum LLDB version "
                + QByteArray::number(data.neededLldbVersion.min));
        if (data.neededLldbVersion.max < m_gdbVersion)
            MSKIP_SINGLE("Need maximum LLDB version "
                + QByteArray::number(data.neededLldbVersion.max));
798
    }
799

hjk's avatar
hjk committed
800
801
802
803
    QString cmd;
    QByteArray output;
    QByteArray error;

804
805
    const char *mainFile = data.forceC ? "main.c" : "main.cpp";

806
807
    QFile proFile(t->buildPath + QLatin1String("/doit.pro"));
    QVERIFY(proFile.open(QIODevice::ReadWrite));
808
809
810
    proFile.write("SOURCES = ");
    proFile.write(mainFile);
    proFile.write("\nTARGET = doit\n");
811
    proFile.write("\nCONFIG -= app_bundle\n");
812
813
    proFile.write("\nCONFIG -= release\n");
    proFile.write("\nCONFIG += debug\n");
hjk's avatar
hjk committed
814
815
816
817
    if (data.useQt)
        proFile.write("QT -= widgets gui\n");
    else
        proFile.write("CONFIG -= QT\n");
818
819
    if (m_useGLibCxxDebug)
        proFile.write("DEFINES += _GLIBCXX_DEBUG\n");
hjk's avatar
hjk committed
820
    proFile.write(data.profileExtra);
hjk's avatar
hjk committed
821
822
    proFile.close();

823
824
    QFile source(t->buildPath + QLatin1Char('/') + QLatin1String(mainFile));
    QVERIFY(source.open(QIODevice::ReadWrite));
hjk's avatar
hjk committed
825
    QByteArray fullCode =
hjk's avatar
hjk committed
826
            "\n\nvoid unused(const void *first,...) { (void) first; }"
hjk's avatar
hjk committed
827
            "\n\nvoid breakHere() {}"
hjk's avatar
hjk committed
828
            "\n\n" + data.includes +
829
830
831
832
833
834
835
            "\n\n" + (data.useQHash ?
                "\n#include <QByteArray>"
                "\n#if QT_VERSION >= 0x050000"
                "\nQT_BEGIN_NAMESPACE"
                "\nQ_CORE_EXPORT extern QBasicAtomicInt qt_qhash_seed; // from qhash.cpp"
                "\nQT_END_NAMESPACE"
                "\n#endif" : "") +
hjk's avatar
hjk committed
836
            "\n\nint main(int argc, char *argv[])"
hjk's avatar
hjk committed
837
            "\n{"
838
            "\n    int qtversion = " + (data.useQt ? "QT_VERSION" : "0") + ";"
hjk's avatar
hjk committed
839
840
841
842
843
            "\n#ifdef __GNUC__"
            "\n    int gccversion = 0x10000 * __GNUC__ + 0x100 * __GNUC_MINOR__;"
            "\n#else"
            "\n    int gccversion = 0;"
            "\n#endif"
844
845
            "\n" + (data.useQHash ?
                "\n#if QT_VERSION >= 0x050000"
846
                "\nqt_qhash_seed.store(0);"
847
                "\n#endif\n" : "") +
hjk's avatar
hjk committed
848
            "\n    unused(&argc, &argv, &qtversion, &gccversion);\n"
hjk's avatar
hjk committed
849
850
            "\n" + data.code +
            "\n    breakHere();"
851
            "\n    return 0;"
hjk's avatar
hjk committed
852
853
            "\n}\n";
    source.write(fullCode);
hjk's avatar
hjk committed
854
855
856
    source.close();

    QProcess qmake;
857
    qmake.setWorkingDirectory(t->buildPath);
hjk's avatar
hjk committed
858
    cmd = QString::fromLatin1(m_qmakeBinary);
hjk's avatar
hjk committed
859
860
    //qDebug() << "Starting qmake: " << cmd;
    qmake.start(cmd);
861
    QVERIFY(qmake.waitForFinished());
hjk's avatar
hjk committed
862
863
864
    output = qmake.readAllStandardOutput();
    error = qmake.readAllStandardError();
    //qDebug() << "stdout: " << output;
865
    if (!error.isEmpty()) { qDebug() << error; QVERIFY(false); }
hjk's avatar
hjk committed
866
867

    QProcess make;
868
    make.setWorkingDirectory(t->buildPath);
869
870
871
872
873
874
    make.setProcessEnvironment(m_env.toProcessEnvironment());

    cmd = m_debuggerEngine == DumpTestCdbEngine ? m_env.searchInPath(QLatin1String("nmake.exe"))
                                                : QLatin1String("make");

    make.start(cmd, QStringList());
875
    QVERIFY(make.waitForFinished());
hjk's avatar
hjk committed
876
877
878
    output = make.readAllStandardOutput();
    error = make.readAllStandardError();
    //qDebug() << "stdout: " << output;
879
    if (make.exitCode()) {
hjk's avatar
hjk committed
880
881
882
883
884
885
        qDebug() << error;
        qDebug() << "\n------------------ CODE --------------------";
        qDebug() << fullCode;
        qDebug() << "\n------------------ CODE --------------------";
        qDebug() << ".pro: " << qPrintable(proFile.fileName());
    }
hjk's avatar
hjk committed
886
887
888

    QByteArray dumperDir = DUMPERDIR;

889
890
891
    QSet<QByteArray> expandedINames;
    expandedINames.insert("local");
    foreach (const Check &check, data.checks) {
hjk's avatar
hjk committed
892
893
894
895
896
897
898
        QByteArray parent = check.iname;
        while (true) {
            parent = parentIName(parent);
            if (parent.isEmpty())
                break;
            expandedINames.insert("local." + parent);
        }
899
900
901
902
903
904
905
906
907
    }

    QByteArray expanded;
    foreach (const QByteArray &iname, expandedINames) {
        if (!expanded.isEmpty())
            expanded.append(',');
        expanded += iname;
    }

908
    QByteArray exe;
909
    QStringList args;
910
    QByteArray cmds;
911

912
    if (m_debuggerEngine == DumpTestGdbEngine) {
913
        exe = m_debuggerBinary;
hjk's avatar
hjk committed
914
915
916
917

        const QFileInfo gdbBinaryFile(QString::fromLatin1(exe));
        const QByteArray uninstalledData = gdbBinaryFile.absolutePath().toLocal8Bit() + "/data-directory/python";

918
919
920
921
922
923
924
925
926
927
928
929
930
        args << QLatin1String("-i")
             << QLatin1String("mi")
             << QLatin1String("-quiet")
             << QLatin1String("-nx");
        QByteArray nograb = "-nograb";

        cmds = "set confirm off\n"
                "file doit\n"
                "break breakHere\n"
                "set print object on\n"
                "set auto-load python-scripts no\n";

        if (m_usePython) {
931
            cmds += "python sys.path.insert(1, '" + dumperDir + "')\n"
hjk's avatar
hjk committed
932
                    "python sys.path.append('" + uninstalledData + "')\n"
933
                    "python from gdbbridge import *\n"
934
935
                    "run " + nograb + "\n"
                    "up\n"
936
                    "python print('@%sS@%s@' % ('N', theDumper.qtNamespace()))\n"
937
                    "bb options:fancy,autoderef,dyntype,pe vars: expanded:" + expanded + " typeformats:\n";
938
939
940
941
942
943
944
945
        } else {
            cmds += "run\n";
            foreach (const Check &check, data.checks) {
                QByteArray iname = check.iname;
                //qDebug() << "INAME: " << iname;
                cmds += "-var-create " + iname + " * "
                        + check.expectedName.name + "\n";
            }
hjk's avatar
hjk committed
946
        }
947
        cmds += "quit\n";
ck's avatar
ck committed
948

949
    } else if (m_debuggerEngine == DumpTestCdbEngine) {
950
        exe = m_debuggerBinary;
951
952
953
954
955
956
957
958
959
960
961
962
        args << QLatin1String("-aqtcreatorcdbext.dll")
             << QLatin1String("-lines")
             << QLatin1String("-G")
             << QLatin1String("-c.idle_cmd")
             << QLatin1String("!qtcreatorcdbext.idle")
             << QLatin1String("debug\\doit.exe");
        cmds = "l+t\n"
               "l+s\n"
               "bu `doit!" + source.fileName().toLatin1() + ":5`\n"
               "sxi 0x4000001f\n"
               "g\n"
               "gu\n"
963
964
965
966
967
968
969
               "!qtcreatorcdbext.expandlocals -t 0 -c 0 " + expanded + "\n";
        int token = 0;
        QStringList sortediNames;
        foreach (QByteArray iName, expandedINames)
            sortediNames << QString::fromLatin1(iName);
        sortediNames.sort();
        foreach (QString iName, sortediNames)
970
971
            cmds += "!qtcreatorcdbext.locals -t " + QByteArray::number(++token)
                    + " -c 0 " + iName.toLatin1() + "\n";
972
        cmds += "q\n";
973
    } else if (m_debuggerEngine == DumpTestLldbEngine) {
974
        exe = "python";
975
        args << QLatin1String(dumperDir + "/lldbbridge.py")
976
             << QString::fromUtf8(m_debuggerBinary)
977
978
979
             << t->buildPath + QLatin1String("/doit")
             << QString::fromUtf8(expanded);
        //qDebug() << exe.constData() << ' ' << qPrintable(args.join(QLatin1Char(' ')));
980
    }
hjk's avatar
hjk committed
981

982
    t->input = cmds;
hjk's avatar
hjk committed
983

hjk's avatar
hjk committed
984
    QProcess debugger;
985
    debugger.setProcessEnvironment(m_env.toProcessEnvironment());
986
    debugger.setWorkingDirectory(t->buildPath);
987
    debugger.start(QString::fromLatin1(exe), args);
988
    QVERIFY(debugger.waitForStarted());
hjk's avatar
hjk committed
989
    debugger.write(cmds);
990
    QVERIFY(debugger.waitForFinished());
hjk's avatar
hjk committed
991
992
993
994
995
    output = debugger.readAllStandardOutput();
    //qDebug() << "stdout: " << output;
    error = debugger.readAllStandardError();
    if (!error.isEmpty()) { qDebug() << error; }

996
    if (keepTemp()) {
997
998
        QFile logger(t->buildPath + QLatin1String("/output.txt"));
        logger.open(QIODevice::ReadWrite);
hjk's avatar
hjk committed
999
1000
1001
1002
        logger.write("=== STDOUT ===\n");
        logger.write(output);
        logger.write("\n=== STDERR ===\n");
        logger.write(error);