1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
|
// Copyright (C) 2021 The Android Open Source Project
//
// 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 java
import (
"fmt"
"path/filepath"
"reflect"
"strings"
"android/soong/android"
"android/soong/dexpreopt"
"github.com/google/blueprint/proptools"
"github.com/google/blueprint"
)
func init() {
registerBootclasspathFragmentBuildComponents(android.InitRegistrationContext)
android.RegisterSdkMemberType(&bootclasspathFragmentMemberType{
SdkMemberTypeBase: android.SdkMemberTypeBase{
PropertyName: "bootclasspath_fragments",
SupportsSdk: true,
},
})
}
func registerBootclasspathFragmentBuildComponents(ctx android.RegistrationContext) {
ctx.RegisterModuleType("bootclasspath_fragment", bootclasspathFragmentFactory)
ctx.RegisterModuleType("prebuilt_bootclasspath_fragment", prebuiltBootclasspathFragmentFactory)
}
type bootclasspathFragmentContentDependencyTag struct {
blueprint.BaseDependencyTag
}
// Avoid having to make bootclasspath_fragment content visible to the bootclasspath_fragment.
//
// This is a temporary workaround to make it easier to migrate to bootclasspath_fragment modules
// with proper dependencies.
// TODO(b/177892522): Remove this and add needed visibility.
func (b bootclasspathFragmentContentDependencyTag) ExcludeFromVisibilityEnforcement() {
}
// The bootclasspath_fragment contents must never depend on prebuilts.
func (b bootclasspathFragmentContentDependencyTag) ReplaceSourceWithPrebuilt() bool {
return false
}
// SdkMemberType causes dependencies added with this tag to be automatically added to the sdk as if
// they were specified using java_boot_libs or java_sdk_libs.
func (b bootclasspathFragmentContentDependencyTag) SdkMemberType(child android.Module) android.SdkMemberType {
// If the module is a java_sdk_library then treat it as if it was specified in the java_sdk_libs
// property, otherwise treat if it was specified in the java_boot_libs property.
if javaSdkLibrarySdkMemberType.IsInstance(child) {
return javaSdkLibrarySdkMemberType
}
return javaBootLibsSdkMemberType
}
func (b bootclasspathFragmentContentDependencyTag) ExportMember() bool {
return true
}
// Contents of bootclasspath fragments in an apex are considered to be directly in the apex, as if
// they were listed in java_libs.
func (b bootclasspathFragmentContentDependencyTag) CopyDirectlyInAnyApex() {}
// Contents of bootclasspath fragments require files from prebuilt apex files.
func (b bootclasspathFragmentContentDependencyTag) RequiresFilesFromPrebuiltApex() {}
// The tag used for the dependency between the bootclasspath_fragment module and its contents.
var bootclasspathFragmentContentDepTag = bootclasspathFragmentContentDependencyTag{}
var _ android.ExcludeFromVisibilityEnforcementTag = bootclasspathFragmentContentDepTag
var _ android.ReplaceSourceWithPrebuilt = bootclasspathFragmentContentDepTag
var _ android.SdkMemberTypeDependencyTag = bootclasspathFragmentContentDepTag
var _ android.CopyDirectlyInAnyApexTag = bootclasspathFragmentContentDepTag
var _ android.RequiresFilesFromPrebuiltApexTag = bootclasspathFragmentContentDepTag
func IsBootclasspathFragmentContentDepTag(tag blueprint.DependencyTag) bool {
return tag == bootclasspathFragmentContentDepTag
}
// Properties that can be different when coverage is enabled.
type BootclasspathFragmentCoverageAffectedProperties struct {
// The contents of this bootclasspath_fragment, could be either java_library, or java_sdk_library.
//
// A java_sdk_library specified here will also be treated as if it was specified on the stub_libs
// property.
//
// The order of this list matters as it is the order that is used in the bootclasspath.
Contents []string
// The properties for specifying the API stubs provided by this fragment.
BootclasspathAPIProperties
}
type bootclasspathFragmentProperties struct {
// The name of the image this represents.
//
// If specified then it must be one of "art" or "boot".
Image_name *string
// Properties whose values need to differ with and without coverage.
BootclasspathFragmentCoverageAffectedProperties
Coverage BootclasspathFragmentCoverageAffectedProperties
// Hidden API related properties.
Hidden_api HiddenAPIFlagFileProperties
// Properties that allow a fragment to depend on other fragments. This is needed for hidden API
// processing as it needs access to all the classes used by a fragment including those provided
// by other fragments.
BootclasspathFragmentsDepsProperties
}
type BootclasspathFragmentModule struct {
android.ModuleBase
android.ApexModuleBase
android.SdkBase
ClasspathFragmentBase
properties bootclasspathFragmentProperties
}
// commonBootclasspathFragment defines the methods that are implemented by both source and prebuilt
// bootclasspath fragment modules.
type commonBootclasspathFragment interface {
// produceHiddenAPIOutput produces the all-flags.csv and intermediate files and encodes the flags
// into dex files.
//
// Returns a *HiddenAPIOutput containing the paths for the generated files. Returns nil if the
// module cannot contribute to hidden API processing, e.g. because it is a prebuilt module in a
// versioned sdk.
produceHiddenAPIOutput(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput
// produceBootImageFiles produces the boot image (i.e. .art, .oat and .vdex) files for each of the
// required android.ArchType values in the returned map.
//
// It must return nil if the boot image files cannot be produced for whatever reason.
produceBootImageFiles(ctx android.ModuleContext, imageConfig *bootImageConfig, contents []android.Module) bootImageFilesByArch
}
var _ commonBootclasspathFragment = (*BootclasspathFragmentModule)(nil)
// bootImageFilesByArch is a map from android.ArchType to the paths to the boot image files.
//
// The paths include the .art, .oat and .vdex files, one for each of the modules from which the boot
// image is created.
type bootImageFilesByArch map[android.ArchType]android.Paths
func bootclasspathFragmentFactory() android.Module {
m := &BootclasspathFragmentModule{}
m.AddProperties(&m.properties)
android.InitApexModule(m)
android.InitSdkAwareModule(m)
initClasspathFragment(m, BOOTCLASSPATH)
android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibCommon)
android.AddLoadHook(m, func(ctx android.LoadHookContext) {
// If code coverage has been enabled for the framework then append the properties with
// coverage specific properties.
if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
err := proptools.AppendProperties(&m.properties.BootclasspathFragmentCoverageAffectedProperties, &m.properties.Coverage, nil)
if err != nil {
ctx.PropertyErrorf("coverage", "error trying to append coverage specific properties: %s", err)
return
}
}
// Initialize the contents property from the image_name.
bootclasspathFragmentInitContentsFromImage(ctx, m)
})
return m
}
// bootclasspathFragmentInitContentsFromImage will initialize the contents property from the image_name if
// necessary.
func bootclasspathFragmentInitContentsFromImage(ctx android.EarlyModuleContext, m *BootclasspathFragmentModule) {
contents := m.properties.Contents
if len(contents) == 0 {
ctx.PropertyErrorf("contents", "required property is missing")
return
}
if m.properties.Image_name == nil {
// Nothing to do.
return
}
imageName := proptools.String(m.properties.Image_name)
if imageName != "art" {
ctx.PropertyErrorf("image_name", `unknown image name %q, expected "art"`, imageName)
return
}
// TODO(b/177892522): Prebuilts (versioned or not) should not use the image_name property.
if android.IsModuleInVersionedSdk(m) {
// The module is a versioned prebuilt so ignore it. This is done for a couple of reasons:
// 1. There is no way to use this at the moment so ignoring it is safe.
// 2. Attempting to initialize the contents property from the configuration will end up having
// the versioned prebuilt depending on the unversioned prebuilt. That will cause problems
// as the unversioned prebuilt could end up with an APEX variant created for the source
// APEX which will prevent it from having an APEX variant for the prebuilt APEX which in
// turn will prevent it from accessing the dex implementation jar from that which will
// break hidden API processing, amongst others.
return
}
// Get the configuration for the art apex jars. Do not use getImageConfig(ctx) here as this is
// too early in the Soong processing for that to work.
global := dexpreopt.GetGlobalConfig(ctx)
modules := global.ArtApexJars
// Make sure that the apex specified in the configuration is consistent and is one for which
// this boot image is available.
commonApex := ""
for i := 0; i < modules.Len(); i++ {
apex := modules.Apex(i)
jar := modules.Jar(i)
if apex == "platform" {
ctx.ModuleErrorf("ArtApexJars is invalid as it requests a platform variant of %q", jar)
continue
}
if !m.AvailableFor(apex) {
ctx.ModuleErrorf("ArtApexJars configuration incompatible with this module, ArtApexJars expects this to be in apex %q but this is only in apexes %q",
apex, m.ApexAvailable())
continue
}
if commonApex == "" {
commonApex = apex
} else if commonApex != apex {
ctx.ModuleErrorf("ArtApexJars configuration is inconsistent, expected all jars to be in the same apex but it specifies apex %q and %q",
commonApex, apex)
}
}
}
// bootclasspathImageNameContentsConsistencyCheck checks that the configuration that applies to this
// module (if any) matches the contents.
//
// This should be a noop as if image_name="art" then the contents will be set from the ArtApexJars
// config by bootclasspathFragmentInitContentsFromImage so it will be guaranteed to match. However,
// in future this will not be the case.
func (b *BootclasspathFragmentModule) bootclasspathImageNameContentsConsistencyCheck(ctx android.BaseModuleContext) {
imageName := proptools.String(b.properties.Image_name)
if imageName == "art" {
// TODO(b/177892522): Prebuilts (versioned or not) should not use the image_name property.
if android.IsModuleInVersionedSdk(b) {
// The module is a versioned prebuilt so ignore it. This is done for a couple of reasons:
// 1. There is no way to use this at the moment so ignoring it is safe.
// 2. Attempting to initialize the contents property from the configuration will end up having
// the versioned prebuilt depending on the unversioned prebuilt. That will cause problems
// as the unversioned prebuilt could end up with an APEX variant created for the source
// APEX which will prevent it from having an APEX variant for the prebuilt APEX which in
// turn will prevent it from accessing the dex implementation jar from that which will
// break hidden API processing, amongst others.
return
}
// Get the configuration for the art apex jars.
modules := b.getImageConfig(ctx).modules
configuredJars := modules.CopyOfJars()
// Skip the check if the configured jars list is empty as that is a common configuration when
// building targets that do not result in a system image.
if len(configuredJars) == 0 {
return
}
contents := b.properties.Contents
if !reflect.DeepEqual(configuredJars, contents) {
ctx.ModuleErrorf("inconsistency in specification of contents. ArtApexJars configuration specifies %#v, contents property specifies %#v",
configuredJars, contents)
}
}
}
var BootclasspathFragmentApexContentInfoProvider = blueprint.NewProvider(BootclasspathFragmentApexContentInfo{})
// BootclasspathFragmentApexContentInfo contains the bootclasspath_fragments contributions to the
// apex contents.
type BootclasspathFragmentApexContentInfo struct {
// The configured modules, will be empty if this is from a bootclasspath_fragment that does not
// set image_name: "art".
modules android.ConfiguredJarList
// Map from arch type to the boot image files.
bootImageFilesByArch bootImageFilesByArch
// Map from the base module name (without prebuilt_ prefix) of a fragment's contents module to the
// hidden API encoded dex jar path.
contentModuleDexJarPaths bootDexJarByModule
}
func (i BootclasspathFragmentApexContentInfo) Modules() android.ConfiguredJarList {
return i.modules
}
// Get a map from ArchType to the associated boot image's contents for Android.
//
// Extension boot images only return their own files, not the files of the boot images they extend.
func (i BootclasspathFragmentApexContentInfo) AndroidBootImageFilesByArchType() bootImageFilesByArch {
return i.bootImageFilesByArch
}
// DexBootJarPathForContentModule returns the path to the dex boot jar for specified module.
//
// The dex boot jar is one which has had hidden API encoding performed on it.
func (i BootclasspathFragmentApexContentInfo) DexBootJarPathForContentModule(module android.Module) (android.Path, error) {
// A bootclasspath_fragment cannot use a prebuilt library so Name() will return the base name
// without a prebuilt_ prefix so is safe to use as the key for the contentModuleDexJarPaths.
name := module.Name()
if dexJar, ok := i.contentModuleDexJarPaths[name]; ok {
return dexJar, nil
} else {
return nil, fmt.Errorf("unknown bootclasspath_fragment content module %s, expected one of %s",
name, strings.Join(android.SortedStringKeys(i.contentModuleDexJarPaths), ", "))
}
}
func (b *BootclasspathFragmentModule) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
tag := ctx.OtherModuleDependencyTag(dep)
if IsBootclasspathFragmentContentDepTag(tag) {
// Boot image contents are automatically added to apex.
return true
}
if android.IsMetaDependencyTag(tag) {
// Cross-cutting metadata dependencies are metadata.
return false
}
panic(fmt.Errorf("boot_image module %q should not have a dependency on %q via tag %s", b, dep, android.PrettyPrintTag(tag)))
}
func (b *BootclasspathFragmentModule) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
return nil
}
// ComponentDepsMutator adds dependencies onto modules before any prebuilt modules without a
// corresponding source module are renamed. This means that adding a dependency using a name without
// a prebuilt_ prefix will always resolve to a source module and when using a name with that prefix
// it will always resolve to a prebuilt module.
func (b *BootclasspathFragmentModule) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
module := ctx.Module()
_, isSourceModule := module.(*BootclasspathFragmentModule)
for _, name := range b.properties.Contents {
// A bootclasspath_fragment must depend only on other source modules, while the
// prebuilt_bootclasspath_fragment must only depend on other prebuilt modules.
//
// TODO(b/177892522) - avoid special handling of jacocoagent.
if !isSourceModule && name != "jacocoagent" {
name = android.PrebuiltNameFromSource(name)
}
ctx.AddDependency(module, bootclasspathFragmentContentDepTag, name)
}
}
func (b *BootclasspathFragmentModule) DepsMutator(ctx android.BottomUpMutatorContext) {
// Add dependencies onto all the modules that provide the API stubs for classes on this
// bootclasspath fragment.
hiddenAPIAddStubLibDependencies(ctx, b.properties.apiScopeToStubLibs())
if SkipDexpreoptBootJars(ctx) {
return
}
// Add a dependency onto the dex2oat tool which is needed for creating the boot image. The
// path is retrieved from the dependency by GetGlobalSoongConfig(ctx).
dexpreopt.RegisterToolDeps(ctx)
}
func (b *BootclasspathFragmentModule) BootclasspathDepsMutator(ctx android.BottomUpMutatorContext) {
// Add dependencies on all the fragments.
b.properties.BootclasspathFragmentsDepsProperties.addDependenciesOntoFragments(ctx)
}
func (b *BootclasspathFragmentModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
// Only perform a consistency check if this module is the active module. That will prevent an
// unused prebuilt that was created without instrumentation from breaking an instrumentation
// build.
if isActiveModule(ctx.Module()) {
b.bootclasspathImageNameContentsConsistencyCheck(ctx)
}
// Generate classpaths.proto config
b.generateClasspathProtoBuildActions(ctx)
// Gather the bootclasspath fragment's contents.
var contents []android.Module
ctx.VisitDirectDeps(func(module android.Module) {
tag := ctx.OtherModuleDependencyTag(module)
if IsBootclasspathFragmentContentDepTag(tag) {
contents = append(contents, module)
}
})
fragments := gatherApexModulePairDepsWithTag(ctx, bootclasspathFragmentDepTag)
// Verify that the image_name specified on a bootclasspath_fragment is valid even if this is a
// prebuilt which will not use the image config.
imageConfig := b.getImageConfig(ctx)
// A versioned prebuilt_bootclasspath_fragment cannot and does not need to perform hidden API
// processing. It cannot do it because it is not part of a prebuilt_apex and so has no access to
// the correct dex implementation jar. It does not need to because the platform-bootclasspath
// always references the latest bootclasspath_fragments.
if !android.IsModuleInVersionedSdk(ctx.Module()) {
// Perform hidden API processing.
hiddenAPIOutput := b.generateHiddenAPIBuildActions(ctx, contents, fragments)
var bootImageFilesByArch bootImageFilesByArch
if imageConfig != nil {
// Delegate the production of the boot image files to a module type specific method.
common := ctx.Module().(commonBootclasspathFragment)
bootImageFilesByArch = common.produceBootImageFiles(ctx, imageConfig, contents)
if shouldCopyBootFilesToPredefinedLocations(ctx, imageConfig) {
// Copy the dex jars of this fragment's content modules to their predefined locations.
copyBootJarsToPredefinedLocations(ctx, hiddenAPIOutput.EncodedBootDexFilesByModule, imageConfig.dexPathsByModule)
}
}
// A prebuilt fragment cannot contribute to an apex.
if !android.IsModulePrebuilt(ctx.Module()) {
// Provide the apex content info.
b.provideApexContentInfo(ctx, imageConfig, hiddenAPIOutput, bootImageFilesByArch)
}
}
}
// shouldCopyBootFilesToPredefinedLocations determines whether the current module should copy boot
// files, e.g. boot dex jars or boot image files, to the predefined location expected by the rest
// of the build.
//
// This ensures that only a single module will copy its files to the image configuration.
func shouldCopyBootFilesToPredefinedLocations(ctx android.ModuleContext, imageConfig *bootImageConfig) bool {
// Bootclasspath fragment modules that are for the platform do not produce boot related files.
apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
if apexInfo.IsForPlatform() {
return false
}
// If the image configuration has no modules specified then it means that the build has been
// configured to build something other than a boot image, e.g. an sdk, so do not try and copy the
// files.
if imageConfig.modules.Len() == 0 {
return false
}
// Only copy files from the module that is preferred.
return isActiveModule(ctx.Module())
}
// provideApexContentInfo creates, initializes and stores the apex content info for use by other
// modules.
func (b *BootclasspathFragmentModule) provideApexContentInfo(ctx android.ModuleContext, imageConfig *bootImageConfig, hiddenAPIOutput *HiddenAPIOutput, bootImageFilesByArch bootImageFilesByArch) {
// Construct the apex content info from the config.
info := BootclasspathFragmentApexContentInfo{
// Populate the apex content info with paths to the dex jars.
contentModuleDexJarPaths: hiddenAPIOutput.EncodedBootDexFilesByModule,
}
if imageConfig != nil {
info.modules = imageConfig.modules
}
info.bootImageFilesByArch = bootImageFilesByArch
// Make the apex content info available for other modules.
ctx.SetProvider(BootclasspathFragmentApexContentInfoProvider, info)
}
// generateClasspathProtoBuildActions generates all required build actions for classpath.proto config
func (b *BootclasspathFragmentModule) generateClasspathProtoBuildActions(ctx android.ModuleContext) {
var classpathJars []classpathJar
if "art" == proptools.String(b.properties.Image_name) {
// ART and platform boot jars must have a corresponding entry in DEX2OATBOOTCLASSPATH
classpathJars = configuredJarListToClasspathJars(ctx, b.ClasspathFragmentToConfiguredJarList(ctx), BOOTCLASSPATH, DEX2OATBOOTCLASSPATH)
} else {
classpathJars = configuredJarListToClasspathJars(ctx, b.ClasspathFragmentToConfiguredJarList(ctx), b.classpathType)
}
b.classpathFragmentBase().generateClasspathProtoBuildActions(ctx, classpathJars)
}
func (b *BootclasspathFragmentModule) ClasspathFragmentToConfiguredJarList(ctx android.ModuleContext) android.ConfiguredJarList {
if "art" == proptools.String(b.properties.Image_name) {
return b.getImageConfig(ctx).modules
}
global := dexpreopt.GetGlobalConfig(ctx)
// Convert content names to their appropriate stems, in case a test library is overriding an actual boot jar
var stems []string
for _, name := range b.properties.Contents {
dep := ctx.GetDirectDepWithTag(name, bootclasspathFragmentContentDepTag)
if m, ok := dep.(ModuleWithStem); ok {
stems = append(stems, m.Stem())
} else {
ctx.PropertyErrorf("contents", "%v is not a ModuleWithStem", name)
}
}
// Only create configs for updatable boot jars. Non-updatable boot jars must be part of the
// platform_bootclasspath's classpath proto config to guarantee that they come before any
// updatable jars at runtime.
jars := global.UpdatableBootJars.Filter(stems)
// TODO(satayev): for apex_test we want to include all contents unconditionally to classpaths
// config. However, any test specific jars would not be present in UpdatableBootJars. Instead,
// we should check if we are creating a config for apex_test via ApexInfo and amend the values.
// This is an exception to support end-to-end test for SdkExtensions, until such support exists.
if android.InList("test_framework-sdkextensions", stems) {
jars = jars.Append("com.android.sdkext", "test_framework-sdkextensions")
}
return jars
}
func (b *BootclasspathFragmentModule) getImageConfig(ctx android.EarlyModuleContext) *bootImageConfig {
// Get a map of the image configs that are supported.
imageConfigs := genBootImageConfigs(ctx)
// Retrieve the config for this image.
imageNamePtr := b.properties.Image_name
if imageNamePtr == nil {
return nil
}
imageName := *imageNamePtr
imageConfig := imageConfigs[imageName]
if imageConfig == nil {
ctx.PropertyErrorf("image_name", "Unknown image name %q, expected one of %s", imageName, strings.Join(android.SortedStringKeys(imageConfigs), ", "))
return nil
}
return imageConfig
}
// generateHiddenAPIBuildActions generates all the hidden API related build rules.
func (b *BootclasspathFragmentModule) generateHiddenAPIBuildActions(ctx android.ModuleContext, contents []android.Module, fragments []android.Module) *HiddenAPIOutput {
// Create hidden API input structure.
input := b.createHiddenAPIFlagInput(ctx, contents, fragments)
var output *HiddenAPIOutput
// Hidden API processing is conditional as a temporary workaround as not all
// bootclasspath_fragments provide the appropriate information needed for hidden API processing
// which leads to breakages of the build.
// TODO(b/179354495): Stop hidden API processing being conditional once all bootclasspath_fragment
// modules have been updated to support it.
if input.canPerformHiddenAPIProcessing(ctx, b.properties) {
// Delegate the production of the hidden API all-flags.csv file to a module type specific method.
common := ctx.Module().(commonBootclasspathFragment)
output = common.produceHiddenAPIOutput(ctx, contents, input)
} else {
// As hidden API processing cannot be performed fall back to trying to retrieve the legacy
// encoded boot dex files, i.e. those files encoded by the individual libraries and returned
// from the DexJarBuildPath() method.
output = &HiddenAPIOutput{
EncodedBootDexFilesByModule: retrieveLegacyEncodedBootDexFiles(ctx, contents),
}
}
// Initialize a HiddenAPIInfo structure.
hiddenAPIInfo := HiddenAPIInfo{
// The monolithic hidden API processing needs access to the flag files that override the default
// flags from all the fragments whether or not they actually perform their own hidden API flag
// generation. That is because the monolithic hidden API processing uses those flag files to
// perform its own flag generation.
FlagFilesByCategory: input.FlagFilesByCategory,
// Other bootclasspath_fragments that depend on this need the transitive set of stub dex jars
// from this to resolve any references from their code to classes provided by this fragment
// and the fragments this depends upon.
TransitiveStubDexJarsByScope: input.transitiveStubDexJarsByScope(),
}
// The monolithic hidden API processing also needs access to all the output files produced by
// hidden API processing of this fragment.
hiddenAPIInfo.HiddenAPIFlagOutput = (*output).HiddenAPIFlagOutput
// Provide it for use by other modules.
ctx.SetProvider(HiddenAPIInfoProvider, hiddenAPIInfo)
return output
}
// retrieveLegacyEncodedBootDexFiles attempts to retrieve the legacy encoded boot dex jar files.
func retrieveLegacyEncodedBootDexFiles(ctx android.ModuleContext, contents []android.Module) bootDexJarByModule {
// If the current bootclasspath_fragment is the active module or a source module then retrieve the
// encoded dex files, otherwise return an empty map.
//
// An inactive (i.e. not preferred) bootclasspath_fragment needs to retrieve the encoded dex jars
// as they are still needed by an apex. An inactive prebuilt_bootclasspath_fragment does not need
// to do so and may not yet have access to dex boot jars from a prebuilt_apex/apex_set.
if isActiveModule(ctx.Module()) || !android.IsModulePrebuilt(ctx.Module()) {
return extractEncodedDexJarsFromModules(ctx, contents)
} else {
return nil
}
}
// createHiddenAPIFlagInput creates a HiddenAPIFlagInput struct and initializes it with information derived
// from the properties on this module and its dependencies.
func (b *BootclasspathFragmentModule) createHiddenAPIFlagInput(ctx android.ModuleContext, contents []android.Module, fragments []android.Module) HiddenAPIFlagInput {
// Merge the HiddenAPIInfo from all the fragment dependencies.
dependencyHiddenApiInfo := newHiddenAPIInfo()
dependencyHiddenApiInfo.mergeFromFragmentDeps(ctx, fragments)
// Create hidden API flag input structure.
input := newHiddenAPIFlagInput()
// Update the input structure with information obtained from the stub libraries.
input.gatherStubLibInfo(ctx, contents)
// Populate with flag file paths from the properties.
input.extractFlagFilesFromProperties(ctx, &b.properties.Hidden_api)
// Store the stub dex jars from this module's fragment dependencies.
input.DependencyStubDexJarsByScope = dependencyHiddenApiInfo.TransitiveStubDexJarsByScope
return input
}
// produceHiddenAPIOutput produces the hidden API all-flags.csv file (and supporting files)
// for the fragment as well as encoding the flags in the boot dex jars.
func (b *BootclasspathFragmentModule) produceHiddenAPIOutput(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput {
// Generate the rules to create the hidden API flags and update the supplied hiddenAPIInfo with the
// paths to the created files.
return hiddenAPIRulesForBootclasspathFragment(ctx, contents, input)
}
// produceBootImageFiles builds the boot image files from the source if it is required.
func (b *BootclasspathFragmentModule) produceBootImageFiles(ctx android.ModuleContext, imageConfig *bootImageConfig, contents []android.Module) bootImageFilesByArch {
if SkipDexpreoptBootJars(ctx) {
return nil
}
// Force the GlobalSoongConfig to be created and cached for use by the dex_bootjars
// GenerateSingletonBuildActions method as it cannot create it for itself.
dexpreopt.GetGlobalSoongConfig(ctx)
// Only generate the boot image if the configuration does not skip it.
if !b.generateBootImageBuildActions(ctx, contents, imageConfig) {
return nil
}
// Only make the files available to an apex if they were actually generated.
files := bootImageFilesByArch{}
for _, variant := range imageConfig.apexVariants() {
files[variant.target.Arch.ArchType] = variant.imagesDeps.Paths()
}
return files
}
// generateBootImageBuildActions generates ninja rules to create the boot image if required for this
// module.
//
// Returns true if the boot image is created, false otherwise.
func (b *BootclasspathFragmentModule) generateBootImageBuildActions(ctx android.ModuleContext, contents []android.Module, imageConfig *bootImageConfig) bool {
global := dexpreopt.GetGlobalConfig(ctx)
if !shouldBuildBootImages(ctx.Config(), global) {
return false
}
// Bootclasspath fragment modules that are for the platform do not produce a boot image.
apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
if apexInfo.IsForPlatform() {
return false
}
// Bootclasspath fragment modules that are versioned do not produce a boot image.
if android.IsModuleInVersionedSdk(ctx.Module()) {
return false
}
// Build a profile for the image config and then use that to build the boot image.
profile := bootImageProfileRule(ctx, imageConfig)
buildBootImage(ctx, imageConfig, profile)
return true
}
type bootclasspathFragmentMemberType struct {
android.SdkMemberTypeBase
}
func (b *bootclasspathFragmentMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
mctx.AddVariationDependencies(nil, dependencyTag, names...)
}
func (b *bootclasspathFragmentMemberType) IsInstance(module android.Module) bool {
_, ok := module.(*BootclasspathFragmentModule)
return ok
}
func (b *bootclasspathFragmentMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
if b.PropertyName == "boot_images" {
return ctx.SnapshotBuilder().AddPrebuiltModule(member, "prebuilt_boot_image")
} else {
return ctx.SnapshotBuilder().AddPrebuiltModule(member, "prebuilt_bootclasspath_fragment")
}
}
func (b *bootclasspathFragmentMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
return &bootclasspathFragmentSdkMemberProperties{}
}
type bootclasspathFragmentSdkMemberProperties struct {
android.SdkMemberPropertiesBase
// The image name
Image_name *string
// Contents of the bootclasspath fragment
Contents []string
// Stub_libs properties.
Stub_libs []string
Core_platform_stub_libs []string
// Flag files by *hiddenAPIFlagFileCategory
Flag_files_by_category FlagFilesByCategory
// The path to the generated stub-flags.csv file.
Stub_flags_path android.OptionalPath
// The path to the generated annotation-flags.csv file.
Annotation_flags_path android.OptionalPath
// The path to the generated metadata.csv file.
Metadata_path android.OptionalPath
// The path to the generated index.csv file.
Index_path android.OptionalPath
// The path to the generated all-flags.csv file.
All_flags_path android.OptionalPath
}
func (b *bootclasspathFragmentSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
module := variant.(*BootclasspathFragmentModule)
b.Image_name = module.properties.Image_name
b.Contents = module.properties.Contents
// Get the hidden API information from the module.
mctx := ctx.SdkModuleContext()
hiddenAPIInfo := mctx.OtherModuleProvider(module, HiddenAPIInfoProvider).(HiddenAPIInfo)
b.Flag_files_by_category = hiddenAPIInfo.FlagFilesByCategory
// Copy all the generated file paths.
b.Stub_flags_path = android.OptionalPathForPath(hiddenAPIInfo.StubFlagsPath)
b.Annotation_flags_path = android.OptionalPathForPath(hiddenAPIInfo.AnnotationFlagsPath)
b.Metadata_path = android.OptionalPathForPath(hiddenAPIInfo.MetadataPath)
b.Index_path = android.OptionalPathForPath(hiddenAPIInfo.IndexPath)
b.All_flags_path = android.OptionalPathForPath(hiddenAPIInfo.AllFlagsPath)
// Copy stub_libs properties.
b.Stub_libs = module.properties.Api.Stub_libs
b.Core_platform_stub_libs = module.properties.Core_platform_api.Stub_libs
}
func (b *bootclasspathFragmentSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
if b.Image_name != nil {
propertySet.AddProperty("image_name", *b.Image_name)
}
builder := ctx.SnapshotBuilder()
requiredMemberDependency := builder.SdkMemberReferencePropertyTag(true)
if len(b.Contents) > 0 {
propertySet.AddPropertyWithTag("contents", b.Contents, requiredMemberDependency)
}
if len(b.Stub_libs) > 0 {
apiPropertySet := propertySet.AddPropertySet("api")
apiPropertySet.AddPropertyWithTag("stub_libs", b.Stub_libs, requiredMemberDependency)
}
if len(b.Core_platform_stub_libs) > 0 {
corePlatformApiPropertySet := propertySet.AddPropertySet("core_platform_api")
corePlatformApiPropertySet.AddPropertyWithTag("stub_libs", b.Core_platform_stub_libs, requiredMemberDependency)
}
hiddenAPISet := propertySet.AddPropertySet("hidden_api")
hiddenAPIDir := "hiddenapi"
// Copy manually curated flag files specified on the bootclasspath_fragment.
if b.Flag_files_by_category != nil {
for _, category := range HiddenAPIFlagFileCategories {
paths := b.Flag_files_by_category[category]
if len(paths) > 0 {
dests := []string{}
for _, p := range paths {
dest := filepath.Join(hiddenAPIDir, p.Base())
builder.CopyToSnapshot(p, dest)
dests = append(dests, dest)
}
hiddenAPISet.AddProperty(category.PropertyName, dests)
}
}
}
copyOptionalPath := func(path android.OptionalPath, property string) {
if path.Valid() {
p := path.Path()
dest := filepath.Join(hiddenAPIDir, p.Base())
builder.CopyToSnapshot(p, dest)
hiddenAPISet.AddProperty(property, dest)
}
}
// Copy all the generated files, if available.
copyOptionalPath(b.Stub_flags_path, "stub_flags")
copyOptionalPath(b.Annotation_flags_path, "annotation_flags")
copyOptionalPath(b.Metadata_path, "metadata")
copyOptionalPath(b.Index_path, "index")
copyOptionalPath(b.All_flags_path, "all_flags")
}
var _ android.SdkMemberType = (*bootclasspathFragmentMemberType)(nil)
// prebuiltBootclasspathFragmentProperties contains additional prebuilt_bootclasspath_fragment
// specific properties.
type prebuiltBootclasspathFragmentProperties struct {
Hidden_api struct {
// The path to the stub-flags.csv file created by the bootclasspath_fragment.
Stub_flags *string `android:"path"`
// The path to the annotation-flags.csv file created by the bootclasspath_fragment.
Annotation_flags *string `android:"path"`
// The path to the metadata.csv file created by the bootclasspath_fragment.
Metadata *string `android:"path"`
// The path to the index.csv file created by the bootclasspath_fragment.
Index *string `android:"path"`
// The path to the all-flags.csv file created by the bootclasspath_fragment.
All_flags *string `android:"path"`
}
}
// A prebuilt version of the bootclasspath_fragment module.
//
// At the moment this is basically just a bootclasspath_fragment module that can be used as a
// prebuilt. Eventually as more functionality is migrated into the bootclasspath_fragment module
// type from the various singletons then this will diverge.
type prebuiltBootclasspathFragmentModule struct {
BootclasspathFragmentModule
prebuilt android.Prebuilt
// Additional prebuilt specific properties.
prebuiltProperties prebuiltBootclasspathFragmentProperties
}
func (module *prebuiltBootclasspathFragmentModule) Prebuilt() *android.Prebuilt {
return &module.prebuilt
}
func (module *prebuiltBootclasspathFragmentModule) Name() string {
return module.prebuilt.Name(module.ModuleBase.Name())
}
// produceHiddenAPIOutput returns a path to the prebuilt all-flags.csv or nil if none is specified.
func (module *prebuiltBootclasspathFragmentModule) produceHiddenAPIOutput(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput {
pathForOptionalSrc := func(src *string) android.Path {
if src == nil {
// TODO(b/179354495): Fail if this is not provided once prebuilts have been updated.
return nil
}
return android.PathForModuleSrc(ctx, *src)
}
// Retrieve the dex files directly from the content modules. They in turn should retrieve the
// encoded dex jars from the prebuilt .apex files.
encodedBootDexJarsByModule := extractEncodedDexJarsFromModules(ctx, contents)
output := HiddenAPIOutput{
HiddenAPIFlagOutput: HiddenAPIFlagOutput{
StubFlagsPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Stub_flags),
AnnotationFlagsPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Annotation_flags),
MetadataPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Metadata),
IndexPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Index),
AllFlagsPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.All_flags),
},
EncodedBootDexFilesByModule: encodedBootDexJarsByModule,
}
return &output
}
// produceBootImageFiles extracts the boot image files from the APEX if available.
func (module *prebuiltBootclasspathFragmentModule) produceBootImageFiles(ctx android.ModuleContext, imageConfig *bootImageConfig, contents []android.Module) bootImageFilesByArch {
if !shouldCopyBootFilesToPredefinedLocations(ctx, imageConfig) {
return nil
}
var deapexerModule android.Module
ctx.VisitDirectDeps(func(module android.Module) {
tag := ctx.OtherModuleDependencyTag(module)
// Save away the `deapexer` module on which this depends, if any.
if tag == android.DeapexerTag {
deapexerModule = module
}
})
if deapexerModule == nil {
// This should never happen as a variant for a prebuilt_apex is only created if the
// deapexer module has been configured to export the dex implementation jar for this module.
ctx.ModuleErrorf("internal error: module does not depend on a `deapexer` module")
return nil
}
di := ctx.OtherModuleProvider(deapexerModule, android.DeapexerProvider).(android.DeapexerInfo)
for _, variant := range imageConfig.apexVariants() {
arch := variant.target.Arch.ArchType
for _, toPath := range variant.imagesDeps {
apexRelativePath := apexRootRelativePathToBootImageFile(arch, toPath.Base())
// Get the path to the file that the deapexer extracted from the prebuilt apex file.
fromPath := di.PrebuiltExportPath(apexRelativePath)
// Copy the file to the predefined location.
ctx.Build(pctx, android.BuildParams{
Rule: android.Cp,
Input: fromPath,
Output: toPath,
})
}
}
// The returned files will be made available to APEXes that include a bootclasspath_fragment.
// However, as a prebuilt_bootclasspath_fragment can never contribute to an APEX there is no point
// in returning any files.
return nil
}
var _ commonBootclasspathFragment = (*prebuiltBootclasspathFragmentModule)(nil)
// createBootImageTag creates the tag to uniquely identify the boot image file among all of the
// files that a module requires from the prebuilt .apex file.
func createBootImageTag(arch android.ArchType, baseName string) string {
tag := fmt.Sprintf(".bootimage-%s-%s", arch, baseName)
return tag
}
// RequiredFilesFromPrebuiltApex returns the list of all files the prebuilt_bootclasspath_fragment
// requires from a prebuilt .apex file.
//
// If there is no image config associated with this fragment then it returns nil. Otherwise, it
// returns the files that are listed in the image config.
func (module *prebuiltBootclasspathFragmentModule) RequiredFilesFromPrebuiltApex(ctx android.BaseModuleContext) []string {
imageConfig := module.getImageConfig(ctx)
if imageConfig != nil {
// Add the boot image files, e.g. .art, .oat and .vdex files.
files := []string{}
for _, variant := range imageConfig.apexVariants() {
arch := variant.target.Arch.ArchType
for _, path := range variant.imagesDeps.Paths() {
base := path.Base()
files = append(files, apexRootRelativePathToBootImageFile(arch, base))
}
}
return files
}
return nil
}
func apexRootRelativePathToBootImageFile(arch android.ArchType, base string) string {
return filepath.Join("javalib", arch.String(), base)
}
var _ android.RequiredFilesFromPrebuiltApex = (*prebuiltBootclasspathFragmentModule)(nil)
func prebuiltBootclasspathFragmentFactory() android.Module {
m := &prebuiltBootclasspathFragmentModule{}
m.AddProperties(&m.properties, &m.prebuiltProperties)
// This doesn't actually have any prebuilt files of its own so pass a placeholder for the srcs
// array.
android.InitPrebuiltModule(m, &[]string{"placeholder"})
android.InitApexModule(m)
android.InitSdkAwareModule(m)
android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibCommon)
// Initialize the contents property from the image_name.
android.AddLoadHook(m, func(ctx android.LoadHookContext) {
bootclasspathFragmentInitContentsFromImage(ctx, &m.BootclasspathFragmentModule)
})
return m
}
|