msvctoolchain.cpp 27.8 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18 19
**
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
28
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
30 31 32 33
**
**************************************************************************/

#include "msvctoolchain.h"
34

35 36
#include "msvcparser.h"
#include "projectexplorerconstants.h"
37
#include "headerpath.h"
38 39 40 41

#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorersettings.h>

42
#include <utils/fileutils.h>
43
#include <utils/synchronousprocess.h>
44
#include <utils/winutils.h>
SteveKing's avatar
SteveKing committed
45
#include <utils/qtcassert.h>
46

47 48 49 50 51 52
#include <QDir>
#include <QProcess>
#include <QSettings>
#include <QUrl>
#include <QFormLayout>
#include <QDesktopServices>
53

54 55 56 57 58
#define KEY_ROOT "ProjectExplorer.MsvcToolChain."
static const char debuggerCommandKeyC[] = KEY_ROOT"Debugger";
static const char varsBatKeyC[] = KEY_ROOT"VarsBat";
static const char varsBatArgKeyC[] = KEY_ROOT"VarsBatArg";
static const char supportedAbiKeyC[] = KEY_ROOT"SupportedAbi";
59

Friedemann Kleint's avatar
Friedemann Kleint committed
60 61
enum { debug = 0 };

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
namespace ProjectExplorer {
namespace Internal {

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

static QString platformName(MsvcToolChain::Platform t)
{
    switch (t) {
    case MsvcToolChain::s32:
        return QLatin1String(" (x86)");
    case MsvcToolChain::s64:
        return QLatin1String(" (x64)");
    case MsvcToolChain::ia64:
        return QLatin1String(" (ia64)");
    case MsvcToolChain::amd64:
        return QLatin1String(" (amd64)");
    }
    return QString();
}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
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)
    {
    case ProjectExplorer::Internal::MsvcToolChain::s32:
        wordWidth = 32;
        break;
    case ProjectExplorer::Internal::MsvcToolChain::ia64:
        arch = Abi::ItaniumArchitecture;
        break;
    case ProjectExplorer::Internal::MsvcToolChain::s64:
    case ProjectExplorer::Internal::MsvcToolChain::amd64:
        break;
    };

    QString msvcVersionString = version;
    if (type == MsvcToolChain::WindowsSDK) {
105 106 107 108 109 110
        if (version.startsWith(QLatin1String("7.")))
            msvcVersionString = QLatin1String("10.0");
        else if (version.startsWith(QLatin1String("6.1"))
                 || (version.startsWith(QLatin1String("6.0")) && version != QLatin1String("6.0")))
            // The 6.0 SDK is shipping MSVC2005, Starting at 6.0a it is MSVC2008.
            msvcVersionString = QLatin1String("9.0");
111
        else
112
            msvcVersionString = QLatin1String("8.0");
113
    }
114
    if (msvcVersionString.startsWith(QLatin1String("10.")))
115
        flavor = Abi::WindowsMsvc2010Flavor;
116
    else if (msvcVersionString.startsWith(QLatin1String("9.")))
117 118 119 120 121 122 123
        flavor = Abi::WindowsMsvc2008Flavor;
    else
        flavor = Abi::WindowsMsvc2005Flavor;

    return Abi(arch, Abi::WindowsOS, flavor, Abi::PEFormat, wordWidth);
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
static QString generateDisplayName(const QString &name,
                                   MsvcToolChain::Type t,
                                   MsvcToolChain::Platform p)
{
    if (t == MsvcToolChain::WindowsSDK) {
        QString sdkName = name;
        sdkName += platformName(p);
        return sdkName;
    }
    // Comes as "9.0" from the registry
    QString vcName = QLatin1String("Microsoft Visual C++ Compiler ");
    vcName += name;
    vcName += platformName(p);
    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__",
146 147 148 149 150 151 152
                                   "__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",
153 154
                                   "_MT", "_NATIVE_WCHAR_T_DEFINED", "_OPENMP",
                                   "_VC_NODEFAULTLIB", "_WCHAR_T_DEFINED", "_WIN32",
155
                                   "_WIN32_WCE", "_WIN64", "_Wp64",
156 157 158 159 160 161 162 163 164 165 166 167 168
                                   "__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.
169 170
QByteArray MsvcToolChain::msvcPredefinedMacros(const QStringList cxxflags,
                                               const Utils::Environment &env) const
171
{
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    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';
        } else {
            toProcess.append(arg);
        }
    }
198

199
    Utils::TempFileSaver saver(QDir::tempPath() + QLatin1String("/envtestXXXXXX.cpp"));
200 201 202 203
    saver.write(msvcCompilationFile());
    if (!saver.finalize()) {
        qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString()));
        return predefinedMacros;
