-
Notifications
You must be signed in to change notification settings - Fork 4k
/
PrerequisiteProducer.java
1230 lines (1139 loc) · 53.7 KB
/
PrerequisiteProducer.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 2022 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.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.devtools.build.lib.analysis.AnalysisRootCauseEvent;
import com.google.devtools.build.lib.analysis.AspectResolver;
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.ExecGroupCollection;
import com.google.devtools.build.lib.analysis.InconsistentAspectOrderException;
import com.google.devtools.build.lib.analysis.PlatformConfiguration;
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.config.BuildConfigurationValue;
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.ToolchainTypeRequirement;
import com.google.devtools.build.lib.analysis.config.transitions.PatchTransition;
import com.google.devtools.build.lib.analysis.constraints.IncompatibleTargetChecker;
import com.google.devtools.build.lib.analysis.constraints.IncompatibleTargetChecker.IncompatibleTargetProducer;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.bugreport.BugReport;
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.events.Event;
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.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.Type;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetEvaluationExceptions.ReportedException;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetEvaluationExceptions.UnreportedException;
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.Environment;
import com.google.devtools.build.skyframe.SkyFunction.Environment.SkyKeyComputeState;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyframeLookupResult;
import com.google.devtools.build.skyframe.state.Driver;
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.Optional;
import java.util.Set;
import java.util.function.Predicate;
import javax.annotation.Nullable;
/**
* Helper logic for {@link ConfiguredTargetFunction}: performs the analysis phase through
* computation of prerequisites.
*
* <p>This includes:
*
* <ul>
* <li>getting this target's {@link Target} and {@link BuildConfigurationValue}
* <li>getting this target's {@code select()} keys (config conditions), which are used to evaluate
* all rule attributes with {@code select()} and determine exact dependencies
* <li>figuring out which toolchains this target needs
* <li>getting the {@link ConfiguredTargetValue}s of this target's prerequisites (through
* recursive calls to {@link ConfiguredTargetFunction}
* </ul>
*
* <p>Cumulatively, this is enough information to run the target's rule logic.
*
* <p>This class also provides getters for the above data for subsequent analysis logic to use.
*
* <p>See {@link ConfiguredTargetFunction} for more review on analysis implementation.
*/
public final class PrerequisiteProducer {
static class State implements SkyKeyComputeState, IncompatibleTargetProducer.ResultSink {
@Nullable TargetAndConfiguration targetAndConfiguration;
/**
* Drives the stateful computation of {@link #incompatibleTarget}.
*
* <p>Non-null only while the computation is in-flight.
*/
@Nullable private Driver incompatibleTargetProducer;
/**
* If a value is present, it means the target was directly incompatible.
*
* <p>Non-null after the {@link #incompatibleTargetProducer} completes.
*/
private Optional<RuleConfiguredTargetValue> incompatibleTarget;
/** Null if not yet computed or if {@link #resolveConfigurationsResult} is non-null. */
@Nullable private OrderedSetMultimap<DependencyKind, DependencyKey> dependentNodeMapResult;
/** Null if not yet computed or if {@link #computeDependenciesResult} is non-null. */
@Nullable private OrderedSetMultimap<DependencyKind, Dependency> resolveConfigurationsResult;
/** Null if not yet computed or if {@link #computeDependenciesResult} is non-null. */
@Nullable
private Map<SkyKey, ConfiguredTargetAndData> resolveConfiguredTargetDependenciesResult;
/** Null if not yet computed or if {@link #computeDependenciesResult} is non-null. */
@Nullable
private OrderedSetMultimap<Dependency, ConfiguredAspect> resolveAspectDependenciesResult;
/**
* Non-null if all the work in {@link #computeDependencies} is already done. This field contains
* the result.
*/
@Nullable
private OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> computeDependenciesResult;
/**
* Non-null if either {@link #resolveConfigurationsResult} or {@link #computeDependenciesResult}
* are non-null. This field contains events (from {@link
* ConfigurationResolver#resolveConfigurations}) that should be replayed.
*
* <p>When {@link #resolveConfigurationsResult} or {@link #computeDependenciesResult} are
* non-null (e.g. populated on a previous call to {@link #computeDependencies} on a previous
* call to {@link #evaluate}), we don't freshly do the work that would cause these events to be
* freshly emitted. So instead we replay these events from the actual call to {@link
* ConfigurationResolver#resolveConfigurations} we did in the past. This is important because
* Skyframe retains and uses only the events emitted to {@code env.getListener()} on a call to
* {@link #evaluate} that had no missing deps. That is, if our earlier {@link #evaluate}'s call
* to {@link ConfigurationResolver#resolveConfigurations} emitted events to {@code
* env.getListener()}, and that {@link #evaluate} call returned null, then those events would be
* thrown away.
*/
@Nullable private StoredEventHandler storedEventHandlerFromResolveConfigurations;
@Override
public void accept(Optional<RuleConfiguredTargetValue> incompatibleTarget) {
this.incompatibleTarget = incompatibleTarget;
}
}
/**
* Thrown if this is an invalid target because it's a rule with a null configuration or a
* non-null-configured dep of a null-configured target.
*/
static class InconsistentNullConfigException extends Exception {}
/**
* Thrown if this target is platform-incompatible with the current build.
*
* <p>See {@link IncompatibleTargetChecker}.
*/
static class IncompatibleTargetException extends Exception {
private final RuleConfiguredTargetValue target;
public IncompatibleTargetException(RuleConfiguredTargetValue target) {
this.target = target;
}
public RuleConfiguredTargetValue target() {
return target;
}
}
/** Lets calling logic provide a semaphore to restrict the number of concurrent analysis calls. */
public interface SemaphoreAcquirer {
void acquireSemaphore() throws InterruptedException;
}
private TargetAndConfiguration targetAndConfiguration = null;
private OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> depValueMap = null;
private ConfigConditions configConditions = null;
private PlatformInfo platformInfo = null;
private ToolchainCollection<UnloadedToolchainContext> unloadedToolchainContexts = null;
private ExecGroupCollection.Builder execGroupCollectionBuilder = null;
/**
* Return this target's {@link TargetAndConfiguration}.
*
* <p>{@link #evaluate} must be called before this info is available.
*/
TargetAndConfiguration getTargetAndConfiguration() {
return Preconditions.checkNotNull(targetAndConfiguration);
}
/**
* Return this target's fully resolved dependencies.
*
* <p>{@link #evaluate} must be called before this info is available.
*/
OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> getDepValueMap() {
return Preconditions.checkNotNull(depValueMap);
}
/**
* Return the keys in this target's {@code select()}s.
*
* <p>{@link #evaluate} must be called before this info is available.
*/
ConfigConditions getConfigConditions() {
return Preconditions.checkNotNull(configConditions);
}
/**
* Return this target's platform metadata, or null if it doesn't use platforms.
*
* <p>{@link #evaluate} must be called before this info is available.
*/
@Nullable
PlatformInfo getPlatformInfo() {
return platformInfo;
}
/**
* Return this target's toolchain requirements, or null if it doesn't use toolchains.
*
* <p>{@link #evaluate} must be called before this info is available.
*/
@Nullable
ToolchainCollection<UnloadedToolchainContext> getUnloadedToolchainContexts() {
return unloadedToolchainContexts;
}
/**
* Return this target's {@link ExecGroupCollection}, as far as this phase of analysis computes.
*
* <p>{@link #evaluate} must be called before this info is available.
*/
ExecGroupCollection.Builder getExecGroupCollectionsBuilder() {
return Preconditions.checkNotNull(execGroupCollectionBuilder);
}
/**
* Run's the analysis phase for this target through prerequisite evaluation.
*
* <p>See {@link PrerequisiteProducer} javadoc for details.
*
* <p>This is the main entry point to {@link PrerequisiteProducer}. This method runs its share of
* the analysis phase, after which all the data is computes is accessible to calling code through
* related getters.
*
* <p>After instantiating this class, this method should be called once. It returns false when any
* Skyframe dependencies need to be evaluated, else true.
*/
public boolean evaluate(
ConfiguredTargetKey configuredTargetKey,
State state,
NestedSetBuilder<Cause> transitiveRootCauses,
@Nullable NestedSetBuilder<Package> transitivePackages,
RuleClassProvider ruleClassProvider,
SkyframeBuildView view,
SemaphoreAcquirer semaphoreLocker,
Environment env)
throws ReportedException,
UnreportedException,
InconsistentNullConfigException,
IncompatibleTargetException,
InterruptedException {
targetAndConfiguration =
computeTargetAndConfiguration(
configuredTargetKey, state, transitiveRootCauses, transitivePackages, env);
if (targetAndConfiguration == null) {
return false;
}
Target target = targetAndConfiguration.getTarget();
if ((target.isConfigurable() && configuredTargetKey.getConfigurationKey() == null)
|| (!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.
throw new InconsistentNullConfigException();
}
SkyframeDependencyResolver resolver = new SkyframeDependencyResolver(env);
// 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.
semaphoreLocker.acquireSemaphore();
try {
// Determine what toolchains are needed by this target.
ComputedToolchainContexts result =
computeUnloadedToolchainContexts(
env,
ruleClassProvider,
targetAndConfiguration,
configuredTargetKey.getExecutionPlatformLabel());
if (env.valuesMissing()) {
// computeUnloadedToolchainContexts may return non-null even when deps are missing.
return false;
}
unloadedToolchainContexts = result.toolchainCollection;
execGroupCollectionBuilder = result.execGroupCollectionBuilder;
platformInfo =
unloadedToolchainContexts != null ? unloadedToolchainContexts.getTargetPlatform() : null;
// Get the configuration targets that trigger this rule's configurable attributes.
configConditions =
computeConfigConditions(
env, targetAndConfiguration, transitivePackages, platformInfo, transitiveRootCauses);
if (configConditions == null) {
return false;
}
// 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();
env.getListener()
.handle(Event.error(target.getLocation(), "Cannot compute config conditions"));
throw new ReportedException(
new ConfiguredValueCreationException(
targetAndConfiguration,
"Cannot compute config conditions",
causes,
getPrioritizedDetailedExitCode(causes)));
}
if (!checkForIncompatibleTarget(env, state, transitivePackages)) {
return false;
}
// Calculate the dependencies of this target.
depValueMap =
computeDependencies(
state,
transitivePackages,
transitiveRootCauses,
env,
resolver,
targetAndConfiguration,
ImmutableList.of(),
configConditions.asProviders(),
unloadedToolchainContexts == null
? null
: unloadedToolchainContexts.asToolchainContexts(),
ruleClassProvider,
view);
if (!transitiveRootCauses.isEmpty()) {
NestedSet<Cause> causes = transitiveRootCauses.build();
// TODO(bazel-team): consider reporting the error in this class vs. exporting it for
// BuildTool to handle. Calling code needs to be untangled for that to work and pass tests.
throw new UnreportedException(
new ConfiguredValueCreationException(
targetAndConfiguration,
"Analysis failed",
causes,
getPrioritizedDetailedExitCode(causes)));
}
if (depValueMap == null) {
return false;
}
} catch (DependencyEvaluationException
| ConfiguredValueCreationException
| AspectCreationException
| ToolchainException e) {
// We handle exceptions in a dedicated method to keep this method concise and readable.
handleException(env, target, e);
}
return true;
}
/**
* Checks if a target is incompatible because of its "target_compatible_with" attribute.
*
* @return false if a {@code Skyframe} restart is needed.
*/
private boolean checkForIncompatibleTarget(
Environment env, State state, @Nullable NestedSetBuilder<Package> transitivePackages)
throws InterruptedException, IncompatibleTargetException {
if (state.incompatibleTarget == null) {
if (state.incompatibleTargetProducer == null) {
state.incompatibleTargetProducer =
new Driver(
new IncompatibleTargetProducer(
targetAndConfiguration.getTarget(),
targetAndConfiguration.getConfiguration(),
configConditions,
platformInfo,
transitivePackages,
state));
}
if (!state.incompatibleTargetProducer.drive(env, env.getListener())) {
return false;
}
state.incompatibleTargetProducer = null;
if (state.incompatibleTarget.isPresent()) {
throw new IncompatibleTargetException(state.incompatibleTarget.get());
}
}
return true;
}
/**
* Handles all exceptions that {@link #evaluate} may throw.
*
* <p>This is its own method because there's a lot of logic here and when directly inlined it
* makes it harder to follow the calling method's control flow.
*/
private void handleException(Environment env, Target target, Exception untyped)
throws ReportedException {
if (untyped instanceof DependencyEvaluationException) {
DependencyEvaluationException e = (DependencyEvaluationException) untyped;
String errorMessage = e.getMessage();
if (!e.depReportedOwnError()) {
env.getListener().handle(Event.error(e.getLocation(), e.getMessage()));
}
ConfiguredValueCreationException cvce = null;
if (e.getCause() instanceof 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()) {
errorMessage = "errors encountered resolving toolchains for " + target.getLabel();
env.getListener().handle(Event.error(target.getLocation(), errorMessage));
}
}
}
throw new ReportedException(
cvce != null
? cvce
: new ConfiguredValueCreationException(
targetAndConfiguration, errorMessage, null, e.getDetailedExitCode()));
} else if (untyped instanceof ConfiguredValueCreationException) {
ConfiguredValueCreationException e = (ConfiguredValueCreationException) untyped;
if (!e.getMessage().isEmpty()) {
// Report the error to the user.
env.getListener().handle(Event.error(e.getLocation(), e.getMessage()));
}
throw new ReportedException(e);
} else if (untyped instanceof AspectCreationException) {
AspectCreationException e = (AspectCreationException) untyped;
if (!e.getMessage().isEmpty()) {
// Report the error to the user.
env.getListener().handle(Event.error(null, e.getMessage()));
}
throw new ReportedException(
new ConfiguredValueCreationException(
targetAndConfiguration, e.getMessage(), e.getCauses(), e.getDetailedExitCode()));
} else if (untyped instanceof ToolchainException) {
ToolchainException e = (ToolchainException) untyped;
ConfiguredValueCreationException cvce =
e.asConfiguredValueCreationException(targetAndConfiguration);
env.getListener().handle(Event.error(target.getLocation(), cvce.getMessage()));
throw new ReportedException(cvce);
} else {
throw new IllegalStateException("unexpected exception with no appropriate handler", untyped);
}
}
@Nullable
private static TargetAndConfiguration computeTargetAndConfiguration(
ConfiguredTargetKey configuredTargetKey,
State state,
NestedSetBuilder<Cause> transitiveRootCauses,
@Nullable NestedSetBuilder<Package> transitivePackages,
Environment env)
throws InterruptedException, ReportedException {
if (state.targetAndConfiguration != null) {
return state.targetAndConfiguration;
}
Label label = configuredTargetKey.getLabel();
BuildConfigurationValue 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);
}
SkyframeLookupResult packageAndMaybeConfigurationValues =
env.getValuesAndExceptions(packageAndMaybeConfiguration);
if (env.valuesMissing()) {
return null;
}
PackageValue packageValue = (PackageValue) packageAndMaybeConfigurationValues.get(packageKey);
if (packageValue == null) {
return null;
}
Package pkg = packageValue.getPackage();
if (configurationKeyMaybe != null) {
configuration =
(BuildConfigurationValue) packageAndMaybeConfigurationValues.get(configurationKeyMaybe);
}
// TODO(ulfjack): This tries to match the logic in TransitiveTargetFunction /
// TargetMarkerFunction. Maybe we can merge the two?
Target target;
try {
target = pkg.getTarget(label.getName());
} catch (NoSuchTargetException e) {
if (!e.getMessage().isEmpty()) {
env.getListener().handle(Event.error(pkg.getBuildFile().getLocation(), e.getMessage()));
}
throw new ReportedException(
new ConfiguredValueCreationException(
pkg.getBuildFile().getLocation(),
e.getMessage(),
label,
configuration.getEventId(),
null,
e.getDetailedExitCode()));
}
if (pkg.containsErrors()) {
FailureDetail failureDetail = pkg.contextualizeFailureDetailForTarget(target);
transitiveRootCauses.add(new LoadingFailedCause(label, DetailedExitCode.of(failureDetail)));
}
if (transitivePackages != null) {
transitivePackages.add(pkg);
}
state.targetAndConfiguration = new TargetAndConfiguration(target, configuration);
return state.targetAndConfiguration;
}
/**
* 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();
}
@VisibleForTesting
@Nullable
public static ComputedToolchainContexts computeUnloadedToolchainContexts(
Environment env,
RuleClassProvider ruleClassProvider,
TargetAndConfiguration targetAndConfig,
@Nullable Label parentExecutionPlatformLabel)
throws InterruptedException, ToolchainException {
// We can only perform toolchain resolution on Targets and Aspects.
if (!(targetAndConfig.getTarget() instanceof Rule)) {
return new ComputedToolchainContexts();
}
Label label = targetAndConfig.getLabel();
Rule rule = ((Rule) targetAndConfig.getTarget());
BuildConfigurationValue configuration = targetAndConfig.getConfiguration();
ImmutableSet<ToolchainTypeRequirement> toolchainTypes =
rule.getRuleClassObject().getToolchainTypes();
// Collect local (target, rule) constraints for filtering out execution platforms.
ImmutableSet<Label> defaultExecConstraintLabels =
getExecutionPlatformConstraints(
rule, configuration.getFragment(PlatformConfiguration.class));
ImmutableMap<String, ExecGroup> execGroups = rule.getRuleClassObject().getExecGroups();
// 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());
BuildConfigurationKey toolchainConfig =
BuildConfigurationKey.withoutPlatformMapping(toolchainOptions);
PlatformConfiguration platformConfig = configuration.getFragment(PlatformConfiguration.class);
boolean useAutoExecGroups;
if (rule.isAttrDefined("$use_auto_exec_groups", Type.BOOLEAN)) {
useAutoExecGroups = (boolean) rule.getAttr("$use_auto_exec_groups");
} else {
useAutoExecGroups = configuration.useAutoExecGroups();
}
return computeUnloadedToolchainContexts(
env,
label,
platformConfig != null && rule.useToolchainResolution(),
l -> platformConfig != null && platformConfig.debugToolchainResolution(l),
useAutoExecGroups,
toolchainConfig,
toolchainTypes,
defaultExecConstraintLabels,
execGroups,
parentExecutionPlatformLabel);
}
/**
* 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.
*/
@Nullable
static ComputedToolchainContexts computeUnloadedToolchainContexts(
Environment env,
Label label,
boolean useToolchainResolution,
Predicate<Label> debugResolution,
boolean useAutoExecGroups,
BuildConfigurationKey configurationKey,
ImmutableSet<ToolchainTypeRequirement> toolchainTypes,
ImmutableSet<Label> defaultExecConstraintLabels,
ImmutableMap<String, ExecGroup> execGroups,
@Nullable Label parentExecutionPlatformLabel)
throws InterruptedException, ToolchainException {
Map<String, ExecGroup> allExecGroups = new HashMap<>();
// Add exec groups that the rule itself has defined (custom exec groups).
allExecGroups.putAll(execGroups);
if (useAutoExecGroups) {
// Create one exec group for each toolchain (automatic exec groups).
for (ToolchainTypeRequirement toolchainType : toolchainTypes) {
allExecGroups.put(
toolchainType.toolchainType().toString(),
ExecGroup.builder().addToolchainType(toolchainType).copyFrom(null).build());
}
}
ExecGroupCollection.Builder execGroupCollectionBuilder =
ExecGroupCollection.builder(
/* execGroups= */ ImmutableMap.copyOf(allExecGroups),
/* defaultExecWith= */ defaultExecConstraintLabels,
/* defaultToolchainTypes= */ toolchainTypes);
// Short circuit and end now if this target doesn't require toolchain resolution.
if (!useToolchainResolution) {
ComputedToolchainContexts result = new ComputedToolchainContexts();
result.execGroupCollectionBuilder = execGroupCollectionBuilder;
return result;
}
Map<String, ToolchainContextKey> toolchainContextKeys = new HashMap<>();
String targetUnloadedToolchainContext = "target-unloaded-toolchain-context";
// Check if this specific target should be debugged for toolchain resolution.
boolean debugTarget = debugResolution.test(label);
ToolchainContextKey.Builder toolchainContextKeyBuilder =
ToolchainContextKey.key()
.configurationKey(configurationKey)
.execConstraintLabels(defaultExecConstraintLabels)
.debugTarget(debugTarget);
// Add toolchain types only if automatic exec groups are not created for this target.
if (!useAutoExecGroups) {
toolchainContextKeyBuilder.toolchainTypes(toolchainTypes);
}
if (parentExecutionPlatformLabel != null) {
// Find out what execution platform the parent used, and force that.
// This should only be set for direct toolchain dependencies.
toolchainContextKeyBuilder.forceExecutionPlatform(parentExecutionPlatformLabel);
}
ToolchainContextKey toolchainContextKey = toolchainContextKeyBuilder.build();
toolchainContextKeys.put(targetUnloadedToolchainContext, toolchainContextKey);
for (String name : execGroupCollectionBuilder.getExecGroupNames()) {
ExecGroup execGroup = execGroupCollectionBuilder.getExecGroup(name);
toolchainContextKeys.put(
name,
ToolchainContextKey.key()
.configurationKey(configurationKey)
.toolchainTypes(execGroup.toolchainTypes())
.execConstraintLabels(execGroup.execCompatibleWith())
.debugTarget(debugTarget)
.build());
}
SkyframeLookupResult values = env.getValuesAndExceptions(toolchainContextKeys.values());
boolean valuesMissing = env.valuesMissing();
ToolchainCollection.Builder<UnloadedToolchainContext> toolchainContexts =
valuesMissing ? null : ToolchainCollection.builder();
for (Map.Entry<String, ToolchainContextKey> unloadedToolchainContextKey :
toolchainContextKeys.entrySet()) {
UnloadedToolchainContext unloadedToolchainContext =
(UnloadedToolchainContext)
values.getOrThrow(unloadedToolchainContextKey.getValue(), ToolchainException.class);
if (valuesMissing != env.valuesMissing()) {
BugReport.logUnexpected(
"Value for: '%s' was missing, this should never happen",
unloadedToolchainContextKey.getValue());
break;
}
if (unloadedToolchainContext != null && unloadedToolchainContext.errorData() != null) {
throw new NoMatchingPlatformException(unloadedToolchainContext.errorData());
}
if (!valuesMissing) {
String execGroup = unloadedToolchainContextKey.getKey();
if (execGroup.equals(targetUnloadedToolchainContext)) {
toolchainContexts.addDefaultContext(unloadedToolchainContext);
} else {
toolchainContexts.addContext(execGroup, unloadedToolchainContext);
}
}
}
ComputedToolchainContexts result = new ComputedToolchainContexts();
result.toolchainCollection = env.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) {
if (platformConfiguration == null) {
return ImmutableSet.of(); // See NoConfigTransition.
}
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 state the compute state
* @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 buildView the build's {@link SkyframeBuildView}
*/
// TODO(b/213351014): Make the control flow of this helper function more readable. This will
// involve making a corresponding change to State to match the control flow.
@Nullable
static OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> computeDependencies(
State state,
@Nullable NestedSetBuilder<Package> transitivePackages,
NestedSetBuilder<Cause> transitiveRootCauses,
Environment env,
SkyframeDependencyResolver resolver,
TargetAndConfiguration ctgValue,
Iterable<Aspect> aspects,
ImmutableMap<Label, ConfigMatchingProvider> configConditions,
@Nullable ToolchainCollection<ToolchainContext> toolchainContexts,
RuleClassProvider ruleClassProvider,
SkyframeBuildView buildView)
throws DependencyEvaluationException,
ConfiguredValueCreationException,
AspectCreationException,
InterruptedException {
try {
if (state.computeDependenciesResult != null) {
state.storedEventHandlerFromResolveConfigurations.replayOn(env.getListener());
return state.computeDependenciesResult;
}
OrderedSetMultimap<DependencyKind, Dependency> depValueNames;
if (state.resolveConfigurationsResult != null) {
depValueNames = state.resolveConfigurationsResult;
} else {
// Create the map from attributes to set of (target, transition) pairs.
OrderedSetMultimap<DependencyKind, DependencyKey> initialDependencies;
if (state.dependentNodeMapResult != null) {
initialDependencies = state.dependentNodeMapResult;
} else {
BuildConfigurationValue configuration = ctgValue.getConfiguration();
Label label = ctgValue.getLabel();
try {
initialDependencies =
resolver.dependentNodeMap(
ctgValue,
aspects,
configConditions,
toolchainContexts,
transitiveRootCauses,
((ConfiguredRuleClassProvider) ruleClassProvider)
.getTrimmingTransitionFactory());
} catch (DependencyResolver.Failure e) {
env.getListener()
.post(new AnalysisRootCauseEvent(configuration, label, e.getMessage()));
throw new DependencyEvaluationException(
new ConfiguredValueCreationException(
e.getLocation(), e.getMessage(), label, configuration.getEventId(), null, null),
// These errors occur within DependencyResolver, which is attached to the current
// target. i.e. no dependent ConfiguredTargetFunction call happens to report its own
// error.
/*depReportedOwnError=*/ false);
} catch (InconsistentAspectOrderException e) {
throw new DependencyEvaluationException(e);
}
if (!env.valuesMissing()) {
state.dependentNodeMapResult = initialDependencies;
}
}
// Trim each dep's configuration so it only includes the fragments needed by its transitive
// closure.
ConfigurationResolver configResolver =
new ConfigurationResolver(
env,
ctgValue,
configConditions,
buildView.getStarlarkTransitionCache());
StoredEventHandler storedEventHandler = new StoredEventHandler();
try {
depValueNames =
configResolver.resolveConfigurations(initialDependencies, storedEventHandler);
} catch (ConfiguredValueCreationException e) {
storedEventHandler.replayOn(env.getListener());
throw e;
}
if (!env.valuesMissing()) {
state.resolveConfigurationsResult = depValueNames;
state.storedEventHandlerFromResolveConfigurations = storedEventHandler;
// We won't need this anymore.
state.dependentNodeMapResult = null;
}
}
// 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()) {
return null;
}
// Resolve configured target dependencies and handle errors.
Map<SkyKey, ConfiguredTargetAndData> depValues;
if (state.resolveConfiguredTargetDependenciesResult != null) {
depValues = state.resolveConfiguredTargetDependenciesResult;
} else {
depValues =
resolveConfiguredTargetDependencies(
env, ctgValue, depValueNames.values(), transitivePackages, transitiveRootCauses);
if (env.valuesMissing()) {
return null;
}
state.resolveConfiguredTargetDependenciesResult = depValues;
}
// Resolve required aspects.
OrderedSetMultimap<Dependency, ConfiguredAspect> depAspects;
if (state.resolveAspectDependenciesResult != null) {
depAspects = state.resolveAspectDependenciesResult;
} else {
depAspects =
AspectResolver.resolveAspectDependencies(
env, depValues, depValueNames.values(), transitivePackages);
if (env.valuesMissing()) {
return null;
}
state.resolveAspectDependenciesResult = depAspects;
}
// Merge the dependent configured targets and aspects into a single map.
OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> mergeAspectsResult;
try {
mergeAspectsResult = AspectResolver.mergeAspects(depValueNames, depValues, depAspects);
} catch (DuplicateException e) {
throw new DependencyEvaluationException(
new ConfiguredValueCreationException(ctgValue, e.getMessage()),
/*depReportedOwnError=*/ false);
}
state.computeDependenciesResult = mergeAspectsResult;
state.storedEventHandlerFromResolveConfigurations.replayOn(env.getListener());
// We won't need these anymore.
state.resolveConfigurationsResult = null;
state.resolveConfiguredTargetDependenciesResult = null;
state.resolveAspectDependenciesResult = null;
return mergeAspectsResult;
} catch (InterruptedException e) {
// In practice, this comes from resolveConfigurations: other InterruptedExceptions are
// declared for Skyframe value retrievals, which don't throw in reality.
if (!transitiveRootCauses.isEmpty()) {
// Allow caller to throw, don't prioritize interrupt: we may be error bubbling.
Thread.currentThread().interrupt();
return null;
}
throw e;
}
}
/**
* 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 computeConfigConditions(
Environment env,
TargetAndConfiguration ctgValue,
@Nullable NestedSetBuilder<Package> transitivePackages,
@Nullable PlatformInfo platformInfo,
NestedSetBuilder<Cause> transitiveRootCauses)
throws ConfiguredValueCreationException, 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;