aboutsummaryrefslogtreecommitdiffstats
path: root/share/qbs/modules/cpp/keil.js
blob: 27e4e12d7e22e6bef46b4ccda4fd27369cb84d92 (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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
/****************************************************************************
**
** Copyright (C) 2019 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** 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 http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 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.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

var Cpp = require("cpp.js");
var Environment = require("qbs.Environment");
var File = require("qbs.File");
var FileInfo = require("qbs.FileInfo");
var ModUtils = require("qbs.ModUtils");
var PathTools = require("qbs.PathTools");
var Process = require("qbs.Process");
var TemporaryDir = require("qbs.TemporaryDir");
var TextFile = require("qbs.TextFile");
var Utilities = require("qbs.Utilities");

function isMcs51Architecture(architecture) {
    return architecture === "mcs51";
}

function isMcs251Architecture(architecture) {
    return architecture === "mcs251";
}

function isMcsArchitecture(architecture) {
    return isMcs51Architecture(architecture)
        || isMcs251Architecture(architecture);
}

function isC166Architecture(architecture) {
    return architecture === "c166";
}

function isArmArchitecture(architecture) {
    return architecture.startsWith("arm");
}

function isMcsCompiler(compilerPath) {
    var base = FileInfo.baseName(compilerPath).toLowerCase();
    return base === "c51" || base === "cx51" || base === "c251";
}

function isC166Compiler(compilerPath) {
    return FileInfo.baseName(compilerPath).toLowerCase() === "c166";
}

function isArmCCCompiler(compilerPath) {
    return FileInfo.baseName(compilerPath).toLowerCase() === "armcc";
}

function isArmClangCompiler(compilerPath) {
    return FileInfo.baseName(compilerPath).toLowerCase() === "armclang";
}

function compilerName(qbs) {
    var architecture = qbs.architecture;
    if (architecture === "mcs51")
        return "c51";
    if (architecture === "mcs251")
        return "c251";
    if (isC166Architecture(architecture))
        return "c166";
    if (isArmArchitecture(architecture))
        return "armcc";
    throw "Unable to deduce compiler name for unsupported architecture: '"
            + architecture + "'";
}

function assemblerName(qbs) {
    var architecture = qbs.architecture;
    if (architecture === "mcs51")
        return "a51";
    if (architecture === "mcs251")
        return "a251";
    if (isC166Architecture(architecture))
        return "a166";
    if (isArmArchitecture(architecture))
        return "armasm";
    throw "Unable to deduce assembler name for unsupported architecture: '"
            + architecture + "'";
}

function linkerName(qbs) {
    var architecture = qbs.architecture;
    if (architecture === "mcs51")
        return "bl51";
    if (architecture === "mcs251")
        return "l251";
    if (isC166Architecture(architecture))
        return "l166";
    if (isArmArchitecture(architecture))
        return "armlink";
    throw "Unable to deduce linker name for unsupported architecture: '"
            + architecture + "'";
}

function archiverName(qbs) {
    var architecture = qbs.architecture;
    if (architecture === "mcs51")
        return "lib51";
    if (architecture === "mcs251")
        return "lib251";
    if (isC166Architecture(architecture))
        return "lib166";
    if (isArmArchitecture(architecture))
        return "armar";
    throw "Unable to deduce archiver name for unsupported architecture: '"
            + architecture + "'";
}

function disassemblerName(qbs) {
    var architecture = qbs.architecture;
    return isArmArchitecture(architecture) ? "fromelf" : undefined;
}

function staticLibrarySuffix(qbs) {
    var architecture = qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture)
            || isArmArchitecture(architecture)) {
        return ".lib";
    }
    throw "Unable to deduce static library suffix for unsupported architecture: '"
            + architecture + "'";
}

function executableSuffix(qbs) {
    var architecture = qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture))
        return ".abs";
    if (isArmArchitecture(architecture))
        return ".axf";
    throw "Unable to deduce executable suffix for unsupported architecture: '"
            + architecture + "'";
}

function objectSuffix(qbs) {
    var architecture = qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture))
        return ".obj";
    if (isArmArchitecture(architecture))
        return ".o";
    throw "Unable to deduce object file suffix for unsupported architecture: '"
            + architecture + "'";
}

function linkerMapSuffix(qbs) {
    var architecture = qbs.architecture;
    if (isMcs51Architecture(architecture))
        return ".m51";
    if (isC166Architecture(architecture))
        return ".m66";
    return ".map";
}

function imageFormat(qbs) {
    var architecture = qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture))
        // Keil OMF51 or OMF2 Object Module Format (which is an
        // extension of the original Intel OMF51).
        return "omf";
    if (isArmArchitecture(architecture))
        return "elf";
    throw "Unable to deduce image format for unsupported architecture: '"
            + architecture + "'";
}

function preincludeFlag(compilerPath) {
    if (isArmCCCompiler(compilerPath))
        return "--preinclude";
    else if (isArmClangCompiler(compilerPath))
        return "-include";
}

function guessArmCCArchitecture(targetArchArm, targetArchThumb) {
    var arch = "arm";
    if (targetArchArm === "4" && targetArchThumb === "0")
        arch += "v4";
    else if (targetArchArm === "4" && targetArchThumb === "1")
        arch += "v4t";
    else if (targetArchArm === "5" && targetArchThumb === "2")
        arch += "v5t";
    else if (targetArchArm === "6" && targetArchThumb === "3")
        arch += "v6";
    else if (targetArchArm === "6" && targetArchThumb === "4")
        arch += "v6t2";
    else if (targetArchArm === "0" && targetArchThumb === "3")
        arch += "v6m";
    else if (targetArchArm === "7" && targetArchThumb === "4")
        arch += "v7r";
    else if (targetArchArm === "0" && targetArchThumb === "4")
        arch += "v7m";
    return arch;
}

function guessArmClangArchitecture(targetArchArm, targetArchProfile) {
    targetArchProfile = targetArchProfile.replace(/'/g, "");
    var arch = "arm";
    if (targetArchArm !== "" && targetArchProfile !== "")
        arch += "v" + targetArchArm + targetArchProfile.toLowerCase();
    return arch;
}

function guessArchitecture(macros) {
    if (macros["__C51__"])
        return "mcs51";
    else if (macros["__C251__"])
        return "mcs251";
    else if (macros["__C166__"])
        return "c166";
    else if (macros["__CC_ARM"] === "1")
        return guessArmCCArchitecture(macros["__TARGET_ARCH_ARM"], macros["__TARGET_ARCH_THUMB"]);
    else if (macros["__clang__"] === "1" && macros["__arm__"] === "1")
        return guessArmClangArchitecture(macros["__ARM_ARCH"], macros["__ARM_ARCH_PROFILE"]);
}

function guessEndianness(macros) {
    if (macros["__C51__"] || macros["__C251__"]) {
        // The 8051 processors are 8-bit. So, the data with an integer type
        // represented by more than one byte is stored as big endian in the
        // Keil toolchain. See for more info:
        // * http://www.keil.com/support/man/docs/c51/c51_ap_2bytescalar.htm
        // * http://www.keil.com/support/man/docs/c51/c51_ap_4bytescalar.htm
        // * http://www.keil.com/support/man/docs/c251/c251_ap_2bytescalar.htm
        // * http://www.keil.com/support/man/docs/c251/c251_ap_4bytescalar.htm
        return "big";
    } else if (macros["__C166__"]) {
        // The C166 processors are 16-bit. So, the data with an integer type
        // represented by more than one byte is stored as little endian in the
        // Keil toolchain. See for more info:
        // * http://www.keil.com/support/man/docs/c166/c166_ap_ints.htm
        // * http://www.keil.com/support/man/docs/c166/c166_ap_longs.htm
        return "little";
    } else if (macros["__CC_ARM"]) {
        return macros["__BIG_ENDIAN"] ? "big" : "little";
    } else if (macros["__clang__"] && macros["__arm__"]) {
        switch (macros["__BYTE_ORDER__"]) {
        case "__ORDER_BIG_ENDIAN__":
            return "big";
        case "__ORDER_LITTLE_ENDIAN__":
            return "little";
        }
    }
}

function guessVersion(macros) {
    if (macros["__C51__"] || macros["__C251__"]) {
        var mcsVersion = macros["__C51__"] || macros["__C251__"];
        return { major: parseInt(mcsVersion / 100),
            minor: parseInt(mcsVersion % 100),
            patch: 0 }
    } else if (macros["__C166__"]) {
        var xcVersion = macros["__C166__"];
        return { major: parseInt(xcVersion / 100),
            minor: parseInt(xcVersion % 100),
            patch: 0 }
    } else if (macros["__CC_ARM"] || macros["__clang__"]) {
        var armVersion = macros["__ARMCC_VERSION"];
        return { major: parseInt(armVersion / 1000000),
            minor: parseInt(armVersion / 10000) % 100,
            patch: parseInt(armVersion) % 10000 }
    }
}

function dumpMcsCompilerMacros(compilerFilePath, tag) {
    // C51 or C251 compiler support only C language.
    if (tag === "cpp")
        return {};

    // Note: The C51 or C251 compiler does not support the predefined
    // macros dumping. So, we do it with the following trick, where we try
    // to create and compile a special temporary file and to parse the console
    // output with the own magic pattern: (""|"key"|"value"|"").

    var outputDirectory = new TemporaryDir();
    var outputFilePath = FileInfo.fromNativeSeparators(FileInfo.joinPaths(outputDirectory.path(),
                                                       "dump-macros.c"));
    var outputFile = new TextFile(outputFilePath, TextFile.WriteOnly);

    outputFile.writeLine("#define VALUE_TO_STRING(x) #x");
    outputFile.writeLine("#define VALUE(x) VALUE_TO_STRING(x)");

    // Predefined keys for C51 and C251 compilers, see details:
    // * https://www.keil.com/support/man/docs/c51/c51_pp_predefmacroconst.htm
    // * https://www.keil.com/support/man/docs/c251/c251_pp_predefmacroconst.htm
    var keys = ["__C51__", "__CX51__", "__C251__", "__MODEL__",
                "__STDC__", "__FLOAT64__", "__MODSRC__"];

    // For C51 compiler.
    outputFile.writeLine("#if defined(__C51__) || defined(__CX51__)");
    outputFile.writeLine("#  define VAR_NAME_VALUE(var) \"(\"\"\"\"|\"#var\"|\"VALUE(var)\"|\"\"\"\")\"");
    for (var i in keys) {
        var key = keys[i];
        outputFile.writeLine("#  if defined (" + key + ")");
        outputFile.writeLine("#    pragma message (VAR_NAME_VALUE(" + key + "))");
        outputFile.writeLine("#  endif");
    }
    outputFile.writeLine("#endif");

    // For C251 compiler.
    outputFile.writeLine("#if defined(__C251__)");
    outputFile.writeLine("#  define VAR_NAME_VALUE(var) \"\"|#var|VALUE(var)|\"\"");
    for (var i in keys) {
        var key = keys[i];
        outputFile.writeLine("#  if defined (" + key + ")");
        outputFile.writeLine("#    warning (VAR_NAME_VALUE(" + key + "))");
        outputFile.writeLine("#  endif");
    }
    outputFile.writeLine("#endif");

    outputFile.close();

    var process = new Process();
    process.exec(compilerFilePath, [outputFilePath], false);
    File.remove(outputFilePath);
    var map = {};
    process.readStdOut().trim().split(/\r?\n/g).map(function(line) {
        var parts = line.split("\"|\"", 4);
        if (parts.length === 4)
            map[parts[1]] = parts[2];
    });
    return map;
}

function dumpC166CompilerMacros(compilerFilePath, tag) {
    // C166 compiler support only C language.
    if (tag === "cpp")
        return {};

    // Note: The C166 compiler does not support the predefined
    // macros dumping. Also, it does not support the '#pragma' and
    // '#message|warning|error' directives properly (it is impossible
    // to print to console the value of macro).
    // So, we do it with the following trick, where we try
    // to create and compile a special temporary file and to parse the console
    // output with the own magic pattern, e.g:
    //
    // *** WARNING C320 IN LINE 41 OF c51.c: __C166__
    // *** WARNING C2 IN LINE 42 OF c51.c: '757': unknown #pragma/control, line ignored
    //
    // where the '__C166__' is a key, and the '757' is a value.

    var outputDirectory = new TemporaryDir();
    var outputFilePath = FileInfo.fromNativeSeparators(outputDirectory.path() + "/dump-macros.c");
    var outputFile = new TextFile(outputFilePath, TextFile.WriteOnly);

    // Predefined keys for C166 compiler, see details:
    // * https://www.keil.com/support/man/docs/c166/c166_pp_predefmacroconst.htm
    var keys = ["__C166__", "__DUS__", "__MAC__", "__MOD167__",
                "__MODEL__", "__MODV2__", "__SAVEMAC__", "__STDC__"];

    // For C166 compiler.
    outputFile.writeLine("#if defined(__C166__)");
    for (var i in keys) {
        var key = keys[i];
        outputFile.writeLine("#  if defined (" + key + ")");
        outputFile.writeLine("#    warning " + key);
        outputFile.writeLine("#    pragma " + key);
        outputFile.writeLine("#  endif");
    }
    outputFile.writeLine("#endif");

    outputFile.close();

    function extractKey(line, knownKeys) {
        for (var i in keys) {
            var key = knownKeys[i];
            var regexp = new RegExp("^\\*\\*\\* WARNING C320 IN LINE .+: (" + key + ")$");
            var match = regexp.exec(line);
            if (match)
                return key;
        }
    };

    function extractValue(line) {
        var regexp = new RegExp("^\\*\\*\\* WARNING C2 IN LINE .+'(.+)':.+$");
        var match = regexp.exec(line);
        if (match)
            return match[1];
    };

    var process = new Process();
    process.exec(compilerFilePath, [outputFilePath], false);
    File.remove(outputFilePath);
    var lines = process.readStdOut().trim().split(/\r?\n/g);
    var map = {};
    for (var i = 0; i < lines.length; ++i) {
        // First line should contains the macro key.
        var keyLine = lines[i];
        var key = extractKey(keyLine, keys);
        if (!key)
            continue;

        i += 1;
        if (i >= lines.length)
            break;

        // Second line should contains the macro value.
        var valueLine = lines[i];
        var value = extractValue(valueLine);
        if (!value)
            continue;
        map[key] = value;
    }
    return map;
}

function dumpArmCCCompilerMacros(compilerFilePath, tag, nullDevice) {
    var args = [ "-E", "--list-macros", "--cpu=cortex-m0", nullDevice ];
    if (tag === "cpp")
        args.push("--cpp");

    var p = new Process();
    p.exec(compilerFilePath, args, false);
    return ModUtils.extractMacros(p.readStdOut());
}

function dumpArmClangCompilerMacros(compilerFilePath, tag, nullDevice) {
    var args = [ "--target=arm-arm-none-eabi", "-mcpu=cortex-m0", "-dM", "-E",
                "-x", ((tag === "cpp") ? "c++" : "c"), nullDevice ];
    var p = new Process();
    p.exec(compilerFilePath, args, false);
    return ModUtils.extractMacros(p.readStdOut());
}

function dumpMacros(compilerFilePath, tag, nullDevice) {
    if (isMcsCompiler(compilerFilePath))
        return dumpMcsCompilerMacros(compilerFilePath, tag, nullDevice);
    else if (isC166Compiler(compilerFilePath))
        return dumpC166CompilerMacros(compilerFilePath, tag, nullDevice);
    else if (isArmCCCompiler(compilerFilePath))
        return dumpArmCCCompilerMacros(compilerFilePath, tag, nullDevice);
    else if (isArmClangCompiler(compilerFilePath))
        return dumpArmClangCompilerMacros(compilerFilePath, tag, nullDevice);
    return {};
}

function dumpMcsCompilerIncludePaths(compilerFilePath) {
    var includePath = compilerFilePath.replace(/bin[\\\/](.*)$/i, "inc");
    return [includePath];
}

function dumpC166CompilerIncludePaths(compilerFilePath) {
    // Same as for MCS compiler.
    return dumpMcsCompilerIncludePaths(compilerFilePath);
}

function dumpArmCCCompilerIncludePaths(compilerFilePath) {
    var includePath = compilerFilePath.replace(/bin[\\\/](.*)$/i, "include");
    return [includePath];
}

function dumpArmClangCompilerIncludePaths(compilerFilePath, nullDevice) {
    var args = [ "--target=arm-arm-none-eabi", "-mcpu=cortex-m0", "-v", "-E",
                "-x", "c++", nullDevice ];
    var p = new Process();
    p.exec(compilerFilePath, args, false);
    var lines = p.readStdErr().trim().split(/\r?\n/g).map(function (line) { return line.trim(); });
    var addIncludes = false;
    var includePaths = [];
    for (var i = 0; i < lines.length; ++i) {
        var line = lines[i];
        if (line === "#include <...> search starts here:")
            addIncludes = true;
        else if (line === "End of search list.")
            addIncludes = false;
        else if (addIncludes)
            includePaths.push(line);
    }
    return includePaths;
}

function dumpDefaultPaths(compilerFilePath, nullDevice) {
    var includePaths = [];
    if (isMcsCompiler(compilerFilePath))
        includePaths = dumpMcsCompilerIncludePaths(compilerFilePath);
    else if (isC166Compiler(compilerFilePath))
        includePaths = dumpC166CompilerIncludePaths(compilerFilePath);
    else if (isArmCCCompiler(compilerFilePath))
        includePaths = dumpArmCCCompilerIncludePaths(compilerFilePath);
    else if (isArmClangCompiler(compilerFilePath))
        includePaths = dumpArmClangCompilerIncludePaths(compilerFilePath, nullDevice);
    return { "includePaths": includePaths };
}

function collectLibraryDependencies(product) {
    var seen = {};
    var result = [];

    function addFilePath(filePath) {
        result.push({ filePath: filePath });
    }

    function addArtifactFilePaths(dep, artifacts) {
        if (!artifacts)
            return;
        var artifactFilePaths = artifacts.map(function(a) { return a.filePath; });
        artifactFilePaths.forEach(addFilePath);
    }

    function addExternalStaticLibs(obj) {
        if (!obj.cpp)
            return;
        function ensureArray(a) {
            return (a instanceof Array) ? a : [];
        }
        function sanitizedModuleListProperty(obj, moduleName, propertyName) {
            return ensureArray(ModUtils.sanitizedModuleProperty(obj, moduleName, propertyName));
        }
        var externalLibs = [].concat(
                    sanitizedModuleListProperty(obj, "cpp", "staticLibraries"));
        var staticLibrarySuffix = obj.moduleProperty("cpp", "staticLibrarySuffix");
        externalLibs.forEach(function(staticLibraryName) {
            if (!staticLibraryName.endsWith(staticLibrarySuffix))
                staticLibraryName += staticLibrarySuffix;
            addFilePath(staticLibraryName);
        });
    }

    function traverse(dep) {
        if (seen.hasOwnProperty(dep.name))
            return;
        seen[dep.name] = true;

        if (dep.parameters.cpp && dep.parameters.cpp.link === false)
            return;

        var staticLibraryArtifacts = dep.artifacts["staticlibrary"];
        if (staticLibraryArtifacts) {
            dep.dependencies.forEach(traverse);
            addArtifactFilePaths(dep, staticLibraryArtifacts);
            addExternalStaticLibs(dep);
        }
    }

    product.dependencies.forEach(traverse);
    addExternalStaticLibs(product);
    return result;
}

function filterMcsOutput(output) {
    var filteredLines = [];
    output.split(/\r\n|\r|\n/).forEach(function(line) {
        var regexp = /^\s*\*{3}\s|^\s{29}|^\s{4}\S|^\s{2}[0-9A-F]{4}|^\s{21,25}\d+|^[0-9A-F]{4}\s\d+/;
        if (regexp.exec(line))
            filteredLines.push(line);
    });
    return filteredLines.join('\n');
};

function filterC166Output(output) {
    var filteredLines = [];
    output.split(/\r\n|\r|\n/).forEach(function(line) {
        var regexp = /^\s*\*{3}\s|^\s{29}|^\s{27,28}\d+|^\s{21}\d+|^\s{4}\S|^\s{2}[0-9A-F]{4}|^[0-9A-F]{4}\s\d+/;
        if (regexp.exec(line))
            filteredLines.push(line);
    });
    return filteredLines.join('\n');
};

function compilerOutputArtifacts(input, isCompilerArtifacts) {
    var artifacts = [];
    artifacts.push({
        fileTags: ["obj"],
        filePath: Utilities.getHash(input.baseDir) + "/"
              + input.fileName + input.cpp.objectSuffix
    });
    if (isCompilerArtifacts && input.cpp.generateCompilerListingFiles) {
        artifacts.push({
            fileTags: ["lst"],
            filePath: Utilities.getHash(input.baseDir) + "/"
                  + input.fileName + input.cpp.compilerListingSuffix
        });
    } else if (!isCompilerArtifacts && input.cpp.generateAssemblerListingFiles) {
        artifacts.push({
            fileTags: ["lst"],
            filePath: Utilities.getHash(input.baseDir) + "/"
                  + input.fileName + input.cpp.assemblerListingSuffix
        });
    }
    return artifacts;
}

function applicationLinkerOutputArtifacts(product) {
    var app = {
        fileTags: ["application"],
        filePath: FileInfo.joinPaths(
                      product.destinationDirectory,
                      PathTools.applicationFilePath(product))
    };
    var mem_map = {
        fileTags: ["mem_map"],
        filePath: FileInfo.joinPaths(
                      product.destinationDirectory,
                      product.targetName + product.cpp.linkerMapSuffix)
    };
    return [app, mem_map];
}

function staticLibraryLinkerOutputArtifacts(product) {
    var staticLib = {
        fileTags: ["staticlibrary"],
        filePath: FileInfo.joinPaths(
                      product.destinationDirectory,
                      PathTools.staticLibraryFilePath(product))
    };
    return [staticLib]
}

function compilerFlags(project, product, input, outputs, explicitlyDependsOn) {
    // Determine which C-language we're compiling.
    var tag = ModUtils.fileTagForTargetLanguage(input.fileTags.concat(outputs.obj[0].fileTags));
    var args = [];

    var allDefines = [];
    var platformDefines = input.cpp.platformDefines;
    if (platformDefines)
        allDefines = allDefines.uniqueConcat(platformDefines);
    var defines = input.cpp.defines;
    if (defines)
        allDefines = allDefines.uniqueConcat(defines);

    var allIncludePaths = [];
    var includePaths = input.cpp.includePaths;
    if (includePaths)
        allIncludePaths = allIncludePaths.uniqueConcat(includePaths);
    var systemIncludePaths = input.cpp.systemIncludePaths;
    if (systemIncludePaths)
        allIncludePaths = allIncludePaths.uniqueConcat(systemIncludePaths);
    var distributionIncludePaths = input.cpp.distributionIncludePaths;
    if (distributionIncludePaths)
        allIncludePaths = allIncludePaths.uniqueConcat(distributionIncludePaths);

    var architecture = input.qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture)) {
        // Input.
        args.push(input.filePath);

        // Output.
        args.push("OBJECT (" + outputs.obj[0].filePath + ")");

        // Defines.
        if (allDefines.length > 0)
            args = args.concat("DEFINE (" + allDefines.join(",") + ")");

        // Includes.
        if (allIncludePaths.length > 0)
            args = args.concat("INCDIR (" + allIncludePaths.join(";") + ")");

        // Debug information flags.
        if (input.cpp.debugInformation)
            args.push("DEBUG");

        // Optimization level flags.
        switch (input.cpp.optimization) {
        case "small":
            args.push("OPTIMIZE (SIZE)");
            break;
        case "fast":
            args.push("OPTIMIZE (SPEED)");
            break;
        case "none":
            args.push("OPTIMIZE (0)");
            break;
        }

        // Warning level flags.
        switch (input.cpp.warningLevel) {
        case "none":
            args.push("WARNINGLEVEL (0)");
            break;
        case "all":
            args.push("WARNINGLEVEL (2)");
            if (architecture === "mcs51")
                args.push("FARWARNING");
            break;
        }

        // Listing files generation flag.
        if (!input.cpp.generateCompilerListingFiles)
            args.push("NOPRINT");
        else
            args.push("PRINT(" + outputs.lst[0].filePath + ")");
    } else if (isArmArchitecture(architecture)) {
        // Input.
        args.push("-c", input.filePath);
        // Output.
        args.push("-o", outputs.obj[0].filePath);

        // Defines.
        args = args.concat(allDefines.map(function(define) { return '-D' + define }));
        // Includes.
        args = args.concat(allIncludePaths.map(function(include) { return '-I' + include }));

        var prefixHeaders = input.cpp.prefixHeaders;
        for (var i in prefixHeaders)
            args.push(input.cpp.preincludeFlag, prefixHeaders[i]);

        var compilerPath = input.cpp.compilerPath;
        if (isArmCCCompiler(compilerPath)) {
            // Debug information flags.
            if (input.cpp.debugInformation) {
                args.push("--debug");
                args.push("-g");
            }

            // Optimization level flags.
            switch (input.cpp.optimization) {
            case "small":
                args.push("-Ospace")
                break;
            case "fast":
                args.push("-Otime")
                break;
            case "none":
                args.push("-O0")
                break;
            }

            // Warning level flags.
            switch (input.cpp.warningLevel) {
            case "none":
                args.push("-W");
                break;
            default:
                // By default all warnings are enabled.
                break;
            }

            if (tag === "c") {
                // C language version flags.
                var knownCLanguageValues = ["c99", "c90"];
                var cLanguageVersion = Cpp.languageVersion(
                            input.cpp.cLanguageVersion, knownCLanguageValues, "C");
                switch (cLanguageVersion) {
                case "c99":
                    args.push("--c99");
                    break;
                case "c90":
                    args.push("--c90");
                    break;
                }
            } else if (tag === "cpp") {
                // C++ language version flags.
                var knownCppLanguageValues = ["c++11", "c++03"];
                var cppLanguageVersion = Cpp.languageVersion(
                            input.cpp.cxxLanguageVersion, knownCppLanguageValues, "C++");
                switch (cppLanguageVersion) {
                case "c++11":
                    args.push("--cpp11");
                    break;
                default:
                    // Default C++ language is C++03.
                    args.push("--cpp");
                    break;
                }

                // Exceptions flags.
                var enableExceptions = input.cpp.enableExceptions;
                if (enableExceptions !== undefined)
                    args.push(enableExceptions ? "--exceptions" : "--no_exceptions");

                // RTTI flags.
                var enableRtti = input.cpp.enableRtti;
                if (enableRtti !== undefined)
                    args.push(enableRtti ? "--rtti" : "--no_rtti");
            }

            // Listing files generation flag.
            if (input.cpp.generateCompilerListingFiles) {
                args.push("--list");
                args.push("--list_dir", FileInfo.path(outputs.lst[0].filePath));
            }
        } else if (isArmClangCompiler(compilerPath)) {
            // Debug information flags.
            if (input.cpp.debugInformation)
                args.push("-g");

            // Optimization level flags.
            switch (input.cpp.optimization) {
            case "small":
                args.push("-Oz")
                break;
            case "fast":
                args.push("-Ofast")
                break;
            case "none":
                args.push("-O0")
                break;
            }

            // Warning level flags.
            switch (input.cpp.warningLevel) {
            case "all":
                args.push("-Wall");
                break;
            default:
                break;
            }

            if (input.cpp.treatWarningsAsErrors)
                args.push("-Werror");

            if (tag === "c") {
                // C language version flags.
                var knownCLanguageValues = ["c11", "c99", "c90", "c89"];
                var cLanguageVersion = Cpp.languageVersion(
                            input.cpp.cLanguageVersion, knownCLanguageValues, "C");
                if (cLanguageVersion)
                    args.push("-std=" + cLanguageVersion);
            } else if (tag === "cpp") {
                // C++ language version flags.
                var knownCppLanguageValues = ["c++17", "c++14", "c++11", "c++03", "c++98"];
                var cppLanguageVersion = Cpp.languageVersion(
                            input.cpp.cxxLanguageVersion, knownCppLanguageValues, "C++");
                if (cppLanguageVersion)
                    args.push("-std=" + cppLanguageVersion);

                // Exceptions flags.
                var enableExceptions = input.cpp.enableExceptions;
                if (enableExceptions !== undefined)
                    args.push(enableExceptions ? "-fexceptions" : "-fno-exceptions");

                // RTTI flags.
                var enableRtti = input.cpp.enableRtti;
                if (enableRtti !== undefined)
                    args.push(enableRtti ? "-frtti" : "-fno-rtti");
            }

            // Listing files generation does not supported!
            // There are only a workaround: http://www.keil.com/support/docs/4152.htm
        }
    }

    // Misc flags.
    args = args.concat(ModUtils.moduleProperty(input, "platformFlags"),
                       ModUtils.moduleProperty(input, "flags"),
                       ModUtils.moduleProperty(input, "platformFlags", tag),
                       ModUtils.moduleProperty(input, "flags", tag),
                       ModUtils.moduleProperty(input, "driverFlags", tag));
    return args;
}

function assemblerFlags(project, product, input, outputs, explicitlyDependsOn) {
    // Determine which C-language we're compiling
    var tag = ModUtils.fileTagForTargetLanguage(input.fileTags.concat(outputs.obj[0].fileTags));
    var args = [];

    var allDefines = [];
    var platformDefines = input.cpp.platformDefines;
    if (platformDefines)
        allDefines = allDefines.uniqueConcat(platformDefines);
    var defines = input.cpp.defines;
    if (defines)
        allDefines = allDefines.uniqueConcat(defines);

    var allIncludePaths = [];
    var includePaths = input.cpp.includePaths;
    if (includePaths)
        allIncludePaths = allIncludePaths.uniqueConcat(includePaths);
    var systemIncludePaths = input.cpp.systemIncludePaths;
    if (systemIncludePaths)
        allIncludePaths = allIncludePaths.uniqueConcat(systemIncludePaths);
    var distributionIncludePaths = input.cpp.distributionIncludePaths;
    if (distributionIncludePaths)
        allIncludePaths = allIncludePaths.uniqueConcat(distributionIncludePaths);

    var architecture = input.qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture)) {
        // Input.
        args.push(input.filePath);

        // Output.
        args.push("OBJECT (" + outputs.obj[0].filePath + ")");

        // Defines.
        if (allDefines.length > 0)
            args = args.concat("DEFINE (" + allDefines.join(",") + ")");

        // Includes.
        if (allIncludePaths.length > 0)
            args = args.concat("INCDIR (" + adjusted.join(";") + ")");

        // Debug information flags.
        if (input.cpp.debugInformation)
            args.push("DEBUG");

        // Enable errors printing.
        args.push("EP");

        // Listing files generation flag.
        if (!input.cpp.generateAssemblerListingFiles)
            args.push("NOPRINT");
        else
            args.push("PRINT(" + outputs.lst[0].filePath + ")");
    } else if (isArmArchitecture(architecture)) {
        // Input.
        args.push(input.filePath);

        // Output.
        args.push("-o", outputs.obj[0].filePath);

        // Defines.
        allDefines.forEach(function(define) {
            var parts = define.split("=");
            args.push("--pd");
            if (parts[1] === undefined)
                args.push(parts[0] + " SETA " + 1);
            else if (parts[1].contains("\""))
                args.push(parts[0] + " SETS " + parts[1]);
            else
                args.push(parts[0] + " SETA " + parts[1]);
        });

        // Includes.
        args = args.concat(allIncludePaths.map(function(include) { return '-I' + include }));

        // Debug information flags.
        if (input.cpp.debugInformation) {
            args.push("--debug");
            args.push("-g");
        }

        // Warning level flags.
        if (input.cpp.warningLevel === "none")
            args.push("--no_warn");

        // Byte order flags.
        var endianness = input.cpp.endianness;
        if (endianness)
            args.push((endianness === "little") ? "--littleend" : "--bigend");

        // Listing files generation flag.
        if (input.cpp.generateAssemblerListingFiles)
            args.push("--list", outputs.lst[0].filePath);
    }

    // Misc flags.
    args = args.concat(ModUtils.moduleProperty(input, "platformFlags", tag),
                       ModUtils.moduleProperty(input, "flags", tag));
    return args;
}

function disassemblerFlags(project, product, input, outputs, explicitlyDependsOn) {
    var args = ["--disassemble", "--interleave=source"];
    args.push(outputs.obj[0].filePath);
    args.push("--output=" + outputs.lst[0].filePath);
    return args;
}

function linkerFlags(project, product, inputs, outputs) {
    var args = [];

    // Library paths.
    var libraryPaths = product.cpp.libraryPaths;

    var architecture = product.qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture)) {
        // Note: The C51, C251, or C166 linker does not distinguish an object files and
        // a libraries, it interpret all this stuff as an input objects,
        // so, we need to pass it together in one string.
        var allObjectPaths = [];

        // Inputs.
        if (inputs.obj)
            inputs.obj.map(function(obj) { allObjectPaths.push(obj.filePath) });

        // Library dependencies.
        var libraryObjects = collectLibraryDependencies(product);
        allObjectPaths = allObjectPaths.concat(libraryObjects.map(function(lib) {
            // Semi-intelligent handling the library paths.
            // We need to add the full path prefix to the library file if this
            // file is not absolute or not relative. Reason is that the C51, C251,
            // and C166 linkers does not support the library paths.
            var filePath = lib.filePath;
            if (FileInfo.isAbsolutePath(filePath))
                return filePath;
            for (var i = 0; i < libraryPaths.length; ++i) {
                var fullPath = FileInfo.joinPaths(libraryPaths[i], filePath);
                if (File.exists(fullPath))
                    return fullPath;
            }
            return filePath;
        }));

        // Add all input objects as arguments (application and library object files).
        if (allObjectPaths.length > 0)
            args = args.concat(allObjectPaths.join(","));

        // Output.
        args.push("TO", outputs.application[0].filePath);

        // Map file generation flag.
        if (!product.cpp.generateLinkerMapFile)
            args.push("NOPRINT");
        else
            args.push("PRINT(" + outputs.mem_map[0].filePath + ")");
    } else if (isArmArchitecture(architecture)) {
        // Inputs.
        if (inputs.obj)
            args = args.concat(inputs.obj.map(function(obj) { return obj.filePath }));

        // Output.
        args.push("--output", outputs.application[0].filePath);

        if (libraryPaths)
            args.push("--userlibpath=" + libraryPaths.join(","));

        // Library dependencies.
        var libraryDependencies = collectLibraryDependencies(product);
        args = args.concat(libraryDependencies.map(function(dep) { return dep.filePath; }));

        // Debug information flag.
        var debugInformation = product.cpp.debugInformation;
        if (debugInformation !== undefined)
            args.push(debugInformation ? "--debug" : "--no_debug");

        // Map file generation flag.
        if (product.cpp.generateLinkerMapFile)
            args.push("--list", outputs.mem_map[0].filePath);

        // Entry point flag.
        if (product.cpp.entryPoint)
            args.push("--entry", product.cpp.entryPoint);

        // Linker scripts flags.
        var linkerScripts = inputs.linkerscript
                ? inputs.linkerscript.map(function(a) { return a.filePath; }) : [];
        linkerScripts.forEach(function(script) { args.push("--scatter", script); });
    }

    // Misc flags.
    args = args.concat(ModUtils.moduleProperty(product, "driverLinkerFlags"));
    return args;
}

function archiverFlags(project, product, inputs, outputs) {
    var args = [];

    var architecture = product.qbs.architecture;
    if (isMcsArchitecture(architecture) || isC166Architecture(architecture)) {
        // Library creation command.
        args.push("TRANSFER");

        var allObjectPaths = [];
        function addObjectPath(obj) {
            allObjectPaths.push(obj.filePath);
        }

        // Inputs.
        if (inputs.obj)
            inputs.obj.map(function(obj) { addObjectPath(obj) });

        // Add all input objects as arguments.
        if (allObjectPaths.length > 0)
            args = args.concat(allObjectPaths.join(","));

        // Output.
        args.push("TO", outputs.staticlibrary[0].filePath);
    } else if (isArmArchitecture(architecture)) {
        // Note: The ARM archiver command line expect the output file
        // first, and then a set of input objects.

        // Output.
        args.push("--create", outputs.staticlibrary[0].filePath);

        // Inputs.
        if (inputs.obj)
            args = args.concat(inputs.obj.map(function(obj) { return obj.filePath }));

        // Debug information flag.
        if (product.cpp.debugInformation)
            args.push("--debug_symbols");
    }

    return args;
}

// The ARMCLANG compiler does not support generation
// for the listing files:
// * https://www.keil.com/support/docs/4152.htm
// So, we generate the listing files from the object files
// using the disassembler.
function generateClangCompilerListing(project, product, inputs, outputs, input, output) {
    if (isArmClangCompiler(input.cpp.compilerPath) && input.cpp.generateCompilerListingFiles) {
        var args = disassemblerFlags(project, product, input, outputs, explicitlyDependsOn);
        var disassemblerPath = input.cpp.disassemblerPath;
        var cmd = new Command(disassemblerPath, args);
        cmd.silent = true;
        return cmd;
    }
}

// The ARMCC compiler generates the listing files only in a short form,
// e.g. to 'module.lst' instead of 'module.{c|cpp}.lst', that complicates
// the auto-tests. Therefore we need to rename generated listing files
// with correct unified names.
function generateArmccCompilerListing(project, product, inputs, outputs, input, output) {
    if (isArmCCCompiler(input.cpp.compilerPath) && input.cpp.generateCompilerListingFiles) {
        var listingPath = FileInfo.path(outputs.lst[0].filePath);
        var cmd = new JavaScriptCommand();
        cmd.oldListing = FileInfo.joinPaths(listingPath, input.baseName + ".lst");
        cmd.newListing = FileInfo.joinPaths(
                    listingPath, input.fileName + input.cpp.compilerListingSuffix);
        cmd.silent = true;
        cmd.sourceCode = function() { File.move(oldListing, newListing); };
        return cmd;
    }
}

function prepareCompiler(project, product, inputs, outputs, input, output, explicitlyDependsOn) {
    var cmds = [];
    var args = compilerFlags(project, product, input, outputs, explicitlyDependsOn);
    var compilerPath = input.cpp.compilerPath;
    var architecture = input.cpp.architecture;
    var cmd = new Command(compilerPath, args);
    cmd.description = "compiling " + input.fileName;
    cmd.highlight = "compiler";
    if (isMcsArchitecture(architecture)) {
        cmd.maxExitCode = 1;
        cmd.stdoutFilterFunction = filterMcsOutput;
    } else if (isC166Architecture(architecture)) {
        cmd.maxExitCode = 1;
        cmd.stdoutFilterFunction = filterC166Output;
    }
    cmds.push(cmd);

    cmd = generateClangCompilerListing(project, product, inputs, outputs, input, output);
    if (cmd)
        cmds.push(cmd);

    cmd = generateArmccCompilerListing(project, product, inputs, outputs, input, output);
    if (cmd)
        cmds.push(cmd);

    return cmds;
}

function prepareAssembler(project, product, inputs, outputs, input, output, explicitlyDependsOn) {
    var args = assemblerFlags(project, product, input, outputs, explicitlyDependsOn);
    var assemblerPath = input.cpp.assemblerPath;
    var architecture = input.cpp.architecture;
    var cmd = new Command(assemblerPath, args);
    cmd.description = "assembling " + input.fileName;
    cmd.highlight = "compiler";
    if (isMcsArchitecture(architecture)) {
        cmd.maxExitCode = 1;
        cmd.stdoutFilterFunction = filterMcsOutput;
    } else if (isC166Architecture(architecture)) {
        cmd.maxExitCode = 1;
        cmd.stdoutFilterFunction = filterC166Output;
    }
    return [cmd];
}

function prepareLinker(project, product, inputs, outputs, input, output) {
    var primaryOutput = outputs.application[0];
    var args = linkerFlags(project, product, inputs, outputs);
    var linkerPath = product.cpp.linkerPath;
    var architecture = product.cpp.architecture;
    var cmd = new Command(linkerPath, args);
    cmd.description = "linking " + primaryOutput.fileName;
    cmd.highlight = "linker";
    if (isMcsArchitecture(architecture)) {
        cmd.maxExitCode = 1;
        cmd.stdoutFilterFunction = filterMcsOutput;
    } else if (isC166Architecture(architecture)) {
        cmd.maxExitCode = 1;
        cmd.stdoutFilterFunction = filterC166Output;
    }
    return [cmd];
}

function prepareArchiver(project, product, inputs, outputs, input, output) {
    var args = archiverFlags(project, product, inputs, outputs);
    var archiverPath = product.cpp.archiverPath;
    var architecture = product.cpp.architecture;
    var cmd = new Command(archiverPath, args);
    cmd.description = "linking " + output.fileName;
    cmd.highlight = "linker";
    if (isMcsArchitecture(architecture)) {
        cmd.stdoutFilterFunction = filterMcsOutput;
    } else if (isC166Architecture(architecture)) {
        cmd.stdoutFilterFunction = filterC166Output;
    }
    return [cmd];
}