204 205
    }
    QProcess cpp;
Friedemann Kleint's avatar
Friedemann Kleint committed
206
    cpp.setEnvironment(env.toStringList());
207 208
    cpp.setWorkingDirectory(QDir::tempPath());
    QStringList arguments;
Friedemann Kleint's avatar
Friedemann Kleint committed
209 210 211 212 213 214
    const QString binary = env.searchInPath(QLatin1String("cl.exe"));
    if (binary.isEmpty()) {
        qWarning("%s: The compiler binary cl.exe could not be found in the path.", Q_FUNC_INFO);
        return predefinedMacros;
    }

215
    arguments << toProcess << QLatin1String("/EP") << QDir::toNativeSeparators(saver.fileName());
Friedemann Kleint's avatar
Friedemann Kleint committed
216
    cpp.start(binary, arguments);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    if (!cpp.waitForStarted()) {
        qWarning("%s: Cannot start '%s': %s", Q_FUNC_INFO, qPrintable(binary),
            qPrintable(cpp.errorString()));
        return predefinedMacros;
    }
    cpp.closeWriteChannel();
    if (!cpp.waitForFinished()) {
        Utils::SynchronousProcess::stopProcess(cpp);
        qWarning("%s: Timeout running '%s'.", Q_FUNC_INFO, qPrintable(binary));
        return predefinedMacros;
    }
    if (cpp.exitStatus() != QProcess::NormalExit) {
        qWarning("%s: '%s' crashed.", Q_FUNC_INFO, qPrintable(binary));
        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);
            if (!value.isEmpty()) {
                value.chop(1); //remove '\n'
            }
            predefinedMacros += "#define ";
            predefinedMacros += key;
            predefinedMacros += ' ';
            predefinedMacros += value;
            predefinedMacros += '\n';
        }
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
249 250
    if (debug)
        qDebug() << "msvcPredefinedMacros" << predefinedMacros;
251 252 253
    return predefinedMacros;
}

Friedemann Kleint's avatar
Friedemann Kleint committed
254 255 256
// 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
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
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
276
Utils::Environment MsvcToolChain::readEnvironmentSetting(Utils::Environment& env) const
277
{
Friedemann Kleint's avatar
Friedemann Kleint committed
278
    Utils::Environment result = env;
SteveKing's avatar
SteveKing committed
279
    if (!QFileInfo(m_vcvarsBat).exists())
Friedemann Kleint's avatar
Friedemann Kleint committed
280
        return result;
281

SteveKing's avatar
SteveKing committed
282 283
    QMap<QString, QString> envPairs;
    if (!generateEnvironmentSettings(env, m_vcvarsBat, m_varsBatArg, envPairs))
284
        return result;
Friedemann Kleint's avatar
Friedemann Kleint committed
285

SteveKing's avatar
SteveKing committed
286 287 288 289 290 291
    // Now loop through and process them
    QMap<QString,QString>::const_iterator envIter;
    for (envIter = envPairs.begin(); envIter!=envPairs.end(); ++envIter) {
        const QString expandedValue = winExpandDelayedEnvReferences(envIter.value(), env);
        if (!expandedValue.isEmpty())
            result.set(envIter.key(), expandedValue);
292 293
    }

Friedemann Kleint's avatar
Friedemann Kleint committed
294 295 296 297 298 299 300 301 302 303
    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;
304 305 306 307 308 309
}

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

