tst_dumpers.cpp 207 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Bill King's avatar
Bill King committed
2
**
3
** Copyright (C) 2014 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 <utils/environment.h>
35
36
37
#include <utils/qtcprocess.h>
#include <utils/fileutils.h>
#include <utils/synchronousprocess.h>
38

39
#include "temporarydir.h"
40

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

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

50
using namespace Debugger;
51
using namespace Utils;
hjk's avatar
hjk committed
52
using namespace Internal;
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
// 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;
}

146
147
static QByteArray noValue = "\001";

148
149
150
151
152
153
154
155
156
157
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
158
159
struct Context
{
hjk's avatar
hjk committed
160
    Context() : qtVersion(0), gccVersion(0) {}
hjk's avatar
hjk committed
161
162
163

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

hjk's avatar
hjk committed
167
168
struct Name
{
hjk's avatar
hjk committed
169
170
171
172
173
    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
174
175
176
    {
        QByteArray actualName = actualName0;
        QByteArray expectedName = name;
hjk's avatar
hjk committed
177
        expectedName.replace("@Q", context.nameSpace + 'Q');
hjk's avatar
hjk committed
178
179
180
181
182
183
184
        return actualName == expectedName;
    }

    QByteArray name;
};

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

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

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

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

struct Value : public ValueBase
{
212
213
214
215
    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) {}
216

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

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

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

        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;
        }


263
        return actualValue == expectedValue;
264
265
    }

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

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

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

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

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

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

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

298
299
struct Type
{
300
301
302
    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
303
304

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    QByteArray contents;
434
435
};

hjk's avatar
hjk committed
436

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

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

452
struct MacLibCppProfile : public Profile
453
{
454
    MacLibCppProfile()
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
      : 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
470
471
};

472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
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;
};

506
507
struct ForceC {};

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

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

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

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

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

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

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

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

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

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

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

        useQt = true;
576
577
        useQHash = true;

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

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

        return *this;
    }

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

        return *this;
    }

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

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

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

    QByteArray input;
    QTemporaryDir buildTemp;
    QString buildPath;
};

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

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

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

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

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

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

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

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

hjk's avatar
hjk committed
689
    m_qmakeBinary = qgetenv("QTC_QMAKE_PATH_FOR_TEST");
hjk's avatar
hjk committed
690
691
    if (m_qmakeBinary.isEmpty())
        m_qmakeBinary = "qmake";
692
693
694
695
696
697
698
    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
699

700
    m_env = Environment::systemEnvironment();
701

