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
161
162
struct GdbOnly {};
struct LldbOnly {};

hjk's avatar
hjk committed
163
164
struct Context
{
hjk's avatar
hjk committed
165
    Context() : qtVersion(0), gccVersion(0) {}
hjk's avatar
hjk committed
166
167
168

    QByteArray nameSpace;
    int qtVersion;
hjk's avatar
hjk committed
169
    int gccVersion;
hjk's avatar
hjk committed
170
171
};

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

    QByteArray name;
};

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

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

hjk's avatar
hjk committed
201
struct ValueBase
202
{
hjk's avatar
hjk committed
203
204
205
206
    ValueBase()
      : hasPtrSuffix(false), isFloatValue(false), substituteNamespace(true),
        qtVersion(0), minimalGccVersion(0)
    {}
hjk's avatar
hjk committed
207
208

    bool hasPtrSuffix;
209
    bool isFloatValue;
210
    bool substituteNamespace;
hjk's avatar
hjk committed
211
212
    int qtVersion;
    int minimalGccVersion;
hjk's avatar
hjk committed
213
214
215
216
};

struct Value : public ValueBase
{
217
218
219
220
    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) {}
221

hjk's avatar
hjk committed
222
    bool matches(const QString &actualValue0, const Context &context) const
223
    {
224
        if (value == QString::fromLatin1(noValue))
225
            return true;
hjk's avatar
hjk committed
226
227

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

253
        if (hasPtrSuffix)
254
255
            return actualValue.startsWith(expectedValue + QLatin1String(" @0x"))
                || actualValue.startsWith(expectedValue + QLatin1String("@0x"));
256
257
258
259
260
261
262
263
264
265
266
267

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


268
        return actualValue == expectedValue;
269
270
    }

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

273
    QString value;
274
275
276
277
278
279
280
281
};

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

282
283
284
285
286
287
struct FloatValue : Value
{
    FloatValue() { isFloatValue = true; }
    FloatValue(const QByteArray &value) : Value(value) { isFloatValue = true; }
};

hjk's avatar
hjk committed
288
289
struct Value4 : Value
{
hjk's avatar
hjk committed
290
    Value4(const QByteArray &value) : Value(value) { qtVersion = 4; }
hjk's avatar
hjk committed
291
292
293
294
};

struct Value5 : Value
{
hjk's avatar
hjk committed
295
    Value5(const QByteArray &value) : Value(value) { qtVersion = 5; }
hjk's avatar
hjk committed
296
297
};

298
299
300
301
302
struct UnsubstitutedValue : Value
{
    UnsubstitutedValue(const QByteArray &value) : Value(value) { substituteNamespace = false; }
};

