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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
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
|
/****************************************************************************
**
** Copyright (C) 2019 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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 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.
**
****************************************************************************/
#include "baremetalconstants.h"
#include "sdccparser.h"
#include "sdcctoolchain.h"
#include <projectexplorer/abiwidget.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectmacro.h>
#include <projectexplorer/toolchainmanager.h>
#include <utils/algorithm.h>
#include <utils/environment.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <utils/synchronousprocess.h>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFormLayout>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QSettings>
#include <QTemporaryFile>
#include <QTextStream>
using namespace ProjectExplorer;
using namespace Utils;
namespace BareMetal {
namespace Internal {
// Helpers:
static const char compilerCommandKeyC[] = "BareMetal.SdccToolChain.CompilerPath";
static const char targetAbiKeyC[] = "BareMetal.SdccToolChain.TargetAbi";
static bool compilerExists(const FilePath &compilerPath)
{
const QFileInfo fi = compilerPath.toFileInfo();
return fi.exists() && fi.isExecutable() && fi.isFile();
}
static QString compilerTargetFlag(const Abi &abi)
{
switch (abi.architecture()) {
case Abi::Architecture::Mcs51Architecture:
return QString("-mmcs51");
case Abi::Architecture::Stm8Architecture:
return QString("-mstm8");
default:
return {};
}
}
static Macros dumpPredefinedMacros(const FilePath &compiler, const QStringList &env,
const Abi &abi)
{
if (compiler.isEmpty() || !compiler.toFileInfo().isExecutable())
return {};
QTemporaryFile fakeIn("XXXXXX.c");
if (!fakeIn.open())
return {};
fakeIn.close();
SynchronousProcess cpp;
cpp.setEnvironment(env);
cpp.setTimeoutS(10);
const CommandLine cmd(compiler, {compilerTargetFlag(abi), "-dM", "-E", fakeIn.fileName()});
const SynchronousProcessResponse response = cpp.runBlocking(cmd);
if (response.result != SynchronousProcessResponse::Finished
|| response.exitCode != 0) {
qWarning() << response.exitMessage(compiler.toString(), 10);
return {};
}
const QByteArray output = response.allOutput().toUtf8();
return Macro::toMacros(output);
}
static HeaderPaths dumpHeaderPaths(const FilePath &compiler, const QStringList &env,
const Abi &abi)
{
if (!compiler.exists())
return {};
SynchronousProcess cpp;
cpp.setEnvironment(env);
cpp.setTimeoutS(10);
const CommandLine cmd(compiler, {compilerTargetFlag(abi), "--print-search-dirs"});
const SynchronousProcessResponse response = cpp.runBlocking(cmd);
if (response.result != SynchronousProcessResponse::Finished
|| response.exitCode != 0) {
qWarning() << response.exitMessage(compiler.toString(), 10);
return {};
}
QString output = response.allOutput();
HeaderPaths headerPaths;
QTextStream in(&output);
QString line;
bool synchronized = false;
while (in.readLineInto(&line)) {
if (!synchronized) {
if (line.startsWith("includedir:"))
synchronized = true;
} else {
if (line.startsWith("programs:") || line.startsWith("datadir:")
|| line.startsWith("libdir:") || line.startsWith("libpath:")) {
break;
} else {
const QString headerPath = QFileInfo(line.trimmed())
.canonicalFilePath();
headerPaths.append({headerPath, HeaderPathType::BuiltIn});
}
}
}
return headerPaths;
}
static QString findMacroValue(const Macros ¯os, const QByteArray &key)
{
for (const Macro ¯o : macros) {
if (macro.key == key)
return QString::fromLocal8Bit(macro.value);
}
return {};
}
static QString guessVersion(const Macros ¯os)
{
const QString major = findMacroValue(macros, "__SDCC_VERSION_MAJOR");
const QString minor = findMacroValue(macros, "__SDCC_VERSION_MINOR");
const QString patch = findMacroValue(macros, "__SDCC_VERSION_PATCH");
return QString("%1.%2.%3").arg(major, minor, patch);
}
static Abi::Architecture guessArchitecture(const Macros ¯os)
{
for (const Macro ¯o : macros) {
if (macro.key == "__SDCC_mcs51")
return Abi::Architecture::Mcs51Architecture;
if (macro.key == "__SDCC_stm8")
return Abi::Architecture::Stm8Architecture;
}
return Abi::Architecture::UnknownArchitecture;
}
static unsigned char guessWordWidth(const Macros ¯os)
{
Q_UNUSED(macros)
// SDCC always have 16-bit word width.
return 16;
}
static Abi::BinaryFormat guessFormat(Abi::Architecture arch)
{
Q_UNUSED(arch)
return Abi::BinaryFormat::UnknownFormat;
}
static Abi guessAbi(const Macros ¯os)
{
const auto arch = guessArchitecture(macros);
return {arch, Abi::OS::BareMetalOS, Abi::OSFlavor::GenericFlavor,
guessFormat(arch), guessWordWidth(macros)};
}
static QString buildDisplayName(Abi::Architecture arch, Core::Id language,
const QString &version)
{
const auto archName = Abi::toString(arch);
const auto langName = ToolChainManager::displayNameOfLanguageId(language);
return SdccToolChain::tr("SDCC %1 (%2, %3)")
.arg(version, langName, archName);
}
static Utils::FilePath compilerPathFromEnvironment(const QString &compilerName)
{
const Environment systemEnvironment = Environment::systemEnvironment();
return systemEnvironment.searchInPath(compilerName);
}
// SdccToolChain
SdccToolChain::SdccToolChain() :
ToolChain(Constants::SDCC_TOOLCHAIN_TYPEID)
{
setTypeDisplayName(Internal::SdccToolChainFactory::tr("SDCC"));
}
void SdccToolChain::setTargetAbi(const Abi &abi)
{
if (abi == m_targetAbi)
return;
m_targetAbi = abi;
toolChainUpdated();
}
Abi SdccToolChain::targetAbi() const
{
return m_targetAbi;
}
bool SdccToolChain::isValid() const
{
return true;
}
ToolChain::MacroInspectionRunner SdccToolChain::createMacroInspectionRunner() const
{
Environment env = Environment::systemEnvironment();
addToEnvironment(env);
const Utils::FilePath compilerCommand = m_compilerCommand;
const Core::Id lang = language();
const Abi abi = m_targetAbi;
MacrosCache macrosCache = predefinedMacrosCache();
return [env, compilerCommand, macrosCache, lang, abi]
(const QStringList &flags) {
Q_UNUSED(flags)
const Macros macros = dumpPredefinedMacros(compilerCommand, env.toStringList(),
abi);
const auto report = MacroInspectionReport{macros, languageVersion(lang, macros)};
macrosCache->insert({}, report);
return report;
};
}
Macros SdccToolChain::predefinedMacros(const QStringList &cxxflags) const
{
return createMacroInspectionRunner()(cxxflags).macros;
}
Utils::LanguageExtensions SdccToolChain::languageExtensions(const QStringList &) const
{
return LanguageExtension::None;
}
WarningFlags SdccToolChain::warningFlags(const QStringList &cxxflags) const
{
Q_UNUSED(cxxflags)
return WarningFlags::Default;
}
ToolChain::BuiltInHeaderPathsRunner SdccToolChain::createBuiltInHeaderPathsRunner(
const Environment &) const
{
Environment env = Environment::systemEnvironment();
addToEnvironment(env);
const Utils::FilePath compilerCommand = m_compilerCommand;
const Abi abi = m_targetAbi;
return [env, compilerCommand, abi](const QStringList &, const QString &, const QString &) {
return dumpHeaderPaths(compilerCommand, env.toStringList(), abi);
};
}
HeaderPaths SdccToolChain::builtInHeaderPaths(const QStringList &cxxFlags,
const FilePath &fileName,
const Environment &env) const
{
return createBuiltInHeaderPathsRunner(env)(cxxFlags, fileName.toString(), "");
}
void SdccToolChain::addToEnvironment(Environment &env) const
{
if (!m_compilerCommand.isEmpty()) {
const FilePath path = m_compilerCommand.parentDir();
env.prependOrSetPath(path.toString());
}
}
IOutputParser *SdccToolChain::outputParser() const
{
return new SdccParser;
}
QVariantMap SdccToolChain::toMap() const
{
QVariantMap data = ToolChain::toMap();
data.insert(compilerCommandKeyC, m_compilerCommand.toString());
data.insert(targetAbiKeyC, m_targetAbi.toString());
return data;
}
bool SdccToolChain::fromMap(const QVariantMap &data)
{
if (!ToolChain::fromMap(data))
return false;
m_compilerCommand = FilePath::fromString(data.value(compilerCommandKeyC).toString());
m_targetAbi = Abi::fromString(data.value(targetAbiKeyC).toString());
return true;
}
std::unique_ptr<ToolChainConfigWidget> SdccToolChain::createConfigurationWidget()
{
return std::make_unique<SdccToolChainConfigWidget>(this);
}
bool SdccToolChain::operator==(const ToolChain &other) const
{
if (!ToolChain::operator==(other))
return false;
const auto customTc = static_cast<const SdccToolChain *>(&other);
return m_compilerCommand == customTc->m_compilerCommand
&& m_targetAbi == customTc->m_targetAbi
;
}
void SdccToolChain::setCompilerCommand(const FilePath &file)
{
if (file == m_compilerCommand)
return;
m_compilerCommand = file;
toolChainUpdated();
}
FilePath SdccToolChain::compilerCommand() const
{
return m_compilerCommand;
}
FilePath SdccToolChain::makeCommand(const Environment &env) const
{
Q_UNUSED(env)
return {};
}
// SdccToolChainFactory
SdccToolChainFactory::SdccToolChainFactory()
{
setDisplayName(tr("SDCC"));
setSupportedToolChainType(Constants::SDCC_TOOLCHAIN_TYPEID);
setSupportedLanguages({ProjectExplorer::Constants::C_LANGUAGE_ID});
setToolchainConstructor([] { return new SdccToolChain; });
setUserCreatable(true);
}
QList<ToolChain *> SdccToolChainFactory::autoDetect(const QList<ToolChain *> &alreadyKnown)
{
Candidates candidates;
if (Utils::HostOsInfo::isWindowsHost()) {
#ifdef Q_OS_WIN64
static const char kRegistryNode[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\SDCC";
#else
static const char kRegistryNode[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\SDCC";
#endif
QSettings registry(kRegistryNode, QSettings::NativeFormat);
QString compilerPath = registry.value("Default").toString();
if (!compilerPath.isEmpty()) {
// Build full compiler path.
compilerPath += "\\bin\\sdcc.exe";
const FilePath fn = FilePath::fromString(
QFileInfo(compilerPath).absoluteFilePath());
if (compilerExists(fn)) {
// Build compiler version.
const QString version = QString("%1.%2.%3").arg(
registry.value("VersionMajor").toString(),
registry.value("VersionMinor").toString(),
registry.value("VersionRevision").toString());
candidates.push_back({fn, version});
}
}
}
const FilePath fn = compilerPathFromEnvironment("sdcc");
if (fn.exists()) {
const auto env = Environment::systemEnvironment();
const auto macros = dumpPredefinedMacros(fn, env.toStringList(), {});
const QString version = guessVersion(macros);
const Candidate candidate = {fn, version};
if (!candidates.contains(candidate))
candidates.push_back(candidate);
}
return autoDetectToolchains(candidates, alreadyKnown);
}
QList<ToolChain *> SdccToolChainFactory::autoDetectToolchains(
const Candidates &candidates, const QList<ToolChain *> &alreadyKnown) const
{
QList<ToolChain *> result;
for (const Candidate &candidate : qAsConst(candidates)) {
const QList<ToolChain *> filtered = Utils::filtered(
alreadyKnown, [candidate](ToolChain *tc) {
return tc->typeId() == Constants::SDCC_TOOLCHAIN_TYPEID
&& tc->compilerCommand() == candidate.compilerPath
&& (tc->language() == ProjectExplorer::Constants::C_LANGUAGE_ID);
});
if (!filtered.isEmpty()) {
result << filtered;
continue;
}
// Create toolchain only for C language (because SDCC does not support C++).
result << autoDetectToolchain(candidate, ProjectExplorer::Constants::C_LANGUAGE_ID);
}
return result;
}
QList<ToolChain *> SdccToolChainFactory::autoDetectToolchain(
const Candidate &candidate, Core::Id language) const
{
const auto env = Environment::systemEnvironment();
// Table of supported ABI's by SDCC compiler.
const Abi knownAbis[] = {
{Abi::Mcs51Architecture},
{Abi::Stm8Architecture}
};
QList<ToolChain *> tcs;
// Probe each ABI from the table, because the SDCC compiler
// can be compiled with or without the specified architecture.
for (const auto &knownAbi : knownAbis) {
const Macros macros = dumpPredefinedMacros(candidate.compilerPath,
env.toStringList(), knownAbi);
if (macros.isEmpty())
continue;
const Abi abi = guessAbi(macros);
if (knownAbi.architecture() != abi.architecture())
continue;
const auto tc = new SdccToolChain;
tc->setDetection(ToolChain::AutoDetection);
tc->setLanguage(language);
tc->setCompilerCommand(candidate.compilerPath);
tc->setTargetAbi(abi);
tc->setDisplayName(buildDisplayName(abi.architecture(), language,
candidate.compilerVersion));
const auto languageVersion = ToolChain::languageVersion(language, macros);
tc->predefinedMacrosCache()->insert({}, {macros, languageVersion});
tcs.push_back(tc);
}
return tcs;
}
// SdccToolChainConfigWidget
SdccToolChainConfigWidget::SdccToolChainConfigWidget(SdccToolChain *tc) :
ToolChainConfigWidget(tc),
m_compilerCommand(new PathChooser),
m_abiWidget(new AbiWidget)
{
m_compilerCommand->setExpectedKind(PathChooser::ExistingCommand);
m_compilerCommand->setHistoryCompleter("PE.SDCC.Command.History");
m_mainLayout->addRow(tr("&Compiler path:"), m_compilerCommand);
m_mainLayout->addRow(tr("&ABI:"), m_abiWidget);
m_abiWidget->setEnabled(false);
addErrorLabel();
setFromToolchain();
connect(m_compilerCommand, &PathChooser::rawPathChanged,
this, &SdccToolChainConfigWidget::handleCompilerCommandChange);
connect(m_abiWidget, &AbiWidget::abiChanged,
this, &ToolChainConfigWidget::dirty);
}
void SdccToolChainConfigWidget::applyImpl()
{
if (toolChain()->isAutoDetected())
return;
const auto tc = static_cast<SdccToolChain *>(toolChain());
const QString displayName = tc->displayName();
tc->setCompilerCommand(m_compilerCommand->fileName());
tc->setTargetAbi(m_abiWidget->currentAbi());
tc->setDisplayName(displayName);
if (m_macros.isEmpty())
return;
const auto languageVersion = ToolChain::languageVersion(tc->language(), m_macros);
tc->predefinedMacrosCache()->insert({}, {m_macros, languageVersion});
setFromToolchain();
}
bool SdccToolChainConfigWidget::isDirtyImpl() const
{
const auto tc = static_cast<SdccToolChain *>(toolChain());
return m_compilerCommand->fileName() != tc->compilerCommand()
|| m_abiWidget->currentAbi() != tc->targetAbi()
;
}
void SdccToolChainConfigWidget::makeReadOnlyImpl()
{
m_compilerCommand->setReadOnly(true);
m_abiWidget->setEnabled(false);
}
void SdccToolChainConfigWidget::setFromToolchain()
{
const QSignalBlocker blocker(this);
const auto tc = static_cast<SdccToolChain *>(toolChain());
m_compilerCommand->setFileName(tc->compilerCommand());
m_abiWidget->setAbis({}, tc->targetAbi());
const bool haveCompiler = compilerExists(m_compilerCommand->fileName());
m_abiWidget->setEnabled(haveCompiler && !tc->isAutoDetected());
}
void SdccToolChainConfigWidget::handleCompilerCommandChange()
{
const FilePath compilerPath = m_compilerCommand->fileName();
const bool haveCompiler = compilerExists(compilerPath);
if (haveCompiler) {
const auto env = Environment::systemEnvironment();
m_macros = dumpPredefinedMacros(compilerPath, env.toStringList(), {});
const Abi guessed = guessAbi(m_macros);
m_abiWidget->setAbis({}, guessed);
}
m_abiWidget->setEnabled(haveCompiler);
emit dirty();
}
} // namespace Internal
} // namespace BareMetal
|