forked from bazelbuild/bazel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfiguredTargetFunction.java
1259 lines (1174 loc) · 56.5 KB
/
ConfiguredTargetFunction.java
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
// 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.skyframe;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
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.Maps;
import com.google.common.flogger.GoogleLogger;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.AnalysisRootCauseEvent;
import com.google.devtools.build.lib.analysis.AspectResolver;
import com.google.devtools.build.lib.analysis.CachingAnalysisEnvironment;
import com.google.devtools.build.lib.analysis.CachingAnalysisEnvironment.MissingDepException;
import com.google.devtools.build.lib.analysis.ConfiguredAspect;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.ConfiguredTargetValue;
import com.google.devtools.build.lib.analysis.Dependency;
import com.google.devtools.build.lib.analysis.DependencyKey;
import com.google.devtools.build.lib.analysis.DependencyKind;
import com.google.devtools.build.lib.analysis.DependencyResolver;
import com.google.devtools.build.lib.analysis.DuplicateException;
import com.google.devtools.build.lib.analysis.EmptyConfiguredTarget;
import com.google.devtools.build.lib.analysis.ExecGroupCollection;
import com.google.devtools.build.lib.analysis.ExecGroupCollection.InvalidExecGroupException;
import com.google.devtools.build.lib.analysis.InconsistentAspectOrderException;
import com.google.devtools.build.lib.analysis.PlatformConfiguration;
import com.google.devtools.build.lib.analysis.ResolvedToolchainContext;
import com.google.devtools.build.lib.analysis.TargetAndConfiguration;
import com.google.devtools.build.lib.analysis.ToolchainCollection;
import com.google.devtools.build.lib.analysis.ToolchainContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
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.BuildOptionsView;
import com.google.devtools.build.lib.analysis.config.ConfigConditions;
import com.google.devtools.build.lib.analysis.config.ConfigMatchingProvider;
import com.google.devtools.build.lib.analysis.config.ConfigurationResolver;
import com.google.devtools.build.lib.analysis.config.DependencyEvaluationException;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.analysis.config.transitions.PatchTransition;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformProviderUtils;
import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.TransitionException;
import com.google.devtools.build.lib.causes.AnalysisFailedCause;
import com.google.devtools.build.lib.causes.Cause;
import com.google.devtools.build.lib.causes.LoadingFailedCause;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.packages.Aspect;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.ConfiguredAttributeMapper;
import com.google.devtools.build.lib.packages.ExecGroup;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.NonconfigurableAttributeMapper;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.RawAttributeMapper;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClassProvider;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.server.FailureDetails.Analysis;
import com.google.devtools.build.lib.server.FailureDetails.Analysis.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.SkyframeExecutor.BuildViewProvider;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.DetailedExitCode.DetailedExitCodeComparator;
import com.google.devtools.build.lib.util.OrderedSetMultimap;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.ValueOrException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/**
* SkyFunction for {@link ConfiguredTargetValue}s.
*
* <p>This class, together with {@link AspectFunction} drives the analysis phase. For more
* information, see {@link com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory}.
*
* @see com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory
*/
public final class ConfiguredTargetFunction implements SkyFunction {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
/**
* Attempt to find a {@link ConfiguredValueCreationException} in a {@link ToolchainException}, or
* its causes.
*
* <p>If one cannot be found, null is returned.
*/
@Nullable
public static ConfiguredValueCreationException asConfiguredValueCreationException(
ToolchainException e) {
for (Throwable cause = e.getCause();
cause != null && cause != cause.getCause();
cause = cause.getCause()) {
if (cause instanceof ConfiguredValueCreationException) {
return (ConfiguredValueCreationException) cause;
}
}
return null;
}
private final BuildViewProvider buildViewProvider;
private final RuleClassProvider ruleClassProvider;
// TODO(b/185987566): Remove this semaphore.
private final AtomicReference<Semaphore> cpuBoundSemaphore;
@Nullable private final ConfiguredTargetProgressReceiver configuredTargetProgress;
/**
* Indicates whether the set of packages transitively loaded for a given {@link
* ConfiguredTargetValue} will be needed for package root resolution later in the build. If not,
* they are not collected and stored.
*/
private final boolean storeTransitivePackagesForPackageRootResolution;
private final boolean shouldUnblockCpuWorkWhenFetchingDeps;
ConfiguredTargetFunction(
BuildViewProvider buildViewProvider,
RuleClassProvider ruleClassProvider,
AtomicReference<Semaphore> cpuBoundSemaphore,
boolean storeTransitivePackagesForPackageRootResolution,
boolean shouldUnblockCpuWorkWhenFetchingDeps,
@Nullable ConfiguredTargetProgressReceiver configuredTargetProgress) {
this.buildViewProvider = buildViewProvider;
this.ruleClassProvider = ruleClassProvider;
this.cpuBoundSemaphore = cpuBoundSemaphore;
this.storeTransitivePackagesForPackageRootResolution =
storeTransitivePackagesForPackageRootResolution;
this.shouldUnblockCpuWorkWhenFetchingDeps = shouldUnblockCpuWorkWhenFetchingDeps;
this.configuredTargetProgress = configuredTargetProgress;
}
private void maybeAcquireSemaphoreWithLogging(SkyKey key) throws InterruptedException {
if (cpuBoundSemaphore.get() == null) {
return;
}
Stopwatch stopwatch = Stopwatch.createStarted();
cpuBoundSemaphore.get().acquire();
long elapsedTime = stopwatch.elapsed().toMillis();
if (elapsedTime > 5) {
logger.atInfo().atMostEvery(10, TimeUnit.SECONDS).log(
"Spent %s milliseconds waiting for lock acquisition for %s", elapsedTime, key);
}
}
private void maybeReleaseSemaphore() {
if (cpuBoundSemaphore.get() != null) {
cpuBoundSemaphore.get().release();
}
}
@Override
public SkyValue compute(SkyKey key, Environment env) throws ConfiguredTargetFunctionException,
InterruptedException {
if (shouldUnblockCpuWorkWhenFetchingDeps) {
env =
new StateInformingSkyFunctionEnvironment(
env,
/*preFetch=*/ this::maybeReleaseSemaphore,
/*postFetch=*/ () -> maybeAcquireSemaphoreWithLogging(key));
}
SkyframeBuildView view = buildViewProvider.getSkyframeBuildView();
NestedSetBuilder<Package> transitivePackagesForPackageRootResolution =
storeTransitivePackagesForPackageRootResolution ? NestedSetBuilder.stableOrder() : null;
NestedSetBuilder<Cause> transitiveRootCauses = NestedSetBuilder.stableOrder();
ConfiguredTargetKey configuredTargetKey = (ConfiguredTargetKey) key.argument();
Label label = configuredTargetKey.getLabel();
BuildConfiguration configuration = null;
ImmutableSet<SkyKey> packageAndMaybeConfiguration;
SkyKey packageKey = PackageValue.key(label.getPackageIdentifier());
SkyKey configurationKeyMaybe = configuredTargetKey.getConfigurationKey();
if (configurationKeyMaybe == null) {
packageAndMaybeConfiguration = ImmutableSet.of(packageKey);
} else {
packageAndMaybeConfiguration = ImmutableSet.of(packageKey, configurationKeyMaybe);
}
Map<SkyKey, SkyValue> packageAndMaybeConfigurationValues =
env.getValues(packageAndMaybeConfiguration);
if (env.valuesMissing()) {
return null;
}
PackageValue packageValue = (PackageValue) packageAndMaybeConfigurationValues.get(packageKey);
if (configurationKeyMaybe != null) {
configuration =
((BuildConfigurationValue) packageAndMaybeConfigurationValues.get(configurationKeyMaybe))
.getConfiguration();
}
// TODO(ulfjack): This tries to match the logic in TransitiveTargetFunction /
// TargetMarkerFunction. Maybe we can merge the two?
Package pkg = packageValue.getPackage();
Target target;
try {
target = pkg.getTarget(label.getName());
} catch (NoSuchTargetException e) {
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(
e.getMessage(), label, configuration, e.getDetailedExitCode()));
}
if (pkg.containsErrors()) {
FailureDetail failureDetail = pkg.contextualizeFailureDetailForTarget(target);
transitiveRootCauses.add(new LoadingFailedCause(label, DetailedExitCode.of(failureDetail)));
}
if (transitivePackagesForPackageRootResolution != null) {
transitivePackagesForPackageRootResolution.add(pkg);
}
if (target.isConfigurable() == (configuredTargetKey.getConfigurationKey() == null)) {
// We somehow ended up in a target that requires a non-null configuration as a dependency of
// one that requires a null configuration or the other way round. This is always an error, but
// we need to analyze the dependencies of the latter target to realize that. Short-circuit the
// evaluation to avoid doing useless work and running code with a null configuration that's
// not prepared for it.
return new NonRuleConfiguredTargetValue(
new EmptyConfiguredTarget(target.getLabel(), configuredTargetKey.getConfigurationKey()),
transitivePackagesForPackageRootResolution == null
? null
: transitivePackagesForPackageRootResolution.build());
}
TargetAndConfiguration ctgValue = new TargetAndConfiguration(target, configuration);
SkyframeDependencyResolver resolver = new SkyframeDependencyResolver(env);
ToolchainCollection<UnloadedToolchainContext> unloadedToolchainContexts = null;
ExecGroupCollection.Builder execGroupCollectionBuilder = null;
// TODO(janakr): this call may tie up this thread indefinitely, reducing the parallelism of
// Skyframe. This is a strict improvement over the prior state of the code, in which we ran
// with #processors threads, but ideally we would call #tryAcquire here, and if we failed,
// would exit this SkyFunction and restart it when permits were available.
maybeAcquireSemaphoreWithLogging(key);
try {
boolean verbose = false;
if (target.toString().equals("objc_library rule //target_skipping:objc")) {
verbose = true;
}
//Map<ConfiguredTargetKey, PlatformInfo> platformInfo = PlatformLookupUtil.getPlatformInfo(
// ImmutableList.<ConfiguredTargetKey>of(configuredTargetKey),
// env,
// true);
System.out.println(" A >> " + target.toString());
// Determine what toolchains are needed by this target.
ComputedToolchainContexts result =
computeUnloadedToolchainContexts(
env, ruleClassProvider, ctgValue, configuredTargetKey.getToolchainContextKey());
if (env.valuesMissing()) {
return null;
}
unloadedToolchainContexts = result.toolchainCollection;
execGroupCollectionBuilder = result.execGroupCollectionBuilder;
System.out.println(" B >> " + target.toString());
//if (verbose) {
// RawAttributeMapper attrs = RawAttributeMapper.of(((Rule) ctgValue.getTarget()));
// List<Label> labels = attrs.get("target_compatible_with", BuildType.LABEL_LIST).stream().collect(Collectors.toList());
// for (Label labelToPrint : labels) {
// System.out.println(" B \\__> " + labelToPrint.toString());
// }
//}
// Get the configuration targets that trigger this rule's configurable attributes.
ConfigConditions configConditions =
getConfigConditions(
env,
ctgValue,
transitivePackagesForPackageRootResolution,
unloadedToolchainContexts == null
? null
: unloadedToolchainContexts.getTargetPlatform(),
transitiveRootCauses);
if (env.valuesMissing()) {
return null;
}
System.out.println(" C >> " + target.toString());
// TODO(ulfjack): ConfiguredAttributeMapper (indirectly used from computeDependencies) isn't
// safe to use if there are missing config conditions, so we stop here, but only if there are
// config conditions - though note that we can't check if configConditions is non-empty - it
// may be empty for other reasons. It would be better to continue here so that we can collect
// more root causes during computeDependencies.
// Note that this doesn't apply to AspectFunction, because aspects can't have configurable
// attributes.
if (!transitiveRootCauses.isEmpty()
&& !Objects.equals(configConditions, ConfigConditions.EMPTY)) {
NestedSet<Cause> causes = transitiveRootCauses.build();
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(
"Cannot compute config conditions",
configuration,
causes,
getPrioritizedDetailedExitCode(causes)));
}
System.out.println(" D >> '" + target.toString() + "'");
if (verbose && unloadedToolchainContexts != null) {
PlatformInfo platformInfo = unloadedToolchainContexts.getTargetPlatform();
if (platformInfo != null && target instanceof Rule) {
Rule rule = (Rule) target;
if (!rule.getRuleClass().equals("toolchain")) {
ConfiguredAttributeMapper attrs = ConfiguredAttributeMapper.of(rule, configConditions.asProviders(), "");
List<Label> labels = attrs.get("target_compatible_with", BuildType.LABEL_LIST).stream().collect(Collectors.toList());
ImmutableList.Builder<Dependency> depsBuilder = ImmutableList.builder();
for (Label configurabilityLabel : labels) {
Dependency configurabilityDependency =
Dependency.builder()
.setLabel(configurabilityLabel)
.setConfiguration(ctgValue.getConfiguration())
.build();
depsBuilder.add(configurabilityDependency);
}
ImmutableList<Dependency> configConditionDeps = depsBuilder.build();
Map<SkyKey, ConfiguredTargetAndData> configValues;
try {
configValues =
resolveConfiguredTargetDependencies(
false,
env,
ctgValue,
configConditionDeps,
transitivePackagesForPackageRootResolution,
transitiveRootCauses);
if (configValues == null) {
return null;
}
} catch (DependencyEvaluationException e) {
// One of the config dependencies doesn't exist, and we need to report that. Unfortunately,
// there's not enough information to know which configurable attribute has the problem.
env.getListener()
.handle(
Event.error(
String.format(
"While resolving configuration keys for %s: %s",
target.getLabel(), e.getCause().getMessage())));
// Re-throw the exception so it is handled by compute().
throw e;
}
List<TransitiveInfoCollection> transitive_info_collections = configValues.values().stream()
.map(targetAndData -> targetAndData.getConfiguredTarget())
.collect(Collectors.toList());
ImmutableList<ConstraintValueInfo> invalidConstraintValues =
PlatformProviderUtils.constraintValues(
transitive_info_collections
/*
* MAGIC conversion between `labels` and `List<? extends
* ProviderCollection>` ???
*/)
.stream()
.filter(cv -> !platformInfo.constraints().hasConstraintValue(cv))
.collect(ImmutableList.toImmutableList());
if (!invalidConstraintValues.isEmpty()) {
System.out.println(" XXXXXXXXXXX >>>> INCOMPATIBLE");
//return createIncompatibleConfiguredTarget(ruleContext, null,
//invalidConstraintValues);
}
for (Label labelToPrint : labels) {
System.out.println(" D \\__> " + labelToPrint.toString());
}
}
}
}
// Calculate the dependencies of this target.
OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> depValueMap =
computeDependencies(
verbose,
env,
resolver,
ctgValue,
ImmutableList.of(),
configConditions.asProviders(),
unloadedToolchainContexts == null
? null
: unloadedToolchainContexts.asToolchainContexts(),
DependencyResolver.shouldUseToolchainTransition(configuration, ctgValue.getTarget()),
ruleClassProvider,
view.getHostConfiguration(configuration),
transitivePackagesForPackageRootResolution,
transitiveRootCauses);
if (target.toString().equals("objc_library rule //target_skipping:objc") && depValueMap != null) {
String foo = "_______________________\n";
for (ConfiguredTargetAndData dep : depValueMap.values()) {
foo += " + " + dep.getConfiguredTarget().toString();
}
foo += "_______________________\n";
System.out.println(foo);
}
if (!transitiveRootCauses.isEmpty()) {
NestedSet<Cause> causes = transitiveRootCauses.build();
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(
"Analysis failed", configuration, causes, getPrioritizedDetailedExitCode(causes)));
}
System.out.println(" E >> " + target.toString());
if (env.valuesMissing()) {
System.out.println("++++++++++++++++++++++ " + target.toString());
return null;
}
Preconditions.checkNotNull(depValueMap);
System.out.println(" F >> " + target.toString());
// Load the requested toolchains into the ToolchainContext, now that we have dependencies.
ToolchainCollection<ResolvedToolchainContext> toolchainContexts = null;
if (unloadedToolchainContexts != null) {
String targetDescription = target.toString();
ToolchainCollection.Builder<ResolvedToolchainContext> contextsBuilder =
ToolchainCollection.builder();
for (Map.Entry<String, UnloadedToolchainContext> unloadedContext :
unloadedToolchainContexts.getContextMap().entrySet()) {
Set<ConfiguredTargetAndData> toolchainDependencies =
depValueMap.get(DependencyKind.forExecGroup(unloadedContext.getKey()));
contextsBuilder.addContext(
unloadedContext.getKey(),
ResolvedToolchainContext.load(
unloadedContext.getValue(),
targetDescription,
toolchainDependencies));
}
toolchainContexts = contextsBuilder.build();
}
System.out.println(" G >> " + target.toString());
ConfiguredTargetValue ans =
createConfiguredTarget(
view,
env,
target,
configuration,
configuredTargetKey,
depValueMap,
configConditions,
toolchainContexts,
execGroupCollectionBuilder,
transitivePackagesForPackageRootResolution);
if (ans != null && configuredTargetProgress != null) {
configuredTargetProgress.doneConfigureTarget();
}
return ans;
} catch (DependencyEvaluationException e) {
if (e.getCause() instanceof ConfiguredValueCreationException) {
ConfiguredValueCreationException cvce = (ConfiguredValueCreationException) e.getCause();
// Check if this is caused by an unresolved toolchain, and report it as such.
if (unloadedToolchainContexts != null) {
ImmutableSet<Label> requiredToolchains =
unloadedToolchainContexts.getResolvedToolchains();
Set<Label> toolchainDependencyErrors =
cvce.getRootCauses().toList().stream()
.map(Cause::getLabel)
.filter(requiredToolchains::contains)
.collect(ImmutableSet.toImmutableSet());
if (!toolchainDependencyErrors.isEmpty()) {
env.getListener()
.handle(
Event.error(
String.format(
"While resolving toolchains for target %s: %s",
target.getLabel(), e.getCause().getMessage())));
}
}
throw new ConfiguredTargetFunctionException(cvce);
} else if (e.getCause() instanceof InconsistentAspectOrderException) {
InconsistentAspectOrderException cause = (InconsistentAspectOrderException) e.getCause();
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(
cause.getMessage(), target.getLabel(), configuration));
} else if (e.getCause() instanceof InvalidConfigurationException) {
InvalidConfigurationException cause = (InvalidConfigurationException) e.getCause();
env.getListener().handle(Event.error(cause.getMessage()));
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(
cause.getMessage(), target.getLabel(), configuration, cause.getDetailedExitCode()));
} else if (e.getCause() instanceof TransitionException) {
TransitionException cause = (TransitionException) e.getCause();
env.getListener().handle(Event.error(cause.getMessage()));
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(e.getMessage(), target.getLabel(), configuration));
} else {
// Unknown exception type.
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(e.getMessage(), target.getLabel(), configuration));
}
} catch (AspectCreationException e) {
throw new ConfiguredTargetFunctionException(
new ConfiguredValueCreationException(
e.getMessage(), configuration, e.getCauses(), e.getDetailedExitCode()));
} catch (ToolchainException e) {
// We need to throw a ConfiguredValueCreationException, so either find one or make one.
ConfiguredValueCreationException cvce = asConfiguredValueCreationException(e);
if (cvce == null) {
cvce =
new ConfiguredValueCreationException(
e.getMessage(), target.getLabel(), configuration, e.getDetailedExitCode());
}
String message =
String.format(
"While resolving toolchains for target %s: %s", target.getLabel(), e.getMessage());
env.getListener().handle(Event.error(message));
throw new ConfiguredTargetFunctionException(cvce);
} catch (ConfiguredValueCreationException e) {
throw new ConfiguredTargetFunctionException(e);
} finally {
maybeReleaseSemaphore();
}
}
/**
* Simple wrapper to allow returning two variables from {@link #computeUnloadedToolchainContexts}.
*/
@VisibleForTesting
public static class ComputedToolchainContexts {
@Nullable public ToolchainCollection<UnloadedToolchainContext> toolchainCollection = null;
public ExecGroupCollection.Builder execGroupCollectionBuilder =
ExecGroupCollection.emptyBuilder();
}
/**
* Returns the toolchain context and exec group collection for this target. The toolchain context
* may be {@code null} if the target doesn't use toolchains.
*
* <p>This involves Skyframe evaluation: callers should check {@link Environment#valuesMissing()
* to check the result is valid.
*/
@VisibleForTesting
@Nullable
public static ComputedToolchainContexts computeUnloadedToolchainContexts(
Environment env,
RuleClassProvider ruleClassProvider,
TargetAndConfiguration targetAndConfig,
@Nullable ToolchainContextKey parentToolchainContextKey)
throws InterruptedException, ToolchainException {
if (!(targetAndConfig.getTarget() instanceof Rule)) {
return new ComputedToolchainContexts();
}
Rule rule = ((Rule) targetAndConfig.getTarget());
BuildConfiguration configuration = targetAndConfig.getConfiguration();
ImmutableSet<Label> requiredDefaultToolchains =
rule.getRuleClassObject().getRequiredToolchains();
// Collect local (target, rule) constraints for filtering out execution platforms.
ImmutableSet<Label> defaultExecConstraintLabels =
getExecutionPlatformConstraints(
rule, configuration.getFragment(PlatformConfiguration.class));
// Create a merged version of the exec groups that handles exec group inheritance properly.
ExecGroup defaultExecGroup =
ExecGroup.create(requiredDefaultToolchains, defaultExecConstraintLabels);
ExecGroupCollection.Builder execGroupCollectionBuilder =
ExecGroupCollection.builder(defaultExecGroup, rule.getRuleClassObject().getExecGroups());
// Short circuit and end now if this target doesn't require toolchain resolution.
if (!rule.getRuleClassObject().useToolchainResolution()) {
ComputedToolchainContexts result = new ComputedToolchainContexts();
result.execGroupCollectionBuilder = execGroupCollectionBuilder;
return result;
}
// The toolchain context's options are the parent rule's options with manual trimming
// auto-applied. This means toolchains don't inherit feature flags. This helps build
// performance: if the toolchain context had the exact same configuration of its parent and that
// included feature flags, all the toolchain's dependencies would apply this transition
// individually. That creates a lot more potentially expensive applications of that transition
// (especially since manual trimming applies to every configured target in the build).
//
// In other words: without this modification:
// parent rule -> toolchain context -> toolchain
// -> toolchain dep 1 # applies manual trimming to remove feature flags
// -> toolchain dep 2 # applies manual trimming to remove feature flags
// ...
//
// With this modification:
// parent rule -> toolchain context # applies manual trimming to remove feature flags
// -> toolchain
// -> toolchain dep 1
// -> toolchain dep 2
// ...
//
// None of this has any effect on rules that don't utilize manual trimming.
PatchTransition toolchainTaggedTrimmingTransition =
((ConfiguredRuleClassProvider) ruleClassProvider).getToolchainTaggedTrimmingTransition();
BuildOptions toolchainOptions =
toolchainTaggedTrimmingTransition.patch(
new BuildOptionsView(
configuration.getOptions(),
toolchainTaggedTrimmingTransition.requiresOptionFragments()),
env.getListener());
BuildConfigurationValue.Key toolchainConfig =
BuildConfigurationValue.keyWithoutPlatformMapping(
configuration.fragmentClasses(), toolchainOptions);
Map<String, ToolchainContextKey> toolchainContextKeys = new HashMap<>();
String targetUnloadedToolchainContext = "target-unloaded-toolchain-context";
ToolchainContextKey.Builder toolchainContextKeyBuilder =
ToolchainContextKey.key()
.configurationKey(toolchainConfig)
.requiredToolchainTypeLabels(requiredDefaultToolchains)
.execConstraintLabels(defaultExecConstraintLabels);
if (parentToolchainContextKey != null) {
// Find out what execution platform the parent used, and force that.
// This key should always be present, but check just in case.
ToolchainContext parentToolchainContext =
(ToolchainContext)
env.getValueOrThrow(parentToolchainContextKey, ToolchainException.class);
if (env.valuesMissing()) {
return null;
}
Label execPlatform = parentToolchainContext.executionPlatform().label();
if (execPlatform != null) {
toolchainContextKeyBuilder.forceExecutionPlatform(execPlatform);
}
}
ToolchainContextKey toolchainContextKey = toolchainContextKeyBuilder.build();
toolchainContextKeys.put(targetUnloadedToolchainContext, toolchainContextKey);
for (String name : execGroupCollectionBuilder.getExecGroupNames()) {
ExecGroup execGroup = execGroupCollectionBuilder.getExecGroup(name);
toolchainContextKeys.put(
name,
ToolchainContextKey.key()
.configurationKey(toolchainConfig)
.requiredToolchainTypeLabels(execGroup.requiredToolchains())
.execConstraintLabels(execGroup.execCompatibleWith())
.build());
}
Map<SkyKey, ValueOrException<ToolchainException>> values =
env.getValuesOrThrow(toolchainContextKeys.values(), ToolchainException.class);
boolean valuesMissing = env.valuesMissing();
ToolchainCollection.Builder<UnloadedToolchainContext> toolchainContexts =
valuesMissing ? null : ToolchainCollection.builder();
for (Map.Entry<String, ToolchainContextKey> unloadedToolchainContextKey :
toolchainContextKeys.entrySet()) {
UnloadedToolchainContext unloadedToolchainContext =
(UnloadedToolchainContext) values.get(unloadedToolchainContextKey.getValue()).get();
if (!valuesMissing) {
String execGroup = unloadedToolchainContextKey.getKey();
if (execGroup.equals(targetUnloadedToolchainContext)) {
toolchainContexts.addDefaultContext(unloadedToolchainContext);
} else {
toolchainContexts.addContext(execGroup, unloadedToolchainContext);
}
}
}
ComputedToolchainContexts result = new ComputedToolchainContexts();
result.toolchainCollection = valuesMissing ? null : toolchainContexts.build();
result.execGroupCollectionBuilder = execGroupCollectionBuilder;
return result;
}
/**
* Returns the target-specific execution platform constraints, based on the rule definition and
* any constraints added by the target, including those added for the target on the command line.
*/
public static ImmutableSet<Label> getExecutionPlatformConstraints(
Rule rule, PlatformConfiguration platformConfiguration) {
NonconfigurableAttributeMapper mapper = NonconfigurableAttributeMapper.of(rule);
ImmutableSet.Builder<Label> execConstraintLabels = new ImmutableSet.Builder<>();
execConstraintLabels.addAll(rule.getRuleClassObject().getExecutionPlatformConstraints());
if (rule.getRuleClassObject()
.hasAttr(RuleClass.EXEC_COMPATIBLE_WITH_ATTR, BuildType.LABEL_LIST)) {
execConstraintLabels.addAll(
mapper.get(RuleClass.EXEC_COMPATIBLE_WITH_ATTR, BuildType.LABEL_LIST));
}
execConstraintLabels.addAll(
platformConfiguration.getAdditionalExecutionConstraintsFor(rule.getLabel()));
return execConstraintLabels.build();
}
/**
* Computes the direct dependencies of a node in the configured target graph (a configured target
* or an aspects).
*
* <p>Returns null if Skyframe hasn't evaluated the required dependencies yet. In this case, the
* caller should also return null to Skyframe.
*
* @param env the Skyframe environment
* @param resolver the dependency resolver
* @param ctgValue the label and the configuration of the node
* @param configConditions the configuration conditions for evaluating the attributes of the node
* @param toolchainContexts the toolchain context for this target
* @param ruleClassProvider rule class provider for determining the right configuration fragments
* to apply to deps
* @param hostConfiguration the host configuration. There's a noticeable performance hit from
* instantiating this on demand for every dependency that wants it, so it's best to compute
* the host configuration as early as possible and pass this reference to all consumers
*/
@Nullable
static OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> computeDependencies(
boolean verbose,
Environment env,
SkyframeDependencyResolver resolver,
TargetAndConfiguration ctgValue,
Iterable<Aspect> aspects,
ImmutableMap<Label, ConfigMatchingProvider> configConditions,
@Nullable ToolchainCollection<ToolchainContext> toolchainContexts,
boolean useToolchainTransition,
RuleClassProvider ruleClassProvider,
BuildConfiguration hostConfiguration,
@Nullable NestedSetBuilder<Package> transitivePackagesForPackageRootResolution,
NestedSetBuilder<Cause> transitiveRootCauses)
throws DependencyEvaluationException, ConfiguredValueCreationException,
AspectCreationException, InterruptedException {
// Create the map from attributes to set of (target, transition) pairs.
OrderedSetMultimap<DependencyKind, DependencyKey> initialDependencies;
BuildConfiguration configuration = ctgValue.getConfiguration();
Label label = ctgValue.getLabel();
try {
initialDependencies =
resolver.dependentNodeMap(
ctgValue,
hostConfiguration,
aspects,
configConditions,
toolchainContexts,
useToolchainTransition,
transitiveRootCauses,
((ConfiguredRuleClassProvider) ruleClassProvider).getTrimmingTransitionFactory());
} catch (DependencyResolver.Failure e) {
env.getListener().handle(Event.error(e.getLocation(), e.getMessage()));
env.getListener().post(new AnalysisRootCauseEvent(configuration, label, e.getMessage()));
if (verbose) {
System.out.println(" ==== Got a DependencyResolver.Failure.");
}
throw new DependencyEvaluationException(
new ConfiguredValueCreationException(e.getMessage(), label, configuration));
} catch (InconsistentAspectOrderException e) {
env.getListener().handle(Event.error(e.getLocation(), e.getMessage()));
if (verbose) {
System.out.println(" ==== Got a InconsistentAspectOrderException.");
}
throw new DependencyEvaluationException(e);
}
if (verbose) {
System.out.println(" ==== Got initialDependencies.");
}
// Trim each dep's configuration so it only includes the fragments needed by its transitive
// closure.
ConfigurationResolver configResolver =
new ConfigurationResolver(env, ctgValue, hostConfiguration, configConditions);
if (verbose) {
System.out.println(" ==== Got configResolver.");
}
OrderedSetMultimap<DependencyKind, Dependency> depValueNames =
configResolver.resolveConfigurations(initialDependencies);
if (verbose) {
System.out.println(" ==== Got depValueNames.");
}
// Return early in case packages were not loaded yet. In theory, we could start configuring
// dependent targets in loaded packages. However, that creates an artificial sync boundary
// between loading all dependent packages (fast) and configuring some dependent targets (can
// have a long tail).
if (env.valuesMissing()) {
if (verbose) {
System.out.println(" ==== env.valuesMissing()");
}
return null;
}
if (verbose) {
System.out.println(" ==== !env.valuesMissing()");
}
// Resolve configured target dependencies and handle errors.
Map<SkyKey, ConfiguredTargetAndData> depValues =
resolveConfiguredTargetDependencies(
verbose,
env,
ctgValue,
depValueNames.values(),
transitivePackagesForPackageRootResolution,
transitiveRootCauses);
if (verbose) {
System.out.println(" ==== depValues");
}
if (depValues == null) {
if (verbose) {
System.out.println(" ==== depValues == null");
}
return null;
}
// Resolve required aspects.
OrderedSetMultimap<Dependency, ConfiguredAspect> depAspects =
AspectResolver.resolveAspectDependencies(
env, depValues, depValueNames.values(), transitivePackagesForPackageRootResolution);
if (verbose) {
System.out.println(" ==== depAspects");
}
if (depAspects == null) {
if (verbose) {
System.out.println(" ==== depAspects == null");
}
return null;
}
if (verbose) {
System.out.println(" ==== AspectResolver.mergeAspects");
}
// Merge the dependent configured targets and aspects into a single map.
try {
return AspectResolver.mergeAspects(depValueNames, depValues, depAspects);
} catch (DuplicateException e) {
env.getListener().handle(
Event.error(ctgValue.getTarget().getLocation(), e.getMessage()));
throw new ConfiguredValueCreationException(e.getMessage(), label, configuration);
}
}
/**
* Returns the targets that key the configurable attributes used by this rule.
*
* <p>>If the configured targets supplying those providers aren't yet resolved by the dependency
* resolver, returns null.
*/
@Nullable
static ConfigConditions getConfigConditions(
Environment env,
TargetAndConfiguration ctgValue,
@Nullable NestedSetBuilder<Package> transitivePackagesForPackageRootResolution,
@Nullable PlatformInfo platformInfo,
NestedSetBuilder<Cause> transitiveRootCauses)
throws DependencyEvaluationException, InterruptedException {
Target target = ctgValue.getTarget();
if (!(target instanceof Rule)) {
return ConfigConditions.EMPTY;
}
RawAttributeMapper attrs = RawAttributeMapper.of(((Rule) target));
if (!attrs.has(RuleClass.CONFIG_SETTING_DEPS_ATTRIBUTE)) {
return ConfigConditions.EMPTY;
}
// Collect the labels of the configured targets we need to resolve.
List<Label> configLabels =
attrs.get(RuleClass.CONFIG_SETTING_DEPS_ATTRIBUTE, BuildType.LABEL_LIST).stream()
.map(configLabel -> target.getLabel().resolveRepositoryRelative(configLabel))
.collect(Collectors.toList());
if (configLabels.isEmpty()) {
return ConfigConditions.EMPTY;
}
// Collect the actual deps without a configuration transition (since by definition config
// conditions evaluate over the current target's configuration). If the dependency is
// (erroneously) something that needs the null configuration, its analysis will be
// short-circuited. That error will be reported later.
ImmutableList.Builder<Dependency> depsBuilder = ImmutableList.builder();
for (Label configurabilityLabel : configLabels) {
Dependency configurabilityDependency =
Dependency.builder()
.setLabel(configurabilityLabel)
.setConfiguration(ctgValue.getConfiguration())
.build();
depsBuilder.add(configurabilityDependency);
}
ImmutableList<Dependency> configConditionDeps = depsBuilder.build();
Map<SkyKey, ConfiguredTargetAndData> configValues;
try {
configValues =
resolveConfiguredTargetDependencies(
false,
env,
ctgValue,
configConditionDeps,
transitivePackagesForPackageRootResolution,
transitiveRootCauses);
if (configValues == null) {
return null;
}
} catch (DependencyEvaluationException e) {
// One of the config dependencies doesn't exist, and we need to report that. Unfortunately,
// there's not enough information to know which configurable attribute has the problem.
env.getListener()
.handle(
Event.error(
String.format(
"While resolving configuration keys for %s: %s",
target.getLabel(), e.getCause().getMessage())));
// Re-throw the exception so it is handled by compute().
throw e;
}
ImmutableMap.Builder<Label, ConfiguredTargetAndData> asConfiguredTargets =
ImmutableMap.builder();
ImmutableMap.Builder<Label, ConfigMatchingProvider> asConfigConditions = ImmutableMap.builder();
// Get the configured targets as ConfigMatchingProvider interfaces.
for (Dependency entry : configConditionDeps) {
SkyKey baseKey = entry.getConfiguredTargetKey();
// The code above guarantees that selectKeyTarget is non-null here.
ConfiguredTargetAndData selectKeyTarget = configValues.get(baseKey);
asConfiguredTargets.put(entry.getLabel(), selectKeyTarget);
try {
asConfigConditions.put(
entry.getLabel(), ConfigConditions.fromConfiguredTarget(selectKeyTarget, platformInfo));
} catch (ConfigConditions.InvalidConditionException e) {
String message =
String.format(
"%s is not a valid select() condition for %s.\n",
selectKeyTarget.getTarget().getLabel(), target.getLabel())
+ String.format(
"To inspect the select(), run: bazel query --output=build %s.\n",
target.getLabel())
+ "For more help, see https://docs.bazel.build/be/functions.html#select.\n\n";
env.getListener().handle(Event.error(TargetUtils.getLocationMaybe(target), message));
throw new DependencyEvaluationException(
new ConfiguredValueCreationException(
message, ctgValue.getLabel(), ctgValue.getConfiguration()));
}
}
return ConfigConditions.create(asConfiguredTargets.build(), asConfigConditions.build());
}
/**
* Resolves the targets referenced in depValueNames and returns their {@link
* ConfiguredTargetAndData} instances.
*
* <p>Returns null if not all instances are available yet.
*/
@Nullable
private static Map<SkyKey, ConfiguredTargetAndData> resolveConfiguredTargetDependencies(
boolean verbose,
Environment env,
TargetAndConfiguration ctgValue,
Collection<Dependency> deps,
@Nullable NestedSetBuilder<Package> transitivePackagesForPackageRootResolution,
NestedSetBuilder<Cause> transitiveRootCauses)
throws DependencyEvaluationException, InterruptedException {
boolean missedValues = env.valuesMissing();
String failWithMessage = null;
DetailedExitCode detailedExitCode = null;
// Naively we would like to just fetch all requested ConfiguredTargets, together with their
// Packages. However, some ConfiguredTargets are AliasConfiguredTargets, which means that their
// associated Targets (and therefore associated Packages) don't correspond to their own Labels.
// We don't know the associated Package until we fetch the ConfiguredTarget. Therefore, we have