msvctoolchain.cpp 33.9 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
** 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
12
13
14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16
17
18
19
20
21
22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
25
26

#include "msvctoolchain.h"
27

28
29
30
#include "msvcparser.h"
#include "projectexplorerconstants.h"

31
#include <utils/algorithm.h>
32
#include <utils/synchronousprocess.h>
33
#include <utils/winutils.h>
SteveKing's avatar
SteveKing committed
34
#include <utils/qtcassert.h>
Daniel Teske's avatar
Daniel Teske committed
35
#include <utils/hostosinfo.h>
36

37
#include <QDir>
38
#include <QFileInfo>
39
40
#include <QProcess>
#include <QSettings>
41
42

#include <QLabel>
43
#include <QFormLayout>
44

45
46
47
48
#define KEY_ROOT "ProjectExplorer.MsvcToolChain."
static const char varsBatKeyC[] = KEY_ROOT"VarsBat";
static const char varsBatArgKeyC[] = KEY_ROOT"VarsBatArg";
static const char supportedAbiKeyC[] = KEY_ROOT"SupportedAbi";
49

Friedemann Kleint's avatar
Friedemann Kleint committed
50
51
enum { debug = 0 };

52
53
54
55
56
57
58
59
60
61
namespace ProjectExplorer {
namespace Internal {

// --------------------------------------------------------------------------
// Helpers:
// --------------------------------------------------------------------------

static QString platformName(MsvcToolChain::Platform t)
{
    switch (t) {
62
    case MsvcToolChain::x86:
63
        return QLatin1String("x86");
64
    case MsvcToolChain::amd64:
65
66
67
        return QLatin1String("amd64");
    case MsvcToolChain::x86_amd64:
        return QLatin1String("x86_amd64");
68
    case MsvcToolChain::ia64:
69
70
71
        return QLatin1String("ia64");
    case MsvcToolChain::x86_ia64:
        return QLatin1String("x86_ia64");
Daniel Teske's avatar
Daniel Teske committed
72
    case MsvcToolChain::arm:
73
74
75
76
77
        return QLatin1String("arm");
    case MsvcToolChain::x86_arm:
        return QLatin1String("x86_arm");
    case MsvcToolChain::amd64_arm:
        return QLatin1String("amd64_arm");
78
79
80
81
    }
    return QString();
}

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
static bool hostSupportsPlatform(MsvcToolChain::Platform platform)
{
    switch (Utils::HostOsInfo::hostArchitecture()) {
    case Utils::HostOsInfo::HostArchitectureAMD64:
        if (platform == MsvcToolChain::amd64 || platform == MsvcToolChain::amd64_arm)
            return true;
        // fall through (all x86 toolchains are also working on an amd64 host)
    case Utils::HostOsInfo::HostArchitectureX86:
        return platform == MsvcToolChain::x86 || platform == MsvcToolChain::x86_amd64
                || platform == MsvcToolChain::x86_ia64 || platform == MsvcToolChain::x86_arm;
    case Utils::HostOsInfo::HostArchitectureArm:
        return platform == MsvcToolChain::arm;
    case Utils::HostOsInfo::HostArchitectureItanium:
        return platform == MsvcToolChain::ia64;
    default:
        return false;
    }
}

101
102
103
104
105
106
107
108
static Abi findAbiOfMsvc(MsvcToolChain::Type type, MsvcToolChain::Platform platform, const QString &version)
{
    Abi::Architecture arch = Abi::X86Architecture;
    Abi::OSFlavor flavor = Abi::UnknownFlavor;
    int wordWidth = 64;

    switch (platform)
    {
109
    case MsvcToolChain::x86:
110
111
        wordWidth = 32;
        break;
112
113
    case MsvcToolChain::ia64:
    case MsvcToolChain::x86_ia64:
114
115
        arch = Abi::ItaniumArchitecture;
        break;
116
117
    case MsvcToolChain::amd64:
    case MsvcToolChain::x86_amd64:
Daniel Teske's avatar
Daniel Teske committed
118
        break;
119
120
121
    case MsvcToolChain::arm:
    case MsvcToolChain::x86_arm:
    case MsvcToolChain::amd64_arm:
Daniel Teske's avatar
Daniel Teske committed
122
123
        arch = Abi::ArmArchitecture;
        wordWidth = 32;
124
125
126
127
128
        break;
    };

    QString msvcVersionString = version;
    if (type == MsvcToolChain::WindowsSDK) {
Daniel Teske's avatar
Daniel Teske committed
129
        if (version == QLatin1String("v7.0") || version.startsWith(QLatin1String("6.")))
130
            msvcVersionString = QLatin1String("9.0");
Daniel Teske's avatar
Daniel Teske committed
131
132
        else if (version == QLatin1String("v7.0A") || version == QLatin1String("v7.1"))
            msvcVersionString = QLatin1String("10.0");
133
    }
Joerg Bornemann's avatar
Joerg Bornemann committed
134
135
136
    if (msvcVersionString.startsWith(QLatin1String("14.")))
        flavor = Abi::WindowsMsvc2015Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("12.")))
Yuchen Deng's avatar
Yuchen Deng committed
137
138
        flavor = Abi::WindowsMsvc2013Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("11.")))