303
304
struct Type
{
305
306
307
    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
308
309

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

struct Type4 : Type
{
hjk's avatar
hjk committed
346
    Type4(const QByteArray &ba) : Type(ba) { qtVersion = 4; }
347
348
349
350
};

struct Type5 : Type
{
hjk's avatar
hjk committed
351
    Type5(const QByteArray &ba) : Type(ba) { qtVersion = 5; }
352
353
};

354
355
356
357
358
struct Pattern : Type
{
    Pattern(const QByteArray &ba) : Type(ba) { isPattern = true; }
};

359
360
enum DebuggerEngine
{
361
362
363
    DumpTestGdbEngine = 0x01,
    DumpTestCdbEngine = 0x02,
    DumpTestLldbEngine = 0x04,
364
365
366
367
};

struct CheckBase
{
368
369
    CheckBase() : enginesForCheck(DumpTestGdbEngine | DumpTestCdbEngine | DumpTestLldbEngine) {}
    mutable int enginesForCheck;
370
371
372
};

struct Check : CheckBase
373
374
375
{
    Check() {}

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

hjk's avatar
hjk committed
381
    Check(const QByteArray &iname, const Name &name,
382
         const Value &value, const Type &type)
383
384
385
386
        : iname(iname), expectedName(name),
          expectedValue(value), expectedType(type)
    {}

387
388
    bool matchesEngine(DebuggerEngine engine) const
    {
389
390
391
392
393
394
395
        return (engine & enginesForCheck);
    }

    const Check &setEngines(int debuggerEngine)
    {
        enginesForCheck = debuggerEngine;
        return *this;
396
397
398
399
    }

    const Check &setForLldbOnly() const
    {
400
        enginesForCheck = DumpTestLldbEngine;
401
402
403
404
405
        return *this;
    }

    const Check &setForGdbOnly() const
    {
406
        enginesForCheck = DumpTestGdbEngine;
407
408
409
        return *this;
    }

410
    const Check &setForCdbOnly()
411
    {
412
413
        enginesForCheck = DumpTestCdbEngine;
        return *this;
414
    }
415

416
    QByteArray iname;
hjk's avatar
hjk committed
417
    Name expectedName;
418
    Value expectedValue;
419
    Type expectedType;
420
421
};

hjk's avatar
hjk committed
422
struct CheckType : public Check
423
{
hjk's avatar
hjk committed
424
    CheckType(const QByteArray &iname, const Name &name,
425
         const Type &type)
426
427
        : Check(iname, name, noValue, type)
    {}
428

429
    CheckType(const QByteArray &iname, const Type &type)
hjk's avatar
hjk committed
430
431
432
433
        : Check(iname, noValue, type)
    {}
};

hjk's avatar
hjk committed
434
struct Profile
hjk's avatar
hjk committed
435
436
437
438
{
    Profile(const QByteArray &contents) : contents(contents) {}

    QByteArray contents;
439
440
};

hjk's avatar
hjk committed
441

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

450
451
452
453
454
455
456
struct BoostProfile : public Profile
{
    BoostProfile()
      : Profile("macx:INCLUDEPATH += /usr/local/include")
    {}
};

457
struct MacLibCppProfile : public Profile
458
{
459
    MacLibCppProfile()
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
      : 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
475
476
};

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
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;
};

511
512
struct ForceC {};

hjk's avatar
hjk committed
513
514
515
516
517
518
struct CoreProfile {};
struct CorePrivateProfile {};
struct GuiProfile {};

struct DataBase
{
519
520
    DataBase()
      : useQt(false), useQHash(false),
521
522
        forceC(false), gdbOnly(false), lldbOnly(false),
        glibcxxDebug(false)
523
    {}
hjk's avatar
hjk committed
524
525

    mutable bool useQt;
526
    mutable bool useQHash;
hjk's avatar
hjk committed
527
    mutable bool forceC;
hjk's avatar
hjk committed
528
529
    mutable bool gdbOnly;
    mutable bool lldbOnly;
530
    mutable bool glibcxxDebug;
531
    mutable GdbVersion neededGdbVersion;
hjk's avatar
hjk committed
532
    mutable LldbVersion neededLldbVersion;
hjk's avatar
hjk committed
533
534
535
};

class Data : public DataBase
536
{
hjk's avatar
hjk committed
537
538
public:
    Data() {}
hjk's avatar
hjk committed
539
    Data(const QByteArray &code) : code(code) {}
540

541
    Data(const QByteArray &includes, const QByteArray &code)
hjk's avatar
hjk committed
542
        : includes(includes), code(code)
hjk's avatar
hjk committed
543
    {}
544

545
546
    const Data &operator%(const Check &check) const
    {
547
        checks.append(check);
548
549
550
        return *this;
    }

hjk's avatar
hjk committed
551
552
553
554
555
556
    const Data &operator%(const Profile &profile) const
    {
        profileExtra += profile.contents;
        return *this;
    }

557
558
559
560
561
562
    const Data &operator%(const GdbVersion &gdbVersion) const
    {
        neededGdbVersion = gdbVersion;
        return *this;
    }

hjk's avatar
hjk committed
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
    const Data &operator%(const LldbVersion &lldbVersion) const
    {
        neededLldbVersion = lldbVersion;
        return *this;
    }

    const Data &operator%(const LldbOnly &) const
    {
        lldbOnly = true;
        return *this;
    }

    const Data &operator%(const GdbOnly &) const
    {
        gdbOnly = true;
        return *this;
    }

hjk's avatar
hjk committed
581
582
583
584
    const Data &operator%(const CoreProfile &) const
    {
        profileExtra +=
            "CONFIG += QT\n"
585
            "QT += core\n";
hjk's avatar
hjk committed
586
587

        useQt = true;
588
589
        useQHash = true;

hjk's avatar
hjk committed
590
591
592
593
594
        return *this;
    }

    const Data &operator%(const GuiProfile &) const
    {
595
        this->operator%(CoreProfile());
hjk's avatar
hjk committed
596
597
598
599
600
601
602
603
604
        profileExtra +=
            "QT += gui\n"
            "greaterThan(QT_MAJOR_VERSION, 4):QT *= widgets\n";

        return *this;
    }

    const Data &operator%(const CorePrivateProfile &) const
    {
605
        this->operator%(CoreProfile());
hjk's avatar
hjk committed
606
607
        profileExtra +=
            "greaterThan(QT_MAJOR_VERSION, 4) {\n"
608
            "  QT += core-private\n"
hjk's avatar
hjk committed
609
610
611
612
613
614
            "  CONFIG += no_private_qt_headers_warning\n"
            "}";

        return *this;
    }

615
616
617
618
619
620
    const Data &operator%(const ForceC &) const
    {
        forceC = true;
        return *this;
    }

hjk's avatar
hjk committed
621
public:
hjk's avatar
hjk committed
622
    mutable QByteArray profileExtra;
623
624
    mutable QByteArray includes;
    mutable QByteArray code;
625
    mutable QList<Check> checks;
hjk's avatar
hjk committed
626
627
};