310
MsvcToolChain::MsvcToolChain(const QString &name, const Abi &abi,
311
                             const QString &varsBat, const QString &varsBatArg, bool autodetect) :
SteveKing's avatar
SteveKing committed
312 313
    AbstractMsvcToolChain(QLatin1String(Constants::MSVC_TOOLCHAIN_ID), autodetect, abi, varsBat),
    m_varsBatArg(varsBatArg)
314 315 316
{
    Q_ASSERT(!name.isEmpty());

317
    setDisplayName(name);
318 319
}

320
MsvcToolChain::MsvcToolChain() :
SteveKing's avatar
SteveKing committed
321
    AbstractMsvcToolChain(QLatin1String(Constants::MSVC_TOOLCHAIN_ID), false)
322 323 324 325 326 327 328 329 330 331 332 333
{
}

MsvcToolChain *MsvcToolChain::readFromMap(const QVariantMap &data)
{
    MsvcToolChain *tc = new MsvcToolChain;
    if (tc->fromMap(data))
        return tc;
    delete tc;
    return 0;
}

334
QString MsvcToolChain::legacyId() const
335 336 337 338
{
    const QChar colon = QLatin1Char(':');
    QString id = QLatin1String(Constants::MSVC_TOOLCHAIN_ID);
    id += colon;
SteveKing's avatar
SteveKing committed
339
    id += m_vcvarsBat;
340 341 342
    id += colon;
    id += m_varsBatArg;
    id += colon;
343
    id += m_debuggerCommand.toString();
344
    return id;
345 346
}

Tobias Hunger's avatar
Tobias Hunger committed
347 348 349 350 351 352
QString MsvcToolChain::type() const
{
    return QLatin1String("msvc");
}

QString MsvcToolChain::typeDisplayName() const
353 354 355 356
{
    return MsvcToolChainFactory::tr("MSVC");
}

357
QList<Utils::FileName> MsvcToolChain::suggestedMkspecList() const
358 359
{
    if (m_abi.osFlavor() == Abi::WindowsMsvc2005Flavor)
360
        return QList<Utils::FileName>() << Utils::FileName::fromString(QLatin1String("win32-msvc2005"));
361
    if (m_abi.osFlavor() == Abi::WindowsMsvc2008Flavor)
362
        return QList<Utils::FileName>() << Utils::FileName::fromString(QLatin1String("win32-msvc2008"));
363
    if (m_abi.osFlavor() == Abi::WindowsMsvc2010Flavor)
364 365
        return QList<Utils::FileName>() << Utils::FileName::fromString(QLatin1String("win32-msvc2010"));
    return QList<Utils::FileName>();
366 367
}

368 369 370
QVariantMap MsvcToolChain::toMap() const
{
    QVariantMap data = ToolChain::toMap();
371
    if (!m_debuggerCommand.isEmpty())
372
        data.insert(QLatin1String(debuggerCommandKeyC), m_debuggerCommand.toString());
SteveKing's avatar
SteveKing committed
373
    data.insert(QLatin1String(varsBatKeyC), m_vcvarsBat);
374 375 376
    if (!m_varsBatArg.isEmpty())
        data.insert(QLatin1String(varsBatArgKeyC), m_varsBatArg);
    data.insert(QLatin1String(supportedAbiKeyC), m_abi.toString());
377 378 379 380 381 382 383
    return data;
}

bool MsvcToolChain::fromMap(const QVariantMap &data)
{
    if (!ToolChain::fromMap(data))
        return false;
SteveKing's avatar
SteveKing committed
384
    m_vcvarsBat = data.value(QLatin1String(varsBatKeyC)).toString();
385
    m_varsBatArg = data.value(QLatin1String(varsBatArgKeyC)).toString();
386
    m_debuggerCommand = Utils::FileName::fromString(data.value(QLatin1String(debuggerCommandKeyC)).toString());
387 388
    const QString abiString = data.value(QLatin1String(supportedAbiKeyC)).toString();
    m_abi = Abi(abiString);
389

SteveKing's avatar
SteveKing committed
390
    return !m_vcvarsBat.isEmpty() && m_abi.isValid();
391 392
}