Tobias Hunger's avatar
Tobias Hunger committed
139
140
        flavor = Abi::WindowsMsvc2012Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("10.")))
141
        flavor = Abi::WindowsMsvc2010Flavor;
142
    else if (msvcVersionString.startsWith(QLatin1String("9.")))
143
144
145
        flavor = Abi::WindowsMsvc2008Flavor;
    else
        flavor = Abi::WindowsMsvc2005Flavor;
Tobias Hunger's avatar
Tobias Hunger committed
146
147
148
149
150
    const Abi result = Abi(arch, Abi::WindowsOS, flavor, Abi::PEFormat, wordWidth);
    if (!result.isValid())
        qWarning("Unable to completely determine the ABI of MSVC version %s (%s).",
                 qPrintable(version), qPrintable(result.toString()));
    return result;
151
152
}

153
154
155
156
157
158
static QString generateDisplayName(const QString &name,
                                   MsvcToolChain::Type t,
                                   MsvcToolChain::Platform p)
{
    if (t == MsvcToolChain::WindowsSDK) {
        QString sdkName = name;
159
        sdkName += QString::fromLatin1(" (%1)").arg(platformName(p));
160
161
162
163
164
        return sdkName;
    }
    // Comes as "9.0" from the registry
    QString vcName = QLatin1String("Microsoft Visual C++ Compiler ");
    vcName += name;
165
    vcName += QString::fromLatin1(" (%1)").arg(platformName(p));
166
167
168
169
170
171
172
173
174
    return vcName;
}

static QByteArray msvcCompilationFile()
{
    static const char* macros[] = {"_ATL_VER", "_CHAR_UNSIGNED", "__CLR_VER",
                                   "__cplusplus_cli", "__COUNTER__", "__cplusplus",
                                   "_CPPLIB_VER", "_CPPRTTI", "_CPPUNWIND",
                                   "_DEBUG", "_DLL", "__FUNCDNAME__",
175
176
177
178
179
180
181
                                   "__FUNCSIG__", "__FUNCTION__", "_INTEGRAL_MAX_BITS",
                                   "_M_ALPHA", "_M_AAMD64", "_M_CEE", "_M_CEE_PURE",
                                   "_M_CEE_SAFE", "_M_IX86", "_M_IA64",
                                   "_M_IX86_FP", "_M_MPPC", "_M_MRX000",
                                   "_M_PPC", "_M_X64", "_MANAGED",
                                   "_MFC_VER", "_MSC_BUILD", "_MSC_EXTENSIONS",
                                   "_MSC_FULL_VER", "_MSC_VER", "__MSVC_RUNTIME_CHECKS",
182
183
                                   "_MT", "_NATIVE_WCHAR_T_DEFINED", "_OPENMP",
                                   "_VC_NODEFAULTLIB", "_WCHAR_T_DEFINED", "_WIN32",
184
                                   "_WIN32_WCE", "_WIN64", "_Wp64",
185
186
187
188
189
190
191
192
193
194
195
196
197
                                   "__DATE__", "__TIME__", "__TIMESTAMP__",
                                   0};
    QByteArray file = "#define __PPOUT__(x) V##x=x\n\n";
    for (int i = 0; macros[i] != 0; ++i) {
        const QByteArray macro(macros[i]);
        file += "#if defined(" + macro + ")\n__PPOUT__("
                + macro + ")\n#endif\n";
    }
    file += "\nvoid main(){}\n\n";
    return file;
}

// Run MSVC 'cl' compiler to obtain #defines.
198
199
QByteArray MsvcToolChain::msvcPredefinedMacros(const QStringList cxxflags,
                                               const Utils::Environment &env) const
200
{
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    QByteArray predefinedMacros = AbstractMsvcToolChain::msvcPredefinedMacros(cxxflags, env);

    QStringList toProcess;
    foreach (const QString &arg, cxxflags) {
        if (arg.startsWith(QLatin1String("/D"))) {
            QString define = arg.mid(2);
            int pos = define.indexOf(QLatin1Char('='));
            if (pos < 0) {
                predefinedMacros += "#define ";
                predefinedMacros += define.toLocal8Bit();
                predefinedMacros += '\n';
            } else {
                predefinedMacros += "#define ";
                predefinedMacros += define.left(pos).toLocal8Bit();
                predefinedMacros += ' ';
                predefinedMacros += define.mid(pos + 1).toLocal8Bit();
                predefinedMacros += '\n';
            }
        } else if (arg.startsWith(QLatin1String("/U"))) {
            predefinedMacros += "#undef ";
            predefinedMacros += arg.mid(2).toLocal8Bit();
            predefinedMacros += '\n';
223
224
        } else if (arg.startsWith(QLatin1String("-I"))) {
            // Include paths should not have any effect on defines
225
226
227
228
        } else {
            toProcess.append(arg);
        }
    }
229

230
    Utils::TempFileSaver saver(QDir::tempPath() + QLatin1String("/envtestXXXXXX.cpp"));
231
232
233
234
    saver.write(msvcCompilationFile());
    if (!saver.finalize()) {
        qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString()));
        return predefinedMacros;