702
    if (m_debuggerEngine == DumpTestGdbEngine) {
703
704
705
706
707
708
709
710
711
712
        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");
713
714
        qDebug() << "Python             : " << (m_usePython ? "ok" : "*** not ok ***");
        qDebug() << "Dumper dir         : " << DUMPERDIR;
715
716
717
718
719
720
721
722
723

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

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

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

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

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

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

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

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

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

822
823
    QFile source(t->buildPath + QLatin1Char('/') + QLatin1String(mainFile));
    QVERIFY(source.open(QIODevice::ReadWrite));
824
    QByteArray fullCode = QByteArray() +
hjk's avatar
hjk committed
825
            "\n\nvoid unused(const void *first,...) { (void) first; }"
826
827
828
829
830
831
832
833
            "\n\n#if defined(_MSC_VER)" + (data.useQt ?
                "\n#include <qt_windows.h>" :
                "\n#include <Windows.h>") +
            "\n#define BREAK DebugBreak();"
            "\n#else"
            "\n#define BREAK asm(\"int $3\");"
            "\n#endif"
            "\n"
hjk's avatar
hjk committed
834
            "\n\n" + data.includes +
835
836
837
838
839
840
841
            "\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
842
            "\n\nint main(int argc, char *argv[])"
hjk's avatar
hjk committed
843
            "\n{"
844
            "\n    int qtversion = " + (data.useQt ? "QT_VERSION" : "0") + ";"
hjk's avatar
hjk committed
845
846
847
848
849
            "\n#ifdef __GNUC__"
            "\n    int gccversion = 0x10000 * __GNUC__ + 0x100 * __GNUC_MINOR__;"
            "\n#else"
            "\n    int gccversion = 0;"
            "\n#endif"
850
851
            "\n" + (data.useQHash ?
                "\n#if QT_VERSION >= 0x050000"
852
                "\nqt_qhash_seed.store(0);"
853
                "\n#endif\n" : "") +
hjk's avatar
hjk committed
854
            "\n    unused(&argc, &argv, &qtversion, &gccversion);\n"
hjk's avatar
hjk committed
855
            "\n" + data.code +
856
            "\n    BREAK;"
857
            "\n    return 0;"
hjk's avatar
hjk committed
858
859
            "\n}\n";
    source.write(fullCode);
hjk's avatar
hjk committed
860
861
862
    source.close();

    QProcess qmake;
863
    qmake.setWorkingDirectory(t->buildPath);
hjk's avatar
hjk committed
864
    cmd = QString::fromLatin1(m_qmakeBinary);
hjk's avatar
hjk committed
865
866
    //qDebug() << "Starting qmake: " << cmd;
    qmake.start(cmd);
867
    QVERIFY(qmake.waitForFinished());
hjk's avatar
hjk committed
868
869
870
    output = qmake.readAllStandardOutput();
    error = qmake.readAllStandardError();
    //qDebug() << "stdout: " << output;
871
    if (!error.isEmpty()) { qDebug() << error; QVERIFY(false); }
hjk's avatar
hjk committed
872
873

    QProcess make;
874
    make.setWorkingDirectory(t->buildPath);
875
876
877
878
879
880
    make.setProcessEnvironment(m_env.toProcessEnvironment());

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

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

    QByteArray dumperDir = DUMPERDIR;

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

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

914
    QByteArray exe;
915
    QStringList args;
916
    QByteArray cmds;
917

918
    if (m_debuggerEngine == DumpTestGdbEngine) {
919
        exe = m_debuggerBinary;
hjk's avatar
hjk committed
920
921
922
923

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

924
925
926
927
928
929
930
931
932
933
934
935
        args << QLatin1String("-i")
             << QLatin1String("mi")
             << QLatin1String("-quiet")
             << QLatin1String("-nx");
        QByteArray nograb = "-nograb";

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

        if (m_usePython) {
936
            cmds += "python sys.path.insert(1, '" + dumperDir + "')\n"
hjk's avatar
hjk committed
937
                    "python sys.path.append('" + uninstalledData + "')\n"
938
                    "python from gdbbridge import *\n"
939
                    "run " + nograb + "\n"
940
                    "python print('@%sS@%s@' % ('N', theDumper.qtNamespace()))\n"
941
                    "bb options:fancy,autoderef,dyntype,pe vars: expanded:" + expanded + " typeformats:\n";
942
943
944
945
946
947
948
949
        } 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
950
        }
951
        cmds += "quit\n";
ck's avatar
ck committed
952

953
    } else if (m_debuggerEngine == DumpTestCdbEngine) {
954
        exe = m_debuggerBinary;
955
956
957
958
959
960
961
962
963
964
965
        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"
               "sxi 0x4000001f\n"
               "g\n"
               "gu\n"
966
967
968
969
970
971
972
               "!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)
973
974
            cmds += "!qtcreatorcdbext.locals -t " + QByteArray::number(++token)
                    + " -c 0 " + iName.toLatin1() + "\n";
975
        cmds += "q\n";
976
    } else if (m_debuggerEngine == DumpTestLldbEngine) {
977
        exe = "python";
978
        args << QLatin1String(dumperDir + "/lldbbridge.py")
979
             << QString::fromUtf8(m_debuggerBinary)
980
981
982
             << t->buildPath + QLatin1String("/doit")
             << QString::fromUtf8(expanded);
        //qDebug() << exe.constData() << ' ' << qPrintable(args.join(QLatin1Char(' ')));
983
    }
hjk's avatar
hjk committed
984

985
    t->input = cmds;
hjk's avatar
hjk committed
986

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

999
    if (keepTemp()) {
1000
1001
        QFile logger(t->buildPath + QLatin1String("/output.txt"));
        logger.open(QIODevice::ReadWrite);