gcctoolchain.cpp 56.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
30 31

#include "gcctoolchain.h"
32
#include "clangparser.h"
33
#include "gcctoolchainfactories.h"
34 35 36
#include "gccparser.h"
#include "linuxiccparser.h"
#include "projectexplorerconstants.h"
37
#include "toolchainmanager.h"
38

39
#include <utils/algorithm.h>
40
#include <utils/environment.h>
41
#include <utils/hostosinfo.h>
42
#include <utils/synchronousprocess.h>
43
#include <utils/pathchooser.h>
44
#include <utils/qtcassert.h>
45
#include <utils/qtcprocess.h>
46

47 48 49 50 51
#include <QBuffer>
#include <QCoreApplication>
#include <QFileInfo>
#include <QProcess>
#include <QScopedPointer>
52

53
#include <QLineEdit>
54
#include <QFormLayout>
55

hjk's avatar
hjk committed
56 57
using namespace Utils;

58 59
namespace ProjectExplorer {

60 61
using namespace Internal;

62 63 64 65
// --------------------------------------------------------------------------
// Helpers:
// --------------------------------------------------------------------------

66
static const char compilerCommandKeyC[] = "ProjectExplorer.GccToolChain.Path";
67 68
static const char compilerPlatformCodeGenFlagsKeyC[] = "ProjectExplorer.GccToolChain.PlatformCodeGenFlags";
static const char compilerPlatformLinkerFlagsKeyC[] = "ProjectExplorer.GccToolChain.PlatformLinkerFlags";
Tobias Hunger's avatar
Tobias Hunger committed
69
static const char targetAbiKeyC[] = "ProjectExplorer.GccToolChain.TargetAbi";
70
static const char supportedAbisKeyC[] = "ProjectExplorer.GccToolChain.SupportedAbis";
71

hjk's avatar
hjk committed
72
static QByteArray runGcc(const FileName &gcc, const QStringList &arguments, const QStringList &env)
73
{
74
    if (gcc.isEmpty() || !gcc.toFileInfo().isExecutable())
75 76 77
        return QByteArray();

    QProcess cpp;
78 79
    // Force locale: This function is used only to detect settings inside the tool chain, so this is save.
    QStringList environment(env);
80
    environment.append(QLatin1String("LC_ALL=C"));
81 82

    cpp.setEnvironment(environment);
83
    cpp.start(gcc.toString(), arguments);
84
    if (!cpp.waitForStarted()) {
85
        qWarning("%s: Cannot start '%s': %s", Q_FUNC_INFO, qPrintable(gcc.toUserOutput()),
86 87 88 89
            qPrintable(cpp.errorString()));
        return QByteArray();
    }
    cpp.closeWriteChannel();
90
    if (!cpp.waitForFinished(10000)) {
hjk's avatar
hjk committed
91
        SynchronousProcess::stopProcess(cpp);
92
        qWarning("%s: Timeout running '%s'.", Q_FUNC_INFO, qPrintable(gcc.toUserOutput()));
93 94 95
        return QByteArray();
    }
    if (cpp.exitStatus() != QProcess::NormalExit) {
96
        qWarning("%s: '%s' crashed.", Q_FUNC_INFO, qPrintable(gcc.toUserOutput()));
97 98
        return QByteArray();
    }
dt's avatar
dt committed
99

100 101
    const QByteArray stdErr = SynchronousProcess::normalizeNewlines(
                QString::fromLocal8Bit(cpp.readAllStandardError())).toLocal8Bit();
102 103 104
    if (cpp.exitCode() != 0) {
        qWarning().nospace()
            << Q_FUNC_INFO << ": " << gcc.toUserOutput() << ' '
hjk's avatar
hjk committed
105
            << arguments.join(QLatin1Char(' ')) << " returned exit code "
106 107 108 109
            << cpp.exitCode() << ": " << stdErr;
        return QByteArray();
    }

110 111
    QByteArray data = SynchronousProcess::normalizeNewlines(
                QString::fromLocal8Bit(cpp.readAllStandardOutput())).toLocal8Bit();
112 113
    if (!data.isEmpty() && !data.endsWith('\n'))
        data.append('\n');
114
    data.append(stdErr);
115
    return data;
116 117
}

118 119 120 121 122
static const QStringList gccPredefinedMacrosOptions()
{
    return QStringList() << QLatin1String("-xc++") << QLatin1String("-E") << QLatin1String("-dM");
}

hjk's avatar
hjk committed
123
static QByteArray gccPredefinedMacros(const FileName &gcc, const QStringList &args, const QStringList &env)
124
{
125
    QStringList arguments = args;
126
    arguments << QLatin1String("-");
127 128

    QByteArray predefinedMacros = runGcc(gcc, arguments, env);
129
    // Sanity check in case we get an error message instead of real output:
130
    QTC_CHECK(predefinedMacros.isNull() || predefinedMacros.startsWith("#define "));
131
    if (HostOsInfo::isMacHost()) {
132 133 134 135
        // Turn off flag indicating Apple's blocks support
        const QByteArray blocksDefine("#define __BLOCKS__ 1");
        const QByteArray blocksUndefine("#undef __BLOCKS__");
        const int idx = predefinedMacros.indexOf(blocksDefine);
136
        if (idx != -1)
137
            predefinedMacros.replace(idx, blocksDefine.length(), blocksUndefine);
138

139 140 141 142
        // Define __strong and __weak (used for Apple's GC extension of C) to be empty
        predefinedMacros.append("#define __strong\n");
        predefinedMacros.append("#define __weak\n");
    }
143 144 145
    return predefinedMacros;
}

146 147
const int GccToolChain::PREDEFINED_MACROS_CACHE_SIZE = 16;

148 149
QList<HeaderPath> GccToolChain::gccHeaderPaths(const FileName &gcc, const QStringList &arguments,
                                               const QStringList &env)
150 151 152 153 154
{
    QList<HeaderPath> systemHeaderPaths;
    QByteArray line;
    QByteArray data = runGcc(gcc, arguments, env);
    QBuffer cpp(&data);
dt's avatar
dt committed
155
    cpp.open(QIODevice::ReadOnly);
156 157 158 159 160 161 162 163 164 165 166 167
    while (cpp.canReadLine()) {
        line = cpp.readLine();
        if (line.startsWith("#include"))
            break;
    }

    if (!line.isEmpty() && line.startsWith("#include")) {
        HeaderPath::Kind kind = HeaderPath::UserHeaderPath;
        while (cpp.canReadLine()) {
            line = cpp.readLine();
            if (line.startsWith("#include")) {
                kind = HeaderPath::GlobalHeaderPath;
168
            } else if (! line.isEmpty() && QChar(QLatin1Char(line.at(0))).isSpace()) {
169 170 171 172 173 174 175 176 177 178 179 180 181 182
                HeaderPath::Kind thisHeaderKind = kind;

                line = line.trimmed();

                const int index = line.indexOf(" (framework directory)");
                if (index != -1) {
                    line.truncate(index);
                    thisHeaderKind = HeaderPath::FrameworkHeaderPath;
                }

                systemHeaderPaths.append(HeaderPath(QFile::decodeName(line), thisHeaderKind));
            } else if (line.startsWith("End of search list.")) {
                break;
            } else {
183
                qWarning("%s: Ignoring line: %s", __FUNCTION__, line.constData());
184 185 186 187 188 189
            }
        }
    }
    return systemHeaderPaths;
}

190
static QList<Abi> guessGccAbi(const QString &m, const QByteArray &macros)
191
{
hjk's avatar
hjk committed
192
    QList<Abi> abiList;
Tobias Hunger's avatar
Tobias Hunger committed
193

194 195
    Abi guessed = Abi::abiFromTargetTriplet(m);
    if (guessed.isNull())
Tobias Hunger's avatar
Tobias Hunger committed
196
        return abiList;
197

198 199 200 201 202
    Abi::Architecture arch = guessed.architecture();
    Abi::OS os = guessed.os();
    Abi::OSFlavor flavor = guessed.osFlavor();
    Abi::BinaryFormat format = guessed.binaryFormat();
    int width = guessed.wordWidth();
Tobias Hunger's avatar
Tobias Hunger committed
203

204 205 206 207 208
    if (macros.contains("#define __SIZEOF_SIZE_T__ 8"))
        width = 64;
    else if (macros.contains("#define __SIZEOF_SIZE_T__ 4"))
        width = 32;

209
    if (os == Abi::MacOS) {
Tobias Hunger's avatar
Tobias Hunger committed
210
        // Apple does PPC and x86!
hjk's avatar
hjk committed
211 212
        abiList << Abi(arch, os, flavor, format, width);
        abiList << Abi(arch, os, flavor, format, width == 64 ? 32 : 64);
Tobias Hunger's avatar
Tobias Hunger committed
213
    } else if (arch == Abi::X86Architecture && (width == 0 || width == 64)) {
214
        abiList << Abi(arch, os, flavor, format, 64);
hjk's avatar
hjk committed
215
        abiList << Abi(arch, os, flavor, format, 32);
Tobias Hunger's avatar
Tobias Hunger committed
216
    } else {
hjk's avatar
hjk committed
217
        abiList << Abi(arch, os, flavor, format, width);
Tobias Hunger's avatar
Tobias Hunger committed
218 219
    }
    return abiList;
220 221
}

222
static QList<Abi> guessGccAbi(const FileName &path, const QStringList &env,
223
                              const QByteArray &macros,
224
                              const QStringList &extraArgs = QStringList())
225
{
226
    if (path.isEmpty())
hjk's avatar
hjk committed
227
        return QList<Abi>();
228

229 230
    QStringList arguments = extraArgs;
    arguments << QLatin1String("-dumpmachine");
231
    QString machine = QString::fromLocal8Bit(runGcc(path, arguments, env)).trimmed();
232 233
    if (machine.isEmpty())
        return QList<Abi>(); // no need to continue if running failed once...
234
    return guessGccAbi(machine, macros);
235 236
}

hjk's avatar
hjk committed
237
static QString gccVersion(const FileName &path, const QStringList &env)
238 239 240 241 242
{
    QStringList arguments(QLatin1String("-dumpversion"));
    return QString::fromLocal8Bit(runGcc(path, arguments, env)).trimmed();
}

243 244 245 246
// --------------------------------------------------------------------------
// GccToolChain
// --------------------------------------------------------------------------

247
GccToolChain::GccToolChain(Detection d) :
248
    ToolChain(Constants::GCC_TOOLCHAIN_ID, d)
249 250
{ }

251 252
GccToolChain::GccToolChain(Core::Id typeId, Detection d) :
    ToolChain(typeId, d)
253 254
{ }

255 256 257 258 259 260 261 262 263 264 265 266 267
void GccToolChain::setCompilerCommand(const FileName &path)
{
    if (path == m_compilerCommand)
        return;

    m_compilerCommand = path;
}

void GccToolChain::setSupportedAbis(const QList<Abi> &m_abis)
{
    m_supportedAbis = m_abis;
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
void GccToolChain::setMacroCache(const QStringList &allCxxflags, const QByteArray &macros) const
{
    if (macros.isNull())
        return;

    CacheItem runResults;
    QByteArray data = macros;
    runResults.first = allCxxflags;
    if (macros.isNull())
        data = QByteArray("");
    runResults.second = data;

    m_predefinedMacros.push_back(runResults);
    if (m_predefinedMacros.size() > PREDEFINED_MACROS_CACHE_SIZE)
        m_predefinedMacros.pop_front();
}

QByteArray GccToolChain::macroCache(const QStringList &allCxxflags) const
{
    for (GccCache::iterator it = m_predefinedMacros.begin(); it != m_predefinedMacros.end(); ++it) {
        if (it->first == allCxxflags) {
            // Increase cached item priority
            CacheItem pair = *it;
            m_predefinedMacros.erase(it);
            m_predefinedMacros.push_back(pair);

            return pair.second;
        }
    }
    return QByteArray();
}

300 301 302
QString GccToolChain::defaultDisplayName() const
{
    if (!m_targetAbi.isValid())
Tobias Hunger's avatar
Tobias Hunger committed
303
        return typeDisplayName();
304 305 306 307 308
    return QCoreApplication::translate("ProjectExplorer::GccToolChain",
                                       "%1 (%2 %3 in %4)").arg(typeDisplayName(),
                                                               Abi::toString(m_targetAbi.architecture()),
                                                               Abi::toString(m_targetAbi.wordWidth()),
                                                               compilerCommand().parentDir().toUserOutput());
309 310
}

311 312 313 314 315
ToolChain::CompilerFlags GccToolChain::defaultCompilerFlags() const
{
    return CompilerFlags(GnuExtensions);
}

Tobias Hunger's avatar
Tobias Hunger committed
316
QString GccToolChain::typeDisplayName() const
317
{
318
    return GccToolChainFactory::tr("GCC");
319 320 321 322 323 324 325
}

Abi GccToolChain::targetAbi() const
{
    return m_targetAbi;
}

326 327 328 329 330 331 332
QString GccToolChain::version() const
{
    if (m_version.isEmpty())
        m_version = detectVersion();
    return m_version;
}

Tobias Hunger's avatar
Tobias Hunger committed
333 334
void GccToolChain::setTargetAbi(const Abi &abi)
{
Tobias Hunger's avatar
Tobias Hunger committed
335 336 337
    if (abi == m_targetAbi)
        return;

338 339
    m_targetAbi = abi;
    toolChainUpdated();
Tobias Hunger's avatar
Tobias Hunger committed
340 341 342 343 344 345 346
}

QList<Abi> GccToolChain::supportedAbis() const
{
    return m_supportedAbis;
}

347 348
bool GccToolChain::isValid() const
{
349 350 351 352 353
    if (m_compilerCommand.isNull())
        return false;

    QFileInfo fi = compilerCommand().toFileInfo();
    return fi.isExecutable();
354 355
}

356 357 358 359 360 361 362 363 364
/**
 * @brief Asks compiler for set of predefined macros
 * @param cxxflags - compiler flags collected from project settings
 * @return defines list, one per line, e.g. "#define __GXX_WEAK__ 1"
 *
 * @note changing compiler flags sometimes changes macros set, e.g. -fopenmp
 * adds _OPENMP macro, for full list of macro search by word "when" on this page:
 * http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
 */
365
QByteArray GccToolChain::predefinedMacros(const QStringList &cxxflags) const
366
{
367
    QStringList allCxxflags = m_platformCodeGenFlags + cxxflags;  // add only cxxflags is empty?
368

369 370 371
    QByteArray macros = macroCache(allCxxflags);
    if (!macros.isNull())
        return macros;
372 373 374 375

    // Using a clean environment breaks ccache/distcc/etc.
    Environment env = Environment::systemEnvironment();
    addToEnvironment(env);
376
    QStringList arguments = gccPredefinedMacrosOptions();
377 378
    for (int iArg = 0; iArg < allCxxflags.length(); ++iArg) {
        const QString &a = allCxxflags.at(iArg);
379 380 381 382
        if (a == QLatin1String("-arch")) {
            if (++iArg < allCxxflags.length() && !arguments.contains(a))
                arguments << a << allCxxflags.at(iArg);
        } else if (a == QLatin1String("--sysroot") || a == QLatin1String("-isysroot")) {
383 384 385
            if (++iArg < allCxxflags.length())
                arguments << a << allCxxflags.at(iArg);
        } else if (a == QLatin1String("-m128bit-long-double") || a == QLatin1String("-m32")
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
                || a == QLatin1String("-m3dnow") || a == QLatin1String("-m3dnowa")
                || a == QLatin1String("-m64") || a == QLatin1String("-m96bit-long-double")
                || a == QLatin1String("-mabm") || a == QLatin1String("-maes")
                || a.startsWith(QLatin1String("-march=")) || a == QLatin1String("-mavx")
                || a.startsWith(QLatin1String("-masm=")) || a == QLatin1String("-mcx16")
                || a == QLatin1String("-mfma") || a == QLatin1String("-mfma4")
                || a == QLatin1String("-mlwp") || a == QLatin1String("-mpclmul")
                || a == QLatin1String("-mpopcnt") || a == QLatin1String("-msse")
                || a == QLatin1String("-msse2") || a == QLatin1String("-msse2avx")
                || a == QLatin1String("-msse3") || a == QLatin1String("-msse4")
                || a == QLatin1String("-msse4.1") || a == QLatin1String("-msse4.2")
                || a == QLatin1String("-msse4a") || a == QLatin1String("-mssse3")
                || a.startsWith(QLatin1String("-mtune=")) || a == QLatin1String("-mxop")
                || a == QLatin1String("-Os") || a == QLatin1String("-O0") || a == QLatin1String("-O1")
                || a == QLatin1String("-O2") || a == QLatin1String("-O3")
                || a == QLatin1String("-ffinite-math-only") || a == QLatin1String("-fshort-double")
                || a == QLatin1String("-fshort-wchar") || a == QLatin1String("-fsignaling-nans")
                || a == QLatin1String("-fno-inline") || a == QLatin1String("-fno-exceptions")
                || a == QLatin1String("-fstack-protector") || a == QLatin1String("-fstack-protector-all")
                || a == QLatin1String("-fsanitize=address") || a == QLatin1String("-fno-rtti")
                || a.startsWith(QLatin1String("-std=")) || a.startsWith(QLatin1String("-stdlib="))
                || a.startsWith(QLatin1String("-specs="))
                || a == QLatin1String("-ansi") || a == QLatin1String("-undef")
                || a.startsWith(QLatin1String("-D")) || a.startsWith(QLatin1String("-U"))
410 411 412
                || a == QLatin1String("-fopenmp") || a == QLatin1String("-Wno-deprecated")
                || a == QLatin1String("-fPIC") || a == QLatin1String("-fpic")
                || a == QLatin1String("-fPIE") || a == QLatin1String("-fpie"))
413 414
            arguments << a;
    }
415 416
    macros = gccPredefinedMacros(m_compilerCommand, reinterpretOptions(arguments),
                                 env.toStringList());
417

418 419
    setMacroCache(allCxxflags, macros);
    return macros;
420 421
}

422 423 424 425
/**
 * @brief Parses gcc flags -std=*, -fopenmp, -fms-extensions, -ansi.
 * @see http://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html
 */
hjk's avatar
hjk committed
426
ToolChain::CompilerFlags GccToolChain::compilerFlags(const QStringList &cxxflags) const
427
{
428 429 430 431 432
    CompilerFlags flags = defaultCompilerFlags();

    const QStringList allCxxflags = m_platformCodeGenFlags + cxxflags; // add only cxxflags is empty?
    foreach (const QString &flag, allCxxflags) {
        if (flag.startsWith(QLatin1String("-std="))) {
433
            const QByteArray std = flag.mid(5).toLatin1();
434
            if (std == "c++98" || std == "c++03") {
435
                flags &= ~CompilerFlags(StandardCxx11 | StandardCxx14 | StandardCxx17 | GnuExtensions);
436
                flags |= StandardCxx98;
437
            } else if (std == "gnu++98" || std == "gnu++03") {
438
                flags &= ~CompilerFlags(StandardCxx11 | StandardCxx14 | StandardCxx17);
439
                flags |= GnuExtensions;
440
            } else if (std == "c++0x" || std == "c++11") {
441
                flags |= StandardCxx11;
442
                flags &= ~CompilerFlags(StandardCxx14 | StandardCxx17 | GnuExtensions);
443 444
            } else if (std == "c++14" || std == "c++1y") {
                flags |= StandardCxx14;
445
                flags &= ~CompilerFlags(StandardCxx11 | StandardCxx17 | GnuExtensions);
446 447
            } else if (std == "c++17" || std == "c++1z") {
                flags |= StandardCxx17;
448
                flags &= ~CompilerFlags(StandardCxx11 | StandardCxx14 | GnuExtensions);
449 450
            } else if (std == "gnu++0x" || std == "gnu++11" || std== "gnu++1y") {
                flags |= CompilerFlags(StandardCxx11 | GnuExtensions);
451
                flags &= ~CompilerFlags(StandardCxx14 | StandardCxx17);
452
            } else if (std == "c89" || std == "c90"
453
                       || std == "iso9899:1990" || std == "iso9899:199409") {
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
                flags &= ~CompilerFlags(StandardC99 | StandardC11);
            } else if (std == "gnu89" || std == "gnu90") {
                flags &= ~CompilerFlags(StandardC99 | StandardC11);
                flags |= GnuExtensions;
            } else if (std == "c99" || std == "c9x"
                       || std == "iso9899:1999" || std == "iso9899:199x") {
                flags |= StandardC99;
                flags &= ~StandardC11;
            } else if (std == "gnu99" || std == "gnu9x") {
                flags |= CompilerFlags(StandardC99 | GnuExtensions);
                flags &= ~StandardC11;
            } else if (std == "c11" || std == "c1x" || std == "iso9899:2011") {
                flags |= CompilerFlags(StandardC99 | StandardC11);
            } else if (std == "gnu11" || std == "gnu1x") {
                flags |= CompilerFlags(StandardC99 | StandardC11 | GnuExtensions);
            }
        } else if (flag == QLatin1String("-fopenmp")) {
            flags |= OpenMP;
        } else if (flag == QLatin1String("-fms-extensions")) {
            flags |= MicrosoftExtensions;
        } else if (flag == QLatin1String("-ansi")) {
            flags &= ~CompilerFlags(StandardCxx11 | GnuExtensions
                                    | StandardC99 | StandardC11);
        }
    }

    return flags;
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
GccToolChain::WarningFlags GccToolChain::warningFlags(const QStringList &cflags) const
{
    // based on 'LC_ALL="en" gcc -Q --help=warnings | grep enabled'
    WarningFlags flags(WarnDeprecated | WarnIgnoredQualfiers
                       | WarnSignedComparison | WarnUninitializedVars);
    WarningFlags groupWall(WarningsAll | WarnUnknownPragma |WarnUnusedFunctions
                           | WarnUnusedLocals | WarnUnusedResult | WarnUnusedValue
                           | WarnSignedComparison | WarnUninitializedVars);
    WarningFlags groupWextra(WarningsExtra | WarnIgnoredQualfiers | WarnUnusedParams);

    foreach (const QString &flag, cflags) {
        if (flag == QLatin1String("--all-warnings"))
            flags |= groupWall;
        else if (flag == QLatin1String("--extra-warnings"))
            flags |= groupWextra;

        WarningFlagAdder add(flag, flags);
        if (add.triggered())
            continue;

        // supported by clang too
        add("error", WarningsAsErrors);
        add("all", groupWall);
        add("extra", groupWextra);
        add("deprecated", WarnDeprecated);
        add("effc++", WarnEffectiveCxx);
        add("ignored-qualifiers", WarnIgnoredQualfiers);
        add("non-virtual-dtor", WarnNonVirtualDestructor);
        add("overloaded-virtual", WarnOverloadedVirtual);
        add("shadow", WarnHiddenLocals);
        add("sign-compare", WarnSignedComparison);
        add("unknown-pragmas", WarnUnknownPragma);
        add("unused", ToolChain::WarningFlag(
                WarnUnusedFunctions | WarnUnusedLocals | WarnUnusedParams
                | WarnUnusedResult | WarnUnusedValue));
        add("unused-function", WarnUnusedFunctions);
        add("unused-variable", WarnUnusedLocals);
        add("unused-parameter", WarnUnusedParams);
        add("unused-result", WarnUnusedResult);
        add("unused-value", WarnUnusedValue);
        add("uninitialized", WarnUninitializedVars);
    }
    return flags;
}

528
QList<HeaderPath> GccToolChain::systemHeaderPaths(const QStringList &cxxflags, const FileName &sysRoot) const
529
{
530
    if (m_headerPaths.isEmpty()) {
531
        // Using a clean environment breaks ccache/distcc/etc.
hjk's avatar
hjk committed
532
        Environment env = Environment::systemEnvironment();
533
        addToEnvironment(env);
534 535 536 537 538 539 540 541 542 543 544 545
        // Prepare arguments
        QStringList arguments;
        if (!sysRoot.isEmpty())
            arguments.append(QString::fromLatin1("--sysroot=%1").arg(sysRoot.toString()));

        QStringList flags;
        flags << m_platformCodeGenFlags << cxxflags;
        foreach (const QString &a, flags) {
            if (a.startsWith(QLatin1String("-stdlib=")))
                arguments << a;
        }

Tobias Hunger's avatar
Tobias Hunger committed
546 547 548 549
        arguments << QLatin1String("-xc++")
                  << QLatin1String("-E")
                  << QLatin1String("-v")
                  << QLatin1String("-");
550 551

        m_headerPaths = gccHeaderPaths(m_compilerCommand, reinterpretOptions(arguments), env.toStringList());
552
    }
553
    return m_headerPaths;
554 555
}

556 557 558 559 560 561
void GccToolChain::addCommandPathToEnvironment(const FileName &command, Environment &env)
{
    if (!command.isEmpty())
        env.prependOrSetPath(command.parentDir().toString());
}

hjk's avatar
hjk committed
562
void GccToolChain::addToEnvironment(Environment &env) const
563
{
564
    addCommandPathToEnvironment(m_compilerCommand, env);
565 566
}

hjk's avatar
hjk committed
567
QList<FileName> GccToolChain::suggestedMkspecList() const
568 569
{
    Abi abi = targetAbi();
570 571 572 573 574 575
    Abi host = Abi::hostAbi();

    // Cross compile: Leave the mkspec alone!
    if (abi.architecture() != host.architecture()
            || abi.os() != host.os()
            || abi.osFlavor() != host.osFlavor()) // Note: This can fail:-(
hjk's avatar
hjk committed
576
        return QList<FileName>();
577

578 579 580
    if (abi.os() == Abi::MacOS) {
        QString v = version();
        // prefer versioned g++ on mac. This is required to enable building for older Mac OS versions
581
        if (v.startsWith(QLatin1String("4.0")) && m_compilerCommand.endsWith(QLatin1String("-4.0")))
582
            return QList<FileName>() << FileName::fromLatin1("macx-g++40");
583
        if (v.startsWith(QLatin1String("4.2")) && m_compilerCommand.endsWith(QLatin1String("-4.2")))
584 585
            return QList<FileName>() << FileName::fromLatin1("macx-g++42");
        return QList<FileName>() << FileName::fromLatin1("macx-g++");
586 587 588 589
    }

    if (abi.os() == Abi::LinuxOS) {
        if (abi.osFlavor() != Abi::GenericLinuxFlavor)
hjk's avatar
hjk committed
590
            return QList<FileName>(); // most likely not a desktop, so leave the mkspec alone.
591 592 593
        if (abi.wordWidth() == host.wordWidth()) {
            // no need to explicitly set the word width, but provide that mkspec anyway to make sure
            // that the correct compiler is picked if a mkspec with a wordwidth is given.
594
            return QList<FileName>() << FileName::fromLatin1("linux-g++")
hjk's avatar
hjk committed
595
                                            << FileName::fromString(QLatin1String("linux-g++-") + QString::number(m_targetAbi.wordWidth()));
596
        }
hjk's avatar
hjk committed
597
        return QList<FileName>() << FileName::fromString(QLatin1String("linux-g++-") + QString::number(m_targetAbi.wordWidth()));
598
    }
599

600
    if (abi.os() == Abi::BsdOS && abi.osFlavor() == Abi::FreeBsdFlavor)
601
        return QList<FileName>() << FileName::fromLatin1("freebsd-g++");
602

hjk's avatar
hjk committed
603
    return QList<FileName>();
604 605
}

606
QString GccToolChain::makeCommand(const Environment &environment) const
607
{
608
    QString make = QLatin1String("make");
609 610
    FileName tmp = environment.searchInPath(make);
    return tmp.isEmpty() ? make : tmp.toString();
611 612 613 614 615 616 617
}

IOutputParser *GccToolChain::outputParser() const
{
    return new GccParser;
}

618
void GccToolChain::resetToolChain(const FileName &path)
619
{
620
    if (path == m_compilerCommand)
621 622
        return;

623 624
    bool resetDisplayName = displayName() == defaultDisplayName();

625
    setCompilerCommand(path);
626

627
    Abi currentAbi = m_targetAbi;
628
    m_supportedAbis = detectSupportedAbis();
629

Tobias Hunger's avatar
Tobias Hunger committed
630
    m_targetAbi = Abi();
631 632 633 634 635
    if (!m_supportedAbis.isEmpty()) {
        if (m_supportedAbis.contains(currentAbi))
            m_targetAbi = currentAbi;
        else
            m_targetAbi = m_supportedAbis.at(0);
Tobias Hunger's avatar
Tobias Hunger committed
636
    }
637 638 639 640 641

    if (resetDisplayName)
        setDisplayName(defaultDisplayName()); // calls toolChainUpdated()!
    else
        toolChainUpdated();
642 643
}

hjk's avatar
hjk committed
644
FileName GccToolChain::compilerCommand() const
645
{
646
    return m_compilerCommand;
647 648
}

649 650 651 652 653 654 655 656 657
void GccToolChain::setPlatformCodeGenFlags(const QStringList &flags)
{
    if (flags != m_platformCodeGenFlags) {
        m_platformCodeGenFlags = flags;
        toolChainUpdated();
    }
}

/*!
658
    Code gen flags that have to be passed to the compiler.
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
 */
QStringList GccToolChain::platformCodeGenFlags() const
{
    return m_platformCodeGenFlags;
}

void GccToolChain::setPlatformLinkerFlags(const QStringList &flags)
{
    if (flags != m_platformLinkerFlags) {
        m_platformLinkerFlags = flags;
        toolChainUpdated();
    }
}

/*!
674
    Flags that have to be passed to the linker.
675

676
    For example: \c{-arch armv7}
677 678 679 680 681 682
 */
QStringList GccToolChain::platformLinkerFlags() const
{
    return m_platformLinkerFlags;
}

683 684 685 686 687 688 689 690
ToolChain *GccToolChain::clone() const
{
    return new GccToolChain(*this);
}

QVariantMap GccToolChain::toMap() const
{
    QVariantMap data = ToolChain::toMap();
691
    data.insert(QLatin1String(compilerCommandKeyC), m_compilerCommand.toString());
692 693
    data.insert(QLatin1String(compilerPlatformCodeGenFlagsKeyC), m_platformCodeGenFlags);
    data.insert(QLatin1String(compilerPlatformLinkerFlagsKeyC), m_platformLinkerFlags);
Tobias Hunger's avatar
Tobias Hunger committed
694
    data.insert(QLatin1String(targetAbiKeyC), m_targetAbi.toString());
695
    QStringList abiList = Utils::transform(m_supportedAbis, &Abi::toString);
696
    data.insert(QLatin1String(supportedAbisKeyC), abiList);
697 698 699 700 701 702 703 704
    return data;
}

bool GccToolChain::fromMap(const QVariantMap &data)
{
    if (!ToolChain::fromMap(data))
        return false;

hjk's avatar
hjk committed
705
    m_compilerCommand = FileName::fromString(data.value(QLatin1String(compilerCommandKeyC)).toString());
706 707
    m_platformCodeGenFlags = data.value(QLatin1String(compilerPlatformCodeGenFlagsKeyC)).toStringList();
    m_platformLinkerFlags = data.value(QLatin1String(compilerPlatformLinkerFlagsKeyC)).toStringList();
Tobias Hunger's avatar
Tobias Hunger committed
708
    m_targetAbi = Abi(data.value(QLatin1String(targetAbiKeyC)).toString());
709 710 711
    QStringList abiList = data.value(QLatin1String(supportedAbisKeyC)).toStringList();
    m_supportedAbis.clear();
    foreach (const QString &a, abiList) {
hjk's avatar
hjk committed
712
        Abi abi(a);
713 714 715 716
        if (!abi.isValid())
            continue;
        m_supportedAbis.append(abi);
    }
717 718 719 720 721 722 723 724 725
    return true;
}

bool GccToolChain::operator ==(const ToolChain &other) const
{
    if (!ToolChain::operator ==(other))
        return false;

    const GccToolChain *gccTc = static_cast<const GccToolChain *>(&other);
726 727 728
    return m_compilerCommand == gccTc->m_compilerCommand && m_targetAbi == gccTc->m_targetAbi
            && m_platformCodeGenFlags == gccTc->m_platformCodeGenFlags
            && m_platformLinkerFlags == gccTc->m_platformLinkerFlags;
729 730 731 732
}

ToolChainConfigWidget *GccToolChain::configurationWidget()
{
733
    return new GccToolChainConfigWidget(this);
734 735
}

Tobias Hunger's avatar
Tobias Hunger committed
736 737
void GccToolChain::updateSupportedAbis() const
{
738 739 740 741 742 743
    if (m_supportedAbis.isEmpty())
        m_supportedAbis = detectSupportedAbis();
}

QList<Abi> GccToolChain::detectSupportedAbis() const
{
hjk's avatar
hjk committed
744
    Environment env = Environment::systemEnvironment();
745
    addToEnvironment(env);
746 747
    QByteArray macros = predefinedMacros(QStringList());
    return guessGccAbi(m_compilerCommand, env.toStringList(), macros, platformCodeGenFlags());
Tobias Hunger's avatar
Tobias Hunger committed
748 749
}

750 751
QString GccToolChain::detectVersion() const
{
hjk's avatar
hjk committed
752
    Environment env = Environment::systemEnvironment();
753
    addToEnvironment(env);
754
    return gccVersion(m_compilerCommand, env.toStringList());
755 756
}

757 758 759 760
// --------------------------------------------------------------------------
// GccToolChainFactory
// --------------------------------------------------------------------------

761
GccToolChainFactory::GccToolChainFactory()
762
{
763
    setTypeId(Constants::GCC_TOOLCHAIN_ID);
764
    setDisplayName(tr("GCC"));
765 766
}

767
bool GccToolChainFactory::canCreate()
768 769 770 771
{
    return true;
}

772
ToolChain *GccToolChainFactory::create()
773 774 775 776
{
    return createToolChain(false);
}

777
QList<ToolChain *> GccToolChainFactory::autoDetect()
778
{
Tobias Hunger's avatar
Tobias Hunger committed
779
    QList<ToolChain *> tcs;
780
    if (HostOsInfo::isMacHost()) {
781 782 783 784
        // Old mac compilers needed to support macx-gccXY mkspecs:
        tcs.append(autoDetectToolchains(QLatin1String("g++-4.0"), Abi::hostAbi()));
        tcs.append(autoDetectToolchains(QLatin1String("g++-4.2"), Abi::hostAbi()));
    }
Tobias Hunger's avatar
Tobias Hunger committed
785
    tcs.append(autoDetectToolchains(QLatin1String("g++"), Abi::hostAbi()));
786 787

    return tcs;
788 789
}

790
// Used by the ToolChainManager to restore user-generated tool chains
791
bool GccToolChainFactory::canRestore(const QVariantMap &data)
792
{
793
    return typeIdFromMap(data) == Constants::GCC_TOOLCHAIN_ID;
794 795
}

796
ToolChain *GccToolChainFactory::restore(const QVariantMap &data)
797
{
798
    GccToolChain *tc = new GccToolChain(ToolChain::ManualDetection);
Tobias Hunger's avatar
Tobias Hunger committed
799 800 801
    // Updating from 2.5:
    QVariantMap updated = data;
    if (tc->fromMap(updated))
802 803 804 805 806 807
        return tc;

    delete tc;
    return 0;
}

808
GccToolChain *GccToolChainFactory::createToolChain(bool autoDetect)
809
{
810
    return new GccToolChain(autoDetect ? ToolChain::AutoDetection : ToolChain::ManualDetection);
811 812
}

813
QList<ToolChain *> GccToolChainFactory::autoDetectToolchains(const QString &compiler,
814
                                                                       const Abi &requiredAbi)
815 816 817
{
    QList<ToolChain *> result;

818
    Environment systemEnvironment = Environment::systemEnvironment();
819
    const FileName compilerPath = systemEnvironment.searchInPath(compiler);
820
    if (compilerPath.isEmpty())
821
        return result;
Tobias Hunger's avatar
Tobias Hunger committed
822

823
    GccToolChain::addCommandPathToEnvironment(compilerPath, systemEnvironment);
824 825 826
    QByteArray macros
            = gccPredefinedMacros(compilerPath, gccPredefinedMacrosOptions(), systemEnvironment.toStringList());
    QList<Abi> abiList = guessGccAbi(compilerPath, systemEnvironment.toStringList(), macros);
827 828 829 830 831 832
    if (!abiList.contains(requiredAbi)) {
        if (requiredAbi.wordWidth() != 64
                || !abiList.contains(Abi(requiredAbi.architecture(), requiredAbi.os(), requiredAbi.osFlavor(),
                                         requiredAbi.binaryFormat(), 32)))
            return result;
    }
Tobias Hunger's avatar
Tobias Hunger committed
833 834 835

    foreach (const Abi &abi, abiList) {
        QScopedPointer<GccToolChain> tc(createToolChain(true));
836
        tc->setMacroCache(QStringList(), macros);
Tobias Hunger's avatar
Tobias Hunger committed
837 838
        if (tc.isNull())
            return result;
839

840
        tc->setCompilerCommand(compilerPath);
841
        tc->setSupportedAbis(abiList);
Tobias Hunger's avatar
Tobias Hunger committed
842
        tc->setTargetAbi(abi);
843
        tc->setDisplayName(tc->defaultDisplayName()); // reset displayname
844 845

        result.append(tc.take());
Tobias Hunger's avatar
Tobias Hunger committed
846
    }
847 848 849 850 851 852 853 854

    return result;
}

// --------------------------------------------------------------------------
// GccToolChainConfigWidget
// --------------------------------------------------------------------------

855
GccToolChainConfigWidget::GccToolChainConfigWidget(GccToolChain *tc) :
856
    ToolChainConfigWidget(tc),
hjk's avatar
hjk committed
857
    m_compilerCommand(new PathChooser),
858 859
    m_abiWidget(new AbiWidget),
    m_isReadOnly(false)
860 861 862
{
    Q_ASSERT(tc);

863
    const QStringList gnuVersionArgs = QStringList(QLatin1String("--version"));
hjk's avatar
hjk committed
864
    m_compilerCommand->setExpectedKind(PathChooser::ExistingCommand);
865
    m_compilerCommand->setCommandVersionArguments(gnuVersionArgs);
866
    m_compilerCommand->setHistoryCompleter(QLatin1String("PE.Gcc.Command.History"));
867
    m_mainLayout->addRow(tr("&Compiler path:"), m_compilerCommand);
868 869 870 871 872 873
    m_platformCodeGenFlagsLineEdit = new QLineEdit(this);
    m_platformCodeGenFlagsLineEdit->setText(QtcProcess::joinArgs(tc->platformCodeGenFlags()));
    m_mainLayout->addRow(tr("Platform codegen flags:"), m_platformCodeGenFlagsLineEdit);
    m_platformLinkerFlagsLineEdit = new QLineEdit(this);
    m_platformLinkerFlagsLineEdit->setText(QtcProcess::joinArgs(tc->platformLinkerFlags()));
    m_mainLayout->addRow(tr("Platform linker flags:"), m_platformLinkerFlagsLineEdit);
874
    m_mainLayout->addRow(tr("&ABI:"), m_abiWidget);
875

Tobias Hunger's avatar
Tobias Hunger committed
876
    m_abiWidget->setEnabled(false);
877
    addErrorLabel();
878

879
    setFromToolchain();
880

881
    connect(m_compilerCommand, SIGNAL(changed(QString)), this, SLOT(handleCompilerCommandChange()));
882 883
    connect(m_platformCodeGenFlagsLineEdit, SIGNAL(editingFinished()), this, SLOT(handlePlatformCodeGenFlagsChange()));
    connect(m_platformLinkerFlagsLineEdit, SIGNAL(editingFinished()), this, SLOT(handlePlatformLinkerFlagsChange()));
Tobias Hunger's avatar
Tobias Hunger committed
884
    connect(m_abiWidget, SIGNAL(abiChanged()), this, SIGNAL(dirty()));
885 886
}

887
void GccToolChainConfigWidget::applyImpl()
888 889 890 891 892 893 894
{
    if (toolChain()->isAutoDetected())
        return;

    GccToolChain *tc = static_cast<GccToolChain *>(toolChain());
    Q_ASSERT(tc);
    QString displayName = tc->displayName();
895
    tc->setCompilerCommand(m_compilerCommand->fileName());
896
    tc->setSupportedAbis(m_abiWidget->supportedAbis());
897
    tc->setTargetAbi(m_abiWidget->currentAbi());
898
    tc->setDisplayName(displayName); // reset display name
899 900
    tc->setPlatformCodeGenFlags(splitString(m_platformCodeGenFlagsLineEdit->text()));
    tc->setPlatformLinkerFlags(splitString(m_platformLinkerFlagsLineEdit->text()));
901
    tc->setMacroCache(tc->platformCodeGenFlags(), m_macros);
902 903
}

904
void GccToolChainConfigWidget::setFromToolchain()
905
{
906 907
    // subwidgets are not yet connected!
    bool blocked = blockSignals(true);
908
    GccToolChain *tc = static_cast<GccToolChain *>(toolChain());
909
    m_compilerCommand->setFileName(tc->compilerCommand());
910 911
    m_platformCodeGenFlagsLineEdit->setText(QtcProcess::joinArgs(tc->platformCodeGenFlags()));
    m_platformLinkerFlagsLineEdit->setText(QtcProcess::joinArgs(tc->platformLinkerFlags()));
Tobias Hunger's avatar
Tobias Hunger committed
912
    m_abiWidget->setAbis(tc->supportedAbis(), tc->targetAbi());