aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/corelib/tools/msvcinfo.cpp
blob: e390c9a30e21bb7debe2c1f64f896be1d2fb49f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
249
250
251
252
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 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.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** 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-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "msvcinfo.h"

#include <tools/error.h>
#include <tools/profile.h>
#include <tools/stringconstants.h>

#include <QtCore/qbytearray.h>
#include <QtCore/qdir.h>
#include <QtCore/qprocess.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qtemporaryfile.h>

#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
#endif

#include <algorithm>
#include <mutex>

using namespace qbs;
using namespace qbs::Internal;

static std::recursive_mutex envMutex;

static QString mkStr(const char *s) { return QString::fromLocal8Bit(s); }
static QString mkStr(const QByteArray &ba) { return mkStr(ba.constData()); }

class TemporaryEnvChanger
{
public:
    TemporaryEnvChanger(const QProcessEnvironment &envChanges) : m_locker(envMutex)
    {
        QProcessEnvironment currentEnv = QProcessEnvironment::systemEnvironment();
        for (const QString &key : envChanges.keys()) {
            m_changesToRestore.insert(key, currentEnv.value(key));
            qputenv(qPrintable(key), qPrintable(envChanges.value(key)));
        }
    }

    ~TemporaryEnvChanger()
    {
        for (const QString &key : m_changesToRestore.keys())
            qputenv(qPrintable(key), qPrintable(m_changesToRestore.value(key)));
    }

private:
    QProcessEnvironment m_changesToRestore;
    std::lock_guard<std::recursive_mutex> m_locker;
};

static QByteArray runProcess(const QString &exeFilePath, const QStringList &args,
                             const QProcessEnvironment &env = QProcessEnvironment(),
                             bool allowFailure = false,
                             const QByteArray &pipeData = QByteArray())
{
    TemporaryEnvChanger envChanger(env);
    QProcess process;
    process.start(exeFilePath, args);
    if (!process.waitForStarted())
        throw ErrorInfo(mkStr("Could not start %1 (%2)").arg(exeFilePath, process.errorString()));
    if (!pipeData.isEmpty()) {
        process.write(pipeData);
        process.closeWriteChannel();
    }
    if (!process.waitForFinished(-1) || process.exitStatus() != QProcess::NormalExit)
        throw ErrorInfo(mkStr("Could not run %1 (%2)").arg(exeFilePath, process.errorString()));
    if (process.exitCode() != 0 && !allowFailure) {
        ErrorInfo e(mkStr("Process '%1' failed with exit code %2.")
                    .arg(exeFilePath).arg(process.exitCode()));
        const QByteArray stdErr = process.readAllStandardError();
        if (!stdErr.isEmpty())
            e.append(mkStr("stderr was: %1").arg(mkStr(stdErr)));
        const QByteArray stdOut = process.readAllStandardOutput();
        if (!stdOut.isEmpty())
            e.append(mkStr("stdout was: %1").arg(mkStr(stdOut)));
        throw e;
    }
    return process.readAllStandardOutput().trimmed();
}

class DummyFile {
public:
    DummyFile(const QString &fp) : filePath(fp) { }
    ~DummyFile() { QFile::remove(filePath); }
    const QString filePath;
};

#ifdef Q_OS_WIN
static QStringList parseCommandLine(const QString &commandLine)
{
    QStringList list;
    auto buf = new wchar_t[commandLine.size() + 1];
    buf[commandLine.toWCharArray(buf)] = 0;
    int argCount = 0;
    LPWSTR *args = CommandLineToArgvW(buf, &argCount);
    if (!args)
        throw ErrorInfo(mkStr("Could not parse command line arguments: ") + commandLine);
    for (int i = 0; i < argCount; ++i)
        list.push_back(QString::fromWCharArray(args[i]));
    delete[] buf;
    return list;
}
#endif

