aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/cpp/CppConfiguration.java
blob: 522e6ec071c02dd859c72e27308fe76ca37ea4a2 (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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.rules.cpp;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactFactory;
import com.google.devtools.build.lib.actions.PackageRootResolutionException;
import com.google.devtools.build.lib.actions.PackageRootResolver;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.ViewCreationFailedException;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.CompilationMode;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.analysis.config.PerLabelOptions;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.rules.cpp.CppConfigurationLoader.CppConfigurationParameters;
import com.google.devtools.build.lib.rules.cpp.FdoSupport.FdoException;
import com.google.devtools.build.lib.syntax.SkylarkCallable;
import com.google.devtools.build.lib.syntax.SkylarkModule;
import com.google.devtools.build.lib.util.IncludeScanningUtil;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.LinkingModeFlags;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.LipoMode;
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import com.google.devtools.common.options.OptionsParsingException;
import com.google.protobuf.TextFormat;
import com.google.protobuf.TextFormat.ParseException;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipException;

import javax.annotation.Nullable;

/**
 * This class represents the C/C++ parts of the {@link BuildConfiguration},
 * including the host architecture, target architecture, compiler version, and
 * a standard library version. It has information about the tools locations and
 * the flags required for compiling.
 */
@SkylarkModule(name = "cpp", doc = "A configuration fragment for C++")
@Immutable
public class CppConfiguration extends BuildConfiguration.Fragment {

  /**
   * String indicating a Mac system, for example when used in a crosstool configuration's host or
   * target system name.
   */
  public static final String MAC_SYSTEM_NAME = "x86_64-apple-macosx";

  /**
   * An enumeration of all the tools that comprise a toolchain.
   */
  public enum Tool {
    AR("ar"),
    CPP("cpp"),
    GCC("gcc"),
    GCOV("gcov"),
    GCOVTOOL("gcov-tool"),
    LD("ld"),
    NM("nm"),
    OBJCOPY("objcopy"),
    OBJDUMP("objdump"),
    STRIP("strip"),
    DWP("dwp");

    private final String namePart;

    private Tool(String namePart) {
      this.namePart = namePart;
    }

    public String getNamePart() {
      return namePart;
    }
  }

  /**
   * Values for the --hdrs_check option.
   */
  public static enum HeadersCheckingMode {
    /** Legacy behavior: Silently allow undeclared headers. */
    LOOSE,
    /** Warn about undeclared headers. */
    WARN,
    /** Disallow undeclared headers. */
    STRICT
  }

  /**
   * --dynamic_mode parses to DynamicModeFlag, but AUTO will be translated based on platform,
   * resulting in a DynamicMode value.
   */
  public enum DynamicMode     { OFF, DEFAULT, FULLY }

  /**
   * This enumeration is used for the --strip option.
   */
  public static enum StripMode {

    ALWAYS("always"),       // Always strip.
    SOMETIMES("sometimes"), // Strip iff compilationMode == FASTBUILD.
    NEVER("never");         // Never strip.

    private final String mode;

    private StripMode(String mode) {
      this.mode = mode;
    }

    @Override
    public String toString() {
      return mode;
    }
  }

  /** Storage for the libc label, if given. */
  public static class LibcTop implements Serializable {
    private final Label label;

    LibcTop(Label label) {
      Preconditions.checkArgument(label != null);
      this.label = label;
    }

    public Label getLabel() {
      return label;
    }

    public PathFragment getSysroot() {
      return label.getPackageFragment();
    }

    @Override
    public String toString() {
      return label.toString();
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof LibcTop) {
        return label.equals(((LibcTop) other).label);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return label.hashCode();
    }
  }

  /**
   * This macro will be passed as a command-line parameter (eg. -DBUILD_FDO_TYPE="LIPO").
   * For possible values see {@code CppModel.getFdoBuildStamp()}.
   */
  public static final String FDO_STAMP_MACRO = "BUILD_FDO_TYPE";

  /**
   * This file (found under the sysroot) may be unconditionally included in every C/C++ compilation.
   */
  private static final PathFragment BUILT_IN_INCLUDE_PATH_FRAGMENT =
      new PathFragment("include/stdc-predef.h");

  /**
   * Represents an optional flag that can be toggled using the package features mechanism.
   */
  @VisibleForTesting
  static class OptionalFlag implements Serializable {
    private final String name;
    private final List<String> flags;

    @VisibleForTesting
    OptionalFlag(String name, List<String> flags) {
      this.name = name;
      this.flags = flags;
    }

    private List<String> getFlags() {
      return flags;
    }

    private String getName() {
      return name;
    }
  }

  @VisibleForTesting
  static class FlagList implements Serializable {
    private List<String> prefixFlags;
    private List<OptionalFlag> optionalFlags;
    private List<String> suffixFlags;

    @VisibleForTesting
    FlagList(List<String> prefixFlags,
                      List<OptionalFlag> optionalFlags,
                      List<String> suffixFlags) {
      this.prefixFlags = prefixFlags;
      this.optionalFlags = optionalFlags;
      this.suffixFlags = suffixFlags;
    }

    @VisibleForTesting
    List<String> evaluate(Collection<String> features) {
      ImmutableList.Builder<String> result = ImmutableList.builder();
      result.addAll(prefixFlags);
      for (OptionalFlag optionalFlag : optionalFlags) {
        // The flag is added if the default is true and the flag is not specified,
        // or if the default is false and the flag is specified.
        if (features.contains(optionalFlag.getName())) {
          result.addAll(optionalFlag.getFlags());
        }
      }

      result.addAll(suffixFlags);
      return result.build();
    }
  }

  private final Label crosstoolTop;
  private final String hostSystemName;
  private final String compiler;
  private final String targetCpu;
  private final String targetSystemName;
  private final String targetLibc;
  private final LipoMode lipoMode;
  private final PathFragment crosstoolTopPathFragment;

  private final String abi;
  private final String abiGlibcVersion;

  private final String toolchainIdentifier;

  private final CcToolchainFeatures toolchainFeatures;
  private final boolean supportsGoldLinker;
  private final boolean supportsThinArchives;
  private final boolean supportsStartEndLib;
  private final boolean supportsInterfaceSharedObjects;
  private final boolean supportsEmbeddedRuntimes;
  private final boolean supportsFission;

  // We encode three states with two booleans:
  // (1) (false false) -> no pic code
  // (2) (true false)  -> shared libraries as pic, but not binaries
  // (3) (true true)   -> both shared libraries and binaries as pic
  private final boolean toolchainNeedsPic;
  private final boolean usePicForBinaries;

  private final FdoSupport fdoSupport;

  // TODO(bazel-team): All these labels (except for ccCompilerRuleLabel) can be removed once the
  // transition to the cc_compiler rule is complete.
  private final Label libcLabel;
  private final Label staticRuntimeLibsLabel;
  private final Label dynamicRuntimeLibsLabel;
  private final Label ccToolchainLabel;

  private final PathFragment sysroot;
  private final PathFragment runtimeSysroot;
  private final List<PathFragment> builtInIncludeDirectories;
  private Artifact builtInIncludeFile;

  private final Map<String, PathFragment> toolPaths;
  private final PathFragment ldExecutable;

  // Only used during construction.
  private final List<String> commonLinkOptions;
  private final ListMultimap<CompilationMode, String> linkOptionsFromCompilationMode;
  private final ListMultimap<LipoMode, String> linkOptionsFromLipoMode;
  private final ListMultimap<LinkingMode, String> linkOptionsFromLinkingMode;

  private final FlagList compilerFlags;
  private final FlagList cxxFlags;
  private final FlagList unfilteredCompilerFlags;
  private final List<String> cOptions;

  private FlagList fullyStaticLinkFlags;
  private FlagList mostlyStaticLinkFlags;
  private FlagList mostlyStaticSharedLinkFlags;
  private FlagList dynamicLinkFlags;
  private FlagList dynamicLibraryLinkFlags;
  private final List<String> testOnlyLinkFlags;

  private final List<String> linkOptions;

  private final List<String> objcopyOptions;
  private final List<String> ldOptions;
  private final List<String> arOptions;
  private final List<String> arThinArchivesOptions;

  private final Map<String, String> additionalMakeVariables;

  private final CppOptions cppOptions;

  // The dynamic mode for linking.
  private final DynamicMode dynamicMode;
  private final boolean stripBinaries;
  private final ImmutableMap<String, String> commandLineDefines;
  private final String solibDirectory;
  private final CompilationMode compilationMode;
  private final Path execRoot;
  /**
   *  If true, the ConfiguredTarget is only used to get the necessary cross-referenced
   *  CppCompilationContexts, but registering build actions is disabled.
   */
  private final boolean lipoContextCollector;
  private final Root greppedIncludesDirectory;

  protected CppConfiguration(CppConfigurationParameters params)
      throws InvalidConfigurationException {
    CrosstoolConfig.CToolchain toolchain = params.toolchain;
    cppOptions = params.buildOptions.get(CppOptions.class);
    this.hostSystemName = toolchain.getHostSystemName();
    this.compiler = toolchain.getCompiler();
    this.targetCpu = toolchain.getTargetCpu();
    this.lipoMode = cppOptions.getLipoMode();
    this.targetSystemName = toolchain.getTargetSystemName();
    this.targetLibc = toolchain.getTargetLibc();
    this.crosstoolTop = params.crosstoolTop;
    this.ccToolchainLabel = params.ccToolchainLabel;
    this.compilationMode =
        params.buildOptions.get(BuildConfiguration.Options.class).compilationMode;
    this.lipoContextCollector = cppOptions.lipoCollector;
    this.execRoot = params.execRoot;

    // Note that the grepped includes directory is not configuration-specific; the paths of the
    // files within that directory, however, are configuration-specific.
    this.greppedIncludesDirectory = Root.asDerivedRoot(execRoot,
        execRoot.getRelative(IncludeScanningUtil.GREPPED_INCLUDES));

    this.crosstoolTopPathFragment = crosstoolTop.getPackageFragment();

    try {
      this.staticRuntimeLibsLabel =
          crosstoolTop.getRelative(toolchain.hasStaticRuntimesFilegroup() ?
              toolchain.getStaticRuntimesFilegroup() : "static-runtime-libs-" + targetCpu);
      this.dynamicRuntimeLibsLabel =
          crosstoolTop.getRelative(toolchain.hasDynamicRuntimesFilegroup() ?
              toolchain.getDynamicRuntimesFilegroup() : "dynamic-runtime-libs-" + targetCpu);
    } catch (LabelSyntaxException e) {
      // All of the above label.getRelative() calls are valid labels, and the crosstool_top
      // was already checked earlier in the process.
      throw new AssertionError(e);
    }

    if (cppOptions.lipoMode == LipoMode.BINARY) {
      // TODO(bazel-team): implement dynamic linking with LIPO
      this.dynamicMode = DynamicMode.OFF;
    } else {
      switch (cppOptions.dynamicMode) {
        case DEFAULT:
          this.dynamicMode = DynamicMode.DEFAULT; break;
        case OFF: this.dynamicMode = DynamicMode.OFF; break;
        case FULLY: this.dynamicMode = DynamicMode.FULLY; break;
        default: throw new IllegalStateException("Invalid dynamicMode.");
      }
    }

    this.fdoSupport = new FdoSupport(
        params.buildOptions.get(CppOptions.class).fdoInstrument, params.fdoZip,
        cppOptions.lipoMode, execRoot);

    this.stripBinaries = (cppOptions.stripBinaries == StripMode.ALWAYS ||
        (cppOptions.stripBinaries == StripMode.SOMETIMES &&
         compilationMode == CompilationMode.FASTBUILD));

    CrosstoolConfigurationIdentifier crosstoolConfig =
        CrosstoolConfigurationIdentifier.fromToolchain(toolchain);
    Preconditions.checkState(crosstoolConfig.getCpu().equals(targetCpu));
    Preconditions.checkState(crosstoolConfig.getCompiler().equals(compiler));
    Preconditions.checkState(crosstoolConfig.getLibc().equals(targetLibc));

    this.solibDirectory = "_solib_" + targetCpu;

    this.toolchainIdentifier = toolchain.getToolchainIdentifier();

    toolchain = addLegacyFeatures(toolchain);
    this.toolchainFeatures = new CcToolchainFeatures(toolchain);
    this.supportsGoldLinker = toolchain.getSupportsGoldLinker();
    this.supportsThinArchives = toolchain.getSupportsThinArchives();
    this.supportsStartEndLib = toolchain.getSupportsStartEndLib();
    this.supportsInterfaceSharedObjects = toolchain.getSupportsInterfaceSharedObjects();
    this.supportsEmbeddedRuntimes = toolchain.getSupportsEmbeddedRuntimes();
    this.supportsFission = toolchain.getSupportsFission();
    this.toolchainNeedsPic = toolchain.getNeedsPic();
    this.usePicForBinaries =
        toolchain.getNeedsPic() && compilationMode != CompilationMode.OPT;

    this.toolPaths = Maps.newHashMap();
    for (CrosstoolConfig.ToolPath tool : toolchain.getToolPathList()) {
      PathFragment path = new PathFragment(tool.getPath());
      if (!path.isNormalized()) {
        throw new IllegalArgumentException("The include path '" + tool.getPath()
            + "' is not normalized.");
      }
      toolPaths.put(tool.getName(), crosstoolTopPathFragment.getRelative(path));
    }

    if (toolPaths.isEmpty()) {
      // If no paths are specified, we just use the names of the tools as the path.
      for (Tool tool : Tool.values()) {
        toolPaths.put(tool.getNamePart(),
            crosstoolTopPathFragment.getRelative(tool.getNamePart()));
      }
    } else {
      Iterable<Tool> neededTools = Iterables.filter(EnumSet.allOf(Tool.class),
          new Predicate<Tool>() {
            @Override
            public boolean apply(Tool tool) {
              if (tool == Tool.DWP) {
                // When fission is unsupported, don't check for the dwp tool.
                return supportsFission();
              } else if (tool == Tool.GCOVTOOL) {
                // gcov-tool is optional, don't check whether it's present
                return false;
              } else {
                return true;
              }
            }
          });
      for (Tool tool : neededTools) {
        if (!toolPaths.containsKey(tool.getNamePart())) {
          throw new IllegalArgumentException("Tool path for '" + tool.getNamePart()
              + "' is missing");
        }
      }
    }

    // We can't use an ImmutableMap.Builder here; we need the ability (at least
    // in tests) to add entries with keys that are already in the map, and only
    // HashMap supports this (by replacing the existing entry under the key).
    Map<String, String> commandLineDefinesBuilder = new HashMap<>();
    for (Map.Entry<String, String> define : cppOptions.commandLineDefinedVariables) {
      commandLineDefinesBuilder.put(define.getKey(), define.getValue());
    }
    commandLineDefines = ImmutableMap.copyOf(commandLineDefinesBuilder);

    ListMultimap<CompilationMode, String> cFlags = ArrayListMultimap.create();
    ListMultimap<CompilationMode, String> cxxFlags = ArrayListMultimap.create();
    linkOptionsFromCompilationMode = ArrayListMultimap.create();
    for (CrosstoolConfig.CompilationModeFlags flags : toolchain.getCompilationModeFlagsList()) {
      // Remove this when CROSSTOOL files no longer contain 'coverage'.
      if (flags.getMode() == CrosstoolConfig.CompilationMode.COVERAGE) {
        continue;
      }
      CompilationMode realmode = importCompilationMode(flags.getMode());
      cFlags.putAll(realmode, flags.getCompilerFlagList());
      cxxFlags.putAll(realmode, flags.getCxxFlagList());
      linkOptionsFromCompilationMode.putAll(realmode, flags.getLinkerFlagList());
    }

    ListMultimap<LipoMode, String> lipoCFlags = ArrayListMultimap.create();
    ListMultimap<LipoMode, String> lipoCxxFlags = ArrayListMultimap.create();
    linkOptionsFromLipoMode = ArrayListMultimap.create();
    for (CrosstoolConfig.LipoModeFlags flags : toolchain.getLipoModeFlagsList()) {
      LipoMode realmode = flags.getMode();
      lipoCFlags.putAll(realmode, flags.getCompilerFlagList());
      lipoCxxFlags.putAll(realmode, flags.getCxxFlagList());
      linkOptionsFromLipoMode.putAll(realmode, flags.getLinkerFlagList());
    }

    linkOptionsFromLinkingMode = ArrayListMultimap.create();
    for (LinkingModeFlags flags : toolchain.getLinkingModeFlagsList()) {
      LinkingMode realmode = importLinkingMode(flags.getMode());
      linkOptionsFromLinkingMode.putAll(realmode, flags.getLinkerFlagList());
    }

    this.commonLinkOptions = ImmutableList.copyOf(toolchain.getLinkerFlagList());
    dynamicLibraryLinkFlags = new FlagList(
        ImmutableList.copyOf(toolchain.getDynamicLibraryLinkerFlagList()),
        convertOptionalOptions(toolchain.getOptionalDynamicLibraryLinkerFlagList()),
        Collections.<String>emptyList());
    this.objcopyOptions = ImmutableList.copyOf(toolchain.getObjcopyEmbedFlagList());
    this.ldOptions = ImmutableList.copyOf(toolchain.getLdEmbedFlagList());
    this.arOptions = copyOrDefaultIfEmpty(toolchain.getArFlagList(), "rcsD");
    this.arThinArchivesOptions = copyOrDefaultIfEmpty(
        toolchain.getArThinArchivesFlagList(), "rcsDT");

    this.abi = toolchain.getAbiVersion();
    this.abiGlibcVersion = toolchain.getAbiLibcVersion();

    // The default value for optional string attributes is the empty string.
    PathFragment defaultSysroot = toolchain.getBuiltinSysroot().length() == 0
        ? null
        : new PathFragment(toolchain.getBuiltinSysroot());
    if ((defaultSysroot != null) && !defaultSysroot.isNormalized()) {
      throw new IllegalArgumentException("The built-in sysroot '" + defaultSysroot
          + "' is not normalized.");
    }

    if ((cppOptions.libcTop != null) && (defaultSysroot == null)) {
      throw new InvalidConfigurationException("The selected toolchain " + toolchainIdentifier
          + " does not support setting --grte_top.");
    }
    LibcTop libcTop = cppOptions.libcTop;
    if ((libcTop == null) && !toolchain.getDefaultGrteTop().isEmpty()) {
      try {
        libcTop = new CppOptions.LibcTopConverter().convert(toolchain.getDefaultGrteTop());
      } catch (OptionsParsingException e) {
        throw new InvalidConfigurationException(e.getMessage(), e);
      }
    }
    if ((libcTop != null) && (libcTop.getLabel() != null)) {
      libcLabel = libcTop.getLabel();
    } else {
      libcLabel = null;
    }

    ImmutableList.Builder<PathFragment> builtInIncludeDirectoriesBuilder
        = ImmutableList.builder();
    sysroot = libcTop == null ? defaultSysroot : libcTop.getSysroot();
    for (String s : toolchain.getCxxBuiltinIncludeDirectoryList()) {
      builtInIncludeDirectoriesBuilder.add(
          resolveIncludeDir(s, sysroot, crosstoolTopPathFragment));
    }
    builtInIncludeDirectories = builtInIncludeDirectoriesBuilder.build();

    // The runtime sysroot should really be set from --grte_top. However, currently libc has no
    // way to set the sysroot. The CROSSTOOL file does set the runtime sysroot, in the
    // builtin_sysroot field. This implies that you can not arbitrarily mix and match Crosstool
    // and libc versions, you must always choose compatible ones.
    runtimeSysroot = defaultSysroot;

    String sysrootFlag;
    if (sysroot != null) {
      sysrootFlag = "--sysroot=" + sysroot;
    } else {
      sysrootFlag = null;
    }

    ImmutableList.Builder<String> unfilteredCoptsBuilder = ImmutableList.builder();
    if (sysrootFlag != null) {
      unfilteredCoptsBuilder.add(sysrootFlag);
    }
    unfilteredCoptsBuilder.addAll(toolchain.getUnfilteredCxxFlagList());
    unfilteredCompilerFlags = new FlagList(
        unfilteredCoptsBuilder.build(),
        convertOptionalOptions(toolchain.getOptionalUnfilteredCxxFlagList()),
        Collections.<String>emptyList());

    ImmutableList.Builder<String> linkoptsBuilder = ImmutableList.builder();
    linkoptsBuilder.addAll(cppOptions.linkoptList);
    if (cppOptions.experimentalOmitfp) {
      linkoptsBuilder.add("-Wl,--eh-frame-hdr");
    }
    if (sysrootFlag != null) {
      linkoptsBuilder.add(sysrootFlag);
    }
    this.linkOptions = linkoptsBuilder.build();

    ImmutableList.Builder<String> coptsBuilder = ImmutableList.<String>builder()
        .addAll(toolchain.getCompilerFlagList())
        .addAll(cFlags.get(compilationMode))
        .addAll(lipoCFlags.get(cppOptions.getLipoMode()));
    if (cppOptions.experimentalOmitfp) {
      coptsBuilder.add("-fomit-frame-pointer");
      coptsBuilder.add("-fasynchronous-unwind-tables");
      coptsBuilder.add("-DNO_FRAME_POINTER");
    }
    this.compilerFlags = new FlagList(
        coptsBuilder.build(),
        convertOptionalOptions(toolchain.getOptionalCompilerFlagList()),
        cppOptions.coptList);

    this.cOptions = ImmutableList.copyOf(cppOptions.conlyoptList);

    ImmutableList.Builder<String> cxxOptsBuilder = ImmutableList.<String>builder()
        .addAll(toolchain.getCxxFlagList())
        .addAll(cxxFlags.get(compilationMode))
        .addAll(lipoCxxFlags.get(cppOptions.getLipoMode()));

    this.cxxFlags = new FlagList(
        cxxOptsBuilder.build(),
        convertOptionalOptions(toolchain.getOptionalCxxFlagList()),
        cppOptions.cxxoptList);

    this.ldExecutable = getToolPathFragment(CppConfiguration.Tool.LD);

    boolean stripBinaries = (cppOptions.stripBinaries == StripMode.ALWAYS) ||
                        ((cppOptions.stripBinaries == StripMode.SOMETIMES) &&
                         (compilationMode == CompilationMode.FASTBUILD));

    fullyStaticLinkFlags = new FlagList(
        configureLinkerOptions(compilationMode, lipoMode, LinkingMode.FULLY_STATIC,
                               ldExecutable, stripBinaries),
        convertOptionalOptions(toolchain.getOptionalLinkerFlagList()),
        Collections.<String>emptyList());
    mostlyStaticLinkFlags = new FlagList(
        configureLinkerOptions(compilationMode, lipoMode, LinkingMode.MOSTLY_STATIC,
                               ldExecutable, stripBinaries),
        convertOptionalOptions(toolchain.getOptionalLinkerFlagList()),
        Collections.<String>emptyList());
    mostlyStaticSharedLinkFlags = new FlagList(
        configureLinkerOptions(compilationMode, lipoMode,
                               LinkingMode.MOSTLY_STATIC_LIBRARIES, ldExecutable, stripBinaries),
        convertOptionalOptions(toolchain.getOptionalLinkerFlagList()),
        Collections.<String>emptyList());
    dynamicLinkFlags = new FlagList(
        configureLinkerOptions(compilationMode, lipoMode, LinkingMode.DYNAMIC,
                               ldExecutable, stripBinaries),
        convertOptionalOptions(toolchain.getOptionalLinkerFlagList()),
        Collections.<String>emptyList());
    testOnlyLinkFlags = ImmutableList.copyOf(toolchain.getTestOnlyLinkerFlagList());

    Map<String, String> makeVariablesBuilder = new HashMap<>();
    // The following are to be used to allow some build rules to avoid the limits on stack frame
    // sizes and variable-length arrays. Ensure that these are always set.
    makeVariablesBuilder.put("STACK_FRAME_UNLIMITED", "");
    makeVariablesBuilder.put("CC_FLAGS", "");
    for (CrosstoolConfig.MakeVariable variable : toolchain.getMakeVariableList()) {
      makeVariablesBuilder.put(variable.getName(), variable.getValue());
    }
    if (sysrootFlag != null) {
      String ccFlags = makeVariablesBuilder.get("CC_FLAGS");
      ccFlags = ccFlags.isEmpty() ? sysrootFlag : ccFlags + " " + sysrootFlag;
      makeVariablesBuilder.put("CC_FLAGS", ccFlags);
    }
    this.additionalMakeVariables = ImmutableMap.copyOf(makeVariablesBuilder);
  }

  private List<OptionalFlag> convertOptionalOptions(
          List<CrosstoolConfig.CToolchain.OptionalFlag> optionalFlagList)
      throws IllegalArgumentException {
    List<OptionalFlag> result = new ArrayList<>();

    for (CrosstoolConfig.CToolchain.OptionalFlag crosstoolOptionalFlag : optionalFlagList) {
      String name = crosstoolOptionalFlag.getDefaultSettingName();
      result.add(new OptionalFlag(
          name,
          ImmutableList.copyOf(crosstoolOptionalFlag.getFlagList())));
    }

    return result;
  }

  // TODO(bazel-team): Remove this once bazel supports all crosstool flags through
  // feature configuration, and all crosstools have been converted.
  private CToolchain addLegacyFeatures(CToolchain toolchain) {
    CToolchain.Builder toolchainBuilder = CToolchain.newBuilder();
    ImmutableSet.Builder<String> featuresBuilder = ImmutableSet.builder();
    for (CToolchain.Feature feature : toolchain.getFeatureList()) {
      featuresBuilder.add(feature.getName());
    }
    Set<String> features = featuresBuilder.build();
    if (features.contains(CppRuleClasses.NO_LEGACY_FEATURES)) {
      // The toolchain requested to not get any legacy features enabled.
      return toolchain;
    }
    try {
      if (!features.contains("include_paths")) {
        TextFormat.merge(""
            + "feature {"
            + "  name: 'include_paths'"
            + "  flag_set {"
            + "    action: 'preprocess-assemble'"
            + "    action: 'c-compile'"
            + "    action: 'c++-compile'"
            + "    action: 'c++-header-parsing'"
            + "    action: 'c++-header-preprocessing'"
            + "    action: 'c++-module-compile'"
            + "    flag_group {"
            + "      flag: '-iquote'"
            + "      flag: '%{quote_include_paths}'"
            + "    }"
            + "    flag_group {"
            + "      flag: '-I%{include_paths}'"
            + "    }"
            + "    flag_group {"
            + "      flag: '-isystem'"
            + "      flag: '%{system_include_paths}'"
            + "    }"
            + "  }"
            + "}",
            toolchainBuilder);
      }
      if (!features.contains("fdo_instrument")) {
        TextFormat.merge(
            ""
                + "feature {"
                + "  name: 'fdo_instrument'"
                + "  provides: 'profile'"
                + "  flag_set {"
                + "    action: 'c-compile'"
                + "    action: 'c++-compile'"
                + "    action: 'c++-link'"
                + "    flag_group {"
                + "      flag: '-Xgcc-only=-fprofile-generate=%{fdo_instrument_path}'"
                + "      flag: '-Xclang-only=-fprofile-instr-generate=%{fdo_instrument_path}'"
                + "    }"
                + "    flag_group {"
                + "      flag: '-fno-data-sections'"
                + "    }"
                + "  }"
                + "}",
            toolchainBuilder);
      }
      if (!features.contains("fdo_optimize")) {
        TextFormat.merge(
            ""
                + "feature {"
                + "  name: 'fdo_optimize'"
                + "  provides: 'profile'"
                + "  flag_set {"
                + "    action: 'c-compile'"
                + "    action: 'c++-compile'"
                + "    expand_if_all_available: 'fdo_profile_path'"
                + "    flag_group {"
                + "      flag: '-Xgcc-only=-fprofile-use=%{fdo_profile_path}'"
                + "      flag: '-Xclang-only=-fprofile-instr-use=%{fdo_profile_path}'"
                + "      flag: '-Xclang-only=-Wno-profile-instr-unprofiled'"
                + "      flag: '-Xclang-only=-Wno-profile-instr-out-of-date'"
                + "      flag: '-fprofile-correction'"
                + "    }"
                + "  }"
                + "}",
            toolchainBuilder);
      }
      if (!features.contains("autofdo")) {
        TextFormat.merge(
            ""
                + "feature {"
                + "  name: 'autofdo'"
                + "  provides: 'profile'"
                + "  flag_set {"
                + "    action: 'c-compile'"
                + "    action: 'c++-compile'"
                + "    expand_if_all_available: 'fdo_profile_path'"
                + "    flag_group {"
                + "      flag: '-fauto-profile=%{fdo_profile_path}'"
                + "      flag: '-fprofile-correction'"
                + "    }"
                + "  }"
                + "}",
            toolchainBuilder);
      }
      if (!features.contains("lipo")) {
        TextFormat.merge(
            ""
                + "feature {"
                + "  name: 'lipo'"
                + "  requires { feature: 'autofdo' }"
                + "  requires { feature: 'fdo_optimize' }"
                + "  requires { feature: 'fdo_instrument' }"
                + "  flag_set {"
                + "    action: 'c-compile'"
                + "    action: 'c++-compile'"
                + "    flag_group {"
                + "      flag: '-fripa'"
                + "    }"
                + "  }"
                + "}",
            toolchainBuilder);
      }
      if (!features.contains("coverage")) {
        TextFormat.merge(
            ""
                + "feature {"
                + "  name: 'coverage'"
                + "  provides: 'profile'"
                + "  flag_set {"
                + "    action: 'preprocess-assemble'"
                + "    action: 'c-compile'"
                + "    action: 'c++-compile'"
                + "    action: 'c++-header-parsing'"
                + "    action: 'c++-header-preprocessing'"
                + "    action: 'c++-module-compile'"
                + "    expand_if_all_available: 'gcov_gcno_file'"
                + "    flag_group {"
                + "      flag: '-fprofile-arcs'"
                + "      flag: '-ftest-coverage'"
                + "    }"
                + "  }"
                + "  flag_set {"
                + "    action: 'c++-link'"
                + "    flag_group {"
                + "      flag: '-lgcov'"
                + "    }"
                + "  }"
                + "}",
            toolchainBuilder);
      }
    } catch (ParseException e) {
      // Can only happen if we change the proto definition without changing our configuration above.
      throw new RuntimeException(e);
    }
    toolchainBuilder.mergeFrom(toolchain);
    return toolchainBuilder.build();
  }

  private static ImmutableList<String> copyOrDefaultIfEmpty(List<String> list,
      String defaultValue) {
    return list.isEmpty() ? ImmutableList.of(defaultValue) : ImmutableList.copyOf(list);
  }

  @VisibleForTesting
  static CompilationMode importCompilationMode(CrosstoolConfig.CompilationMode mode) {
    return CompilationMode.valueOf(mode.name());
  }

  @VisibleForTesting
  static LinkingMode importLinkingMode(CrosstoolConfig.LinkingMode mode) {
    return LinkingMode.valueOf(mode.name());
  }

  private static final PathFragment SYSROOT_FRAGMENT = new PathFragment("%sysroot%");

  /**
   * Resolve the given include directory. If it is not absolute, it is
   * interpreted relative to the crosstool top. If it starts with %sysroot%/,
   * that part is replaced with the actual sysroot.
   */
  static PathFragment resolveIncludeDir(String s, PathFragment sysroot,
      PathFragment crosstoolTopPathFragment) {
    PathFragment path = new PathFragment(s);
    if (!path.isNormalized()) {
      throw new IllegalArgumentException("The include path '" + s + "' is not normalized.");
    }
    if (path.startsWith(SYSROOT_FRAGMENT)) {
      if (sysroot == null) {
        throw new IllegalArgumentException("A %sysroot% prefix is only allowed if the "
            + "default_sysroot option is set");
      }
      return sysroot.getRelative(path.relativeTo(SYSROOT_FRAGMENT));
    } else {
      return crosstoolTopPathFragment.getRelative(path);
    }
  }

  /**
   * Returns the configuration-independent grepped-includes directory.
   */
  public Root getGreppedIncludesDirectory() {
    return greppedIncludesDirectory;
  }

  @VisibleForTesting
  List<String> configureLinkerOptions(
      CompilationMode compilationMode, LipoMode lipoMode, LinkingMode linkingMode,
      PathFragment ldExecutable, boolean stripBinaries) {
    List<String> result = new ArrayList<>();
    result.addAll(commonLinkOptions);

    if (stripBinaries) {
      result.add("-Wl,-S");
    }

    result.addAll(linkOptionsFromCompilationMode.get(compilationMode));
    result.addAll(linkOptionsFromLipoMode.get(lipoMode));
    result.addAll(linkOptionsFromLinkingMode.get(linkingMode));
    return ImmutableList.copyOf(result);
  }

  /**
   * Returns the toolchain identifier, which uniquely identifies the compiler
   * version, target libc version, target cpu, and LIPO linkage.
   */
  public String getToolchainIdentifier() {
    return toolchainIdentifier;
  }

  /**
   * Returns the system name which is required by the toolchain to run.
   */
  public String getHostSystemName() {
    return hostSystemName;
  }

  @Override
  public String toString() {
    return toolchainIdentifier;
  }

  /**
   * Returns the compiler version string (e.g. "gcc-4.1.1").
   */
  @SkylarkCallable(name = "compiler", structField = true, doc = "C++ compiler.")
  public String getCompiler() {
    return compiler;
  }

  /**
   * Returns the libc version string (e.g. "glibc-2.2.2").
   */
  @SkylarkCallable(name = "libc", structField = true, doc = "libc version string.")
  public String getTargetLibc() {
    return targetLibc;
  }

  /**
   * Returns the target architecture using blaze-specific constants (e.g. "piii").
   */
  @SkylarkCallable(name = "cpu", structField = true, doc = "Target CPU of the C++ toolchain.")
  public String getTargetCpu() {
    return targetCpu;
  }

  /**
   * Returns the path fragment that is either absolute or relative to the
   * execution root that can be used to execute the given tool.
   *
   * <p>Note that you must not use this method to get the linker location, but
   * use {@link #getLdExecutable} instead!
   */
  public PathFragment getToolPathFragment(CppConfiguration.Tool tool) {
    return toolPaths.get(tool.getNamePart());
  }

  /**
   * Returns a label that forms a dependency to the files required for the
   * sysroot that is used.
   */
  public Label getLibcLabel() {
    return libcLabel;
  }

  /**
   * Returns a label that references the library files needed to statically
   * link the C++ runtime (i.e. libgcc.a, libgcc_eh.a, libstdc++.a) for the
   * target architecture.
   */
  public Label getStaticRuntimeLibsLabel() {
    return supportsEmbeddedRuntimes() ? staticRuntimeLibsLabel : null;
  }

  /**
   * Returns a label that references the library files needed to dynamically
   * link the C++ runtime (i.e. libgcc_s.so, libstdc++.so) for the target
   * architecture.
   */
  public Label getDynamicRuntimeLibsLabel() {
    return supportsEmbeddedRuntimes() ? dynamicRuntimeLibsLabel : null;
  }

  /**
   * Returns the label of the <code>cc_compiler</code> rule for the C++ configuration.
   */
  public Label getCcToolchainRuleLabel() {
    return ccToolchainLabel;
  }

  /**
   * Returns the abi we're using, which is a gcc version. E.g.: "gcc-3.4".
   * Note that in practice we might be using gcc-3.4 as ABI even when compiling
   * with gcc-4.1.0, because ABIs are backwards compatible.
   */
  // TODO(bazel-team): The javadoc should clarify how this is used in Blaze.
  public String getAbi() {
    return abi;
  }

  /**
   * Returns the glibc version used by the abi we're using.  This is a
   * glibc version number (e.g., "2.2.2").  Note that in practice we
   * might be using glibc 2.2.2 as ABI even when compiling with
   * gcc-4.2.2, gcc-4.3.1, or gcc-4.4.0 (which use glibc 2.3.6),
   * because ABIs are backwards compatible.
   */
  // TODO(bazel-team): The javadoc should clarify how this is used in Blaze.
  public String getAbiGlibcVersion() {
    return abiGlibcVersion;
  }

  /**
   * Returns the configured features of the toolchain. Rules should not call this directly, but
   * instead use {@code CcToolchainProvider.getFeatures}.
   */
  public CcToolchainFeatures getFeatures() {
    return toolchainFeatures;
  }

  /**
   * Returns the configured current compilation mode. Rules should not call this directly, but
   * instead use {@code CcToolchainProvider.getCompilationMode}.
   */
  public CompilationMode getCompilationMode() {
    return compilationMode;
  }

  /**
   * Returns whether the toolchain supports the gold linker.
   */
  public boolean supportsGoldLinker() {
    return supportsGoldLinker;
  }

  /**
   * Returns whether the toolchain supports thin archives.
   */
  public boolean supportsThinArchives() {
    return supportsThinArchives;
  }

  /**
   * Returns whether the toolchain supports the --start-lib/--end-lib options.
   */
  public boolean supportsStartEndLib() {
    return supportsStartEndLib;
  }

  /**
   * Returns whether build_interface_so can build interface shared objects for this toolchain.
   * Should be true if this toolchain generates ELF objects.
   */
  public boolean supportsInterfaceSharedObjects() {
    return supportsInterfaceSharedObjects;
  }

  /**
   * Returns whether the toolchain supports linking C/C++ runtime libraries
   * supplied inside the toolchain distribution.
   */
  public boolean supportsEmbeddedRuntimes() {
    return supportsEmbeddedRuntimes;
  }

  /**
   * Returns whether the toolchain supports EXEC_ORIGIN libraries resolution.
   */
  public boolean supportsExecOrigin() {
    // We're rolling out support for this in the same release that also supports embedded runtimes.
    return supportsEmbeddedRuntimes;
  }

  /**
   * Returns whether the toolchain supports "Fission" C++ builds, i.e. builds
   * where compilation partitions object code and debug symbols into separate
   * output files.
   */
  public boolean supportsFission() {
    return supportsFission;
  }

  /**
   * Returns whether shared libraries must be compiled with position
   * independent code on this platform.
   */
  public boolean toolchainNeedsPic() {
    return toolchainNeedsPic;
  }

  /**
   * Returns whether binaries must be compiled with position independent code.
   */
  public boolean usePicForBinaries() {
    return usePicForBinaries;
  }

  /**
   * Returns the type of archives being used.
   */
  public Link.ArchiveType archiveType() {
    if (useStartEndLib()) {
      return Link.ArchiveType.START_END_LIB;
    }
    if (useThinArchives()) {
      return Link.ArchiveType.THIN;
    }
    return Link.ArchiveType.FAT;
  }

  /**
   * Returns the ar flags to be used.
   */
  public List<String> getArFlags(boolean thinArchives) {
    return thinArchives ? arThinArchivesOptions : arOptions;
  }

  /**
   * Returns the built-in list of system include paths for the toolchain
   * compiler. All paths in this list should be relative to the exec directory.
   * They may be absolute if they are also installed on the remote build nodes or
   * for local compilation.
   */
  public List<PathFragment> getBuiltInIncludeDirectories() {
    return builtInIncludeDirectories;
  }

  /**
   * Returns the built-in header automatically included by the toolchain compiler. All C++ files
   * may implicitly include this file. May be null if {@link #getSysroot} is null.
   */
  @Nullable
  public Artifact getBuiltInIncludeFile() {
    return builtInIncludeFile;
  }

  /**
   * Returns the sysroot to be used. If the toolchain compiler does not support
   * different sysroots, or the sysroot is the same as the default sysroot, then
   * this method returns <code>null</code>.
   */
  @SkylarkCallable(name = "sysroot", structField = true,
      doc = "Returns the sysroot to be used. If the toolchain compiler does not support "
      + "different sysroots, or the sysroot is the same as the default sysroot, then "
      + "this method returns <code>None</code>.")
  public PathFragment getSysroot() {
    return sysroot;
  }

  /**
   * Returns the run time sysroot, which is where the dynamic linker
   * and system libraries are found at runtime.  This is usually an absolute path. If the
   * toolchain compiler does not support sysroots, then this method returns <code>null</code>.
   */
  public PathFragment getRuntimeSysroot() {
    return runtimeSysroot;
  }

  /**
   * Returns the default options to use for compiling C, C++, and assembler.
   * This is just the options that should be used for all three languages.
   * There may be additional C-specific or C++-specific options that should be used,
   * in addition to the ones returned by this method.
   */
  @SkylarkCallable(name = "compiler_options",
      doc = "Returns the default options to use for compiling C, C++, and assembler. "
      + "This is just the options that should be used for all three languages. "
      + "There may be additional C-specific or C++-specific options that should be used, "
      + "in addition to the ones returned by this method")
  public List<String> getCompilerOptions(Collection<String> features) {
    return compilerFlags.evaluate(features);
  }

  /**
   * Returns the list of additional C-specific options to use for compiling
   * C. These should be go on the command line after the common options
   * returned by {@link #getCompilerOptions}.
   */
  @SkylarkCallable(name = "c_options", structField = true,
      doc = "Returns the list of additional C-specific options to use for compiling C. "
      + "These should be go on the command line after the common options returned by "
      + "<code>compiler_options</code>")
  public List<String> getCOptions() {
    return cOptions;
  }

  /**
   * Returns the list of additional C++-specific options to use for compiling
   * C++. These should be go on the command line after the common options
   * returned by {@link #getCompilerOptions}.
   */
  @SkylarkCallable(name = "cxx_options",
      doc = "Returns the list of additional C++-specific options to use for compiling C++. "
      + "These should be go on the command line after the common options returned by "
      + "<code>compiler_options</code>")
  public List<String> getCxxOptions(Collection<String> features) {
    return cxxFlags.evaluate(features);
  }

  /**
   * Returns the default list of options which cannot be filtered by BUILD
   * rules. These should be appended to the command line after filtering.
   */
  @SkylarkCallable(name = "unfiltered_compiler_options",
      doc = "Returns the default list of options which cannot be filtered by BUILD "
      + "rules. These should be appended to the command line after filtering.")
  public List<String> getUnfilteredCompilerOptions(Collection<String> features) {
    return unfilteredCompilerFlags.evaluate(features);
  }

  /**
   * Returns the set of command-line linker options, including any flags
   * inferred from the command-line options.
   *
   * @see Link
   */
  // TODO(bazel-team): Clean up the linker options computation!
  @SkylarkCallable(name = "link_options", structField = true,
      doc = "Returns the set of command-line linker options, including any flags "
      + "inferred from the command-line options.")
  public List<String> getLinkOptions() {
    return linkOptions;
  }

  /**
   * Returns the immutable list of linker options for fully statically linked
   * outputs. Does not include command-line options passed via --linkopt or
   * --linkopts.
   *
   * @param features default settings affecting this link
   * @param sharedLib true if the output is a shared lib, false if it's an executable
   */
  public List<String> getFullyStaticLinkOptions(Collection<String> features,
      boolean sharedLib) {
    if (sharedLib) {
      return getSharedLibraryLinkOptions(mostlyStaticLinkFlags, features);
    } else {
      return fullyStaticLinkFlags.evaluate(features);
    }
  }

  /**
   * Returns the immutable list of linker options for mostly statically linked
   * outputs. Does not include command-line options passed via --linkopt or
   * --linkopts.
   *
   * @param features default settings affecting this link
   * @param sharedLib true if the output is a shared lib, false if it's an executable
   */
  public List<String> getMostlyStaticLinkOptions(Collection<String> features,
      boolean sharedLib) {
    if (sharedLib) {
      return getSharedLibraryLinkOptions(
          supportsEmbeddedRuntimes ? mostlyStaticSharedLinkFlags : dynamicLinkFlags,
          features);
    } else {
      return mostlyStaticLinkFlags.evaluate(features);
    }
  }

  /**
   * Returns the immutable list of linker options for artifacts that are not
   * fully or mostly statically linked. Does not include command-line options
   * passed via --linkopt or --linkopts.
   *
   * @param features default settings affecting this link
   * @param sharedLib true if the output is a shared lib, false if it's an executable
   */
  public List<String> getDynamicLinkOptions(Collection<String> features,
      boolean sharedLib) {
    if (sharedLib) {
      return getSharedLibraryLinkOptions(dynamicLinkFlags, features);
    } else {
      return dynamicLinkFlags.evaluate(features);
    }
  }

  /**
   * Returns link options for the specified flag list, combined with universal options
   * for all shared libraries (regardless of link staticness).
   */
  private List<String> getSharedLibraryLinkOptions(FlagList flags,
      Collection<String> features) {
    return ImmutableList.<String>builder()
        .addAll(flags.evaluate(features))
        .addAll(dynamicLibraryLinkFlags.evaluate(features))
        .build();
  }

  /**
   * Returns test-only link options such that certain test-specific features can be configured
   * separately (e.g. lazy binding).
   */
  public List<String> getTestOnlyLinkOptions() {
    return testOnlyLinkFlags;
  }


  /**
   * Returns the list of options to be used with 'objcopy' when converting
   * binary files to object files, or {@code null} if this operation is not
   * supported.
   */
  public List<String> getObjCopyOptionsForEmbedding() {
    return objcopyOptions;
  }

  /**
   * Returns the list of options to be used with 'ld' when converting
   * binary files to object files, or {@code null} if this operation is not
   * supported.
   */
  public List<String> getLdOptionsForEmbedding() {
    return ldOptions;
  }

  /**
   * Returns a map of additional make variables for use by {@link
   * BuildConfiguration}. These are to used to allow some build rules to
   * avoid the limits on stack frame sizes and variable-length arrays.
   *
   * <p>The returned map must contain an entry for {@code STACK_FRAME_UNLIMITED},
   * though the entry may be an empty string.
   */
  @VisibleForTesting
  public Map<String, String> getAdditionalMakeVariables() {
    return additionalMakeVariables;
  }

  /**
   * Returns the execution path to the linker binary to use for this build.
   * Relative paths are relative to the execution root.
   */
  public PathFragment getLdExecutable() {
    return ldExecutable;
  }

  /**
   * Returns the dynamic linking mode (full, off, or default).
   */
  public DynamicMode getDynamicMode() {
    return dynamicMode;
  }

  /*
   * If true then the directory name for non-LIPO targets will have a '-lipodata' suffix in
   * AutoFDO mode.
   */
  public boolean getAutoFdoLipoData() {
    return cppOptions.autoFdoLipoData;
  }

  /**
   * Returns the STL label if given on the command line. {@code null}
   * otherwise.
   */
  public Label getStl() {
    return cppOptions.stl;
  }

  /*
   * Returns the command-line "Make" variable overrides.
   */
  @Override
  public ImmutableMap<String, String> getCommandLineDefines() {
    return commandLineDefines;
  }

  /**
   * Returns the command-line override value for the specified "Make" variable
   * for this configuration, or null if none.
   */
  public String getMakeVariableOverride(String var) {
    return commandLineDefines.get(var);
  }

  public boolean shouldScanIncludes() {
    if (Constants.HARD_DISABLE_CC_INCLUDE_SCANNING) {
      return false;
    }
    return cppOptions.scanIncludes;
  }

  /**
   * Returns the currently active LIPO compilation mode.
   */
  public LipoMode getLipoMode() {
    return cppOptions.lipoMode;
  }

  public boolean isFdo() {
    return cppOptions.isFdo();
  }

  public boolean isLipoOptimization() {
    // The LIPO optimization bits are set in the LIPO context collector configuration, too.
    return cppOptions.isLipoOptimization() && !isLipoContextCollector();
  }

  public boolean isLipoOptimizationOrInstrumentation() {
    return cppOptions.isLipoOptimizationOrInstrumentation();
  }

  /**
   * Returns true if it is AutoFDO LIPO build.
   */
  public boolean isAutoFdoLipo() {
    return cppOptions.fdoOptimize != null && FdoSupport.isAutoFdo(cppOptions.fdoOptimize)
           && getLipoMode() != LipoMode.OFF;
  }

  /**
   * Returns the default header check mode.
   */
  public HeadersCheckingMode getHeadersCheckingMode() {
    return cppOptions.headersCheckingMode;
  }

  /**
   * Returns whether or not to strip the binaries.
   */
  public boolean shouldStripBinaries() {
    return stripBinaries;
  }

  /**
   * Returns the additional options to pass to strip when generating a
   * {@code <name>.stripped} binary by this build.
   */
  public List<String> getStripOpts() {
    return cppOptions.stripoptList;
  }

  /**
   * Returns whether temporary outputs from gcc will be saved.
   */
  public boolean getSaveTemps() {
    return cppOptions.saveTemps;
  }

  /**
   * Returns the {@link PerLabelOptions} to apply to the gcc command line, if
   * the label of the compiled file matches the regular expression.
   */
  public List<PerLabelOptions> getPerFileCopts() {
    return cppOptions.perFileCopts;
  }

  public Label getLipoContextLabel() {
    return cppOptions.getLipoContextLabel();
  }

  /**
   * Returns the custom malloc library label.
   */
  public Label customMalloc() {
    return cppOptions.customMalloc;
  }

  /**
   * Returns the extra warnings enabled for C compilation.
   */
  public List<String> getCWarns() {
    return cppOptions.cWarns;
  }

  /**
   * Returns true if mostly-static C++ binaries should be skipped.
   */
  public boolean skipStaticOutputs() {
    return cppOptions.skipStaticOutputs;
  }

  /**
   * Returns true if Fission is specified for this build and supported by the crosstool.
   */
  public boolean useFission() {
    return cppOptions.fissionModes.contains(compilationMode) && supportsFission();
  }

  /**
   * Returns true if all C++ compilations should produce position-independent code, links should
   * produce position-independent executables, and dependencies with equivalent pre-built pic and
   * nopic versions should apply the pic versions. Returns false if default settings should be
   * applied (i.e. make no special provisions for pic code).
   */
  public boolean forcePic() {
    return cppOptions.forcePic;
  }

  public boolean useStartEndLib() {
    return cppOptions.useStartEndLib && supportsStartEndLib();
  }

  public boolean useThinArchives() {
    return cppOptions.useThinArchives && supportsThinArchives();
  }

  /**
   * Returns true if interface shared objects should be used.
   */
  public boolean useInterfaceSharedObjects() {
    return supportsInterfaceSharedObjects() && cppOptions.useInterfaceSharedObjects;
  }

  public boolean forceIgnoreDashStatic() {
    return cppOptions.forceIgnoreDashStatic;
  }

  /**
   * Returns true iff this build configuration requires inclusion extraction
   * (for include scanning) in the action graph.
   */
  public boolean needsIncludeScanning() {
    return cppOptions.extractInclusions;
  }

  /**
   * Returns true if shared libraries must be compiled with position independent code
   * on this platform or in this configuration.
   */
  public boolean needsPic() {
    return forcePic() || toolchainNeedsPic();
  }

  /**
   * Returns true iff we should use ".pic.o" files when linking executables.
   */
  public boolean usePicObjectsForBinaries() {
    return forcePic() || usePicForBinaries();
  }

  public boolean legacyWholeArchive() {
    return cppOptions.legacyWholeArchive;
  }

  public boolean getSymbolCounts() {
    return cppOptions.symbolCounts;
  }

  public boolean getInmemoryDotdFiles() {
    return cppOptions.inmemoryDotdFiles;
  }

  public boolean useIsystemForIncludes() {
    return cppOptions.useIsystemForIncludes;
  }

  public LibcTop getLibcTop() {
    return cppOptions.libcTop;
  }

  public boolean getUseInterfaceSharedObjects() {
    return cppOptions.useInterfaceSharedObjects;
  }

  /**
   * Returns the FDO support object.
   */
  public FdoSupport getFdoSupport() {
    return fdoSupport;
  }

  /**
   * Return the name of the directory (relative to the bin directory) that
   * holds mangled links to shared libraries. This name is always set to
   * the '{@code _solib_<cpu_archictecture_name>}.
   */
  public String getSolibDirectory() {
    return solibDirectory;
  }

  /**
   * Returns the path to the GNU binutils 'objcopy' binary to use for this
   * build. (Corresponds to $(OBJCOPY) in make-dbg.) Relative paths are
   * relative to the execution root.
   */
  @SkylarkCallable(name = "objcopy_executable", structField = true,
      doc = "Path to GNU binutils 'objcopy' binary")
  public PathFragment getObjCopyExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.OBJCOPY);
  }

  /**
   * Returns the path to the GNU binutils 'gcc' binary that should be used
   * by this build.  This binary should support compilation of both C (*.c)
   * and C++ (*.cc) files. Relative paths are relative to the execution root.
   */
  @SkylarkCallable(name = "compiler_executable", structField = true,
      doc = "Path to C/C++ compiler binary")
  public PathFragment getCppExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.GCC);
  }

  /**
   * Returns the path to the GNU binutils 'g++' binary that should be used
   * by this build.  This binary should support linking of both C (*.c)
   * and C++ (*.cc) files. Relative paths are relative to the execution root.
   */
  public PathFragment getCppLinkExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.GCC);
  }

  /**
   * Returns the path to the GNU binutils 'cpp' binary that should be used
   * by this build. Relative paths are relative to the execution root.
   */
  public PathFragment getCpreprocessorExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.CPP);
  }

  /**
   * Returns the path to the GNU binutils 'gcov' binary that should be used
   * by this build to analyze C++ coverage data. Relative paths are relative to
   * the execution root.
   */
  public PathFragment getGcovExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.GCOV);
  }

  /**
   * Returns the path to the 'gcov-tool' executable that should be used
   * by this build. Relative paths are relative to the execution root.
   */
  public PathFragment getGcovToolExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.GCOVTOOL);
  }

  /**
   * Returns the path to the GNU binutils 'nm' executable that should be used
   * by this build. Used only for testing. Relative paths are relative to the
   * execution root.
   */
  @SkylarkCallable(name = "nm_executable", structField = true,
      doc = "Path to GNU binutils 'nm' binary")
  public PathFragment getNmExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.NM);
  }

  /**
   * Returns the path to the GNU binutils 'objdump' executable that should be
   * used by this build. Used only for testing. Relative paths are relative to
   * the execution root.
   */
  @SkylarkCallable(name = "objdump_executable", structField = true,
      doc = "Path to GNU binutils 'objdump' binary")
  public PathFragment getObjdumpExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.OBJDUMP);
  }

  /**
   * Returns the path to the GNU binutils 'ar' binary to use for this build.
   * Relative paths are relative to the execution root.
   */
  @SkylarkCallable(name = "ar_executable", structField = true,
      doc = "Path to GNU binutils 'ar' binary")
  public PathFragment getArExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.AR);
  }

  /**
   * Returns the path to the GNU binutils 'strip' executable that should be used
   * by this build. Relative paths are relative to the execution root.
   */
  @SkylarkCallable(name = "strip_executable", structField = true,
      doc = "Path to GNU binutils 'strip' binary")
  public PathFragment getStripExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.STRIP);
  }

  /**
   * Returns the path to the GNU binutils 'dwp' binary that should be used by this
   * build to combine debug info output from individual C++ compilations (i.e. .dwo
   * files) into aggregate target-level debug packages. Relative paths are relative to the
   * execution root. See https://gcc.gnu.org/wiki/DebugFission .
   */
  public PathFragment getDwpExecutable() {
    return getToolPathFragment(CppConfiguration.Tool.DWP);
  }

  /**
   * Returns the GNU System Name
   */
  @SkylarkCallable(name = "target_gnu_system_name", structField = true,
      doc = "The GNU System Name.")
  public String getTargetGnuSystemName() {
    return targetSystemName;
  }

  /**
   * Returns the architecture component of the GNU System Name
   */
  public String getGnuSystemArch() {
    if (targetSystemName.indexOf('-') == -1) {
      return targetSystemName;
    }
    return targetSystemName.substring(0, targetSystemName.indexOf('-'));
  }

  /**
   * Returns whether the configuration's purpose is only to collect LIPO-related data.
   */
  public boolean isLipoContextCollector() {
    return lipoContextCollector;
  }

  @Override
  public void reportInvalidOptions(EventHandler reporter, BuildOptions buildOptions) {
    CppOptions cppOptions = buildOptions.get(CppOptions.class);
    if (stripBinaries) {
      boolean warn = cppOptions.coptList.contains("-g");
      for (PerLabelOptions opt : cppOptions.perFileCopts) {
        warn |= opt.getOptions().contains("-g");
      }
      if (warn) {
        reporter.handle(Event.warn("Stripping enabled, but '--copt=-g' (or --per_file_copt=...@-g) "
            + "specified. Debug information will be generated and then stripped away. This is "
            + "probably not what you want! Use '-c dbg' for debug mode, or use '--strip=never' "
            + "to disable stripping"));
      }
    }

    if (cppOptions.fdoInstrument != null && cppOptions.fdoOptimize != null) {
      reporter.handle(Event.error("Cannot instrument and optimize for FDO at the same time. "
          + "Remove one of the '--fdo_instrument' and '--fdo_optimize' options"));
    }

    if (cppOptions.lipoContext != null) {
      if (cppOptions.lipoMode != LipoMode.BINARY || cppOptions.fdoOptimize == null) {
        reporter.handle(Event.warn("The --lipo_context option can only be used together with "
            + "--fdo_optimize=<profile zip> and --lipo=binary. LIPO context will be ignored."));
      }
    } else {
      if (cppOptions.lipoMode == LipoMode.BINARY && cppOptions.fdoOptimize != null) {
        reporter.handle(Event.error("The --lipo_context option must be specified when using "
            + "--fdo_optimize=<profile zip> and --lipo=binary"));
      }
    }
    if (cppOptions.lipoMode == LipoMode.BINARY &&
        compilationMode != CompilationMode.OPT) {
      reporter.handle(Event.error(
          "'--lipo=binary' can only be used with '--compilation_mode=opt' (or '-c opt')"));
    }

    if (cppOptions.fissionModes.contains(compilationMode) && !supportsFission()) {
      reporter.handle(
          Event.warn("Fission is not supported by this crosstool. Please use a supporting " +
              "crosstool to enable fission"));
    }
  }

  @Override
  public void addGlobalMakeVariables(Builder<String, String> globalMakeEnvBuilder) {
    // hardcoded CC->gcc setting for unit tests
    globalMakeEnvBuilder.put("CC", getCppExecutable().getPathString());

    // Make variables provided by crosstool/gcc compiler suite.
    globalMakeEnvBuilder.put("AR", getArExecutable().getPathString());
    globalMakeEnvBuilder.put("NM", getNmExecutable().getPathString());
    globalMakeEnvBuilder.put("OBJCOPY", getObjCopyExecutable().getPathString());
    globalMakeEnvBuilder.put("STRIP", getStripExecutable().getPathString());

    PathFragment gcovtool = getGcovToolExecutable();
    if (gcovtool != null) {
      // gcov-tool is optional in Crosstool
      globalMakeEnvBuilder.put("GCOVTOOL", gcovtool.getPathString());
    }

    if (getTargetLibc().startsWith("glibc-")) {
      globalMakeEnvBuilder.put("GLIBC_VERSION",
          getTargetLibc().substring("glibc-".length()));
    } else {
      globalMakeEnvBuilder.put("GLIBC_VERSION", getTargetLibc());
    }

    globalMakeEnvBuilder.put("C_COMPILER", getCompiler());
    globalMakeEnvBuilder.put("TARGET_CPU", getTargetCpu());

    // Deprecated variables

    // TODO(bazel-team): delete all of these.
    globalMakeEnvBuilder.put("CROSSTOOLTOP", crosstoolTopPathFragment.getPathString());

    globalMakeEnvBuilder.putAll(getAdditionalMakeVariables());

    globalMakeEnvBuilder.put("ABI_GLIBC_VERSION", getAbiGlibcVersion());
    globalMakeEnvBuilder.put("ABI", abi);
  }

  @Override
  public void addImplicitLabels(Multimap<String, Label> implicitLabels) {
    if (getLibcLabel() != null) {
      implicitLabels.put("crosstool", getLibcLabel());
    }

    implicitLabels.put("crosstool", crosstoolTop);
  }

  @Override
  public void prepareHook(Path execRoot, ArtifactFactory artifactFactory, PathFragment genfilesPath,
      PackageRootResolver resolver) throws ViewCreationFailedException {
    // TODO(bazel-team): Remove the "relative" guard. sysroot should always be relative, and this
    // should be enforced in the creation of CppConfiguration.
    if (getSysroot() != null && !getSysroot().isAbsolute()) {
      Root sysrootRoot;
      try {
        sysrootRoot = Iterables.getOnlyElement(
          resolver.findPackageRoots(ImmutableList.of(getSysroot())).entrySet()).getValue();
      } catch (PackageRootResolutionException prre) {
        throw new ViewCreationFailedException("Failed to determine sysroot", prre);
      }

      PathFragment sysrootExecPath = sysroot.getRelative(BUILT_IN_INCLUDE_PATH_FRAGMENT);
      if (sysrootRoot.getPath().getRelative(sysrootExecPath).exists()) {
        builtInIncludeFile = Preconditions.checkNotNull(
            artifactFactory.getSourceArtifact(sysrootExecPath, sysrootRoot),
            "%s %s", sysrootRoot, sysroot);
      }
    }
    try {
      getFdoSupport().prepareToBuild(execRoot, genfilesPath, artifactFactory, resolver);
    } catch (ZipException e) {
      throw new ViewCreationFailedException("Error reading provided FDO zip file", e);
    } catch (FdoException | IOException | PackageRootResolutionException e) {
      throw new ViewCreationFailedException("Error while initializing FDO support", e);
    }
  }

  @Override
  public void declareSkyframeDependencies(Environment env) {
    getFdoSupport().declareSkyframeDependencies(env, execRoot);
  }

  @Override
  public void addRoots(List<Root> roots) {
    // Fdo root can only exist for the target configuration.
    FdoSupport fdoSupport = getFdoSupport();
    if (fdoSupport.getFdoRoot() != null) {
      roots.add(fdoSupport.getFdoRoot());
    }

    // Grepped header includes; this root is not configuration specific.
    roots.add(getGreppedIncludesDirectory());
  }

  @Override
  public Map<String, String> getCoverageEnvironment() {
    ImmutableMap.Builder<String, String> env = ImmutableMap.builder();
    env.put("COVERAGE_GCOV_PATH", getGcovExecutable().getPathString());
    PathFragment fdoInstrument = getFdoSupport().getFdoInstrument();
    if (fdoInstrument != null) {
      env.put("FDO_DIR", fdoInstrument.getPathString());
    }
    return env.build();
  }

  @Override
  public ImmutableList<Label> getGcovLabels() {
    // TODO(bazel-team): Using a gcov-specific crosstool filegroup here could reduce the number of
    // inputs significantly. We'd also need to add logic in tools/coverage/collect_coverage.sh to
    // drop crosstool dependency if metadataFiles does not contain *.gcno artifacts.
    return ImmutableList.of(crosstoolTop);
  }

  @Override
  public String getOutputDirectoryName() {
    String lipoSuffix;
    if (getLipoMode() != LipoMode.OFF && !isAutoFdoLipo()) {
      lipoSuffix = "-lipo";
    } else if (getAutoFdoLipoData()) {
      lipoSuffix = "-lipodata";
    } else {
      lipoSuffix = "";
    }
    return toolchainIdentifier + lipoSuffix;
  }

  @Override
  public String getPlatformName() {
    return getToolchainIdentifier();
  }

  @Override
  public boolean supportsIncrementalBuild() {
    return !isLipoOptimization();
  }

  @Override
  public boolean performsStaticLink() {
    return getLinkOptions().contains("-static");
  }

  /**
   * Returns true if we should share identical native libraries between different targets.
   */
  public boolean shareNativeDeps() {
    return cppOptions.shareNativeDeps;
  }

  @Override
  public void prepareForExecutionPhase() throws IOException {
    // _fdo has a prefix of "_", but it should nevertheless be deleted. Detailed description
    // of the structure of the symlinks / directories can be found at FdoSupport.extractFdoZip().
    // We actually create a directory named "blaze-fdo" under the exec root, the previous version
    // of which is deleted in FdoSupport.prepareToBuildExec(). We cannot do that just before the
    // execution phase because that needs to happen before the analysis phase (in order to create
    // the artifacts corresponding to the .gcda files).
    Path tempPath = execRoot.getRelative("_fdo");
    if (tempPath.exists()) {
      FileSystemUtils.deleteTree(tempPath);
    }
  }

  @Override
  public Map<String, Object> lateBoundOptionDefaults() {
    // --cpu and --compiler initially default to null because their *actual* defaults aren't known
    // until they're read from the CROSSTOOL. Feed the CROSSTOOL defaults in here.
    return ImmutableMap.<String, Object>of(
        "cpu", getTargetCpu(),
        "compiler", getCompiler()
    );
  }

  /**
   * Return set of features enabled by the CppConfiguration, specifically
   * the FDO and LIPO related features enabled by options.
   */
  @Override
  public ImmutableSet<String> configurationEnabledFeatures(RuleContext ruleContext) {
    ImmutableSet.Builder<String> requestedFeatures = ImmutableSet.builder();
    FdoSupport fdoSupport = getFdoSupport();
    if (fdoSupport.getFdoInstrument() != null) {
      requestedFeatures.add(CppRuleClasses.FDO_INSTRUMENT);
    }
    if (fdoSupport.getFdoOptimizeProfile() != null
        && !fdoSupport.isAutoFdoEnabled()) {
      requestedFeatures.add(CppRuleClasses.FDO_OPTIMIZE);
    }
    if (fdoSupport.isAutoFdoEnabled()) {
      requestedFeatures.add(CppRuleClasses.AUTOFDO);
    }
    if (isLipoOptimizationOrInstrumentation()) {
      requestedFeatures.add(CppRuleClasses.LIPO);
    }
    if (ruleContext.getConfiguration().isCodeCoverageEnabled()) {
      requestedFeatures.add(CppRuleClasses.COVERAGE);
    }
    return requestedFeatures.build();
  }
}