235
236
    }
    QProcess cpp;
Friedemann Kleint's avatar
Friedemann Kleint committed
237
    cpp.setEnvironment(env.toStringList());
238
239
    cpp.setWorkingDirectory(QDir::tempPath());
    QStringList arguments;
240
    const Utils::FileName binary = env.searchInPath(QLatin1String("cl.exe"));
Friedemann Kleint's avatar
Friedemann Kleint committed
241
242
243
244
245
    if (binary.isEmpty()) {
        qWarning("%s: The compiler binary cl.exe could not be found in the path.", Q_FUNC_INFO);
        return predefinedMacros;
    }

246
    arguments << toProcess << QLatin1String("/EP") << QDir::toNativeSeparators(saver.fileName());
247
    cpp.start(binary.toString(), arguments);
248
    if (!cpp.waitForStarted()) {
249
        qWarning("%s: Cannot start '%s': %s", Q_FUNC_INFO, qPrintable(binary.toUserOutput()),
250
251
252
253
254
255
            qPrintable(cpp.errorString()));
        return predefinedMacros;
    }
    cpp.closeWriteChannel();
    if (!cpp.waitForFinished()) {
        Utils::SynchronousProcess::stopProcess(cpp);
256
        qWarning("%s: Timeout running '%s'.", Q_FUNC_INFO, qPrintable(binary.toUserOutput()));
257
258
259
        return predefinedMacros;
    }
    if (cpp.exitStatus() != QProcess::NormalExit) {
260
        qWarning("%s: '%s' crashed.", Q_FUNC_INFO, qPrintable(binary.toUserOutput()));
261
262
263
264
265
266
267
268
269
        return predefinedMacros;
    }

    const QList<QByteArray> output = cpp.readAllStandardOutput().split('\n');
    foreach (const QByteArray& line, output) {
        if (line.startsWith('V')) {
            QList<QByteArray> split = line.split('=');
            const QByteArray key = split.at(0).mid(1);
            QByteArray value = split.at(1);
270
            if (!value.isEmpty())
271
272
273
274
275
276
277
278
                value.chop(1); //remove '\n'
            predefinedMacros += "#define ";
            predefinedMacros += key;
            predefinedMacros += ' ';
            predefinedMacros += value;
            predefinedMacros += '\n';
        }
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
279
280
    if (debug)
        qDebug() << "msvcPredefinedMacros" << predefinedMacros;
281
282
283
    return predefinedMacros;
}

Friedemann Kleint's avatar
Friedemann Kleint committed
284
285
286
// Windows: Expand the delayed evaluation references returned by the
// SDK setup scripts: "PATH=!Path!;foo". Some values might expand
// to empty and should not be added
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
static QString winExpandDelayedEnvReferences(QString in, const Utils::Environment &env)
{
    const QChar exclamationMark = QLatin1Char('!');
    for (int pos = 0; pos < in.size(); ) {
        // Replace "!REF!" by its value in process environment
        pos = in.indexOf(exclamationMark, pos);
        if (pos == -1)
            break;
        const int nextPos = in.indexOf(exclamationMark, pos + 1);
        if (nextPos == -1)
            break;
        const QString var = in.mid(pos + 1, nextPos - pos - 1);
        const QString replacement = env.value(var.toUpper());
        in.replace(pos, nextPos + 1 - pos, replacement);
        pos += replacement.size();
    }
    return in;
}

SteveKing's avatar
SteveKing committed
306
Utils::Environment MsvcToolChain::readEnvironmentSetting(Utils::Environment& env) const
307
{
Friedemann Kleint's avatar
Friedemann Kleint committed
308
    Utils::Environment result = env;
309
    if (!QFileInfo::exists(m_vcvarsBat))
Friedemann Kleint's avatar
Friedemann Kleint committed
310
        return result;
311

SteveKing's avatar
SteveKing committed
312
313
    QMap<QString, QString> envPairs;
    if (!generateEnvironmentSettings(env, m_vcvarsBat, m_varsBatArg, envPairs))
314
        return result;
Friedemann Kleint's avatar
Friedemann Kleint committed
315

SteveKing's avatar
SteveKing committed
316
317
    // Now loop through and process them
    QMap<QString,QString>::const_iterator envIter;
318
    for (envIter = envPairs.constBegin(); envIter!=envPairs.constEnd(); ++envIter) {
SteveKing's avatar
SteveKing committed
319
320
321
        const QString expandedValue = winExpandDelayedEnvReferences(envIter.value(), env);
        if (!expandedValue.isEmpty())
            result.set(envIter.key(), expandedValue);
322
323
    }

Friedemann Kleint's avatar
Friedemann Kleint committed
324
325
326
327
328
329
330
331
332
333
    if (debug) {
        const QStringList newVars = result.toStringList();
        const QStringList oldVars = env.toStringList();
        QDebug nsp = qDebug().nospace();
        foreach (const QString &n, newVars) {
            if (!oldVars.contains(n))
                nsp << n << '\n';
        }
    }
    return result;
334
335
336
337
338
339
}

