forked from bazelbuild/bazel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AndroidBinary.java
2233 lines (2060 loc) · 97.6 KB
/
AndroidBinary.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 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.devtools.build.lib.collect.nestedset.Order.STABLE_ORDER;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.Type.STRING;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;
import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.actions.CommandLine;
import com.google.devtools.build.lib.actions.FailAction;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.actions.ParamFileInfo;
import com.google.devtools.build.lib.actions.ParameterFile;
import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType;
import com.google.devtools.build.lib.analysis.Allowlist;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.OutputGroupInfo;
import com.google.devtools.build.lib.analysis.RequiredConfigFragmentsProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RuleErrorConsumer;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.actions.CustomCommandLine;
import com.google.devtools.build.lib.analysis.actions.CustomCommandLine.VectorArg;
import com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.actions.SpawnActionTemplate;
import com.google.devtools.build.lib.analysis.actions.SpawnActionTemplate.OutputPathMapper;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
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.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.TriState;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.rules.android.AndroidBinaryMobileInstall.MobileInstallResourceApks;
import com.google.devtools.build.lib.rules.android.AndroidRuleClasses.MultidexMode;
import com.google.devtools.build.lib.rules.android.ProguardHelper.ProguardOutput;
import com.google.devtools.build.lib.rules.android.ZipFilterBuilder.CheckHashMismatchMode;
import com.google.devtools.build.lib.rules.android.databinding.DataBinding;
import com.google.devtools.build.lib.rules.cpp.CppSemantics;
import com.google.devtools.build.lib.rules.java.DeployArchiveBuilder;
import com.google.devtools.build.lib.rules.java.JavaCommon;
import com.google.devtools.build.lib.rules.java.JavaConfiguration;
import com.google.devtools.build.lib.rules.java.JavaConfiguration.OneVersionEnforcementLevel;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaTargetAttributes;
import com.google.devtools.build.lib.rules.java.JavaToolchainProvider;
import com.google.devtools.build.lib.rules.java.OneVersionCheckActionBuilder;
import com.google.devtools.build.lib.rules.java.ProguardSpecProvider;
import com.google.devtools.build.lib.server.FailureDetails.FailAction.Code;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
import net.starlark.java.eval.StarlarkInt;
/** An implementation for the "android_binary" rule. */
public abstract class AndroidBinary implements RuleConfiguredTargetFactory {
private static final String DX_MINIMAL_MAIN_DEX_OPTION = "--minimal-main-dex";
protected abstract JavaSemantics createJavaSemantics();
protected abstract AndroidSemantics createAndroidSemantics();
protected abstract CppSemantics createCppSemantics();
@Override
@Nullable
public final ConfiguredTarget create(RuleContext ruleContext)
throws InterruptedException, RuleErrorException, ActionConflictException {
CppSemantics cppSemantics = createCppSemantics();
JavaSemantics javaSemantics = createJavaSemantics();
AndroidSemantics androidSemantics = createAndroidSemantics();
androidSemantics.checkForMigrationTag(ruleContext);
androidSemantics.validateAndroidBinaryRuleContext(ruleContext);
AndroidSdkProvider.verifyPresence(ruleContext);
NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder();
RuleConfiguredTargetBuilder builder =
init(ruleContext, filesBuilder, cppSemantics, javaSemantics, androidSemantics);
return builder.build();
}
@Override
public final void addRuleImplSpecificRequiredConfigFragments(
RequiredConfigFragmentsProvider.Builder requiredFragments,
AttributeMap attributes,
BuildConfigurationValue configuration) {
requiredFragments.addStarlarkOptions(AndroidFeatureFlagSetProvider.getFeatureFlags(attributes));
}
/** Checks expected rule invariants, throws rule errors if anything is set wrong. */
private static void validateRuleContext(RuleContext ruleContext, AndroidDataContext dataContext)
throws RuleErrorException {
if (getMultidexMode(ruleContext) != MultidexMode.LEGACY
&& ruleContext
.attributes()
.isAttributeValueExplicitlySpecified("main_dex_proguard_specs")) {
ruleContext.throwWithAttributeError(
"main_dex_proguard_specs",
"The 'main_dex_proguard_specs' attribute is only allowed if 'multidex' is"
+ " set to 'legacy'");
}
if (ruleContext.attributes().isAttributeValueExplicitlySpecified("proguard_apply_mapping")) {
if (dataContext.throwOnProguardApplyMapping()) {
ruleContext.throwWithAttributeError(
"proguard_apply_mapping", "This attribute is not supported");
}
if (ruleContext
.attributes()
.get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST)
.isEmpty()) {
ruleContext.throwWithAttributeError(
"proguard_apply_mapping",
"'proguard_apply_mapping' can only be used when 'proguard_specs' is also set");
}
}
if (ruleContext.attributes().isAttributeValueExplicitlySpecified("proguard_apply_dictionary")) {
if (dataContext.throwOnProguardApplyDictionary()) {
ruleContext.throwWithAttributeError(
"proguard_apply_dictionary", "This attribute is not supported");
}
if (ruleContext
.attributes()
.get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST)
.isEmpty()) {
ruleContext.throwWithAttributeError(
"proguard_apply_dictionary",
"'proguard_apply_dictionary' can only be used when 'proguard_specs' is also set");
}
}
if (ruleContext.attributes().isAttributeValueExplicitlySpecified("shrink_resources")
&& dataContext.throwOnShrinkResources()) {
ruleContext.throwWithAttributeError("shrink_resources", "This attribute is not supported");
}
if (ruleContext.attributes().isAttributeValueExplicitlySpecified("min_sdk_version")
&& Allowlist.hasAllowlist(ruleContext, "allow_min_sdk_version")
&& !Allowlist.isAvailable(ruleContext, "allow_min_sdk_version")) {
ruleContext.attributeError(
"min_sdk_version", "Target is not permitted to set min_sdk_version");
}
if (ruleContext.getFragment(JavaConfiguration.class).enforceProguardFileExtension()
&& ruleContext.attributes().has(ProguardHelper.PROGUARD_SPECS)) {
List<PathFragment> pathsWithUnexpectedExtension =
ruleContext.getPrerequisiteArtifacts(ProguardHelper.PROGUARD_SPECS).list().stream()
.filter(Artifact::isSourceArtifact)
.map(Artifact::getRootRelativePath)
.filter(
// This checks the filename directly instead of using FileType because we want to
// exclude third_party/, but FileType is generally only given the basename.
//
// See e.g. RuleContext#validateDirectPrerequisiteType and
// PrerequisiteArtifacts#filter.
path ->
!path.getFileExtension().equals("pgcfg")
&& !path.startsWith(RuleClass.THIRD_PARTY_PREFIX)
&& !path.startsWith(RuleClass.EXPERIMENTAL_PREFIX))
.collect(toImmutableList());
if (!pathsWithUnexpectedExtension.isEmpty()) {
ruleContext.throwWithAttributeError(
ProguardHelper.PROGUARD_SPECS,
"Proguard spec files must use the .pgcfg extension. These files do not end in .pgcfg: "
+ pathsWithUnexpectedExtension);
}
}
}
private static RuleConfiguredTargetBuilder init(
RuleContext ruleContext,
NestedSetBuilder<Artifact> filesBuilder,
CppSemantics cppSemantics,
JavaSemantics javaSemantics,
AndroidSemantics androidSemantics)
throws InterruptedException, RuleErrorException {
ResourceDependencies resourceDeps =
ResourceDependencies.fromRuleDeps(ruleContext, /* neverlink= */ false);
AndroidDataContext dataContext = androidSemantics.makeContextForNative(ruleContext);
validateRuleContext(ruleContext, dataContext);
NativeLibs nativeLibs =
NativeLibs.fromLinkedNativeDeps(
ruleContext,
ImmutableList.of("deps"),
androidSemantics.getNativeDepsFileName(),
cppSemantics);
// Retrieve and compile the resources defined on the android_binary rule.
AndroidResources.validateRuleContext(ruleContext);
Map<String, String> manifestValues = StampedAndroidManifest.getManifestValues(ruleContext);
StampedAndroidManifest manifest;
if (isInstrumentation(ruleContext)
&& dataContext.getAndroidConfig().disableInstrumentationManifestMerging()) {
manifest =
AndroidManifest.fromAttributes(ruleContext, dataContext, androidSemantics)
.stamp(dataContext);
} else {
manifest =
AndroidManifest.fromAttributes(ruleContext, dataContext, androidSemantics)
.mergeWithDeps(
dataContext,
androidSemantics,
ruleContext,
resourceDeps,
manifestValues,
ruleContext.getRule().isAttrDefined("manifest_merger", STRING)
? ruleContext.attributes().get("manifest_merger", STRING)
: null);
}
boolean shrinkResourceCycles =
shouldShrinkResourceCycles(
dataContext.getAndroidConfig(), ruleContext, dataContext.isResourceShrinkingEnabled());
ProcessedAndroidData processedAndroidData =
ProcessedAndroidData.processBinaryDataFrom(
dataContext,
ruleContext,
manifest,
/* conditionalKeepRules= */ shrinkResourceCycles,
manifestValues,
AndroidResources.from(ruleContext, "resource_files"),
AndroidAssets.from(ruleContext),
resourceDeps,
AssetDependencies.fromRuleDeps(ruleContext, /* neverlink = */ false),
ResourceFilterFactory.fromRuleContextAndAttrs(ruleContext),
ruleContext.getExpander().withDataLocations().tokenized("nocompress_extensions"),
ruleContext.attributes().get("crunch_png", Type.BOOLEAN),
DataBinding.contextFrom(ruleContext, dataContext.getAndroidConfig()));
AndroidApplicationResourceInfo androidApplicationResourceInfo =
ruleContext.getPrerequisite(
"application_resources", AndroidApplicationResourceInfo.PROVIDER);
final ResourceApk resourceApk;
boolean shouldCompileJavaSrcs = true;
if (androidApplicationResourceInfo == null) {
resourceApk =
new RClassGeneratorActionBuilder()
.withDependencies(resourceDeps)
.finalFields(!shrinkResourceCycles)
.setClassJarOut(
dataContext.createOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR))
.build(dataContext, processedAndroidData);
} else {
resourceApk =
ResourceApk.fromAndroidApplicationResourceInfo(
ruleContext, dataContext.getAndroidConfig(), androidApplicationResourceInfo);
shouldCompileJavaSrcs = androidApplicationResourceInfo.shouldCompileJavaSrcs();
}
if (dataContext.useResourcePathShortening()) {
filesBuilder.add(
ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCE_PATH_SHORTENING_MAP));
}
ruleContext.assertNoErrors();
JavaCommon javaCommon =
AndroidCommon.createJavaCommonWithAndroidDataBinding(
ruleContext,
javaSemantics,
resourceApk.asDataBindingContext(),
/* isLibrary */ false,
shouldCompileJavaSrcs);
javaSemantics.checkRule(ruleContext, javaCommon);
javaSemantics.checkForProtoLibraryAndJavaProtoLibraryOnSameProto(ruleContext, javaCommon);
AndroidCommon androidCommon = new AndroidCommon(javaCommon, /* asNeverLink= */ true);
// Remove the library resource JARs from the binary's runtime classpath.
// Resource classes from android_library dependencies are replaced by the binary's resource
// class. We remove them only at the top level so that resources included by a library that is
// a dependency of a java_library are still included, since these resources are propagated via
// android-specific providers and won't show up when we collect the library resource JARs.
// TODO(b/69552500): Instead, handle this properly so R JARs aren't put on the classpath for
// both binaries and libraries.
NestedSet<Artifact> excludedRuntimeArtifacts = getLibraryResourceJars(ruleContext);
JavaTargetAttributes resourceClasses =
androidCommon.init(
javaSemantics,
androidSemantics,
resourceApk,
ruleContext.getConfiguration().isCodeCoverageEnabled(),
/* collectJavaCompilationArgs= */ true,
/* isBinary= */ true,
shouldCompileJavaSrcs,
excludedRuntimeArtifacts,
/* generateExtensionRegistry= */ true);
ruleContext.assertNoErrors();
Function<Artifact, Artifact> derivedJarFunction =
collectDesugaredJars(ruleContext, androidCommon, androidSemantics, resourceClasses);
Artifact deployJar =
createDeployJar(
ruleContext,
javaSemantics,
androidCommon,
resourceClasses,
AndroidCommon.getAndroidConfig(ruleContext).checkDesugarDeps(),
derivedJarFunction);
boolean isBinaryJarFiltered = isInstrumentation(ruleContext);
if (isBinaryJarFiltered) {
deployJar = getFilteredDeployJar(ruleContext, deployJar);
}
OneVersionEnforcementLevel oneVersionEnforcementLevel =
ruleContext.getFragment(JavaConfiguration.class).oneVersionEnforcementLevel();
Artifact oneVersionOutputArtifact = null;
if (oneVersionEnforcementLevel != OneVersionEnforcementLevel.OFF) {
NestedSet<Artifact> transitiveDependencies =
NestedSetBuilder.<Artifact>stableOrder()
.addAll(
Iterables.transform(
resourceClasses.getRuntimeClassPath().toList(), derivedJarFunction))
.addAll(
Iterables.transform(
androidCommon.getJarsProducedForRuntime().toList(), derivedJarFunction))
.build();
oneVersionOutputArtifact =
OneVersionCheckActionBuilder.newBuilder()
.withEnforcementLevel(oneVersionEnforcementLevel)
.outputArtifact(
ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_ONE_VERSION_ARTIFACT))
.useToolchain(JavaToolchainProvider.from(ruleContext))
.checkJars(transitiveDependencies)
.build(ruleContext);
}
Artifact proguardMapping = ruleContext.getPrerequisiteArtifact("proguard_apply_mapping");
MobileInstallResourceApks mobileInstallResourceApks =
AndroidBinaryMobileInstall.createMobileInstallResourceApks(
ruleContext, dataContext, manifest);
Artifact manifestValidation = null;
boolean shouldValidateMultidex =
(Allowlist.hasAllowlist(ruleContext, "android_multidex_native_min_sdk_allowlist")
&& !Allowlist.isAvailable(ruleContext, "android_multidex_native_min_sdk_allowlist")
&& getMultidexMode(ruleContext) == MultidexMode.NATIVE);
boolean shouldValidateMinSdk = getMinSdkVersion(ruleContext) > 0;
if (ruleContext.isAttrDefined("$validate_manifest", LABEL)
&& (shouldValidateMultidex || shouldValidateMinSdk)) {
manifestValidation =
ruleContext.getPackageRelativeArtifact(
ruleContext.getLabel().getName() + "_manifest_validation_output",
ruleContext.getBinOrGenfilesDirectory());
ruleContext.registerAction(
createSpawnActionBuilder(ruleContext)
.setExecutable(ruleContext.getExecutablePrerequisite("$validate_manifest"))
.setProgressMessage("Validating %{input}")
.setMnemonic("ValidateManifest")
.addInput(manifest.getManifest())
.addOutput(manifestValidation)
.addCommandLine(
CustomCommandLine.builder()
.addExecPath("--manifest", manifest.getManifest())
.addExecPath("--output", manifestValidation)
.addFormatted(
"--validate_multidex=%s", Boolean.toString(shouldValidateMultidex))
.add(
"--expected_min_sdk_version",
Integer.toString(getMinSdkVersion(ruleContext)))
.build())
.build(ruleContext));
}
return createAndroidBinary(
ruleContext,
dataContext,
filesBuilder,
deployJar,
derivedJarFunction,
isBinaryJarFiltered,
androidCommon,
javaSemantics,
androidSemantics,
nativeLibs,
resourceApk,
mobileInstallResourceApks,
resourceClasses,
ImmutableList.of(),
ImmutableList.of(),
proguardMapping,
oneVersionOutputArtifact,
manifestValidation);
}
public static RuleConfiguredTargetBuilder createAndroidBinary(
RuleContext ruleContext,
AndroidDataContext dataContext,
NestedSetBuilder<Artifact> filesBuilder,
Artifact binaryJar,
Function<Artifact, Artifact> derivedJarFunction,
boolean isBinaryJarFiltered,
AndroidCommon androidCommon,
JavaSemantics javaSemantics,
AndroidSemantics androidSemantics,
NativeLibs nativeLibs,
ResourceApk resourceApk,
@Nullable MobileInstallResourceApks mobileInstallResourceApks,
JavaTargetAttributes resourceClasses,
ImmutableList<Artifact> apksUnderTest,
ImmutableList<Artifact> additionalMergedManifests,
Artifact proguardMapping,
@Nullable Artifact oneVersionEnforcementArtifact,
@Nullable Artifact manifestValidation)
throws InterruptedException, RuleErrorException {
List<ProguardSpecProvider> proguardDeps = new ArrayList<>();
Iterables.addAll(
proguardDeps, ruleContext.getPrerequisites("deps", ProguardSpecProvider.PROVIDER));
Iterables.addAll(
proguardDeps,
ruleContext.getPrerequisites("application_resources", ProguardSpecProvider.PROVIDER));
if (ruleContext.getConfiguration().isCodeCoverageEnabled()
&& ruleContext.attributes().has("$jacoco_runtime", BuildType.LABEL)) {
proguardDeps.add(
ruleContext.getPrerequisite("$jacoco_runtime", ProguardSpecProvider.PROVIDER));
}
ImmutableList<Artifact> proguardSpecs =
getProguardSpecs(
dataContext,
androidSemantics,
resourceApk.getResourceProguardConfig(),
resourceApk.getManifest(),
ruleContext.attributes().has(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST)
? ruleContext.getPrerequisiteArtifacts(ProguardHelper.PROGUARD_SPECS).list()
: ImmutableList.of(),
ruleContext.getPrerequisiteArtifacts(":extra_proguard_specs").list(),
proguardDeps);
boolean hasProguardSpecs = !proguardSpecs.isEmpty();
// TODO(bazel-team): Verify that proguard spec files don't contain -printmapping directions
// which this -printmapping command line flag will override.
Artifact proguardOutputMap = null;
boolean generateProguardMap =
ProguardHelper.genProguardMapping(ruleContext.attributes())
|| dataContext.isResourceShrinkingEnabled();
boolean postprocessingRewritesMap = androidSemantics.postprocessClassesRewritesMap(ruleContext);
boolean desugarJava8LibsGeneratesMap =
AndroidCommon.getAndroidConfig(ruleContext).desugarJava8Libs();
if (generateProguardMap) {
// Determine the output of the Proguard map from shrinking the app. This depends on the
// additional steps which can process the map before the final Proguard map artifact is
// generated.
if (!hasProguardSpecs && !postprocessingRewritesMap) {
// When no shrinking happens a generating rule for the output map artifact is still needed.
proguardOutputMap = androidSemantics.getProguardOutputMap(ruleContext);
} else if (postprocessingRewritesMap) {
// Proguard map from shrinking goes to postprocessing.
proguardOutputMap =
ProguardHelper.getProguardTempArtifact(ruleContext, "proguard_output_for_rex.map");
} else if (desugarJava8LibsGeneratesMap) {
// Proguard map from shrinking will be merged with desugared library proguard map.
proguardOutputMap =
getDxArtifact(ruleContext, "_proguard_output_for_desugared_library.map");
} else {
// Proguard map from shrinking is the final output.
proguardOutputMap = androidSemantics.getProguardOutputMap(ruleContext);
}
}
ProguardOutput proguardOutput =
applyProguard(
ruleContext,
androidCommon,
javaSemantics,
binaryJar,
proguardSpecs,
proguardMapping,
proguardOutputMap);
// Determine the outputs for the proguard map transition through post-processing and adding of
// desugared library map.
Artifact postProcessingOutputMap = null;
Artifact finalProguardOutputMap = null;
if (proguardOutput.hasMapping()) {
// Determine the Proguard map artifacts for the additional steps (if any) if shrinking of
// the app is enabled.
if (postprocessingRewritesMap && desugarJava8LibsGeneratesMap) {
// Proguard map from preprocessing will be merged with Proguard map for desugared
// library.
postProcessingOutputMap =
getDxArtifact(ruleContext, "_proguard_output_for_desugared_library.map");
finalProguardOutputMap = androidSemantics.getProguardOutputMap(ruleContext);
} else if (postprocessingRewritesMap) {
// No desugared library, Proguard map from preprocessing is the final Proguard map.
postProcessingOutputMap = androidSemantics.getProguardOutputMap(ruleContext);
finalProguardOutputMap = postProcessingOutputMap;
} else if (desugarJava8LibsGeneratesMap) {
// No postprocessing, Proguard map from merging with the desugared library map is the
// final Proguard map.
postProcessingOutputMap = proguardOutputMap;
finalProguardOutputMap = androidSemantics.getProguardOutputMap(ruleContext);
} else {
// No postprocessing, no desugared library, the final Proguard map is the Proguard map
// from shrinking
postProcessingOutputMap = proguardOutputMap;
finalProguardOutputMap = proguardOutputMap;
}
}
if (dataContext.useResourceShrinking(hasProguardSpecs)) {
resourceApk =
shrinkResources(
ruleContext,
androidSemantics.makeContextForNative(ruleContext),
resourceApk,
proguardOutput,
filesBuilder);
}
resourceApk = maybeOptimizeResources(dataContext, resourceApk, hasProguardSpecs);
Artifact jarToDex = proguardOutput.getOutputJar();
DexingOutput dexingOutput =
dex(
ruleContext,
androidSemantics,
binaryJar,
jarToDex,
isBinaryJarFiltered,
androidCommon,
resourceApk.getMainDexProguardConfig(),
resourceClasses,
derivedJarFunction,
proguardOutputMap);
// Collect all native shared libraries across split transitions. Some AARs contain shared
// libraries across multiple architectures, e.g. x86 and armeabi-v7a, and need to be packed
// into the APK.
NestedSetBuilder<Artifact> transitiveNativeLibs = NestedSetBuilder.naiveLinkOrder();
for (Map.Entry<
com.google.common.base.Optional<String>,
? extends List<? extends TransitiveInfoCollection>>
entry : ruleContext.getSplitPrerequisites("deps").entrySet()) {
for (AndroidNativeLibsInfo provider :
AnalysisUtils.getProviders(entry.getValue(), AndroidNativeLibsInfo.PROVIDER)) {
transitiveNativeLibs.addTransitive(provider.getNativeLibs());
}
}
NestedSet<Artifact> nativeLibsAar = transitiveNativeLibs.build();
DexPostprocessingOutput dexPostprocessingOutput =
androidSemantics.postprocessClassesDexZip(
ruleContext,
filesBuilder,
dexingOutput.classesDexZip,
proguardOutput,
postProcessingOutputMap);
// Compute the final DEX files by appending Java 8 legacy .dex if used.
Artifact finalClassesDex;
Java8LegacyDexOutput java8LegacyDexOutput;
ImmutableList<Artifact> finalShardDexZips = dexingOutput.shardDexZips;
if (AndroidCommon.getAndroidConfig(ruleContext).desugarJava8Libs()
&& dexPostprocessingOutput.classesDexZip().getFilename().endsWith(".zip")) {
if (binaryJar.equals(jarToDex)) {
// No shrinking: use canned Java 8 legacy .dex file
java8LegacyDexOutput = Java8LegacyDexOutput.getCanned(ruleContext);
} else {
// Shrinking is used: build custom Java 8 legacy .dex file
java8LegacyDexOutput = buildJava8LegacyDex(ruleContext, jarToDex);
// Merge the mapping files from shrinking the program and Java 8 legacy .dex file.
if (finalProguardOutputMap != null) {
ruleContext.registerAction(
createSpawnActionBuilder(ruleContext)
.useDefaultShellEnvironment()
.setExecutable(ruleContext.getExecutablePrerequisite("$merge_proguard_maps"))
.addInput(dexPostprocessingOutput.proguardMap())
.addInput(java8LegacyDexOutput.getMap())
.addOutput(finalProguardOutputMap)
.addCommandLine(
CustomCommandLine.builder()
.addExecPath("--pg-map", dexPostprocessingOutput.proguardMap())
.addExecPath("--pg-map", java8LegacyDexOutput.getMap())
.addExecPath("--pg-map-output", finalProguardOutputMap)
.build())
.setMnemonic("MergeProguardMaps")
.setProgressMessage(
"Merging app and desugared library Proguard maps for %{label}")
.build(ruleContext));
}
}
// Append legacy .dex library to app's .dex files
finalClassesDex = getDxArtifact(ruleContext, "_final_classes.dex.zip");
ruleContext.registerAction(
createSpawnActionBuilder(ruleContext)
.useDefaultShellEnvironment()
.setMnemonic("AppendJava8LegacyDex")
.setProgressMessage("Adding Java 8 legacy library for %s", ruleContext.getLabel())
.setExecutable(ruleContext.getExecutablePrerequisite("$merge_dexzips"))
.addInput(dexPostprocessingOutput.classesDexZip())
.addInput(java8LegacyDexOutput.getDex())
.addOutput(finalClassesDex)
// Order matters here: we want java8LegacyDex to be the highest-numbered classesN.dex
.addCommandLine(
CustomCommandLine.builder()
.addExecPath("--input_zip", dexPostprocessingOutput.classesDexZip())
.addExecPath("--input_zip", java8LegacyDexOutput.getDex())
.addExecPath("--output_zip", finalClassesDex)
.build())
.build(ruleContext));
finalShardDexZips =
ImmutableList.<Artifact>builder()
.addAll(finalShardDexZips)
.add(java8LegacyDexOutput.getDex())
.build();
} else {
finalClassesDex = dexPostprocessingOutput.classesDexZip();
}
if (hasProguardSpecs) {
proguardOutput.addAllToSet(filesBuilder, finalProguardOutputMap);
}
Artifact artProfileZip =
androidSemantics.getArtProfileForApk(
ruleContext, finalClassesDex, proguardOutputMap, hasProguardSpecs);
Artifact unsignedApk =
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_UNSIGNED_APK);
Artifact zipAlignedApk =
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_APK);
Artifact v4Signature =
(dataContext.getAndroidConfig().apkSigningMethodV4() != null
&& dataContext.getAndroidConfig().apkSigningMethodV4())
? ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_V4_SIGNATURE)
: null;
ImmutableList<Artifact> signingKeys = AndroidCommon.getApkDebugSigningKeys(ruleContext);
Artifact signingLineage = ruleContext.getPrerequisiteArtifact("debug_signing_lineage_file");
String keyRotationMinSdk = ruleContext.attributes().get("key_rotation_min_sdk", Type.STRING);
FilesToRunProvider resourceExtractor =
ruleContext.getExecutablePrerequisite("$resource_extractor");
ApkActionsBuilder actionsBuilder =
ApkActionsBuilder.create("apk")
.setClassesDex(finalClassesDex)
.addInputZip(resourceApk.getArtifact())
.setJavaResourceZip(dexingOutput.javaResourceJar, resourceExtractor)
.addInputZips(nativeLibsAar.toList())
.setNativeLibs(nativeLibs)
.setUnsignedApk(unsignedApk)
.setSignedApk(zipAlignedApk)
.setSigningKeys(signingKeys)
.setSigningLineageFile(signingLineage)
.setSigningKeyRotationMinSdk(keyRotationMinSdk)
.setV4Signature(v4Signature)
.setZipalignApk(true)
.setDeterministicSigning(androidSemantics.deterministicSigning());
if (artProfileZip != null) {
actionsBuilder.addInputZip(artProfileZip);
}
actionsBuilder.registerActions(ruleContext);
filesBuilder.add(binaryJar);
filesBuilder.add(unsignedApk);
filesBuilder.add(zipAlignedApk);
if (v4Signature != null) {
filesBuilder.add(v4Signature);
}
NestedSet<Artifact> filesToBuild = filesBuilder.build();
Artifact deployInfo = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.DEPLOY_INFO);
ImmutableList.Builder<Artifact> listBuilder =
ImmutableList.<Artifact>builder().add(zipAlignedApk).addAll(apksUnderTest);
if (v4Signature != null) {
listBuilder.add(v4Signature);
}
AndroidDeployInfoAction.createDeployInfoAction(
ruleContext,
deployInfo,
resourceApk.getManifest(),
additionalMergedManifests,
listBuilder.build());
RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
// If this is an instrumentation APK, create the provider for android_instrumentation_test.
if (isInstrumentation(ruleContext)) {
ApkInfo targetApkProvider = ruleContext.getPrerequisite("instruments", ApkInfo.PROVIDER);
AndroidInstrumentationInfo instrumentationProvider =
new AndroidInstrumentationInfo(targetApkProvider);
builder.addNativeDeclaredProvider(instrumentationProvider);
// At this point, the Android manifests of both target and instrumentation APKs are finalized.
FilesToRunProvider checker =
ruleContext.getExecutablePrerequisite("$instrumentation_test_check");
Artifact targetManifest = targetApkProvider.getMergedManifest();
Artifact instrumentationManifest = resourceApk.getManifest();
Artifact checkOutput =
ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.INSTRUMENTATION_TEST_CHECK_RESULTS);
SpawnAction.Builder checkAction =
createSpawnActionBuilder(ruleContext)
.setExecutable(checker)
.addInput(targetManifest)
.addInput(instrumentationManifest)
.addOutput(checkOutput)
.setProgressMessage(
"Validating the merged manifests of the target and instrumentation APKs")
.setMnemonic("AndroidManifestInstrumentationCheck");
CustomCommandLine commandLine =
CustomCommandLine.builder()
.addExecPath("--instrumentation_manifest", instrumentationManifest)
.addExecPath("--target_manifest", targetManifest)
.addExecPath("--output", checkOutput)
.build();
builder.addOutputGroup(OutputGroupInfo.HIDDEN_TOP_LEVEL, checkOutput);
checkAction.addCommandLine(commandLine);
ruleContext.registerAction(checkAction.build(ruleContext));
}
androidCommon.addTransitiveInfoProviders(
builder,
/* aar= */ null,
resourceApk,
zipAlignedApk,
apksUnderTest,
nativeLibs,
androidCommon.isNeverLink(),
/* isLibrary = */ false);
if (dexPostprocessingOutput.proguardMap() != null) {
builder.addNativeDeclaredProvider(
new ProguardMappingProvider(dexPostprocessingOutput.proguardMap()));
}
if (oneVersionEnforcementArtifact != null) {
builder.addOutputGroup(OutputGroupInfo.HIDDEN_TOP_LEVEL, oneVersionEnforcementArtifact);
}
if (mobileInstallResourceApks != null) {
AndroidBinaryMobileInstall.addMobileInstall(
ruleContext,
builder,
dexingOutput.javaResourceJar,
finalShardDexZips,
javaSemantics,
nativeLibs,
resourceApk,
mobileInstallResourceApks,
resourceExtractor,
nativeLibsAar,
signingKeys,
signingLineage,
additionalMergedManifests);
}
if (manifestValidation != null) {
builder.addOutputGroup(
OutputGroupInfo.VALIDATION, NestedSetBuilder.create(STABLE_ORDER, manifestValidation));
}
// First propagate validations from most rule attributes as usual; then handle "deps" separately
// to propagate validations from each config split but avoid known-redundant Android Lint
// validations (b/168038145, b/180746622).
// TODO(b/180746622): remove custom filtering once semantically identical actions with
// different configurations are deduped (while still propagating actions from all splits)
RuleConfiguredTargetBuilder.collectTransitiveValidationOutputGroups(
ruleContext,
attr -> !"deps".equals(attr),
validations -> builder.addOutputGroup(OutputGroupInfo.VALIDATION_TRANSITIVE, validations));
boolean filterSplitValidations = false; // propagate validations from first split unfiltered
for (List<? extends TransitiveInfoCollection> deps :
ruleContext.getSplitPrerequisites("deps").values()) {
for (OutputGroupInfo provider :
AnalysisUtils.getProviders(deps, OutputGroupInfo.STARLARK_CONSTRUCTOR)) {
NestedSet<Artifact> validations = provider.getOutputGroup(OutputGroupInfo.VALIDATION);
if (filterSplitValidations) {
// Filter out Android Lint validations by name: we know these validations are expensive
// and duplicative between splits, so arbitrarily only propagate them from the first split
// (b/180746622). While it's cheesy to rely on naming patterns, more semantic filtering
// requires a lot of work (e.g., using an aspect that observes actions by mnemonic).
NestedSetBuilder<Artifact> filtered = NestedSetBuilder.stableOrder();
validations.toList().stream()
.filter(Artifact::hasKnownGeneratingAction)
.filter(a -> !a.getFilename().endsWith("android_lint_output.xml"))
.forEach(filtered::add);
validations = filtered.build();
}
if (!validations.isEmpty()) {
builder.addOutputGroup(OutputGroupInfo.VALIDATION_TRANSITIVE, validations);
}
}
// Filter out Android Lint Validations from any subsequent split,
// because they're redundant with those in the first split.
filterSplitValidations = true;
}
return builder
.setFilesToBuild(filesToBuild)
.addProvider(
RunfilesProvider.class,
RunfilesProvider.simple(
ruleContext, new Runfiles.Builder(
ruleContext.getWorkspaceName(),
ruleContext.getConfiguration().legacyExternalRunfiles())
.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES)
.addTransitiveArtifacts(filesToBuild)
.build()))
.addNativeDeclaredProvider(
new ApkInfo(
zipAlignedApk,
unsignedApk,
binaryJar,
getCoverageInstrumentationJarForApk(ruleContext),
resourceApk.getManifest(),
signingKeys,
signingLineage,
keyRotationMinSdk))
.addNativeDeclaredProvider(new AndroidPreDexJarProvider(jarToDex))
.addNativeDeclaredProvider(
AndroidFeatureFlagSetProvider.create(
AndroidFeatureFlagSetProvider.getAndValidateFlagMapFromRuleContext(ruleContext)))
.addOutputGroup("android_deploy_info", deployInfo)
.addOutputGroup("android_deploy_info", resourceApk.getManifest());
}
static class Java8LegacyDexOutput {
private final Artifact dex;
private final Artifact map;
private Java8LegacyDexOutput(Artifact dex, Artifact map) {
this.dex = dex;
this.map = map;
}
static Java8LegacyDexOutput getCanned(RuleContext ruleContext) {
return new Java8LegacyDexOutput(
ruleContext.getPrerequisiteArtifact("$java8_legacy_dex"), null);
}
boolean isEmpty() {
return dex == null;
}
public Artifact getDex() {
return dex;
}
public Artifact getMap() {
return map;
}
}
static Java8LegacyDexOutput buildJava8LegacyDex(RuleContext ruleContext, Artifact jarToDex) {
Artifact java8LegacyDexRules = getDxArtifact(ruleContext, "_java8_legacy.dex.pgcfg");
Artifact java8LegacyDex = getDxArtifact(ruleContext, "_java8_legacy.dex.zip");
Artifact java8LegacyDexMap = getDxArtifact(ruleContext, "_java8_legacy.dex.map");
Artifact androidJar = AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar();
ruleContext.registerAction(
createSpawnActionBuilder(ruleContext)
.setExecutable(ruleContext.getExecutablePrerequisite("$build_java8_legacy_dex"))
.addInput(jarToDex)
.addInput(androidJar)
.addOutput(java8LegacyDexRules)
.addOutput(java8LegacyDex)
.addOutput(java8LegacyDexMap)
.addCommandLine(
CustomCommandLine.builder()
.addExecPath("--rules", java8LegacyDexRules)
.addExecPath("--binary", jarToDex)
.addExecPath("--android_jar", androidJar)
.addExecPath("--output", java8LegacyDex)
.addExecPath("--output_map", java8LegacyDexMap)
.build())
.setMnemonic("BuildLegacyDex")
.setProgressMessage("Building Java 8 legacy library for %{label}")
.build(ruleContext));
return new Java8LegacyDexOutput(java8LegacyDex, java8LegacyDexMap);
}
/**
* For coverage builds, this returns a Jar containing <b>un</b>instrumented bytecode for the
* coverage reporter's consumption. This method simply returns the deploy Jar. Note the deploy Jar
* is built anyway for Android binaries.
*
* @return A Jar containing uninstrumented bytecode or {@code null} for non-coverage builds
*/
@Nullable
private static Artifact getCoverageInstrumentationJarForApk(RuleContext ruleContext)
throws InterruptedException {
return ruleContext.getConfiguration().isCodeCoverageEnabled()
? ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_DEPLOY_JAR)
: null;
}
public static NestedSet<Artifact> getLibraryResourceJars(RuleContext ruleContext) {
Iterable<AndroidLibraryResourceClassJarProvider> libraryResourceJarProviders =
AndroidCommon.getTransitivePrerequisites(
ruleContext, AndroidLibraryResourceClassJarProvider.PROVIDER);
NestedSetBuilder<Artifact> libraryResourceJarsBuilder = NestedSetBuilder.naiveLinkOrder();
for (AndroidLibraryResourceClassJarProvider provider : libraryResourceJarProviders) {
libraryResourceJarsBuilder.addTransitive(provider.getResourceClassJars());
}
return libraryResourceJarsBuilder.build();
}
/** Generates an uncompressed _deploy.jar of all the runtime jars. */
public static Artifact createDeployJar(
RuleContext ruleContext,
JavaSemantics javaSemantics,
AndroidCommon common,
JavaTargetAttributes attributes,
boolean checkDesugarDeps,
Function<Artifact, Artifact> derivedJarFunction)
throws InterruptedException {
Artifact deployJar =
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_DEPLOY_JAR);
new DeployArchiveBuilder(javaSemantics, ruleContext)
.setOutputJar(deployJar)
.setAttributes(attributes)
.addRuntimeJars(common.getRuntimeJars())
.setDerivedJarFunction(derivedJarFunction)
.setCheckDesugarDeps(checkDesugarDeps)
.build();
return deployJar;
}
/**
* Applies the proguard specifications, and creates a ProguardedJar. Proguard's output artifacts
* are added to the given {@code filesBuilder}.
*/
private static ProguardOutput applyProguard(
RuleContext ruleContext,
AndroidCommon common,
JavaSemantics javaSemantics,
Artifact deployJarArtifact,
ImmutableList<Artifact> proguardSpecs,
Artifact proguardMapping,
@Nullable Artifact proguardOutputMap)
throws InterruptedException {
Artifact proguardOutputJar =
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_PROGUARD_JAR);
// Proguard will be only used for binaries which specify a proguard_spec
if (proguardSpecs.isEmpty()) {
// Although normally the Proguard jar artifact is not needed for binaries which do not specify