628
629
630
631
struct TempStuff
{
    TempStuff() : buildTemp(QLatin1String("qt_tst_dumpers_"))
    {
632
        buildPath = QDir::currentPath() + QLatin1Char('/')  + buildTemp.path();
633
634
635
636
637
638
639
640
641
        buildTemp.setAutoRemove(false);
        QVERIFY(!buildPath.isEmpty());
    }

    QByteArray input;
    QTemporaryDir buildTemp;
    QString buildPath;
};

hjk's avatar
hjk committed
642
Q_DECLARE_METATYPE(Data)
hjk's avatar
hjk committed
643

644
class tst_Dumpers : public QObject
645
646
647
648
{
    Q_OBJECT

public:
649
650
651
    tst_Dumpers()
    {
        t = 0;
652
        m_keepTemp = true;
653
        m_forceKeepTemp = false;
654
655
656
657
658
        m_gdbVersion = 0;
        m_gdbBuildVersion = 0;
        m_lldbVersion = 0;
        m_isMacGdb = false;
        m_isQnxGdb = false;
659
        m_useGLibCxxDebug = false;
660
    }
661
662

private slots:
hjk's avatar
hjk committed
663
    void initTestCase();
hjk's avatar
hjk committed
664
665
    void dumper();
    void dumper_data();
666
667
    void init();
    void cleanup();
hjk's avatar
hjk committed
668
669

private:
670
    bool keepTemp() const { return m_keepTemp || m_forceKeepTemp; }
671
    TempStuff *t;
hjk's avatar
hjk committed
672
673
    QByteArray m_debuggerBinary;
    QByteArray m_qmakeBinary;
674
    Environment m_env;
hjk's avatar
hjk committed
675
    bool m_usePython;
676
    DebuggerEngine m_debuggerEngine;
hjk's avatar
hjk committed
677
    bool m_keepTemp;
678
    bool m_forceKeepTemp;
679
680
    int m_gdbVersion; // 7.5.1 -> 70501
    int m_gdbBuildVersion;
681
    int m_lldbVersion;
682
683
    bool m_isMacGdb;
    bool m_isQnxGdb;
684
    bool m_useGLibCxxDebug;
hjk's avatar
hjk committed
685
686
687
688
};