// --------------------------------------------------------------------------
// MsvcToolChain
// --------------------------------------------------------------------------

340
MsvcToolChain::MsvcToolChain(const QString &name, const Abi &abi,
341
                             const QString &varsBat, const QString &varsBatArg, Detection d) :
342
343
344
345
346
347
348
349
350
    MsvcToolChain(Constants::MSVC_TOOLCHAIN_TYPEID, name, abi, varsBat, varsBatArg, d)
{
}

MsvcToolChain::MsvcToolChain(Core::Id typeId, const QString &name, const Abi &abi,
                             const QString &varsBat, const QString &varsBatArg,
                              Detection d)
    : AbstractMsvcToolChain(typeId, d, abi, varsBat)
    , m_varsBatArg(varsBatArg)
351
352
353
{
    Q_ASSERT(!name.isEmpty());

354
    setDisplayName(name);
355
356
}

357
358
359
360
361
bool MsvcToolChain::isValid() const
{
    if (!AbstractMsvcToolChain::isValid())
        return false;
    QString vcVarsBat = MsvcToolChainFactory::vcVarsBatFor(QFileInfo(m_vcvarsBat).absolutePath(), m_varsBatArg);
362
    return QFileInfo::exists(vcVarsBat);
363
364
}

365
366
MsvcToolChain::MsvcToolChain(Core::Id typeId)
    : AbstractMsvcToolChain(typeId, ManualDetection)
367
368
369
{
}

370
MsvcToolChain::MsvcToolChain() : MsvcToolChain(Constants::MSVC_TOOLCHAIN_TYPEID)
371
372
373
{
}

Tobias Hunger's avatar
Tobias Hunger committed
374
QString MsvcToolChain::typeDisplayName() const
375
376
377
378
{
    return MsvcToolChainFactory::tr("MSVC");
}

379
Utils::FileNameList MsvcToolChain::suggestedMkspecList() const
380
{
Tobias Hunger's avatar
Tobias Hunger committed
381
    switch (m_abi.osFlavor()) {
382
    case Abi::WindowsMsvc2005Flavor:
383
        return Utils::FileNameList() << Utils::FileName::fromLatin1("win32-msvc2005");
384
    case Abi::WindowsMsvc2008Flavor:
385
        return Utils::FileNameList() << Utils::FileName::fromLatin1("win32-msvc2008");
386
    case Abi::WindowsMsvc2010Flavor:
387
        return Utils::FileNameList() << Utils::FileName::fromLatin1("win32-msvc2010");
388
    case Abi::WindowsMsvc2012Flavor:
389
        return Utils::FileNameList()
390
391
            << Utils::FileName::fromLatin1("win32-msvc2012")
            << Utils::FileName::fromLatin1("win32-msvc2010");
392
    case Abi::WindowsMsvc2013Flavor:
393
        return Utils::FileNameList()
394
            << Utils::FileName::fromLatin1("win32-msvc2013")
395
396
397
398
399
            << Utils::FileName::fromLatin1("winphone-arm-msvc2013")
            << Utils::FileName::fromLatin1("winphone-x86-msvc2013")
            << Utils::FileName::fromLatin1("winrt-arm-msvc2013")
            << Utils::FileName::fromLatin1("winrt-x86-msvc2013")
            << Utils::FileName::fromLatin1("winrt-x64-msvc2013")
400
401
            << Utils::FileName::fromLatin1("win32-msvc2012")
            << Utils::FileName::fromLatin1("win32-msvc2010");
Joerg Bornemann's avatar
Joerg Bornemann committed
402
    case Abi::WindowsMsvc2015Flavor:
403
        return Utils::FileNameList()
Joerg Bornemann's avatar
Joerg Bornemann committed
404
405
406
407
408
409
            << Utils::FileName::fromLatin1("win32-msvc2015")
            << Utils::FileName::fromLatin1("winphone-arm-msvc2015")
            << Utils::FileName::fromLatin1("winphone-x86-msvc2015")
            << Utils::FileName::fromLatin1("winrt-arm-msvc2015")
            << Utils::FileName::fromLatin1("winrt-x86-msvc2015")
            << Utils::FileName::fromLatin1("winrt-x64-msvc2015");
Tobias Hunger's avatar
Tobias Hunger committed
410
411
412
    default:
        break;
    }
413
    return Utils::FileNameList();
414
415
}

