aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/mcusupport/mcusupportsdk.cpp
blob: 908d86abbafebe5553f1c7d1717cb3d475c53b13 (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
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
/****************************************************************************
**
** Copyright (C) 2020 The Qt Company Ltd.
** 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 "mcusupportsdk.h"
#include "mcuhelpers.h"
#include "mcukitmanager.h"
#include "mculegacyconstants.h"
#include "mcupackage.h"
#include "mcusupportconstants.h"
#include "mcusupportoptions.h"
#include "mcusupportplugin.h"
#include "mcusupportversiondetection.h"
#include "mcutarget.h"
#include "mcutargetdescription.h"
#include "mcutargetfactory.h"
#include "mcutargetfactorylegacy.h"

#include <baremetal/baremetalconstants.h>
#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/toolchainmanager.h>
#include <utils/algorithm.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>

#include <QDir>
#include <QDirIterator>
#include <QHash>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariant>

#include <memory>

using namespace ProjectExplorer;
using namespace Utils;

namespace McuSupport::Internal {

namespace {
const char CMAKE_ENTRIES[]{"cmakeEntries"};
} // namespace

McuPackagePtr createQtForMCUsPackage(const SettingsHandler::Ptr &settingsHandler)
{
    return McuPackagePtr{
        new McuPackage(settingsHandler,
                       McuPackage::tr("Qt for MCUs SDK"),
                       FileUtils::homePath(), // defaultPath
                       FilePath(Legacy::Constants::QT_FOR_MCUS_SDK_PACKAGE_VALIDATION_PATH)
                           .withExecutableSuffix(),                     // detectionPath
                       Constants::SETTINGS_KEY_PACKAGE_QT_FOR_MCUS_SDK, // settingsKey
                       Legacy::Constants::QUL_CMAKE_VAR,
                       Legacy::Constants::QUL_ENV_VAR)};
}

namespace Legacy {

static FilePath findInProgramFiles(const QString &folder)
{
    for (auto envVar : {"ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"}) {
        if (!qEnvironmentVariableIsSet(envVar))
            continue;
        const FilePath dir = FilePath::fromUserInput(qEnvironmentVariable(envVar)) / folder;
        if (dir.exists())
            return dir;
    }
    return {};
}

static McuPackageVersionDetector *generatePackageVersionDetector(const QString &envVar)
{
    if (envVar.startsWith("EVK"))
        return new McuPackageXmlVersionDetector("*_manifest_*.xml", "ksdk", "version", ".*");

    if (envVar.startsWith("STM32"))
        return new McuPackageXmlVersionDetector("package.xml",
                                                "PackDescription",
                                                "Release",
                                                R"(\b(\d+\.\d+\.\d+)\b)");

    if (envVar.startsWith("RGL"))
        return new McuPackageDirectoryVersionDetector("rgl_*_obj_*", R"(\d+\.\d+\.\w+)", false);

    return nullptr;
}

McuPackagePtr createBoardSdkPackage(const SettingsHandler::Ptr &settingsHandler,
                                    const McuTargetDescription &desc)
{
    const auto generateSdkName = [](const QString &envVar) {
        qsizetype postfixPos = envVar.indexOf("_SDK_PATH");
        if (postfixPos < 0) {
            postfixPos = envVar.indexOf("_DIR");
        }
        const QString sdkName = postfixPos > 0 ? envVar.left(postfixPos) : envVar;
        return QString{"MCU SDK (%1)"}.arg(sdkName);
    };
    const QString sdkName = generateSdkName(desc.boardSdk.envVar);

    const FilePath defaultPath = [&] {
        const auto envVar = desc.boardSdk.envVar.toLatin1();
        if (qEnvironmentVariableIsSet(envVar))
            return FilePath::fromUserInput(qEnvironmentVariable(envVar));
        if (!desc.boardSdk.defaultPath.isEmpty()) {
            FilePath defaultPath = FilePath::fromUserInput(QDir::rootPath()
                                                           + desc.boardSdk.defaultPath.toString());
            if (defaultPath.exists())
                return defaultPath;
        }
        return FilePath();
    }();

    const auto versionDetector = generatePackageVersionDetector(desc.boardSdk.envVar);

    return McuPackagePtr{new McuPackage(settingsHandler,
                                        sdkName,
                                        defaultPath,
                                        {},                             // detection path
                                        desc.boardSdk.envVar,           // settings key
                                        Constants::BOARD_SDK_CMAKE_VAR, // cmake var
                                        desc.boardSdk.envVar,           // env var
                                        desc.boardSdk.versions,
                                        {}, // download URL
                                        versionDetector)};
}

McuPackagePtr createFreeRTOSSourcesPackage(const SettingsHandler::Ptr &settingsHandler,
                                           const QString &envVar,
                                           const FilePath &boardSdkDir)
{
    const QString envVarPrefix = removeRtosSuffix(envVar);

    FilePath defaultPath;
    if (qEnvironmentVariableIsSet(envVar.toLatin1()))
        defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar.toLatin1()));
    else if (!boardSdkDir.isEmpty())
        defaultPath = boardSdkDir;

    return McuPackagePtr{
        new McuPackage(settingsHandler,
                       QString::fromLatin1("FreeRTOS Sources (%1)").arg(envVarPrefix),
                       defaultPath,
                       {}, // detection path
                       QString{Constants::SETTINGS_KEY_FREERTOS_PREFIX}.append(envVarPrefix),
                       "FREERTOS_DIR",           // cmake var
                       envVar,                   // env var
                       {},                       // versions
                       "https://freertos.org")}; // download url
}

McuPackagePtr createUnsupportedToolChainFilePackage(const SettingsHandler::Ptr &settingsHandler,
                                                    const FilePath &qtForMCUSdkPath)
{
    const FilePath toolchainFilePath = qtForMCUSdkPath / Constants::QUL_TOOLCHAIN_CMAKE_DIR
                                       / "unsupported.cmake";
    return McuPackagePtr{new McuPackage(settingsHandler,
                                        {},
                                        toolchainFilePath,
                                        {},
                                        {},
                                        Constants::TOOLCHAIN_FILE_CMAKE_VARIABLE,
                                        {})};
}

McuToolChainPackagePtr createUnsupportedToolChainPackage(const SettingsHandler::Ptr &settingsHandler)
{
    return McuToolChainPackagePtr{
        new McuToolChainPackage(settingsHandler,
                                {},
                                {},
                                {},
                                {},
                                McuToolChainPackage::ToolChainType::Unsupported,
                                {},
                                {},
                                {},
                                nullptr)};
}

McuToolChainPackagePtr createMsvcToolChainPackage(const SettingsHandler::Ptr &settingsHandler,
                                                  const QStringList &versions)
{
    ToolChain *toolChain = McuToolChainPackage::msvcToolChain(
        ProjectExplorer::Constants::CXX_LANGUAGE_ID);

    const FilePath detectionPath = FilePath("cl").withExecutableSuffix();
    const FilePath defaultPath = toolChain ? toolChain->compilerCommand().parentDir() : FilePath();

    const auto versionDetector
        = new McuPackageExecutableVersionDetector(detectionPath,
                                                  {"--version"},
                                                  "\\b(\\d+\\.\\d+)\\.\\d+\\b");

    return McuToolChainPackagePtr{new McuToolChainPackage(settingsHandler,
                                                          McuPackage::tr("MSVC Binary directory"),
                                                          defaultPath,
                                                          detectionPath,
                                                          "MsvcToolchain",
                                                          McuToolChainPackage::ToolChainType::MSVC,
                                                          versions,
                                                          {},
                                                          {},
                                                          versionDetector)};
}

McuToolChainPackagePtr createGccToolChainPackage(const SettingsHandler::Ptr &settingsHandler,
                                                 const QStringList &versions)
{
    ToolChain *toolChain = McuToolChainPackage::gccToolChain(
        ProjectExplorer::Constants::CXX_LANGUAGE_ID);

    const FilePath detectionPath = FilePath("bin/g++").withExecutableSuffix();
    const FilePath defaultPath = toolChain ? toolChain->compilerCommand().parentDir().parentDir()
                                           : FilePath();

    const auto versionDetector
        = new McuPackageExecutableVersionDetector(detectionPath,
                                                  {"--version"},
                                                  "\\b(\\d+\\.\\d+\\.\\d+)\\b");

    return McuToolChainPackagePtr{new McuToolChainPackage(settingsHandler,
                                                          McuPackage::tr("GCC Toolchain"),
                                                          defaultPath,
                                                          detectionPath,
                                                          "GnuToolchain",
                                                          McuToolChainPackage::ToolChainType::GCC,
                                                          versions,
                                                          {},
                                                          {},
                                                          versionDetector)};
}

McuToolChainPackagePtr createArmGccToolchainPackage(const SettingsHandler::Ptr &settingsHandler,
                                                    const QStringList &versions)
{
    const char envVar[] = "ARMGCC_DIR";

    FilePath defaultPath;
    if (qEnvironmentVariableIsSet(envVar))
        defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));
    if (defaultPath.isEmpty() && HostOsInfo::isWindowsHost()) {
        const FilePath installDir = findInProgramFiles("GNU Tools ARM Embedded");
        if (installDir.exists()) {
            // If GNU Tools installation dir has only one sub dir,
            // select the sub dir, otherwise the installation dir.
            const FilePaths subDirs = installDir.dirEntries(QDir::Dirs | QDir::NoDotAndDotDot);
            if (subDirs.count() == 1)
                defaultPath = subDirs.first();
        }
    }

    const FilePath detectionPath = FilePath("bin/arm-none-eabi-g++").withExecutableSuffix();
    const auto versionDetector = new McuPackageExecutableVersionDetector(detectionPath,
                                                                         {"--version"},
                                                                         R"(\b(\d+\.\d+\.\d+)\b)");

    return McuToolChainPackagePtr{
        new McuToolChainPackage(settingsHandler,
                                McuPackage::tr("GNU Arm Embedded Toolchain"),
                                defaultPath,
                                detectionPath,
                                "GNUArmEmbeddedToolchain",                  // settingsKey
                                McuToolChainPackage::ToolChainType::ArmGcc, // toolchainType
                                versions,
                                Constants::TOOLCHAIN_DIR_CMAKE_VARIABLE, // cmake var
                                envVar,                                  // env var
                                versionDetector)};
}

McuToolChainPackagePtr createGhsToolchainPackage(const SettingsHandler::Ptr &settingsHandler,
                                                 const QStringList &versions)
{
    const char envVar[] = "GHS_COMPILER_DIR";

    const FilePath defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));

    const auto versionDetector
        = new McuPackageExecutableVersionDetector(FilePath("as850").withExecutableSuffix(),
                                                  {"-V"},
                                                  R"(\bv(\d+\.\d+\.\d+)\b)");

    return McuToolChainPackagePtr{
        new McuToolChainPackage(settingsHandler,
                                "Green Hills Compiler",
                                defaultPath,
                                FilePath("ccv850").withExecutableSuffix(), // detectionPath
                                "GHSToolchain",                            // settingsKey
                                McuToolChainPackage::ToolChainType::GHS,   // toolchainType
                                versions,
                                Constants::TOOLCHAIN_DIR_CMAKE_VARIABLE, // cmake var
                                envVar,                                  // env var
                                versionDetector)};
}

McuToolChainPackagePtr createGhsArmToolchainPackage(const SettingsHandler::Ptr &settingsHandler,
                                                    const QStringList &versions)
{
    const char envVar[] = "GHS_ARM_COMPILER_DIR";

    const FilePath defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));

    const auto versionDetector
        = new McuPackageExecutableVersionDetector(FilePath("asarm").withExecutableSuffix(),
                                                  {"-V"},
                                                  R"(\bv(\d+\.\d+\.\d+)\b)");

    return McuToolChainPackagePtr{
        new McuToolChainPackage(settingsHandler,
                                "Green Hills Compiler for ARM",
                                defaultPath,
                                FilePath("cxarm").withExecutableSuffix(),   // detectionPath
                                "GHSArmToolchain",                          // settingsKey
                                McuToolChainPackage::ToolChainType::GHSArm, // toolchainType
                                versions,
                                Constants::TOOLCHAIN_DIR_CMAKE_VARIABLE, // cmake var
                                envVar,                                  // env var
                                versionDetector)};
}

McuToolChainPackagePtr createIarToolChainPackage(const SettingsHandler::Ptr &settingsHandler,
                                                 const QStringList &versions)
{
    const char envVar[] = "IAR_ARM_COMPILER_DIR";

    FilePath defaultPath;
    if (qEnvironmentVariableIsSet(envVar))
        defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));
    else {
        const ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainManager::toolChain(
            [](const ProjectExplorer::ToolChain *t) {
                return t->typeId() == BareMetal::Constants::IAREW_TOOLCHAIN_TYPEID;
            });
        if (tc) {
            const FilePath compilerExecPath = tc->compilerCommand();
            defaultPath = compilerExecPath.parentDir().parentDir();
        }
    }

    const FilePath detectionPath = FilePath("bin/iccarm").withExecutableSuffix();
    const auto *versionDetector
        = new McuPackageExecutableVersionDetector(detectionPath,
                                                  {"--version"},
                                                  R"(\bV(\d+\.\d+\.\d+)\.\d+\b)");

    return McuToolChainPackagePtr{
        new McuToolChainPackage(settingsHandler,
                                "IAR ARM Compiler",
                                defaultPath,
                                detectionPath,
                                "IARToolchain",                          // settings key
                                McuToolChainPackage::ToolChainType::IAR, // toolchainType
                                versions,
                                Constants::TOOLCHAIN_DIR_CMAKE_VARIABLE, // cmake var
                                envVar,                                  // env var
                                versionDetector)};
}

static McuPackagePtr createStm32CubeProgrammerPackage(const SettingsHandler::Ptr &settingsHandler)
{
    FilePath defaultPath;
    const QString cubePath = "STMicroelectronics/STM32Cube/STM32CubeProgrammer";
    if (HostOsInfo::isWindowsHost()) {
        const FilePath programPath = findInProgramFiles(cubePath);
        if (!programPath.isEmpty())
            defaultPath = programPath;
    } else {
        const FilePath programPath = FileUtils::homePath() / cubePath;
        if (programPath.exists())
            defaultPath = programPath;
    }

    const FilePath detectionPath = FilePath::fromUserInput(
        QLatin1String(Utils::HostOsInfo::isWindowsHost() ? "/bin/STM32_Programmer_CLI.exe"
                                                         : "/bin/STM32_Programmer.sh"));

    return McuPackagePtr{
        new McuPackage(settingsHandler,
                       McuPackage::tr("STM32CubeProgrammer"),
                       defaultPath,
                       detectionPath,
                       "Stm32CubeProgrammer",
                       {},                                                           // cmake var
                       {},                                                           // env var
                       {},                                                           // versions
                       "https://www.st.com/en/development-tools/stm32cubeprog.html", // download url
                       nullptr, // version detector
                       true,    // add to path
                       "/bin"   // relative path modifier
                       )};
}

static McuPackagePtr createMcuXpressoIdePackage(const SettingsHandler::Ptr &settingsHandler)
{
    const char envVar[] = "MCUXpressoIDE_PATH";

    FilePath defaultPath;
    if (qEnvironmentVariableIsSet(envVar)) {
        defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));
    } else if (HostOsInfo::isWindowsHost()) {
        const FilePath programPath = FilePath::fromString(QDir::rootPath()) / "nxp";
        if (programPath.exists()) {
            defaultPath = programPath;
            // If default dir has exactly one sub dir that could be the IDE path, pre-select that.
            const FilePaths subDirs = defaultPath.dirEntries(
                {{"MCUXpressoIDE*"}, QDir::Dirs | QDir::NoDotAndDotDot});
            if (subDirs.count() == 1)
                defaultPath = subDirs.first();
        }
    } else {
        const FilePath programPath = FilePath::fromUserInput("/usr/local/mcuxpressoide/");
        if (programPath.exists())
            defaultPath = programPath;
    }

    return McuPackagePtr{new McuPackage(settingsHandler,
                                        "MCUXpresso IDE",
                                        defaultPath,
                                        FilePath("ide/binaries/crt_emu_cm_redlink")
                                            .withExecutableSuffix(), // detection path
                                        "MCUXpressoIDE",             // settings key
                                        "MCUXPRESSO_IDE_PATH",       // cmake var
                                        envVar,
                                        {},                                     // versions
                                        "https://www.nxp.com/mcuxpresso/ide")}; // download url
}

static McuPackagePtr createCypressProgrammerPackage(const SettingsHandler::Ptr &settingsHandler)
{
    const char envVar[] = "CYPRESS_AUTO_FLASH_UTILITY_DIR";

    FilePath defaultPath;
    if (qEnvironmentVariableIsSet(envVar)) {
        defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));
    } else if (HostOsInfo::isWindowsHost()) {
        const FilePath candidate = findInProgramFiles("Cypress");
        if (candidate.exists()) {
            // "Cypress Auto Flash Utility 1.0"
            const auto subDirs = candidate.dirEntries({{"Cypress Auto Flash Utility*"}, QDir::Dirs},
                                                      QDir::Unsorted);
            if (!subDirs.empty())
                defaultPath = subDirs.first();
        }
    }

    return McuPackagePtr{
        new McuPackage(settingsHandler,
                       "Cypress Auto Flash Utility",
                       defaultPath,
                       FilePath::fromUserInput("/bin/openocd").withExecutableSuffix(),
                       "CypressAutoFlashUtil",            // settings key
                       "INFINEON_AUTO_FLASH_UTILITY_DIR", // cmake var
                       envVar)};                          // env var
}

static McuPackagePtr createRenesasProgrammerPackage(const SettingsHandler::Ptr &settingsHandler)
{
    const char envVar[] = "RENESAS_FLASH_PROGRAMMER_PATH";

    FilePath defaultPath;
    if (qEnvironmentVariableIsSet(envVar)) {
        defaultPath = FilePath::fromUserInput(qEnvironmentVariable(envVar));
    } else if (HostOsInfo::isWindowsHost()) {
        const FilePath candidate = findInProgramFiles("Renesas Electronics/Programming Tools");
        if (candidate.exists()) {
            // "Renesas Flash Programmer V3.09"
            const auto subDirs = candidate.dirEntries({{"Renesas Flash Programmer*"}, QDir::Dirs},
                                                      QDir::Unsorted);
            if (!subDirs.empty())
                defaultPath = subDirs.first();
        }
    }

    return McuPackagePtr{new McuPackage(settingsHandler,
                                        "Renesas Flash Programmer",
                                        defaultPath,
                                        FilePath("rfp-cli").withExecutableSuffix(),
                                        "RenesasFlashProgrammer",        // settings key
                                        "RENESAS_FLASH_PROGRAMMER_PATH", // cmake var
                                        envVar)};                        // env var
}

} // namespace Legacy

static McuAbstractTargetFactory::Ptr createFactory(bool isLegacy,
                                                   const SettingsHandler::Ptr &settingsHandler,
                                                   const FilePath &qtMcuSdkPath)
{
    McuAbstractTargetFactory::Ptr result;
    if (isLegacy) {
        static const QHash<QString, Legacy::ToolchainCompilerCreator> toolchainCreators = {
            {{"armgcc"}, {[settingsHandler](const QStringList &versions) {
                 return Legacy::createArmGccToolchainPackage(settingsHandler, versions);
             }}},
            {{"greenhills"},
             [settingsHandler](const QStringList &versions) {
                 return Legacy::createGhsToolchainPackage(settingsHandler, versions);
             }},
            {{"iar"}, {[settingsHandler](const QStringList &versions) {
                 return Legacy::createIarToolChainPackage(settingsHandler, versions);
             }}},
            {{"msvc"}, {[settingsHandler](const QStringList &versions) {
                 return Legacy::createMsvcToolChainPackage(settingsHandler, versions);
             }}},
            {{"gcc"}, {[settingsHandler](const QStringList &versions) {
                 return Legacy::createGccToolChainPackage(settingsHandler, versions);
             }}},
            {{"arm-greenhills"}, {[settingsHandler](const QStringList &versions) {
                 return Legacy::createGhsArmToolchainPackage(settingsHandler, versions);
             }}},
        };

        const FilePath toolchainFilePrefix = qtMcuSdkPath
                                             / Legacy::Constants::QUL_TOOLCHAIN_CMAKE_DIR;
        static const QHash<QString, McuPackagePtr> toolchainFiles
            = {{{"armgcc"},
                McuPackagePtr{new McuPackage{settingsHandler,
                                             {},
                                             toolchainFilePrefix / "armgcc.cmake",
                                             {},
                                             {},
                                             Legacy::Constants::TOOLCHAIN_FILE_CMAKE_VARIABLE,
                                             {}}}},

               {{"iar"},
                McuPackagePtr{new McuPackage{settingsHandler,
                                             {},
                                             toolchainFilePrefix / "iar.cmake",
                                             {},
                                             {},
                                             Legacy::Constants::TOOLCHAIN_FILE_CMAKE_VARIABLE,
                                             {}}}},
               {"greenhills",
                McuPackagePtr{new McuPackage{settingsHandler,
                                             {},
                                             toolchainFilePrefix / "ghs.cmake",
                                             {},
                                             {},
                                             Legacy::Constants::TOOLCHAIN_FILE_CMAKE_VARIABLE,
                                             {}}}},
               {"arm-greenhills",
                McuPackagePtr{new McuPackage{settingsHandler,
                                             {},
                                             toolchainFilePrefix / "arm-ghs.cmake",
                                             {},
                                             {},
                                             Legacy::Constants::TOOLCHAIN_FILE_CMAKE_VARIABLE,
                                             {}}}}

            };

        // Note: the vendor name (the key of the hash) is case-sensitive. It has to match the "platformVendor" key in the
        // json file.
        static const QHash<QString, McuPackagePtr> vendorPkgs = {
            {{"ST"}, McuPackagePtr{Legacy::createStm32CubeProgrammerPackage(settingsHandler)}},
            {{"NXP"}, McuPackagePtr{Legacy::createMcuXpressoIdePackage(settingsHandler)}},
            {{"CYPRESS"}, McuPackagePtr{Legacy::createCypressProgrammerPackage(settingsHandler)}},
            {{"RENESAS"}, McuPackagePtr{Legacy::createRenesasProgrammerPackage(settingsHandler)}},
        };

        result = std::make_unique<Legacy::McuTargetFactory>(toolchainCreators,
                                                            toolchainFiles,
                                                            vendorPkgs,
                                                            settingsHandler);
    } else {
        result = std::make_unique<McuTargetFactory>(settingsHandler);
    }
    return result;
}

McuSdkRepository targetsFromDescriptions(const QList<McuTargetDescription> &descriptions,
                                         const SettingsHandler::Ptr &settingsHandler,
                                         const FilePath &qtForMCUSdkPath,
                                         bool isLegacy)
{
    Targets mcuTargets;
    Packages mcuPackages;

    McuAbstractTargetFactory::Ptr targetFactory = createFactory(isLegacy,
                                                                settingsHandler,
                                                                qtForMCUSdkPath);
    for (const McuTargetDescription &desc : descriptions) {
        auto [targets, packages] = targetFactory->createTargets(desc, qtForMCUSdkPath);
        mcuTargets.append(targets);
        mcuPackages.unite(packages);
    }

    if (isLegacy) {
        auto [toolchainPkgs, vendorPkgs]{targetFactory->getAdditionalPackages()};
        for (McuToolChainPackagePtr &package : toolchainPkgs) {
            mcuPackages.insert(package);
        }
        for (McuPackagePtr &package : vendorPkgs) {
            mcuPackages.insert(package);
        }
    }
    return McuSdkRepository{mcuTargets, mcuPackages};
}

FilePath kitsPath(const FilePath &qtMcuSdkPath)
{
    return qtMcuSdkPath / "kits/";
}

static FilePaths targetDescriptionFiles(const FilePath &dir)
{
    return kitsPath(dir).dirEntries(Utils::FileFilter({"*.json"}, QDir::Files));
}

VersionDetection parseVersionDetection(const QJsonObject &packageEntry)
{
    const QJsonObject versioning = packageEntry.value("versionDetection").toObject();
    return {
        versioning["regex"].toString(),
        versioning["filePattern"].toString(),
        versioning["executableArgs"].toString(),
        versioning["xmlElement"].toString(),
        versioning["xmlAttribute"].toString(),
        versioning["isFile"].toBool(true),
    };
}

static PackageDescription parsePackage(const QJsonObject &cmakeEntry)
{
    const QVariantList versionsVariantList = cmakeEntry["versions"].toArray().toVariantList();
    const auto versions = Utils::transform<QStringList>(versionsVariantList,
                                                        [&](const QVariant &version) {
                                                            return version.toString();
                                                        });
    return {cmakeEntry["label"].toString(),
            cmakeEntry["envVar"].toString(),
            cmakeEntry["cmakeVar"].toString(),
            cmakeEntry["description"].toString(),
            cmakeEntry["setting"].toString(),
            FilePath::fromUserInput(cmakeEntry["defaultValue"].toString()),
            FilePath::fromUserInput(cmakeEntry["validation"].toString()),
            versions,
            parseVersionDetection(cmakeEntry),
            false};
}

static QList<PackageDescription> parsePackages(const QJsonArray &cmakeEntries)
{
    QList<PackageDescription> result;
    for (const auto &cmakeEntryRef : cmakeEntries) {
        const QJsonObject cmakeEntry{cmakeEntryRef.toObject()};
        result.push_back(parsePackage(cmakeEntry));
    }
    return result;
}

McuTargetDescription parseDescriptionJson(const QByteArray &data)
{
    const QJsonDocument document = QJsonDocument::fromJson(data);
    const QJsonObject target = document.object();
    const QString qulVersion = target.value("qulVersion").toString();
    const QJsonObject platform = target.value("platform").toObject();
    const QString compatVersion = target.value("compatVersion").toString();
    const QJsonObject toolchain = target.value("toolchain").toObject();
    const QJsonObject toolchainFile = toolchain.value("file").toObject();
    const QJsonObject compiler = toolchain.value("compiler").toObject();
    const QJsonObject boardSdk = target.value("boardSdk").toObject();
    const QJsonObject freeRTOS = target.value("freeRTOS").toObject();

    const QJsonArray platformEntries = platform.value(CMAKE_ENTRIES).toArray();
    const QList<PackageDescription> platformPackages{parsePackages(platformEntries)};

    const PackageDescription toolchainPackage = parsePackage(compiler);
    const PackageDescription toolchainFilePackage = parsePackage(toolchainFile);
    const PackageDescription boardSdkPackage{parsePackage(boardSdk)};
    const PackageDescription freeRtosPackage{parsePackage(freeRTOS)};

    const QVariantList toolchainVersions = toolchain.value("versions").toArray().toVariantList();
    const auto toolchainVersionsList = Utils::transform<QStringList>(toolchainVersions,
                                                                     [&](const QVariant &version) {
                                                                         return version.toString();
                                                                     });
    const QVariantList boardSdkVersions = boardSdk.value("versions").toArray().toVariantList();
    const auto boardSdkVersionsList = Utils::transform<QStringList>(boardSdkVersions,
                                                                    [&](const QVariant &version) {
                                                                        return version.toString();
                                                                    });

    const QVariantList colorDepths = platform.value("colorDepths").toArray().toVariantList();
    const auto colorDepthsVector = Utils::transform<QVector<int>>(colorDepths,
                                                                  [&](const QVariant &colorDepth) {
                                                                      return colorDepth.toInt();
                                                                  });
    const QString platformName = platform.value("platformName").toString();

    return {qulVersion,
            compatVersion,
            {platform.value("id").toString(),
             platformName,
             platform.value("vendor").toString(),
             colorDepthsVector,
             platformName == "Desktop" ? McuTargetDescription::TargetType::Desktop
                                       : McuTargetDescription::TargetType::MCU,
             platformPackages},
            {toolchain.value("id").toString(),
             toolchainVersionsList,
             toolchainPackage,
             toolchainFilePackage},
            boardSdkPackage,
            {freeRTOS.value("envVar").toString(),
             freeRtosPackage}};
}

// https://doc.qt.io/qtcreator/creator-developing-mcu.html#supported-qt-for-mcus-sdks
static const QString legacySupportVersionFor(const QString &sdkVersion)
{
    static const QHash<QString, QString> oldSdkQtcRequiredVersion
        = {{{"1.0"}, {"4.11.x"}}, {{"1.1"}, {"4.12.0 or 4.12.1"}}, {{"1.2"}, {"4.12.2 or 4.12.3"}}};
    if (oldSdkQtcRequiredVersion.contains(sdkVersion))
        return oldSdkQtcRequiredVersion.value(sdkVersion);

    if (QVersionNumber::fromString(sdkVersion).majorVersion() == 1)
        return "4.12.4 up to 6.0";

    return QString();
}

bool checkDeprecatedSdkError(const FilePath &qulDir, QString &message)
{
    const McuPackagePathVersionDetector versionDetector(R"((?<=\bQtMCUs.)(\d+\.\d+))");
    const QString sdkDetectedVersion = versionDetector.parseVersion(qulDir);
    const QString legacyVersion = legacySupportVersionFor(sdkDetectedVersion);

    if (!legacyVersion.isEmpty()) {
        message = McuTarget::tr("Qt for MCUs SDK version %1 detected, "
                                "only supported by Qt Creator version %2. "
                                "This version of Qt Creator requires Qt for MCUs %3 or greater.")
                      .arg(sdkDetectedVersion,
                           legacyVersion,
                           McuSupportOptions::minimalQulVersion().toString());
        return true;
    }

    return false;
}

McuSdkRepository targetsAndPackages(const FilePath &qtForMCUSdkPath,
                                    const SettingsHandler::Ptr &settingsHandler)
{
    QList<McuTargetDescription> descriptions;
    bool isLegacy{false};

    const FilePaths descriptionFiles = targetDescriptionFiles(qtForMCUSdkPath);
    for (const FilePath &filePath : descriptionFiles) {
        if (!filePath.isReadableFile())
            continue;
        const McuTargetDescription desc = parseDescriptionJson(filePath.fileContents());
        bool ok = false;
        const int compatVersion = desc.compatVersion.toInt(&ok);
        if (!desc.compatVersion.isEmpty() && ok && compatVersion > MAX_COMPATIBILITY_VERSION) {
            printMessage(McuTarget::tr("Skipped %1. Unsupported version \"%2\".")
                             .arg(QDir::toNativeSeparators(filePath.fileNameWithPathComponents(1)),
                                  desc.qulVersion),
                         false);
            continue;
        }

        const auto qulVersion{QVersionNumber::fromString(desc.qulVersion)};
        isLegacy = McuSupportOptions::isLegacyVersion(qulVersion);

        if (qulVersion < McuSupportOptions::minimalQulVersion()) {
            const QString legacyVersion = legacySupportVersionFor(desc.qulVersion);
            const QString qtcSupportText
                = !legacyVersion.isEmpty()
                      ? McuTarget::tr("Detected version \"%1\", only supported by Qt Creator %2.")
                            .arg(desc.qulVersion, legacyVersion)
                      : McuTarget::tr("Unsupported version \"%1\".").arg(desc.qulVersion);
            printMessage(McuTarget::tr("Skipped %1. %2 Qt for MCUs version >= %3 required.")
                             .arg(QDir::toNativeSeparators(filePath.fileNameWithPathComponents(1)),
                                  qtcSupportText,
                                  McuSupportOptions::minimalQulVersion().toString()),
                         false);
            continue;
        }
        descriptions.append(desc);
    }

    // No valid description means invalid or old SDK installation.
    if (descriptions.empty()) {
        if (kitsPath(qtForMCUSdkPath).exists()) {
            printMessage(McuTarget::tr("No valid kit descriptions found at %1.")
                             .arg(kitsPath(qtForMCUSdkPath).toUserOutput()),
                         true);
            return McuSdkRepository{};
        } else {
            QString deprecationMessage;
            if (checkDeprecatedSdkError(qtForMCUSdkPath, deprecationMessage)) {
                printMessage(deprecationMessage, true);
                return McuSdkRepository{};
            }
        }
    }
    McuSdkRepository repo = targetsFromDescriptions(descriptions,
                                                    settingsHandler,
                                                    qtForMCUSdkPath,
                                                    isLegacy);

    // Keep targets sorted lexicographically
    Utils::sort(repo.mcuTargets, [](const McuTargetPtr &lhs, const McuTargetPtr &rhs) {
        return McuKitManager::generateKitNameFromTarget(lhs.get())
               < McuKitManager::generateKitNameFromTarget(rhs.get());
    });

    for (const auto &target : repo.mcuTargets) {
        printMessage(McuTarget::tr("Kit for %1 created.")
                         .arg(McuKitManager::generateKitNameFromTarget(target.get())),
                     false);
    }
    return repo;
}

} // namespace McuSupport::Internal