SteveKing's avatar
SteveKing committed
393

394 395 396 397 398 399 400
ToolChainConfigWidget *MsvcToolChain::configurationWidget()
{
    return new MsvcToolChainConfigWidget(this);
}

ToolChain *MsvcToolChain::clone() const
{
401
    return new MsvcToolChain(*this);
402 403
}

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
// --------------------------------------------------------------------------
// MsvcDebuggerConfigLabel
// --------------------------------------------------------------------------

static const char dgbToolsDownloadLink32C[] = "http://www.microsoft.com/whdc/devtools/debugging/installx86.Mspx";
static const char dgbToolsDownloadLink64C[] = "http://www.microsoft.com/whdc/devtools/debugging/install64bit.Mspx";

QString MsvcDebuggerConfigLabel::labelText()
{
#ifdef Q_OS_WIN
    const bool is64bit = Utils::winIs64BitSystem();
#else
    const bool is64bit = false;
#endif
    const QString link = is64bit ? QLatin1String(dgbToolsDownloadLink64C) : QLatin1String(dgbToolsDownloadLink32C);
    //: Label text for path configuration. %2 is "x-bit version".
    return tr(
    "<html><body><p>Specify the path to the "
    "<a href=\"%1\">Windows Console Debugger executable</a>"
    " (%2) here.</p>"
    "</body></html>").arg(link, (is64bit ? tr("64-bit version")
                                         : tr("32-bit version")));
}

MsvcDebuggerConfigLabel::MsvcDebuggerConfigLabel(QWidget *parent) :
        QLabel(labelText(), parent)
{
    connect(this, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString)));
    setTextInteractionFlags(Qt::TextBrowserInteraction);
}

void MsvcDebuggerConfigLabel::slotLinkActivated(const QString &link)
{
    QDesktopServices::openUrl(QUrl(link));
}

440 441 442 443 444
// --------------------------------------------------------------------------
// MsvcToolChainConfigWidget
// --------------------------------------------------------------------------

MsvcToolChainConfigWidget::MsvcToolChainConfigWidget(ToolChain *tc) :
445 446
    ToolChainConfigWidget(tc),
    m_varsBatDisplayLabel(new QLabel(this))
447
{
448 449
    QFormLayout *formLayout = new QFormLayout(this);
    formLayout->addRow(new QLabel(tc->displayName()));
450 451
    m_varsBatDisplayLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
    formLayout->addRow(tr("Initialization:"), m_varsBatDisplayLabel);
452
    formLayout->addRow(new MsvcDebuggerConfigLabel);
453 454
    addDebuggerCommandControls(formLayout, QStringList(QLatin1String("-version")));
    addDebuggerAutoDetection(this, SLOT(autoDetectDebugger()));
455
    addMkspecControls(formLayout);
456 457
    addErrorLabel(formLayout);
    setFromToolChain();
458 459 460 461
}

void MsvcToolChainConfigWidget::apply()
{
462 463 464
    MsvcToolChain *tc = static_cast<MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return; );
    tc->setDebuggerCommand(debuggerCommand());
465
    tc->setMkspecList(mkspecList());
466 467
}

468
void MsvcToolChainConfigWidget::setFromToolChain()
469
{
470 471
    MsvcToolChain *tc = static_cast<MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return);
472 473 474 475 476 477
    QString varsBatDisplay = tc->varsBat();
    if (!tc->varsBatArg().isEmpty()) {
        varsBatDisplay += QLatin1Char(' ');
        varsBatDisplay += tc->varsBatArg();
    }
    m_varsBatDisplayLabel->setText(varsBatDisplay);
478
    setDebuggerCommand(tc->debuggerCommand());