416
417
QVariantMap MsvcToolChain::toMap() const
{
418
    QVariantMap data = AbstractMsvcToolChain::toMap();
SteveKing's avatar
SteveKing committed
419
    data.insert(QLatin1String(varsBatKeyC), m_vcvarsBat);
420
421
422
    if (!m_varsBatArg.isEmpty())
        data.insert(QLatin1String(varsBatArgKeyC), m_varsBatArg);
    data.insert(QLatin1String(supportedAbiKeyC), m_abi.toString());
423
424
425
426
427
428
429
    return data;
}

bool MsvcToolChain::fromMap(const QVariantMap &data)
{
    if (!ToolChain::fromMap(data))
        return false;
430
    m_vcvarsBat = QDir::fromNativeSeparators(data.value(QLatin1String(varsBatKeyC)).toString());
431
432
433
    m_varsBatArg = data.value(QLatin1String(varsBatArgKeyC)).toString();
    const QString abiString = data.value(QLatin1String(supportedAbiKeyC)).toString();
    m_abi = Abi(abiString);
434

SteveKing's avatar
SteveKing committed
435
    return !m_vcvarsBat.isEmpty() && m_abi.isValid();
436
437
}

SteveKing's avatar
SteveKing committed
438

439
440
441
442
443
444
445
ToolChainConfigWidget *MsvcToolChain::configurationWidget()
{
    return new MsvcToolChainConfigWidget(this);
}

ToolChain *MsvcToolChain::clone() const
{
446
    return new MsvcToolChain(*this);
447
448
449
}

// --------------------------------------------------------------------------
450
451
452
// MsvcBasedToolChainConfigWidget: Creates a simple GUI without error label
// to display name and varsBat. Derived classes should add the error label and
// call setFromMsvcToolChain().
453
454
// --------------------------------------------------------------------------

455
456
457
458
MsvcBasedToolChainConfigWidget::MsvcBasedToolChainConfigWidget(ToolChain *tc)
    : ToolChainConfigWidget(tc)
    , m_nameDisplayLabel(new QLabel(this))
    , m_varsBatDisplayLabel(new QLabel(this))
459
{
460
461
    m_nameDisplayLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
    m_mainLayout->addRow(m_nameDisplayLabel);
462
    m_varsBatDisplayLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
463
    m_mainLayout->addRow(tr("Initialization:"), m_varsBatDisplayLabel);
464
465
}

466
void MsvcBasedToolChainConfigWidget::setFromMsvcToolChain()
467
{
468
    const MsvcToolChain *tc = static_cast<const MsvcToolChain *>(toolChain());
469
    QTC_ASSERT(tc, return);
470
    m_nameDisplayLabel->setText(tc->displayName());
471
    QString varsBatDisplay = QDir::toNativeSeparators(tc->varsBat());
472
473
474
475
476
    if (!tc->varsBatArg().isEmpty()) {
        varsBatDisplay += QLatin1Char(' ');
        varsBatDisplay += tc->varsBatArg();
    }
    m_varsBatDisplayLabel->setText(varsBatDisplay);
477
478
}

479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// --------------------------------------------------------------------------
// MsvcToolChainConfigWidget
// --------------------------------------------------------------------------

MsvcToolChainConfigWidget::MsvcToolChainConfigWidget(ToolChain *tc) :
    MsvcBasedToolChainConfigWidget(tc)
{
    addErrorLabel();
    setFromMsvcToolChain();
}

// --------------------------------------------------------------------------
// ClangClToolChainConfigWidget
// --------------------------------------------------------------------------

ClangClToolChainConfigWidget::ClangClToolChainConfigWidget(ToolChain *tc)
    : MsvcBasedToolChainConfigWidget(tc)
    , m_llvmDirLabel(new QLabel(this))
{
    m_llvmDirLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
    m_mainLayout->addRow(tr("LLVM:"), m_llvmDirLabel);
    addErrorLabel();
    setFromClangClToolChain();
}

void ClangClToolChainConfigWidget::setFromClangClToolChain()
{
    setFromMsvcToolChain();
    const ClangClToolChain *tc = static_cast<const ClangClToolChain *>(toolChain());
    QTC_ASSERT(tc, return);
    m_llvmDirLabel->setText(QDir::toNativeSeparators(tc-> llvmDir()));
}

// --------------------------------------------------------------------------
// ClangClToolChain, piggy-backing on MSVC2015 and providing the compiler
// clang-cl.exe as a [to some extent] compatible drop-in replacement for cl.
// --------------------------------------------------------------------------

static const char clangClBinary[] = "clang-cl.exe";

ClangClToolChain::ClangClToolChain(const QString &name, const QString &llvmDir,
                                   const Abi &abi,
                                   const QString &varsBat, const QString &varsBatArg,
                                   Detection d)
    : MsvcToolChain(Constants::CLANG_CL_TOOLCHAIN_TYPEID, name, abi, varsBat, varsBatArg, d)
    , m_llvmDir(llvmDir)
    , m_compiler(Utils::FileName::fromString(m_llvmDir + QStringLiteral("/bin/") + QLatin1String(clangClBinary)))
{
}

