aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
blob: 8e80211b102d30f609eafc42064aa6f1374f171d (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
// Copyright 2014 Google Inc. 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.analysis.config;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
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.actions.ArtifactFactory;
import com.google.devtools.build.lib.actions.PackageRootResolver;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ViewCreationFailedException;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationCollection.Transitions;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.Configurator;
import com.google.devtools.build.lib.packages.Attribute.SplitTransition;
import com.google.devtools.build.lib.packages.Attribute.Transition;
import com.google.devtools.build.lib.packages.InputFile;
import com.google.devtools.build.lib.packages.PackageGroup;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.rules.test.TestActionBuilder;
import com.google.devtools.build.lib.syntax.Label;
import com.google.devtools.build.lib.syntax.Label.SyntaxException;
import com.google.devtools.build.lib.syntax.SkylarkCallable;
import com.google.devtools.build.lib.syntax.SkylarkModule;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.RegexFilter;
import com.google.devtools.build.lib.util.StringUtilities;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import com.google.devtools.common.options.Converter;
import com.google.devtools.common.options.Converters;
import com.google.devtools.common.options.EnumConverter;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.TriState;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import javax.annotation.Nullable;

/**
 * Instances of BuildConfiguration represent a collection of context
 * information which may affect a build (for example: the target platform for
 * compilation, or whether or not debug tables are required).  In fact, all
 * "environmental" information (e.g. from the tool's command-line, as opposed
 * to the BUILD file) that can affect the output of any build tool should be
 * explicitly represented in the BuildConfiguration instance.
 *
 * <p>A single build may require building tools to run on a variety of
 * platforms: when compiling a server application for production, we must build
 * the build tools (like compilers) to run on the host platform, but cross-compile
 * the application for the production environment.
 *
 * <p>There is always at least one BuildConfiguration instance in any build:
 * the one representing the host platform. Additional instances may be created,
 * in a cross-compilation build, for example.
 *
 * <p>Instances of BuildConfiguration are canonical:
 * <pre>c1.equals(c2) <=> c1==c2.</pre>
 */
@SkylarkModule(name = "configuration",
    doc = "Data required for the analysis of a target that comes from targets that "
        + "depend on it and not targets that it depends on.")
public final class BuildConfiguration implements Serializable {

  /**
   * An interface for language-specific configurations.
   */
  public abstract static class Fragment implements Serializable {
    /**
     * Returns a human-readable name of the configuration fragment.
     */
    public abstract String getName();

    /**
     * Validates the options for this Fragment. Issues warnings for the
     * use of deprecated options, and warnings or errors for any option settings
     * that conflict.
     */
    @SuppressWarnings("unused")
    public void reportInvalidOptions(EventHandler reporter, BuildOptions buildOptions) {
    }

    /**
     * Adds mapping of names to values of "Make" variables defined by this configuration.
     */
    @SuppressWarnings("unused")
    public void addGlobalMakeVariables(ImmutableMap.Builder<String, String> globalMakeEnvBuilder) {
    }

    /**
     * Collects all labels that should be implicitly loaded from labels that were specified as
     * options, keyed by the name to be displayed to the user if something goes wrong.
     * The resulting set only contains labels that were derived from command-line options; the
     * intention is that it can be used to sanity-check that the command-line options actually
     * contain these in their transitive closure.
     */
    @SuppressWarnings("unused")
    public void addImplicitLabels(Multimap<String, Label> implicitLabels) {
    }

    /**
     * Returns a string that identifies the configuration fragment.
     */
    public abstract String cacheKey();

    /**
     * The fragment may use this hook to perform I/O and read data into memory that is used during
     * analysis. During the analysis phase disk I/O operations are disallowed.
     *
     * <p>This hook is only called for the top-level configuration after the loading phase is
     * complete.
     */
    @SuppressWarnings("unused")
    public void prepareHook(Path execPath, ArtifactFactory artifactFactory,
        PathFragment genfilesPath, PackageRootResolver resolver)
        throws ViewCreationFailedException {
    }

    /**
     * Adds all the roots from this fragment.
     */
    @SuppressWarnings("unused")
    public void addRoots(List<Root> roots) {
    }

    /**
     * Returns a (key, value) mapping to insert into the subcommand environment for coverage.
     */
    public Map<String, String> getCoverageEnvironment() {
      return ImmutableMap.<String, String>of();
    }

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

    /**
     * Returns all the coverage labels for the fragment.
     */
    public ImmutableList<Label> getCoverageLabels() {
      return ImmutableList.of();
    }

    /**
     * Returns the coverage report generator tool labels.
     */
    public ImmutableList<Label> getCoverageReportGeneratorLabels() {
      return ImmutableList.of();
    }

    /**
     * Returns a fragment of the output directory name for this configuration. The output
     * directory for the whole configuration contains all the short names by all fragments.
     */
    @Nullable
    public String getOutputDirectoryName() {
      return null;
    }

    /**
     * This will be added to the name of the configuration, but not to the output directory name.
     */
    @Nullable
    public String getConfigurationNameSuffix() {
      return null;
    }

    /**
     * The platform name is a concatenation of fragment platform names.
     */
    public String getPlatformName() {
      return "";
    }

    /**
     * Return false if incremental build is not possible for some reason.
     */
    public boolean supportsIncrementalBuild() {
      return true;
    }

    /**
     * Return true if the fragment performs static linking. This information is needed for
     * lincence checking.
     */
    public boolean performsStaticLink() {
      return false;
    }

    /**
     * Fragments should delete temporary directories they create for their inner mechanisms.
     * This is only called for target configuration.
     */
    @SuppressWarnings("unused")
    public void prepareForExecutionPhase() throws IOException {
    }

    /**
     * Add items to the shell environment.
     */
    @SuppressWarnings("unused")
    public void setupShellEnvironment(ImmutableMap.Builder<String, String> builder) {
    }

    /**
     * Add mappings from generally available tool names (like "sh") to their paths
     * that actions can access.
     */
    @SuppressWarnings("unused")
    public void defineExecutables(ImmutableMap.Builder<String, PathFragment> builder) {
    }

    /**
     * Returns { 'option name': 'alternative default' } entries for options where the
     * "real default" should be something besides the default specified in the {@link Option}
     * declaration.
     */
    public Map<String, Object> lateBoundOptionDefaults() {
      return ImmutableMap.of();
    }

    /**
     * Declares dependencies on any relevant Skyframe values (for example, relevant FileValues).
     *
     * @param env the skyframe environment
     */
    public void declareSkyframeDependencies(Environment env) {
    }
  }

  /**
   * A converter from strings to Labels.
   */
  public static class LabelConverter implements Converter<Label> {
    @Override
    public Label convert(String input) throws OptionsParsingException {
      try {
        // Check if the input starts with '/'. We don't check for "//" so that
        // we get a better error message if the user accidentally tries to use
        // an absolute path (starting with '/') for a label.
        if (!input.startsWith("/")) {
          input = "//" + input;
        }
        return Label.parseAbsolute(input);
      } catch (SyntaxException e) {
        throw new OptionsParsingException(e.getMessage());
      }
    }

    @Override
    public String getTypeDescription() {
      return "a build target label";
    }
  }

  public static class PluginOptionConverter implements Converter<Map.Entry<String, String>> {
    @Override
    public Map.Entry<String, String> convert(String input) throws OptionsParsingException {
      int index = input.indexOf('=');
      if (index == -1) {
        throw new OptionsParsingException("Plugin option not in the plugin=option format");
      }
      String option = input.substring(0, index);
      String value = input.substring(index + 1);
      return Maps.immutableEntry(option, value);
    }

    @Override
    public String getTypeDescription() {
      return "An option for a plugin";
    }
  }

  public static class RunsPerTestConverter extends PerLabelOptions.PerLabelOptionsConverter {
    @Override
    public PerLabelOptions convert(String input) throws OptionsParsingException {
      try {
        return parseAsInteger(input);
      } catch (NumberFormatException ignored) {
        return parseAsRegex(input);
      }
    }

    private PerLabelOptions parseAsInteger(String input)
        throws NumberFormatException, OptionsParsingException {
      int numericValue = Integer.parseInt(input);
      if (numericValue <= 0) {
        throw new OptionsParsingException("'" + input + "' should be >= 1");
      } else {
        RegexFilter catchAll = new RegexFilter(Collections.singletonList(".*"),
            Collections.<String>emptyList());
        return new PerLabelOptions(catchAll, Collections.singletonList(input));
      }
    }

    private PerLabelOptions parseAsRegex(String input) throws OptionsParsingException {
      PerLabelOptions testRegexps = super.convert(input);
      if (testRegexps.getOptions().size() != 1) {
        throw new OptionsParsingException(
            "'" + input + "' has multiple runs for a single pattern");
      }
      String runsPerTest = Iterables.getOnlyElement(testRegexps.getOptions());
      try {
        int numericRunsPerTest = Integer.parseInt(runsPerTest);
        if (numericRunsPerTest <= 0) {
          throw new OptionsParsingException("'" + input + "' has a value < 1");
        }
      } catch (NumberFormatException e) {
        throw new OptionsParsingException("'" + input + "' has a non-numeric value", e);
      }
      return testRegexps;
    }

    @Override
    public String getTypeDescription() {
      return "a positive integer or test_regex@runs. This flag may be passed more than once";
    }
  }

  /**
   * Values for the --strict_*_deps option
   */
  public static enum StrictDepsMode {
    /** Silently allow referencing transitive dependencies. */
    OFF,
    /** Warn about transitive dependencies being used directly. */
    WARN,
    /** Fail the build when transitive dependencies are used directly. */
    ERROR,
    /** Transition to strict by default. */
    STRICT,
    /** When no flag value is specified on the command line. */
    DEFAULT
  }

  /**
   * Converter for the --strict_*_deps option.
   */
  public static class StrictDepsConverter extends EnumConverter<StrictDepsMode> {
    public StrictDepsConverter() {
      super(StrictDepsMode.class, "strict dependency checking level");
    }
  }

  /**
   * Options that affect the value of a BuildConfiguration instance.
   *
   * <p>(Note: any client that creates a view will also need to declare
   * BuildView.Options, which affect the <i>mechanism</i> of view construction,
   * even if they don't affect the value of the BuildConfiguration instances.)
   *
   * <p>IMPORTANT: when adding new options, be sure to consider whether those
   * values should be propagated to the host configuration or not (see
   * {@link ConfigurationFactory#getConfiguration}.
   *
   * <p>ALSO IMPORTANT: all option types MUST define a toString method that
   * gives identical results for semantically identical option values. The
   * simplest way to ensure that is to return the input string.
   */
  public static class Options extends FragmentOptions implements Cloneable {
    public String getCpu() {
      return cpu;
    }

    @Option(name = "cpu",
            defaultValue = "null",
            category = "semantics",
            help = "The target CPU.")
    public String cpu;

    @Option(name = "min_param_file_size",
        defaultValue = "32768",
        category = "undocumented",
        help = "Minimum command line length before creating a parameter file.")
    public int minParamFileSize;

    @Option(name = "experimental_extended_sanity_checks",
        defaultValue = "false",
        category = "undocumented",
        help  = "Enables internal validation checks to make sure that configured target "
            + "implementations only access things they should. Causes a performance hit.")
    public boolean extendedSanityChecks;

    @Option(name = "experimental_allow_runtime_deps_on_neverlink",
        defaultValue = "true",
        category = "undocumented",
        help = "Flag to help transition from allowing to disallowing runtime_deps on neverlink"
        + " Java archives. The depot needs to be cleaned up to roll this out by default.")
    public boolean allowRuntimeDepsOnNeverLink;

    @Option(name = "strict_filesets",
            defaultValue = "false",
            category = "semantics",
            help = "If this option is enabled, filesets crossing package boundaries are reported "
                + "as errors. It does not work when check_fileset_dependencies_recursively is "
                + "disabled.")
    public boolean strictFilesets;

    // Plugins are build using the host config. To avoid cycles we just don't propagate
    // this option to the host config. If one day we decide to use plugins when building
    // host tools, we can improve this by (for example) creating a compiler configuration that is
    // used only for building plugins.
    @Option(name = "plugin",
            converter = LabelConverter.class,
            allowMultiple = true,
            defaultValue = "",
            category = "flags",
            help = "Plugins to use in the build. Currently works with java_plugin.")
    public List<Label> pluginList;

    @Option(name = "plugin_copt",
            converter = PluginOptionConverter.class,
            allowMultiple = true,
            category = "flags",
            defaultValue = ":",
            help = "Plugin options")
    public List<Map.Entry<String, String>> pluginCoptList;

    @Option(name = "stamp",
        defaultValue = "true",
        category = "semantics",
        help = "Stamp binaries with the date, username, hostname, workspace information, etc.")
    public boolean stampBinaries;

    // TODO(bazel-team): delete from OSS tree
    @Option(name = "instrumentation_filter",
        converter = RegexFilter.RegexFilterConverter.class,
        defaultValue = "-javatests,-_test$",
        category = "semantics",
        help = "When coverage is enabled, only rules with names included by the "
            + "specified regex-based filter will be instrumented. Rules prefixed "
            + "with '-' are excluded instead. By default, rules containing "
            + "'javatests' or ending with '_test' will not be instrumented.")
    public RegexFilter instrumentationFilter;

    @Option(name = "show_cached_analysis_results",
        defaultValue = "true",
        category = "undocumented",
        help = "Bazel reruns a static analysis only if it detects changes in the analysis "
            + "or its dependencies. If this option is enabled, Bazel will show the analysis' "
            + "results, even if it did not rerun the analysis.  If this option is disabled, "
            + "Bazel will show analysis results only if it reran the analysis.")
    public boolean showCachedAnalysisResults;

    @Option(name = "host_cpu",
        defaultValue = "null",
        category = "semantics",
        help = "The host CPU.")
    public String hostCpu;

    @Option(name = "compilation_mode",
        abbrev = 'c',
        converter = CompilationMode.Converter.class,
        defaultValue = "fastbuild",
        category = "semantics", // Should this be "flags"?
        help = "Specify the mode the binary will be built in. "
               + "Values: 'fastbuild', 'dbg', 'opt'.")
    public CompilationMode compilationMode;

    /**
     * This option is used internally to set the short name (see {@link
     * #getShortName()}) of the <i>host</i> configuration to a constant, so
     * that the output files for the host are completely independent of those
     * for the target, no matter what options are in force (k8/piii, opt/dbg,
     * etc).
     */
    @Option(name = "configuration short name", // (Spaces => can't be specified on command line.)
        defaultValue = "null",
        category = "undocumented")
    public String shortName;

    @Option(name = "platform_suffix",
            defaultValue = "null",
            category = "misc",
            help = "Specifies a suffix to be added to the configuration directory.")
    public String platformSuffix;

    @Option(name = "test_env",
        converter = Converters.OptionalAssignmentConverter.class,
        allowMultiple = true,
        defaultValue = "",
        category = "testing",
        help = "Specifies additional environment variables to be injected into the test runner "
            + "environment. Variables can be either specified by name, in which case its value "
            + "will be read from the Bazel client environment, or by the name=value pair. "
            + "This option can be used multiple times to specify several variables. "
            + "Used only by the 'bazel test' command."
        )
    public List<Map.Entry<String, String>> testEnvironment;

    @Option(name = "collect_code_coverage",
        defaultValue = "false",
        category = "testing",
        help = "If specified, Bazel will instrument code (using offline instrumentation where "
               + "possible) and will collect coverage information during tests. Only targets that "
               + " match --instrumentation_filter will be affected. Usually this option should "
               + " not be specified directly - 'bazel coverage' command should be used instead."
        )
    public boolean collectCodeCoverage;

    @Option(name = "microcoverage",
        defaultValue = "false",
        category = "testing",
        help = "If specified with coverage, Blaze will collect microcoverage (per test method "
            + "coverage) information during tests. Only targets that match "
            + "--instrumentation_filter will be affected. Usually this option should not be "
            + "specified directly - 'blaze coverage --microcoverage' command should be used "
            + "instead."
        )
    public boolean collectMicroCoverage;

    @Option(name = "cache_test_results",
        defaultValue = "auto",
        category = "testing",
        abbrev = 't', // it's useful to toggle this on/off quickly
        help = "If 'auto', Bazel will only rerun a test if any of the following conditions apply: "
        + "(1) Bazel detects changes in the test or its dependencies "
        + "(2) the test is marked as external "
        + "(3) multiple test runs were requested with --runs_per_test"
        + "(4) the test failed"
        + "If 'yes', the caching behavior will be the same as 'auto' except that "
        + "it may cache test failures and test runs with --runs_per_test."
        + "If 'no', all tests will be always executed.")
    public TriState cacheTestResults;

    @Deprecated
    @Option(name = "test_result_expiration",
        defaultValue = "-1", // No expiration by defualt.
        category = "testing",
        help = "This option is deprecated and has no effect.")
    public int testResultExpiration;

    @Option(name = "test_sharding_strategy",
        defaultValue = "explicit",
        category = "testing",
        converter = TestActionBuilder.ShardingStrategyConverter.class,
        help = "Specify strategy for test sharding: "
            + "'explicit' to only use sharding if the 'shard_count' BUILD attribute is present. "
            + "'disabled' to never use test sharding. "
            + "'experimental_heuristic' to enable sharding on remotely executed tests without an "
            + "explicit  'shard_count' attribute which link in a supported framework. Considered "
            + "experimental.")
    public TestActionBuilder.TestShardingStrategy testShardingStrategy;

    @Option(name = "runs_per_test",
        allowMultiple = true,
        defaultValue = "1",
        category = "testing",
        converter = RunsPerTestConverter.class,
        help = "Specifies number of times to run each test. If any of those attempts "
            + "fail for any reason, the whole test would be considered failed. "
            + "Normally the value specified is just an integer. Example: --runs_per_test=3 "
            + "will run all tests 3 times. "
            + "Alternate syntax: regex_filter@runs_per_test. Where runs_per_test stands for "
            + "an integer value and regex_filter stands "
            + "for a list of include and exclude regular expression patterns (Also see "
            + "--instrumentation_filter). Example: "
            + "--runs_per_test=//foo/.*,-//foo/bar/.*@3 runs all tests in //foo/ "
            + "except those under foo/bar three times. "
            + "This option can be passed multiple times. ")
    public List<PerLabelOptions> runsPerTest;

    @Option(name = "build_runfile_links",
            defaultValue = "true",
            category = "strategy",
            help = "If true, build runfiles symlink forests for all targets.  "
                + "If false, write only manifests when possible.")
    public boolean buildRunfiles;

    @Option(name = "test_arg",
        allowMultiple = true,
        defaultValue = "",
        category = "testing",
        help = "Specifies additional options and arguments that should be passed to the test "
            + "executable. Can be used multiple times to specify several arguments. "
            + "If multiple tests are executed, each of them will receive identical arguments. "
            + "Used only by the 'bazel test' command."
        )
    public List<String> testArguments;

    @Option(name = "test_filter",
        allowMultiple = false,
        defaultValue = "null",
        category = "testing",
        help = "Specifies a filter to forward to the test framework.  Used to limit "
        + "the tests run. Note that this does not affect which targets are built.")
    public String testFilter;

    @Option(name = "check_fileset_dependencies_recursively",
            defaultValue = "true",
            category = "semantics",
            help = "If false, fileset targets will, whenever possible, create "
            + "symlinks to directories instead of creating one symlink for each "
            + "file inside the directory. Disabling this will significantly "
            + "speed up fileset builds, but targets that depend on filesets will "
            + "not be rebuilt if files are added, removed or modified in a "
            + "subdirectory which has not been traversed.")
    public boolean checkFilesetDependenciesRecursively;

    @Option(name = "run_under",
            category = "run",
            defaultValue = "null",
            converter = RunUnderConverter.class,
            help = "Prefix to insert in front of command before running. "
                + "Examples:\n"
                + "\t--run_under=valgrind\n"
                + "\t--run_under=strace\n"
                + "\t--run_under='strace -c'\n"
                + "\t--run_under='valgrind --quiet --num-callers=20'\n"
                + "\t--run_under=//package:target\n"
                + "\t--run_under='//package:target --options'\n")
    public RunUnder runUnder;

    @Option(name = "distinct_host_configuration",
            defaultValue = "true",
            category = "strategy",
            help = "Build all the tools used during the build for a distinct configuration from "
            + "that used for the target program.  By default, the same configuration is used "
            + "for host and target programs, but this may cause undesirable rebuilds of tool "
            + "such as the protocol compiler (and then everything downstream) whenever a minor "
            + "change is made to the target configuration, such as setting the linker options.  "
            + "When this flag is specified, a distinct configuration will be used to build the "
            + "tools, preventing undesired rebuilds.  However, certain libraries will then "
            + "need to be compiled twice, once for each configuration, which may cause some "
            + "builds to be slower.  As a rule of thumb, this option is likely to benefit "
            + "users that make frequent changes in configuration (e.g. opt/dbg).  "
            + "Please read the user manual for the full explanation.")
    public boolean useDistinctHostConfiguration;

    @Option(name = "check_visibility",
            defaultValue = "true",
            category = "checking",
            help = "If disabled, visibility errors are demoted to warnings.")
    public boolean checkVisibility;

    // Moved from viewOptions to here because license information is very expensive to serialize.
    // Having it here allows us to skip computation of transitive license information completely
    // when the setting is disabled.
    @Option(name = "check_licenses",
        defaultValue = "false",
        category = "checking",
        help = "Check that licensing constraints imposed by dependent packages "
        + "do not conflict with distribution modes of the targets being built. "
        + "By default, licenses are not checked.")
    public boolean checkLicenses;

    @Option(name = "experimental_enforce_constraints",
        defaultValue = "true",
        category = "undocumented",
        help = "Checks the environments each target is compatible with and reports errors if any "
            + "target has dependencies that don't support the same environments")
    public boolean enforceConstraints;

    @Option(name = "experimental_action_listener",
            allowMultiple = true,
            defaultValue = "",
            category = "experimental",
            converter = LabelConverter.class,
            help = "Use action_listener to attach an extra_action to existing build actions.")
    public List<Label> actionListeners;

    @Option(name = "is host configuration",
        defaultValue = "false",
        category = "undocumented",
        help = "Shows whether these options are set for host configuration.")
    public boolean isHost;

    @Option(name = "experimental_proto_header_modules",
        defaultValue = "false",
        category = "undocumented",
        help  = "Enables compilation of C++ header modules for proto libraries.")
    public boolean protoHeaderModules;

    @Option(name = "features",
        allowMultiple = true,
        defaultValue = "",
        category = "flags",
        help = "The given features will be enabled or disabled by default for all packages. "
          + "Specifying -<feature> will disable the feature globally. "
          + "Negative features always override positive ones. "
          + "This flag is used to enable rolling out default feature changes without a "
          + "Blaze release.")
    public List<String> defaultFeatures;

    @Override
    public FragmentOptions getHost(boolean fallback) {
      Options host = (Options) getDefault();

      host.shortName = "host";
      host.compilationMode = CompilationMode.OPT;
      host.isHost = true;

      if (fallback) {
        // In the fallback case, we have already tried the target options and they didn't work, so
        // now we try the default options; the hostCpu field has the default value, because we use
        // getDefault() above.
        host.cpu = computeHostCpu(host.hostCpu);
      } else {
        host.cpu = computeHostCpu(hostCpu);
      }

      // === Runfiles ===
      // Ideally we could force this the other way, and skip runfiles construction
      // for host tools which are never run locally, but that's probably a very
      // small optimization.
      host.buildRunfiles = true;

      // === Linkstamping ===
      // Disable all link stamping for the host configuration, to improve action
      // cache hit rates for tools.
      host.stampBinaries = false;

      // === Visibility ===
      host.checkVisibility = checkVisibility;

      // === Licenses ===
      host.checkLicenses = checkLicenses;

      // === Allow runtime_deps to depend on neverlink Java libraries.
      host.allowRuntimeDepsOnNeverLink = allowRuntimeDepsOnNeverLink;

      // === Pass on C++ compiler features.
      host.defaultFeatures = ImmutableList.copyOf(defaultFeatures);

      return host;
    }

    private static String computeHostCpu(String explicitHostCpu) {
      if (explicitHostCpu != null) {
        return explicitHostCpu;
      }
      switch (OS.getCurrent()) {
        case DARWIN:
          return "darwin";
        default:
          return "k8";
      }
    }

    @Override
    public void addAllLabels(Multimap<String, Label> labelMap) {
      labelMap.putAll("action_listener", actionListeners);
      labelMap.putAll("plugins", pluginList);
      if ((runUnder != null) && (runUnder.getLabel() != null)) {
        labelMap.put("RunUnder", runUnder.getLabel());
      }
    }
  }

  /**
   * A list of build configurations that only contains the null element.
   */
  private static final List<BuildConfiguration> NULL_LIST =
      Collections.unmodifiableList(Arrays.asList(new BuildConfiguration[] { null }));

  private final String cacheKey;
  private final String shortCacheKey;

  private Transitions transitions;
  private Set<BuildConfiguration> allReachableConfigurations;

  private final ImmutableMap<Class<? extends Fragment>, Fragment> fragments;

  // Directories in the output tree
  private final Root outputDirectory; // the configuration-specific output directory.
  private final Root binDirectory;
  private final Root genfilesDirectory;
  private final Root coverageMetadataDirectory; // for coverage-related metadata, artifacts, etc.
  private final Root testLogsDirectory;
  private final Root includeDirectory;
  private final Root middlemanDirectory;

  private final PathFragment binFragment;
  private final PathFragment genfilesFragment;

  // If false, AnalysisEnviroment doesn't register any actions created by the ConfiguredTarget.
  private final boolean actionsEnabled;

  private final ImmutableSet<Label> coverageLabels;
  private final ImmutableSet<Label> coverageReportGeneratorLabels;

  // Executables like "perl" or "sh"
  private final ImmutableMap<String, PathFragment> executables;

  // All the "defglobals" in //tools:GLOBALS for this platform/configuration:
  private final ImmutableMap<String, String> globalMakeEnv;

  private final ImmutableMap<String, String> defaultShellEnvironment;
  private final BuildOptions buildOptions;
  private final Options options;

  private final String shortName;
  private final String mnemonic;
  private final String platformName;

  /**
   * It is not fingerprinted because it should only be used to access
   * variables that do not break the hermetism of build rules.
   */
  private final ImmutableMap<String, String> clientEnvironment;

  /**
   * Helper container for {@link #transitiveOptionsMap} below.
   */
  private static class OptionDetails implements Serializable {
    private OptionDetails(Class<? extends OptionsBase> optionsClass, Object value,
        boolean allowsMultiple) {
      this.optionsClass = optionsClass;
      this.value = value;
      this.allowsMultiple = allowsMultiple;
    }

    /** The {@link FragmentOptions} class that defines this option. */
    private final Class<? extends OptionsBase> optionsClass;

    /**
     * The value of the given option (either explicitly defined or default). May be null.
     */
    private final Object value;

    /** Whether or not this option supports multiple values. */
    private final boolean allowsMultiple;
  }

  /**
   * Maps option names to the {@link OptionDetails} the option takes for this configuration.
   *
   * <p>This can be used to:
   * <ol>
   *   <li>Find an option's (parsed) value given its command-line name</li>
   *   <li>Parse alternative values for the option.</li>
   * </ol>
   *
   * <p>This map is "transitive" in that it includes *all* options recognizable by this
   * configuration, including those defined in child fragments.
   */
  private final Map<String, OptionDetails> transitiveOptionsMap;


  /**
   * Validates the options for this BuildConfiguration. Issues warnings for the
   * use of deprecated options, and warnings or errors for any option settings
   * that conflict.
   */
  public void reportInvalidOptions(EventHandler reporter) {
    for (Fragment fragment : fragments.values()) {
      fragment.reportInvalidOptions(reporter, this.buildOptions);
    }

    Set<String> plugins = new HashSet<>();
    for (Label plugin : options.pluginList) {
      String name = plugin.getName();
      if (plugins.contains(name)) {
        reporter.handle(Event.error("A build cannot have two plugins with the same name"));
      }
      plugins.add(name);
    }
    for (Map.Entry<String, String> opt : options.pluginCoptList) {
      if (!plugins.contains(opt.getKey())) {
        reporter.handle(Event.error("A plugin_copt must refer to an existing plugin"));
      }
    }

    if (options.shortName != null) {
      reporter.handle(Event.error(
          "The internal '--configuration short name' option cannot be used on the command line"));
    }

    if (options.testShardingStrategy
        == TestActionBuilder.TestShardingStrategy.EXPERIMENTAL_HEURISTIC) {
      reporter.handle(Event.warn(
          "Heuristic sharding is intended as a one-off experimentation tool for determing the "
          + "benefit from sharding certain tests. Please don't keep this option in your "
          + ".blazerc or continuous build"));
    }
  }

  private ImmutableMap<String, String> setupShellEnvironment() {
    ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
    for (Fragment fragment : fragments.values()) {
      fragment.setupShellEnvironment(builder);
    }
    return builder.build();
  }

  BuildConfiguration(BlazeDirectories directories,
                     Map<Class<? extends Fragment>, Fragment> fragmentsMap,
                     BuildOptions buildOptions,
                     Map<String, String> clientEnv,
                     boolean actionsDisabled) {
    this.actionsEnabled = !actionsDisabled;
    fragments = ImmutableMap.copyOf(fragmentsMap);

    // This is a view that will be updated upon each client command.
    this.clientEnvironment = ImmutableMap.copyOf(clientEnv);

    this.buildOptions = buildOptions;
    this.options = buildOptions.get(Options.class);

    this.mnemonic = buildMnemonic();
    String outputDirName = (options.shortName != null) ? options.shortName : mnemonic;
    this.shortName = buildShortName(outputDirName);

    this.executables = collectExecutables();

    Path execRoot = directories.getExecRoot();
    // configuration-specific output tree
    Path outputDir = directories.getOutputPath().getRelative(outputDirName);
    this.outputDirectory = Root.asDerivedRoot(execRoot, outputDir);

    // specific subdirs under outputDirectory
    this.binDirectory = Root.asDerivedRoot(execRoot, outputDir.getRelative("bin"));
    this.genfilesDirectory = Root.asDerivedRoot(execRoot, outputDir.getRelative("genfiles"));
    this.coverageMetadataDirectory = Root.asDerivedRoot(execRoot,
        outputDir.getRelative("coverage-metadata"));
    this.testLogsDirectory = Root.asDerivedRoot(execRoot, outputDir.getRelative("testlogs"));
    this.includeDirectory = Root.asDerivedRoot(execRoot,
        outputDir.getRelative(BlazeDirectories.RELATIVE_INCLUDE_DIR));
    this.middlemanDirectory = Root.middlemanRoot(execRoot, outputDir);

    // precompute some frequently-used relative paths
    this.binFragment = getBinDirectory().getExecPath();
    this.genfilesFragment = getGenfilesDirectory().getExecPath();

    ImmutableSet.Builder<Label> coverageLabelsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<Label> coverageReportGeneratorLabelsBuilder = ImmutableSet.builder();
    for (Fragment fragment : fragments.values()) {
      coverageLabelsBuilder.addAll(fragment.getCoverageLabels());
      coverageReportGeneratorLabelsBuilder.addAll(fragment.getCoverageReportGeneratorLabels());
    }
    this.coverageLabels = coverageLabelsBuilder.build();
    this.coverageReportGeneratorLabels = coverageReportGeneratorLabelsBuilder.build();

    // Platform name
    StringBuilder platformNameBuilder = new StringBuilder();
    for (Fragment fragment : fragments.values()) {
      platformNameBuilder.append(fragment.getPlatformName());
    }
    this.platformName = platformNameBuilder.toString();

    this.defaultShellEnvironment = setupShellEnvironment();

    this.transitiveOptionsMap = computeOptionsMap(buildOptions, fragments.values());

    ImmutableMap.Builder<String, String> globalMakeEnvBuilder = ImmutableMap.builder();
    for (Fragment fragment : fragments.values()) {
      fragment.addGlobalMakeVariables(globalMakeEnvBuilder);
    }

    // Lots of packages in third_party assume that BINMODE expands to either "-dbg", or "-opt". So
    // for backwards compatibility we preserve that invariant, setting BINMODE to "-dbg" rather than
    // "-fastbuild" if the compilation mode is "fastbuild".
    // We put the real compilation mode in a new variable COMPILATION_MODE.
    globalMakeEnvBuilder.put("COMPILATION_MODE", options.compilationMode.toString());
    globalMakeEnvBuilder.put("BINMODE", "-"
        + ((options.compilationMode == CompilationMode.FASTBUILD)
            ? "dbg"
            : options.compilationMode.toString()));
    /*
     * Attention! Document these in the build-encyclopedia
     */
    // the bin directory and the genfiles directory
    // These variables will be used on Windows as well, so we need to make sure
    // that paths use the correct system file-separator.
    globalMakeEnvBuilder.put("BINDIR", binFragment.getPathString());
    globalMakeEnvBuilder.put("INCDIR",
        getIncludeDirectory().getExecPath().getPathString());
    globalMakeEnvBuilder.put("GENDIR", genfilesFragment.getPathString());
    globalMakeEnv = globalMakeEnvBuilder.build();

    cacheKey = computeCacheKey(
        directories, fragmentsMap, this.buildOptions, this.clientEnvironment);
    shortCacheKey = shortName + "-" + Fingerprint.md5Digest(cacheKey);
  }


  /**
   * Computes and returns the transitive optionName -> "option info" map for
   * this configuration.
   */
  private static Map<String, OptionDetails> computeOptionsMap(BuildOptions buildOptions,
      Iterable<Fragment> fragments) {
    // Collect from our fragments "alternative defaults" for options where the default
    // should be something other than what's specified in Option.defaultValue.
    Map<String, Object> lateBoundDefaults = Maps.newHashMap();
    for (Fragment fragment : fragments) {
      lateBoundDefaults.putAll(fragment.lateBoundOptionDefaults());
    }

    ImmutableMap.Builder<String, OptionDetails> map = ImmutableMap.builder();
    try {
      for (FragmentOptions options : buildOptions.getOptions()) {
        for (Field field : options.getClass().getFields()) {
          if (field.isAnnotationPresent(Option.class)) {
            Option option = field.getAnnotation(Option.class);
            Object value = field.get(options);
            if (value == null) {
              if (lateBoundDefaults.containsKey(option.name())) {
                value = lateBoundDefaults.get(option.name());
              } else if (!option.defaultValue().equals("null")) {
                 // See {@link Option#defaultValue} for an explanation of default "null" strings.
                value = option.defaultValue();
              }
            }
            map.put(option.name(),
                new OptionDetails(options.getClass(), value, option.allowMultiple()));
          }
        }
      }
    } catch (IllegalAccessException e) {
      throw new IllegalStateException(
          "Unexpected illegal access trying to create this configuration's options map: ", e);
    }
    return map.build();
  }

  private String buildShortName(String outputDirName) {
    ArrayList<String> nameParts = new ArrayList<>(ImmutableList.of(outputDirName));
    for (Fragment fragment : fragments.values()) {
      nameParts.add(fragment.getConfigurationNameSuffix());
    }
    return Joiner.on('-').skipNulls().join(nameParts);
  }

  private String buildMnemonic() {
    // See explanation at getShortName().
    String platformSuffix = (options.platformSuffix != null) ? options.platformSuffix : "";
    ArrayList<String> nameParts = new ArrayList<String>();
    for (Fragment fragment : fragments.values()) {
      nameParts.add(fragment.getOutputDirectoryName());
    }
    nameParts.add(getCompilationMode() + platformSuffix);
    return Joiner.on('-').join(Iterables.filter(nameParts, Predicates.notNull()));
  }

  /**
   * Set the outgoing configuration transitions. During the lifetime of a given build configuration,
   * this must happen exactly once, shortly after the configuration is created.
   * TODO(bazel-team): this makes the object mutable, get rid of it.
   */
  public void setConfigurationTransitions(Transitions transitions) {
    Preconditions.checkNotNull(transitions);
    Preconditions.checkState(this.transitions == null);
    this.transitions = transitions;
  }

  public Transitions getTransitions() {
    Preconditions.checkState(this.transitions != null || isHostConfiguration());
    return transitions;
  }

  /**
   * Returns all configurations that can be reached from this configuration through any kind of
   * configuration transition.
   */
  public synchronized Collection<BuildConfiguration> getAllReachableConfigurations() {
    if (allReachableConfigurations == null) {
      // This is needed for every configured target in skyframe m2, so we cache it.
      // We could alternatively make the corresponding dependencies into a skyframe node.
      this.allReachableConfigurations = computeAllReachableConfigurations();
    }
    return allReachableConfigurations;
  }

  /**
   * Returns all configurations that can be reached from this configuration through any kind of
   * configuration transition.
   */
  private Set<BuildConfiguration> computeAllReachableConfigurations() {
    Set<BuildConfiguration> result = new LinkedHashSet<>();
    Queue<BuildConfiguration> queue = new LinkedList<>();
    queue.add(this);
    while (!queue.isEmpty()) {
      BuildConfiguration config = queue.remove();
      if (!result.add(config)) {
        continue;
      }
      config.getTransitions().addDirectlyReachableConfigurations(queue);
    }
    return result;
  }

  /**
   * Returns the new configuration after traversing a dependency edge with a given configuration
   * transition.
   *
   * @param transition the configuration transition
   * @return the new configuration
   * @throws IllegalArgumentException if the transition is a {@link SplitTransition}
   */
  public BuildConfiguration getConfiguration(Transition transition) {
    Preconditions.checkArgument(!(transition instanceof SplitTransition));
    return transitions.getConfiguration(transition);
  }

  /**
   * Returns the new configurations after traversing a dependency edge with a given split
   * transition.
   *
   * @param transition the split configuration transition
   * @return the new configurations
   */
  public List<BuildConfiguration> getSplitConfigurations(SplitTransition<?> transition) {
    return transitions.getSplitConfigurations(transition);
  }

  /**
   * Calculates the configurations of a direct dependency. If a rule in some BUILD file refers
   * to a target (like another rule or a source file) using a label attribute, that target needs
   * to have a configuration, too. This method figures out the proper configuration for the
   * dependency.
   *
   * @param fromRule the rule that's depending on some target
   * @param attribute the attribute using which the rule depends on that target (eg. "srcs")
   * @param toTarget the target that's dependeded on
   * @return the configuration that should be associated to {@code toTarget}
   */
  public Iterable<BuildConfiguration> evaluateTransition(final Rule fromRule,
      final Attribute attribute, final Target toTarget) {
    // Fantastic configurations and where to find them:

    // I. Input files and package groups have no configurations. We don't want to duplicate them.
    if (toTarget instanceof InputFile || toTarget instanceof PackageGroup) {
      return NULL_LIST;
    }

    // II. Host configurations never switch to another. All prerequisites of host targets have the
    // same host configuration.
    if (isHostConfiguration()) {
      return ImmutableList.of(this);
    }

    // Make sure config_setting dependencies are resolved in the referencing rule's configuration,
    // unconditionally. For example, given:
    //
    // genrule(
    //     name = 'myrule',
    //     tools = select({ '//a:condition': [':sometool'] })
    //
    // all labels in "tools" get resolved in the host configuration (since the "tools" attribute
    // declares a host configuration transition). We want to explicitly exclude configuration labels
    // from these transitions, since their *purpose* is to do computation on the owning
    // rule's configuration.
    // TODO(bazel-team): implement this more elegantly. This is far too hackish. Specifically:
    // don't reference the rule name explicitly and don't require special-casing here.
    if (toTarget instanceof Rule && ((Rule) toTarget).getRuleClass().equals("config_setting")) {
      return ImmutableList.of(this);
    }

    List<BuildConfiguration> toConfigurations;
    if (attribute.getConfigurationTransition() instanceof SplitTransition) {
      Preconditions.checkState(attribute.getConfigurator() == null);
      toConfigurations = getSplitConfigurations(
          (SplitTransition<?>) attribute.getConfigurationTransition());
    } else {
      // III. Attributes determine configurations. The configuration of a prerequisite is determined
      // by the attribute.
      @SuppressWarnings("unchecked")
      Configurator<BuildConfiguration, Rule> configurator =
          (Configurator<BuildConfiguration, Rule>) attribute.getConfigurator();
      toConfigurations = ImmutableList.of((configurator != null)
          ? configurator.apply(fromRule, this, attribute, toTarget)
          : getConfiguration(attribute.getConfigurationTransition()));
    }

    return Iterables.transform(toConfigurations,
        new Function<BuildConfiguration, BuildConfiguration>() {
      @Override
      public BuildConfiguration apply(BuildConfiguration input) {
        // IV. Allow the transition object to perform an arbitrary switch. Blaze modules can inject
        // configuration transition logic by extending the Transitions class.
        BuildConfiguration actual = getTransitions().configurationHook(
            fromRule, attribute, toTarget, input);

        // V. Allow rule classes to override their own configurations.
        Rule associatedRule = toTarget.getAssociatedRule();
        if (associatedRule != null) {
          @SuppressWarnings("unchecked")
          RuleClass.Configurator<BuildConfiguration, Rule> func =
              associatedRule.getRuleClassObject().<BuildConfiguration, Rule>getConfigurator();
          actual = func.apply(associatedRule, actual);
        }

        return actual;
      }
    });
  }

  /**
   * Returns a multimap of all labels that should be implicitly loaded from labels that were
   * specified as options, keyed by the name to be displayed to the user if something goes wrong.
   * The returned set only contains labels that were derived from command-line options; the
   * intention is that it can be used to sanity-check that the command-line options actually contain
   * these in their transitive closure.
   */
  public ListMultimap<String, Label> getImplicitLabels() {
    ListMultimap<String, Label> implicitLabels = ArrayListMultimap.create();
    for (Fragment fragment : fragments.values()) {
      fragment.addImplicitLabels(implicitLabels);
    }
    return implicitLabels;
  }

  /**
   * For an given environment, returns a subset containing all
   * variables in the given list if they are defined in the given
   * environment.
   */
  @VisibleForTesting
  static Map<String, String> getMapping(List<String> variables,
                                        Map<String, String> environment) {
    Map<String, String> result = new HashMap<>();
    for (String var : variables) {
      if (environment.containsKey(var)) {
        result.put(var, environment.get(var));
      }
    }
    return result;
  }

  /**
   * Avoid this method. The client environment is not part of the configuration's signature, so
   * calls to this method introduce a non-hermetic access to data that is not visible to Skyframe.
   *
   * @return an unmodifiable view of the bazel client's environment
   *         upon its most recent request.
   */
  // TODO(bazel-team): Remove this.
  public Map<String, String> getClientEnv() {
    return clientEnvironment;
  }

  /**
   * Returns the {@link Option} class the defines the given option, null if the
   * option isn't recognized.
   *
   * <p>optionName is the name of the option as it appears on the command line
   * e.g. {@link Option#name}).
   */
  Class<? extends OptionsBase> getOptionClass(String optionName) {
    OptionDetails optionData = transitiveOptionsMap.get(optionName);
    return optionData == null ? null : optionData.optionsClass;
  }

  /**
   * Returns the value of the specified option for this configuration or null if the
   * option isn't recognized. Since an option's legitimate value could be null, use
   * {@link #getOptionClass} to distinguish between that and an unknown option.
   *
   * <p>optionName is the name of the option as it appears on the command line
   * e.g. {@link Option#name}).
   */
  Object getOptionValue(String optionName) {
    OptionDetails optionData = transitiveOptionsMap.get(optionName);
    return (optionData == null) ? null : optionData.value;
  }

  /**
   * Returns whether or not the given option supports multiple values at the command line (e.g.
   * "--myoption value1 --myOption value2 ..."). Returns false for unrecognized options. Use
   * {@link #getOptionClass} to distinguish between those and legitimate single-value options.
   *
   * <p>As declared in {@link Option#allowMultiple}, multi-value options are expected to be
   * of type {@code List<T>}.
   */
  boolean allowsMultipleValues(String optionName) {
    OptionDetails optionData = transitiveOptionsMap.get(optionName);
    return (optionData == null) ? false : optionData.allowsMultiple;
  }

  /**
   * The platform string, suitable for use as a key into a MakeEnvironment.
   */
  public String getPlatformName() {
    return platformName;
  }

  /**
   * Returns the output directory for this build configuration.
   */
  public Root getOutputDirectory() {
    return outputDirectory;
  }

  /**
   * Returns the bin directory for this build configuration.
   */
  @SkylarkCallable(name = "bin_dir", structField = true,
      doc = "The root corresponding to bin directory.")
  public Root getBinDirectory() {
    return binDirectory;
  }

  /**
   * Returns a relative path to the bin directory at execution time.
   */
  public PathFragment getBinFragment() {
    return binFragment;
  }

  /**
   * Returns the include directory for this build configuration.
   */
  public Root getIncludeDirectory() {
    return includeDirectory;
  }

  /**
   * Returns the genfiles directory for this build configuration.
   */
  @SkylarkCallable(name = "genfiles_dir", structField = true,
      doc = "The root corresponding to genfiles directory.")
  public Root getGenfilesDirectory() {
    return genfilesDirectory;
  }

  /**
   * Returns the directory where coverage-related artifacts and metadata files
   * should be stored. This includes for example uninstrumented class files
   * needed for Jacoco's coverage reporting tools.
   */
  public Root getCoverageMetadataDirectory() {
    return coverageMetadataDirectory;
  }

  /**
   * Returns the testlogs directory for this build configuration.
   */
  public Root getTestLogsDirectory() {
    return testLogsDirectory;
  }

  /**
   * Returns a relative path to the genfiles directory at execution time.
   */
  public PathFragment getGenfilesFragment() {
    return genfilesFragment;
  }

  /**
   * Returns the path separator for the host platform. This is basically the same as {@link
   * java.io.File#pathSeparator}, except that that returns the value for this JVM, which may or may
   * not match the host platform. You should only use this when invoking tools that are known to use
   * the native path separator, i.e., the path separator for the machine that they run on.
   */
  @SkylarkCallable(name = "host_path_separator", structField = true,
      doc = "Returns the separator for PATH variable, which is ':' on Unix.")
  public String getHostPathSeparator() {
    // TODO(bazel-team): This needs to change when we support Windows.
    return ":";
  }

  /**
   * Returns the internal directory (used for middlemen) for this build configuration.
   */
  public Root getMiddlemanDirectory() {
    return middlemanDirectory;
  }

  public boolean getAllowRuntimeDepsOnNeverLink() {
    return options.allowRuntimeDepsOnNeverLink;
  }

  public boolean isStrictFilesets() {
    return options.strictFilesets;
  }

  public List<Label> getPlugins() {
    return options.pluginList;
  }

  public List<Map.Entry<String, String>> getPluginCopts() {
    return options.pluginCoptList;
  }

  /**
   *  Implements a non-injective mapping from BuildConfiguration instances to
   *  strings.  The result should identify the aspects of the configuration
   *  that should be reflected in the output file names.  Furthermore the
   *  returned string must not contain shell metacharacters.
   *
   *  <p>The intention here is that we use this string as the directory name
   *  for artifacts of this build.
   *
   *  <p>For configuration settings which are NOT part of the short name,
   *  rebuilding with a different value of such a setting will build in
   *  the same output directory.  This means that any actions whose
   *  keys (see Action.getKey()) have changed will be rerun.  That
   *  may result in a lot of recompilation.
   *
   *  <p>For configuration settings which ARE part of the short name,
   *  rebuilding with a different value of such a setting will rebuild
   *  in a different output directory; this will result in higher disk
   *  usage and more work the _first_ time you rebuild with a different
   *  setting, but will result in less work if you regularly switch
   *  back and forth between different settings.
   *
   *  <p>With one important exception, it's sound to choose any subset of the
   *  config's components for this string, it just alters the dimensionality
   *  of the cache.  In other words, it's a trade-off on the "injectiveness"
   *  scale: at one extreme (shortName is in fact a complete fingerprint, and
   *  thus injective) you get extremely precise caching (no competition for the
   *  same output-file locations) but you have to rebuild for even the
   *  slightest change in configuration.  At the other extreme
   *  (PartialFingerprint is a constant) you have very high competition for
   *  output-file locations, but if a slight change in configuration doesn't
   *  affect a particular build step, you're guaranteed not to have to
   *  rebuild it.   The important exception has to do with cross-compilation:
   *  the host and target configurations must not map to the same output
   *  directory, because then files would need to get built for the host
   *  and then rebuilt for the target even within a single build, and that
   *  wouldn't work.
   *
   *  <p>Just to re-iterate: cross-compilation builds (i.e. hostConfig !=
   *  targetConfig) will not work if the two configurations' short names are
   *  equal.  This is an important practical case: the mere addition of
   *  a compile flag to the target configuration would cause the build to
   *  fail.  In other words, it would break if the host and target
   *  configurations are not identical but are "too close".  The current
   *  solution is to set the host configuration equal to the target
   *  configuration if they are "too close"; this may cause the tools to get
   *  rebuild for the new host configuration though.
   */
  public String getShortName() {
    return shortName;
  }

  /**
   * Like getShortName(), but always returns a configuration-dependent string even for
   * the host configuration.
   */
  public String getMnemonic() {
    return mnemonic;
  }

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

  /**
   * Returns the default shell environment
   */
  @SkylarkCallable(name = "default_shell_env", structField = true,
      doc = "A dictionary representing the default environment. It maps variables "
      + "to their values (strings).")
  public ImmutableMap<String, String> getDefaultShellEnvironment() {
    return defaultShellEnvironment;
  }

  /**
   * Returns the path to sh.
   */
  public PathFragment getShExecutable() {
    return executables.get("sh");
  }

  /**
   * Returns a regex-based instrumentation filter instance that used to match label
   * names to identify targets to be instrumented in the coverage mode.
   */
  public RegexFilter getInstrumentationFilter() {
    return options.instrumentationFilter;
  }

  /**
   * Returns the set of labels for coverage.
   */
  public Set<Label> getCoverageLabels() {
    return coverageLabels;
  }

  /**
   * Returns the set of labels for the coverage report generator.
   */
  public Set<Label> getCoverageReportGeneratorLabels() {
    return coverageReportGeneratorLabels;
  }

  /**
   * Returns true if bazel should show analyses results, even if it did not
   * re-run the analysis.
   */
  public boolean showCachedAnalysisResults() {
    return options.showCachedAnalysisResults;
  }

  /**
   * Returns a new, unordered mapping of names to values of "Make" variables defined by this
   * configuration.
   *
   * <p>This does *not* include package-defined overrides (e.g. vardef)
   * and so should not be used by the build logic.  This is used only for
   * the 'info' command.
   *
   * <p>Command-line definitions of make enviroments override variables defined by
   * {@code Fragment.addGlobalMakeVariables()}.
   */
  public Map<String, String> getMakeEnvironment() {
    Map<String, String> makeEnvironment = new HashMap<>();
    makeEnvironment.putAll(globalMakeEnv);
    for (Fragment fragment : fragments.values()) {
      makeEnvironment.putAll(fragment.getCommandLineDefines());
    }
    return ImmutableMap.copyOf(makeEnvironment);
  }

  /**
   * Returns a new, unordered mapping of names that are set through the command lines.
   * (Fragments, in particular the Google C++ support, can set variables through the
   * command line.)
   */
  public Map<String, String> getCommandLineDefines() {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    for (Fragment fragment : fragments.values()) {
      builder.putAll(fragment.getCommandLineDefines());
    }
    return builder.build();
  }

  /**
   * Returns the global defaults for this configuration for the Make environment.
   */
  public Map<String, String> getGlobalMakeEnvironment() {
    return globalMakeEnv;
  }

  /**
   * Returns a (key, value) mapping to insert into the subcommand environment for coverage
   * actions.
   */
  public Map<String, String> getCoverageEnvironment() {
    Map<String, String> env = new HashMap<>();
    for (Fragment fragment : fragments.values()) {
      env.putAll(fragment.getCoverageEnvironment());
    }
    return env;
  }

  /**
   * Returns the default value for the specified "Make" variable for this
   * configuration.  Returns null if no value was found.
   */
  public String getMakeVariableDefault(String var) {
    return globalMakeEnv.get(var);
  }

  /**
   * Returns a configuration fragment instances of the given class.
   */
  @SkylarkCallable(name = "fragment", doc = "Returns a configuration fragment using the key.")
  public <T extends Fragment> T getFragment(Class<T> clazz) {
    return clazz.cast(fragments.get(clazz));
  }

  /**
   * Returns true if the requested configuration fragment is present.
   */
  public <T extends Fragment> boolean hasFragment(Class<T> clazz) {
    return getFragment(clazz) != null;
  }

  /**
   * Returns true if all requested configuration fragment are present (this may be slow).
   */
  public boolean hasAllFragments(Set<Class<?>> fragmentClasses) {
    for (Class<?> fragmentClass : fragmentClasses) {
      if (!hasFragment(fragmentClass.asSubclass(Fragment.class))) {
        return false;
      }
    }
    return true;
  }

  /**
   * Returns true if non-functional build stamps are enabled.
   */
  public boolean stampBinaries() {
    return options.stampBinaries;
  }

  /**
   * Returns true if extended sanity checks should be enabled.
   */
  public boolean extendedSanityChecks() {
    return options.extendedSanityChecks;
  }

  /**
   * Returns true if we are building runfiles symlinks for this configuration.
   */
  public boolean buildRunfiles() {
    return options.buildRunfiles;
  }

  public boolean getCheckFilesetDependenciesRecursively() {
    return options.checkFilesetDependenciesRecursively;
  }

  public List<String> getTestArguments() {
    return options.testArguments;
  }

  public String getTestFilter() {
    return options.testFilter;
  }

  /**
   * Returns user-specified test environment variables and their values, as
   * set by the --test_env options.
   */
  public Map<String, String> getTestEnv() {
    return getTestEnv(options.testEnvironment, clientEnvironment);
  }

  /**
   * Returns user-specified test environment variables and their values, as
   * set by the --test_env options.
   *
   * @param envOverrides The --test_env flag values.
   * @param clientEnvironment The full client environment.
   */
  public static Map<String, String> getTestEnv(List<Map.Entry<String, String>> envOverrides,
                                        Map<String, String> clientEnvironment) {
    Map<String, String> testEnv = new HashMap<>();
    for (Map.Entry<String, String> var : envOverrides) {
      if (var.getValue() != null) {
        testEnv.put(var.getKey(), var.getValue());
      } else {
        String value = clientEnvironment.get(var.getKey());
        if (value != null) {
          testEnv.put(var.getKey(), value);
        }
      }
    }
    return testEnv;
  }

  public TriState cacheTestResults() {
    return options.cacheTestResults;
  }

  public int getMinParamFileSize() {
    return options.minParamFileSize;
  }

  @SkylarkCallable(name = "coverage_enabled", structField = true,
      doc = "A boolean that tells whether code coverage is enabled.")
  public boolean isCodeCoverageEnabled() {
    return options.collectCodeCoverage;
  }

  public boolean isMicroCoverageEnabled() {
    return options.collectMicroCoverage;
  }

  public boolean isActionsEnabled() {
    return actionsEnabled;
  }

  public TestActionBuilder.TestShardingStrategy testShardingStrategy() {
    return options.testShardingStrategy;
  }

  /**
   * @return number of times the given test should run.
   * If the test doesn't match any of the filters, runs it once.
   */
  public int getRunsPerTestForLabel(Label label) {
    for (PerLabelOptions perLabelRuns : options.runsPerTest) {
      if (perLabelRuns.isIncluded(label)) {
        return Integer.parseInt(Iterables.getOnlyElement(perLabelRuns.getOptions()));
      }
    }
    return 1;
  }

  public RunUnder getRunUnder() {
    return options.runUnder;
  }

  /**
   * Returns true if this is a host configuration.
   */
  public boolean isHostConfiguration() {
    return options.isHost;
  }

  public boolean checkVisibility() {
    return options.checkVisibility;
  }

  public boolean checkLicenses() {
    return options.checkLicenses;
  }

  public boolean enforceConstraints() {
    return options.enforceConstraints;
  }

  public List<Label> getActionListeners() {
    return actionsEnabled ? options.actionListeners : ImmutableList.<Label>of();
  }

  /**
   * Returns compilation mode.
   */
  public CompilationMode getCompilationMode() {
    return options.compilationMode;
  }

  /**
   * Helper method to create a key from the BuildConfiguration initialization
   * parameters and any additional component suppliers.
   */
  static String computeCacheKey(BlazeDirectories directories,
      Map<Class<? extends Fragment>, Fragment> fragments,
      BuildOptions buildOptions, Map<String, String> clientEnv) {

    // Creates a full fingerprint of all constructor parameters, used for
    // canonicalization.
    //
    // Note the use of each Path's FileSystem field; the test suite creates
    // many paths of equal name but belonging to distinct filesystems, so we
    // have to detect this. (Note however that we're relying on the
    // injectiveness of identityHashCode for FileSystem, which is inelegant,
    // but only affects the tests, since the production code uses only one
    // instance.)

    ImmutableList.Builder<String> keys = ImmutableList.builder();

    // NOTE: identityHashCode isn't sound; may cause tests to fail.
    keys.add(String.valueOf(System.identityHashCode(directories.getOutputBase().getFileSystem())));
    keys.add(directories.getOutputBase().toString());
    keys.add(buildOptions.computeCacheKey());
    // This is needed so that if we have --test_env=VAR, the configuration key is updated if the
    // environment variable VAR is updated.
    keys.add(BuildConfiguration.getTestEnv(
        buildOptions.get(Options.class).testEnvironment, clientEnv).toString());
    keys.add(directories.getWorkspace().toString());

    for (Fragment fragment : fragments.values()) {
      keys.add(fragment.cacheKey());
    }

    // TODO(bazel-team): add hash of the FDO/LIPO profile file to config cache key

    return StringUtilities.combineKeys(keys.build());
  }

  /**
   * Returns a string that identifies the configuration.
   *
   *  <p>The string uniquely identifies the configuration. As a result, it can be rather long and
   * include spaces and other non-alphanumeric characters. If you need a shorter key, use
   * {@link #shortCacheKey()}.
   *
   * @see #computeCacheKey
   */
  public final String cacheKey() {
    return cacheKey;
  }

  /**
   * Returns a (relatively) short key that identifies the configuration.
   *
   * <p>The short key is the short name of the configuration concatenated with a hash of the
   * {@link #cacheKey()}.
   */
  public final String shortCacheKey() {
    return shortCacheKey;
  }

  /** Returns a copy of the build configuration options for this configuration. */
  public BuildOptions cloneOptions() {
    return buildOptions.clone();
  }

  /**
   * Prepare the fdo support. It reads data into memory that is used during analysis. The analysis
   * phase is generally not allowed to perform disk I/O. This code is here because it is
   * conceptually part of the analysis phase, and it needs to happen when the loading phase is
   * complete.
   */
  public void prepareToBuild(Path execRoot, ArtifactFactory artifactFactory,
      PackageRootResolver resolver) throws ViewCreationFailedException {
    for (Fragment fragment : fragments.values()) {
      fragment.prepareHook(execRoot, artifactFactory, getGenfilesFragment(), resolver);
    }
  }

  /**
   * Declares dependencies on any relevant Skyframe values (for example, relevant FileValues).
   */
  public void declareSkyframeDependencies(SkyFunction.Environment env) {
    for (Fragment fragment : fragments.values()) {
      fragment.declareSkyframeDependencies(env);
    }
  }

  /**
   * Returns all the roots for this configuration.
   */
  public List<Root> getRoots() {
    List<Root> roots = new ArrayList<>();

    // Configuration-specific roots.
    roots.add(getBinDirectory());
    roots.add(getGenfilesDirectory());
    roots.add(getIncludeDirectory());
    roots.add(getMiddlemanDirectory());
    roots.add(getTestLogsDirectory());

    // Fragment-defined roots
    for (Fragment fragment : fragments.values()) {
      fragment.addRoots(roots);
    }

    return ImmutableList.copyOf(roots);
  }

  public ListMultimap<String, Label> getAllLabels() {
    return buildOptions.getAllLabels();
  }

  public String getCpu() {
    return options.cpu;
  }

  /**
   * Returns true is incremental builds are supported with this configuration.
   */
  public boolean supportsIncrementalBuild() {
    for (Fragment fragment : fragments.values()) {
      if (!fragment.supportsIncrementalBuild()) {
        return false;
      }
    }
    return true;
  }

  /**
   * Returns true if the configuration performs static linking.
   */
  public boolean performsStaticLink() {
    for (Fragment fragment : fragments.values()) {
      if (fragment.performsStaticLink()) {
        return true;
      }
    }
    return false;
  }

  /**
   * Deletes temporary directories before execution phase. This is only called for
   * target configuration.
   */
  public void prepareForExecutionPhase() throws IOException {
    for (Fragment fragment : fragments.values()) {
      fragment.prepareForExecutionPhase();
    }
  }

  /**
   * Collects executables defined by fragments.
   */
  private ImmutableMap<String, PathFragment> collectExecutables() {
    ImmutableMap.Builder<String, PathFragment> builder = new ImmutableMap.Builder<>();
    for (Fragment fragment : fragments.values()) {
      fragment.defineExecutables(builder);
    }
    return builder.build();
  }

  /**
   * See {@code BuildConfigurationCollection.Transitions.getArtifactOwnerConfiguration()}.
   */
  public BuildConfiguration getArtifactOwnerConfiguration() {
    return transitions.getArtifactOwnerConfiguration();
  }

  /**
   * @return whether proto header modules should be built.
   */
  public boolean getProtoHeaderModules() {
    return options.protoHeaderModules;
  }

  /**
   * @return the list of default features used for all packages.
   */
  public List<String> getDefaultFeatures() {
    return options.defaultFeatures;
  }
}