void tst_Dumpers::initTestCase()
{
689
    m_debuggerBinary = qgetenv("QTC_DEBUGGER_PATH_FOR_TEST");
hjk's avatar
hjk committed
690
691
    if (m_debuggerBinary.isEmpty())
        m_debuggerBinary = "gdb";
692
    qDebug() << "Debugger           : " << m_debuggerBinary.constData();
693

694
    m_debuggerEngine = DumpTestGdbEngine;
695
    if (m_debuggerBinary.endsWith("cdb.exe"))
696
        m_debuggerEngine = DumpTestCdbEngine;
697

698
    if (m_debuggerBinary.endsWith("lldb"))
699
        m_debuggerEngine = DumpTestLldbEngine;
hjk's avatar
hjk committed
700

hjk's avatar
hjk committed
701
    m_qmakeBinary = qgetenv("QTC_QMAKE_PATH_FOR_TEST");
hjk's avatar
hjk committed
702
703
    if (m_qmakeBinary.isEmpty())
        m_qmakeBinary = "qmake";
704
705
706
707
708
709
710
    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
711

712
    m_env = Environment::systemEnvironment();
713

714
    if (m_debuggerEngine == DumpTestGdbEngine) {
715
716
717
718
719
720
721
722
723
724
        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");
725
726
        qDebug() << "Python             : " << (m_usePython ? "ok" : "*** not ok ***");
        qDebug() << "Dumper dir         : " << DUMPERDIR;
727
728
729
730
731
732
733
734
735

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

771
void tst_Dumpers::init()
hjk's avatar
hjk committed
772
{
773
    t = new TempStuff();
hjk's avatar
hjk committed
774
775
}

776
void tst_Dumpers::cleanup()
hjk's avatar
hjk committed
777
{
778
779
    if (!t->buildTemp.autoRemove()) {
        QFile logger(t->buildPath + QLatin1String("/input.txt"));
hjk's avatar
hjk committed
780
        logger.open(QIODevice::ReadWrite);
781
        logger.write(t->input);
hjk's avatar
hjk committed
782
    }
783
784
    delete t;
}
785

hjk's avatar
hjk committed
786
787
788
789
void tst_Dumpers::dumper()
{
    QFETCH(Data, data);

790
    if (m_debuggerEngine == DumpTestGdbEngine) {
791
        if (data.neededGdbVersion.min > m_gdbVersion)
hjk's avatar
hjk committed
792
793
            MSKIP_SINGLE("Need minimum GDB version "
                + QByteArray::number(data.neededGdbVersion.min));
794
        if (data.neededGdbVersion.max < m_gdbVersion)
hjk's avatar
hjk committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
            MSKIP_SINGLE("Need maximum GDB version "
                + QByteArray::number(data.neededGdbVersion.max));
    } else {
        if (data.gdbOnly)
            MSKIP_SINGLE("Test is GDB specific");
    }

    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));
    } else {
        if (data.lldbOnly)
            MSKIP_SINGLE("Test is LLDB specific");
812
    }
813

hjk's avatar
hjk committed
814
815
816
817
    QString cmd;
    QByteArray output;
    QByteArray error;

818
819
    const char *mainFile = data.forceC ? "main.c" : "main.cpp";

820
821
    QFile proFile(t->buildPath + QLatin1String("/doit.pro"));
    QVERIFY(proFile.open(QIODevice::ReadWrite));
822
823
824
    proFile.write("SOURCES = ");
    proFile.write(mainFile);
    proFile.write("\nTARGET = doit\n");
825
    proFile.write("\nCONFIG -= app_bundle\n");
826
827
    proFile.write("\nCONFIG -= release\n");
    proFile.write("\nCONFIG += debug\n");
hjk's avatar
hjk committed
828
829
830
831
    if (data.useQt)
        proFile.write("QT -= widgets gui\n");
    else
        proFile.write("CONFIG -= QT\n");
832
833
    if (m_useGLibCxxDebug)
        proFile.write("DEFINES += _GLIBCXX_DEBUG\n");
hjk's avatar
hjk committed
834
    proFile.write(data.profileExtra);
hjk's avatar
hjk committed
835
836
    proFile.close();

837
838
    QFile source(t->buildPath + QLatin1Char('/') + QLatin1String(mainFile));
    QVERIFY(source.open(QIODevice::ReadWrite));
hjk's avatar
hjk committed
839
    QByteArray fullCode =
hjk's avatar
hjk committed
840
            "\n\nvoid unused(const void *first,...) { (void) first; }"
hjk's avatar
hjk committed
841
            "\n\nvoid breakHere() {}"
hjk's avatar
hjk committed
842
            "\n\n" + data.includes +
843
844
845
846
847
848
849
            "\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
850
            "\n\nint main(int argc, char *argv[])"
hjk's avatar
hjk committed
851
            "\n{"
852
            "\n    int qtversion = " + (data.useQt ? "QT_VERSION" : "0") + ";"
hjk's avatar
hjk committed
853
854
855
856
857
            "\n#ifdef __GNUC__"
            "\n    int gccversion = 0x10000 * __GNUC__ + 0x100 * __GNUC_MINOR__;"
            "\n#else"
            "\n    int gccversion = 0;"
            "\n#endif"