ClangClToolChain::ClangClToolChain()
    : MsvcToolChain(Constants::CLANG_CL_TOOLCHAIN_TYPEID)
{
}

bool ClangClToolChain::isValid() const
{
    return MsvcToolChain::isValid() && m_compiler.exists();
}

void ClangClToolChain::addToEnvironment(Utils::Environment &env) const
{
    MsvcToolChain::addToEnvironment(env);
    env.prependOrSetPath(m_llvmDir + QStringLiteral("/bin"));
}

QString ClangClToolChain::typeDisplayName() const
{
    return QCoreApplication::translate("ProjectExplorer::ClangToolChainFactory", "Clang");
}

QList<Utils::FileName> ClangClToolChain::suggestedMkspecList() const
{
    const QString mkspec = QLatin1String("win32-clang-") + Abi::toString(targetAbi().osFlavor());
    return QList<Utils::FileName>{Utils::FileName::fromString(mkspec)};
}

IOutputParser *ClangClToolChain::outputParser() const
{
    return new ClangClParser;
}

ToolChain *ClangClToolChain::clone() const
{
    return new ClangClToolChain(*this);
}

static inline QString llvmDirKey() { return QStringLiteral("ProjectExplorer.ClangClToolChain.LlvmDir"); }

QVariantMap ClangClToolChain::toMap() const
{
    QVariantMap result = MsvcToolChain::toMap();
    result.insert(llvmDirKey(), m_llvmDir);
    return result;
}

bool ClangClToolChain::fromMap(const QVariantMap &data)
{
    if (!MsvcToolChain::fromMap(data))
        return false;
    const QString llvmDir = data.value(llvmDirKey()).toString();
    if (llvmDir.isEmpty())
        return false;
    m_llvmDir = llvmDir;
    return true;
}

ToolChainConfigWidget *ClangClToolChain::configurationWidget()
{
    return new ClangClToolChainConfigWidget(this);
}

591
592
593
594
// --------------------------------------------------------------------------
// MsvcToolChainFactory
// --------------------------------------------------------------------------

595
MsvcToolChainFactory::MsvcToolChainFactory()
596
{
597
    setDisplayName(tr("MSVC"));
598
599
}

600
601
602
603
604
605
606
607
608
609
610
611
612
bool MsvcToolChainFactory::checkForVisualStudioInstallation(const QString &vsName)
{
    const QSettings vsRegistry(
#ifdef Q_OS_WIN64
                QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7"),
#else
                QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7"),
#endif
                QSettings::NativeFormat);

    return vsRegistry.contains(vsName);
}

613
614
QString MsvcToolChainFactory::vcVarsBatFor(const QString &basePath, const QString &toolchainName)
{
615
616
    if (toolchainName.startsWith(QLatin1Char('/'))) // windows sdk case, all use SetEnv.cmd
        return basePath + QLatin1String("/SetEnv.cmd");
617
618
    if (toolchainName == QLatin1String("x86"))
        return basePath + QLatin1String("/bin/vcvars32.bat");
619
620
    if (toolchainName == QLatin1String("amd64_arm"))
        return basePath + QLatin1String("/bin/amd64_arm/vcvarsamd64_arm.bat");
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
    if (toolchainName == QLatin1String("x86_amd64"))
        return basePath + QLatin1String("/bin/x86_amd64/vcvarsx86_amd64.bat");
    if (toolchainName == QLatin1String("amd64"))
        return basePath + QLatin1String("/bin/amd64/vcvars64.bat");
    if (toolchainName == QLatin1String("x86_arm"))
        return basePath + QLatin1String("/bin/x86_arm/vcvarsx86_arm.bat");
    if (toolchainName == QLatin1String("arm"))
        return basePath + QLatin1String("/bin/arm/vcvarsarm.bat");
    if (toolchainName == QLatin1String("ia64"))
        return basePath + QLatin1String("/bin/ia64/vcvars64.bat");
    if (toolchainName == QLatin1String("x86_ia64"))
        return basePath + QLatin1String("/bin/x86_ia64/vcvarsx86_ia64.bat");

    return QString();
}

637
638
639
640
641
QString MsvcToolChainFactory::vcVarsBatFor(const QString &basePath, MsvcToolChain::Platform platform)
{
    return vcVarsBatFor(basePath, platformName(platform));
}

642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
static ToolChain *findOrCreateToolChain(const QList<ToolChain *> &alreadyKnown,
                                        const QString &name, const Abi &abi,
                                        const QString &varsBat, const QString &varsBatArg,
                                        ToolChain::Detection d = ToolChain::ManualDetection)
{
    ToolChain *tc = Utils::findOrDefault(alreadyKnown,
                                         [&varsBat, &varsBatArg](ToolChain *tc) -> bool {
                                              if (tc->typeId() != Constants::MSVC_TOOLCHAIN_TYPEID)
                                                  return false;
                                              auto mtc = static_cast<MsvcToolChain *>(tc);
                                              return mtc->varsBat() == varsBat
                                                      && mtc->varsBatArg() == varsBatArg;
                                         });
    if (!tc)
        tc = new MsvcToolChain(name, abi, varsBat, varsBatArg, d);
    return tc;
}