479
    setMkspecList(tc->mkspecList());
480 481 482 483
}

bool MsvcToolChainConfigWidget::isDirty() const
{
484 485
    MsvcToolChain *tc = static_cast<MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return false);
486
    return debuggerCommand() != tc->debuggerCommand()
487
            || mkspecList() != tc->mkspecList();
488 489
}

490 491
void MsvcToolChainConfigWidget::autoDetectDebugger()
{
492 493 494 495 496 497
    clearErrorMessage();

    MsvcToolChain *tc = static_cast<MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return);
    ProjectExplorer::Abi abi = tc->targetAbi();

498 499
    const QPair<Utils::FileName, Utils::FileName> cdbExecutables = MsvcToolChain::autoDetectCdbDebugger();
    Utils::FileName debugger;
500 501 502 503
    if (abi.wordWidth() == 32) {
        if (cdbExecutables.first.isEmpty()) {
            setErrorMessage(tr("No CDB debugger detected (neither 32bit nor 64bit)."));
            return;
504
        }
505 506 507 508 509 510 511 512 513 514 515
        debugger = cdbExecutables.first;
    } else if (abi.wordWidth() == 64) {
        if (cdbExecutables.second.isEmpty()) {
            setErrorMessage(tr("No 64bit CDB debugger detected."));
            return;
        }
        debugger = cdbExecutables.second;
    }
    if (debugger != debuggerCommand()) {
        setDebuggerCommand(debugger);
        emitDirty();
516 517 518
    }
}

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
// --------------------------------------------------------------------------
// MsvcToolChainFactory
// --------------------------------------------------------------------------

QString MsvcToolChainFactory::displayName() const
{
    return tr("MSVC");
}

QString MsvcToolChainFactory::id() const
{
    return QLatin1String(Constants::MSVC_TOOLCHAIN_ID);
}

QList<ToolChain *> MsvcToolChainFactory::autoDetect()
{
    QList<ToolChain *> results;

    // 1) Installed SDKs preferred over standalone Visual studio
538
    const QSettings sdkRegistry(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows"),
539 540 541 542 543
                                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();
544
            const QString version = sdkRegistry.value(sdkKey + QLatin1String("/ProductVersion")).toString();
545 546 547 548 549 550 551 552
            const QString folder = sdkRegistry.value(sdkKey + QLatin1String("/InstallationFolder")).toString();
            if (folder.isEmpty())
                continue;

            const QString sdkVcVarsBat = folder + QLatin1String("bin\\SetEnv.cmd");
            if (!QFileInfo(sdkVcVarsBat).exists())
                continue;
            QList<ToolChain *> tmp;
553 554 555

            tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::s32),
                                         findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::s32, version),
556 557
                                         sdkVcVarsBat, QLatin1String("/x86"), true));
            // Add all platforms
558 559
            tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::s64),
                                         findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::s64, version),
560
                                         sdkVcVarsBat, QLatin1String("/x64"), true));
561 562
            tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::ia64),
                                         findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::ia64, version),
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
                                         sdkVcVarsBat, QLatin1String("/ia64"), true));
            // 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;

        const QString path = vsRegistry.value(vsName).toString();
        const int version = vsName.left(dotPos).toInt();
        // Check existence of various install scripts
        const QString vcvars32bat = path + QLatin1String("bin\\vcvars32.bat");
        if (QFileInfo(vcvars32bat).isFile())
591 592
            results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::s32),
                                             findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::s32, vsName),
593 594 595 596 597
                                             vcvars32bat, QString(), true));
        if (version >= 10) {
            // Just one common file
            const QString vcvarsAllbat = path + QLatin1String("vcvarsall.bat");
            if (QFileInfo(vcvarsAllbat).isFile()) {
598 599
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::s32),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::s32, vsName),
600
                                                 vcvarsAllbat, QLatin1String("x86"), true));
601 602
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
603
                                                 vcvarsAllbat, QLatin1String("amd64"), true));