static QVariantMap getMsvcDefines(const QString &compilerFilePath,
                                  const QProcessEnvironment &compilerEnv,
                                  MSVC::CompilerLanguage language)
{
#ifdef Q_OS_WIN
    QString backendSwitch, languageSwitch;
    switch (language) {
    case MSVC::CLanguage:
        backendSwitch = QStringLiteral("/B1");
        languageSwitch = QStringLiteral("/TC");
        break;
    case MSVC::CPlusPlusLanguage:
        backendSwitch = QStringLiteral("/Bx");
        languageSwitch = QStringLiteral("/TP");
        break;
    }
    const QByteArray commands("set MSC_CMD_FLAGS\n");
    QStringList out = QString::fromLocal8Bit(runProcess(compilerFilePath, QStringList()
               << QStringLiteral("/nologo")
               << backendSwitch
               << QString::fromWCharArray(_wgetenv(L"COMSPEC"))
               << QStringLiteral("/c")
               << languageSwitch
               << QStringLiteral("NUL"),
               compilerEnv, true, commands)).split(QLatin1Char('\n'));

    auto findResult = std::find_if(out.cbegin(), out.cend(), [] (const QString &line) {
            return line.startsWith(QLatin1String("MSC_CMD_FLAGS="));
        });
    if (findResult == out.cend()) {
        throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
                        + out.join(QLatin1Char('\n')));
    }

    QVariantMap map;
    const QStringList args = parseCommandLine(findResult->trimmed());
    for (const QString &arg : args) {
        if (!arg.startsWith(QStringLiteral("-D")))
            continue;
        int idx = arg.indexOf(QLatin1Char('='), 2);
        if (idx > 2)
            map.insert(arg.mid(2, idx - 2), arg.mid(idx + 1));
        else
            map.insert(arg.mid(2), QVariant());
    }

    return map;
#else
    Q_UNUSED(compilerFilePath);
    Q_UNUSED(compilerEnv);
    Q_UNUSED(language);
    return QVariantMap();
#endif
}

void MSVC::init()
{
    determineCompilerVersion();
}

QString MSVC::binPathForArchitecture(const QString &arch) const
{
    QString archSubDir;
    if (arch != StringConstants::x86Arch())
        archSubDir = arch;
    return QDir::cleanPath(vcInstallPath + QLatin1Char('/') + pathPrefix + QLatin1Char('/')
                           + archSubDir);
}

static QString clExeSuffix() { return QStringLiteral("/cl.exe"); }

QString MSVC::clPathForArchitecture(const QString &arch) const
{
    return binPathForArchitecture(arch) + clExeSuffix();
}

QVariantMap MSVC::compilerDefines(const QString &compilerFilePath,
                                  MSVC::CompilerLanguage language) const
{
    return getMsvcDefines(compilerFilePath, environment, language);
}

void MSVC::determineCompilerVersion()
{
    QString cppFilePath;
    {
        QTemporaryFile cppFile(QDir::tempPath() + QLatin1String("/qbsXXXXXX.cpp"));
        cppFile.setAutoRemove(false);
        if (!cppFile.open()) {
            throw ErrorInfo(mkStr("Could not create temporary file (%1)")
                            .arg(cppFile.errorString()));
        }
        cppFilePath = cppFile.fileName();
        cppFile.write("_MSC_FULL_VER");
        cppFile.close();
    }
    DummyFile fileDeleter(cppFilePath);

    std::lock_guard<std::recursive_mutex> locker(envMutex);
    const QByteArray origPath = qgetenv("PATH");
    qputenv("PATH", environment.value(StringConstants::pathEnvVar()).toLatin1() + ';' + origPath);
    QByteArray versionStr = runProcess(
                binPath + clExeSuffix(),
                QStringList() << QStringLiteral("/nologo") << QStringLiteral("/EP")
                << QDir::toNativeSeparators(cppFilePath));
    qputenv("PATH", origPath);
    compilerVersion = Version(versionStr.mid(0, 2).toInt(), versionStr.mid(2, 2).toInt(),
                              versionStr.mid(4).toInt());
}