660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// Detect build tools introduced with MSVC2015
static void detectCppBuildTools(QList<ToolChain *> *list)
{
    struct Entry {
        const char *postFix;
        const char *varsBatArg;
        Abi::Architecture architecture;
        Abi::BinaryFormat format;
        unsigned char wordSize;
    };

    const Entry entries[] = {
        {" (x86)", "x86", Abi::X86Architecture, Abi::PEFormat, 32},
        {" (x64)", "amd64", Abi::X86Architecture, Abi::PEFormat, 64},
        {" (x86_arm)", "x86_arm", Abi::ArmArchitecture, Abi::PEFormat, 32},
        {" (x64_arm)", "amd64_arm", Abi::ArmArchitecture, Abi::PEFormat, 64}
    };

#ifdef Q_OS_WIN64
    const char programFilesC[] = "ProgramFiles(x86)";
#else
    const char programFilesC[] = "ProgramFiles";
#endif
    const QString name = QStringLiteral("Microsoft Visual C++ Build Tools");
    const QString vcVarsBat = QFile::decodeName(qgetenv(programFilesC))
        + QLatin1Char('/') + name + QStringLiteral("/vcbuildtools.bat");
    if (!QFileInfo(vcVarsBat).isFile())
        return;
    const size_t count = sizeof(entries) / sizeof(entries[0]);
    for (size_t i = 0; i < count; ++i) {
        const Entry &e = entries[i];
        const Abi abi(e.architecture, Abi::WindowsOS, Abi::WindowsMsvc2015Flavor,
                      e.format, e.wordSize);
        list->append(new MsvcToolChain(name + QLatin1String(e.postFix), abi,
                                       vcVarsBat, QLatin1String(e.varsBatArg),
                                       ToolChain::AutoDetection));
    }
}