604 605
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::s64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::s64, vsName),
606
                                                 vcvarsAllbat, QLatin1String("x64"), true));
607 608
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
609 610 611 612 613 614 615 616
                                                 vcvarsAllbat, QLatin1String("ia64"), true));
            } else {
                qWarning("Unable to find MSVC setup script %s in version %d", qPrintable(vcvarsAllbat), version);
            }
        } else {
            // Amd 64 is the preferred 64bit platform
            const QString vcvarsAmd64bat = path + QLatin1String("bin\\amd64\\vcvarsamd64.bat");
            if (QFileInfo(vcvarsAmd64bat).isFile())
617 618
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
619 620 621
                                                 vcvarsAmd64bat, QString(), true));
            const QString vcvarsAmd64bat2 = path + QLatin1String("bin\\vcvarsx86_amd64.bat");
            if (QFileInfo(vcvarsAmd64bat2).isFile())
622 623
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
624 625 626
                                                 vcvarsAmd64bat2, QString(), true));
            const QString vcvars64bat = path + QLatin1String("bin\\vcvars64.bat");
            if (QFileInfo(vcvars64bat).isFile())
627 628
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::s64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::s64, vsName),
629 630 631
                                                 vcvars64bat, QString(), true));
            const QString vcvarsIA64bat = path + QLatin1String("bin\\vcvarsx86_ia64.bat");
            if (QFileInfo(vcvarsIA64bat).isFile())
632 633
                results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
                                                 findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
634 635 636
                                                 vcvarsIA64bat, QString(), true));
        }
    }
637
    if (!results.isEmpty()) { // Detect debugger
638
        const QPair<Utils::FileName, Utils::FileName> cdbDebugger = MsvcToolChain::autoDetectCdbDebugger();
639 640
        foreach (ToolChain *tc, results)
            static_cast<MsvcToolChain *>(tc)->setDebuggerCommand(tc->targetAbi().wordWidth() == 32 ? cdbDebugger.first : cdbDebugger.second);
641
    }
SteveKing's avatar
SteveKing committed
642

643 644 645
    return results;
}

646
QPair<Utils::FileName, Utils::FileName> MsvcToolChain::autoDetectCdbDebugger()
647
{
648 649
    QPair<Utils::FileName, Utils::FileName> result;
    QList<Utils::FileName> cdbs;
650

651 652 653 654
    QStringList programDirs;
    programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles")));
    programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles(x86)")));
    programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramW6432")));
655

656 657 658 659 660 661
    foreach (const QString &dirName, programDirs) {
        if (dirName.isEmpty())
            continue;
        QDir dir(dirName);
        foreach (const QFileInfo &fi, dir.entryInfoList(QStringList(QLatin1String("Debugging Tools for Windows*")),
                                                        QDir::Dirs | QDir::NoDotAndDotDot)) {
662 663
            Utils::FileName filePath(fi);
            filePath.appendPath(QLatin1String("cdb.exe"));
664
            if (!cdbs.contains(filePath))
665
                cdbs.append(filePath);
666
        }
667
    }
668

669 670
    foreach (const Utils::FileName &cdb, cdbs) {
        QList<ProjectExplorer::Abi> abis = ProjectExplorer::Abi::abisOfBinary(cdb);
671 672 673 674 675 676 677 678 679 680 681 682 683
        if (abis.isEmpty())
            continue;
        if (abis.first().wordWidth() == 32)
            result.first = cdb;
        else if (abis.first().wordWidth() == 64)
            result.second = cdb;
    }

    // prefer 64bit debugger, even for 32bit binaries:
    if (!result.second.isEmpty())
        result.first = result.second;

    return result;
684 685
}

686 687 688 689 690 691 692 693
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;
}

694 695 696 697 698
bool MsvcToolChainFactory::canRestore(const QVariantMap &data)
{
    return idFromMap(data).startsWith(QLatin1String(Constants::MSVC_TOOLCHAIN_ID) + QLatin1Char(':'));
}

699 700
} // namespace Internal
} // namespace ProjectExplorer