858
859
            "\n" + (data.useQHash ?
                "\n#if QT_VERSION >= 0x050000"
860
                "\nqt_qhash_seed.store(0);"
861
                "\n#endif\n" : "") +
hjk's avatar
hjk committed
862
            "\n    unused(&argc, &argv, &qtversion, &gccversion);\n"
hjk's avatar
hjk committed
863
864
            "\n" + data.code +
            "\n    breakHere();"
865
            "\n    return 0;"
hjk's avatar
hjk committed
866
867
            "\n}\n";
    source.write(fullCode);
hjk's avatar
hjk committed
868
869
870
    source.close();

    QProcess qmake;
871
    qmake.setWorkingDirectory(t->buildPath);
hjk's avatar
hjk committed
872
    cmd = QString::fromLatin1(m_qmakeBinary);
hjk's avatar
hjk committed
873
874
    //qDebug() << "Starting qmake: " << cmd;
    qmake.start(cmd);
875
    QVERIFY(qmake.waitForFinished());
hjk's avatar
hjk committed
876
877
878
    output = qmake.readAllStandardOutput();
    error = qmake.readAllStandardError();
    //qDebug() << "stdout: " << output;
879
    if (!error.isEmpty()) { qDebug() << error; QVERIFY(false); }
hjk's avatar
hjk committed
880
881

    QProcess make;
882
    make.setWorkingDirectory(t->buildPath);
883
884
885
886
887
888
    make.setProcessEnvironment(m_env.toProcessEnvironment());

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

    make.start(cmd, QStringList());
889
    QVERIFY(make.waitForFinished());
hjk's avatar
hjk committed
890
891
892
    output = make.readAllStandardOutput();
    error = make.readAllStandardError();
    //qDebug() << "stdout: " << output;
893
    if (make.exitCode()) {
hjk's avatar
hjk committed
894
895
896
897
898
899
        qDebug() << error;
        qDebug() << "\n------------------ CODE --------------------";
        qDebug() << fullCode;
        qDebug() << "\n------------------ CODE --------------------";
        qDebug() << ".pro: " << qPrintable(proFile.fileName());
    }
hjk's avatar
hjk committed
900
901
902

    QByteArray dumperDir = DUMPERDIR;

903
904
905
    QSet<QByteArray> expandedINames;
    expandedINames.insert("local");
    foreach (const Check &check, data.checks) {
hjk's avatar
hjk committed
906
907
908
909
910
911
912
        QByteArray parent = check.iname;
        while (true) {
            parent = parentIName(parent);
            if (parent.isEmpty())
                break;
            expandedINames.insert("local." + parent);
        }
913
914
915
916
917
918
919
920
921
    }

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

922
    QByteArray exe;
923
    QStringList args;
924
    QByteArray cmds;
925

926
    if (m_debuggerEngine == DumpTestGdbEngine) {
927
        exe = m_debuggerBinary;
hjk's avatar
hjk committed
928
929
930
931

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

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

963
    } else if (m_debuggerEngine == DumpTestCdbEngine) {
964
        exe = m_debuggerBinary;
965
966
967
968
969
970
971
972
973
974
975
976
        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"
977
978
979
980
981
982
983
               "!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)
984
985
            cmds += "!qtcreatorcdbext.locals -t " + QByteArray::number(++token)
                    + " -c 0 " + iName.toLatin1() + "\n";
986
        cmds += "q\n";
987
    } else if (m_debuggerEngine == DumpTestLldbEngine) {
988
        exe = "python";
989
        args << QLatin1String(dumperDir + "/lldbbridge.py")
990
             << QString::fromUtf8(m_debuggerBinary)
991
992
993
             << t->buildPath + QLatin1String("/doit")
             << QString::fromUtf8(expanded);
        //qDebug() << exe.constData() << ' ' << qPrintable(args.join(QLatin1Char(' ')));
994
    }
hjk's avatar
hjk committed
995

996
    t->input = cmds;
hjk's avatar
hjk committed
997

hjk's avatar
hjk committed
998
    QProcess debugger;
999
    debugger.setProcessEnvironment(m_env.toProcessEnvironment());
1000
    debugger.setWorkingDirectory(t->buildPath);
For faster browsing, not all history is shown. View entire blame