699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
// Detect Clang-cl on top of MSVC2015.
static void detectClangClToolChain(QList<ToolChain *> *list)
{
#ifdef Q_OS_WIN64
    const char registryNode[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\LLVM\\LLVM";
#else
    const char registryNode[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\LLVM\\LLVM";
#endif

    const QSettings registry(QLatin1String(registryNode), QSettings::NativeFormat);
    if (registry.status() != QSettings::NoError)
        return;
    const QString path = QDir::cleanPath(registry.value(QStringLiteral(".")).toString());
    if (path.isEmpty())
        return;
    const unsigned char wordWidth = Utils::is64BitWindowsBinary(path + QStringLiteral("/bin/") + QLatin1String(clangClBinary))
        ? 64 : 32;
    const auto it = std::find_if(list->cbegin(), list->cend(),
                                 [wordWidth] (ToolChain *tc) { const Abi abi = tc->targetAbi();
                                                               return abi.osFlavor() == Abi::WindowsMsvc2015Flavor
                                                                   && wordWidth == abi.wordWidth();} );
    if (it == list->cend())
        qWarning("Unable to find a suitable MSVC version for \"%s\".", qPrintable(QDir::toNativeSeparators(path)));

    const MsvcToolChain *msvcToolChain = static_cast<MsvcToolChain *>(*it);
    const QString name = QStringLiteral("LLVM ") + QString::number(wordWidth)
        + QStringLiteral("bit based on MSVC2015");
    list->append(new ClangClToolChain(name, path, msvcToolChain->targetAbi(),
                                      msvcToolChain->varsBat(), msvcToolChain->varsBatArg(),
                                      ToolChain::AutoDetection));
}

731
QList<ToolChain *> MsvcToolChainFactory::autoDetect(const QList<ToolChain *> &alreadyKnown)
732
733
734
735
{
    QList<ToolChain *> results;

    // 1) Installed SDKs preferred over standalone Visual studio
736
    const QSettings sdkRegistry(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows"),
737
738
739
740
741
742
743
744
745
                                QSettings::NativeFormat);
    const QString defaultSdkPath = sdkRegistry.value(QLatin1String("CurrentInstallFolder")).toString();
    if (!defaultSdkPath.isEmpty()) {
        foreach (const QString &sdkKey, sdkRegistry.childGroups()) {
            const QString name = sdkRegistry.value(sdkKey + QLatin1String("/ProductName")).toString();
            const QString folder = sdkRegistry.value(sdkKey + QLatin1String("/InstallationFolder")).toString();
            if (folder.isEmpty())
                continue;

Yuchen Deng's avatar
Yuchen Deng committed
746
747
748
749
750
            QDir dir(folder);
            if (!dir.cd(QLatin1String("bin")))
                continue;
            QFileInfo fi(dir, QLatin1String("SetEnv.cmd"));
            if (!fi.exists())
751
                continue;
752

Yuchen Deng's avatar
Yuchen Deng committed
753
            QList<ToolChain *> tmp;
754
755
756
757
            tmp.append(findOrCreateToolChain(alreadyKnown,
                                             generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::x86),
                                             findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::x86, sdkKey),
                                             fi.absoluteFilePath(), QLatin1String("/x86"), ToolChain::AutoDetection));
758
            // Add all platforms, cross-compiler is automatically selected by SetEnv.cmd if needed
759
760
761
762
763
764
765
766
            tmp.append(findOrCreateToolChain(alreadyKnown,
                                             generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::amd64),
                                             findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::amd64, sdkKey),
                                             fi.absoluteFilePath(), QLatin1String("/x64"), ToolChain::AutoDetection));
            tmp.append(findOrCreateToolChain(alreadyKnown,
                                             generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::ia64),
                                             findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::ia64, sdkKey),
                                             fi.absoluteFilePath(), QLatin1String("/ia64"), ToolChain::AutoDetection));
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
            // Make sure the default is front.
            if (folder == defaultSdkPath)
                results = tmp + results;
            else
                results += tmp;
        } // foreach
    }

    // 2) Installed MSVCs
    const QSettings vsRegistry(
#ifdef Q_OS_WIN64
                QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7"),
#else
                QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7"),
#endif
                QSettings::NativeFormat);
    foreach (const QString &vsName, vsRegistry.allKeys()) {
        // Scan for version major.minor
        const int dotPos = vsName.indexOf(QLatin1Char('.'));
        if (dotPos == -1)
            continue;
788
789
        if (!checkForVisualStudioInstallation(vsName))
            continue;
790

791
        QString path = QDir::fromNativeSeparators(vsRegistry.value(vsName).toString());
792
793
        if (path.endsWith(QLatin1Char('/')))
            path.chop(1);
794
        const int version = vsName.leftRef(dotPos).toInt();
795
        const QString vcvarsAllbat = path + QLatin1String("/vcvarsall.bat");
Daniel Teske's avatar
Daniel Teske committed
796
        if (QFileInfo(vcvarsAllbat).isFile()) {
797
            QList<MsvcToolChain::Platform> platforms; // prioritized list
798
799
800
            // x86_arm was put before amd64_arm as a workaround for auto detected windows phone
            // toolchains. As soon as windows phone builds support x64 cross builds, this change
            // can be reverted.
801
802
            platforms << MsvcToolChain::x86
                      << MsvcToolChain::amd64 << MsvcToolChain::x86_amd64
803
                      << MsvcToolChain::arm << MsvcToolChain::x86_arm << MsvcToolChain::amd64_arm
804
805
806
807
                      << MsvcToolChain::ia64 << MsvcToolChain::x86_ia64;
            foreach (const MsvcToolChain::Platform &platform, platforms) {
                if (hostSupportsPlatform(platform)
                        && QFileInfo(vcVarsBatFor(path, platform)).isFile()) {
808
809
                    results.append(findOrCreateToolChain(
                                       alreadyKnown,
810
811
                                       generateDisplayName(vsName, MsvcToolChain::VS, platform),
                                       findAbiOfMsvc(MsvcToolChain::VS, platform, vsName),
812
                                       vcvarsAllbat, platformName(platform),
813
                                       ToolChain::AutoDetection));
Daniel Teske's avatar
Daniel Teske committed
814
815
                }
            }
816
        } else {
Daniel Teske's avatar
Daniel Teske committed
817
            qWarning("Unable to find MSVC setup script %s in version %d", qPrintable(vcvarsAllbat), version);
818
819
        }
    }
SteveKing's avatar
SteveKing committed
820

821
822
    detectCppBuildTools(&results);

823
824
    detectClangClToolChain(&results);

825
826
827
    return results;
}

828
829
830
831
832
833
834
835
bool MsvcToolChain::operator ==(const ToolChain &other) const
{
    if (!AbstractMsvcToolChain::operator ==(other))
        return false;
    const MsvcToolChain *msvcTc = static_cast<const MsvcToolChain *>(&other);
    return m_varsBatArg == msvcTc->m_varsBatArg;
}

836
837
bool MsvcToolChainFactory::canRestore(const QVariantMap &data)
{
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
    const Core::Id id = typeIdFromMap(data);
    return id == Constants::MSVC_TOOLCHAIN_TYPEID || id == Constants::CLANG_CL_TOOLCHAIN_TYPEID;
}

template <class ToolChainType>
ToolChainType *readFromMap(const QVariantMap &data)
{
    ToolChainType *result = new ToolChainType;
    if (result->fromMap(data))
        return result;
    delete result;
    return nullptr;
}

ToolChain *MsvcToolChainFactory::restore(const QVariantMap &data)
{
    const Core::Id id = typeIdFromMap(data);
    if (id == Constants::CLANG_CL_TOOLCHAIN_TYPEID)
        return readFromMap<ClangClToolChain>(data);
    return readFromMap<MsvcToolChain>(data);
858
859
}

860
861
} // namespace Internal
} // namespace ProjectExplorer