blob: d9c57c375ba3b1059f9f1e723d9a3fe9600076aa [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Paul Duffin3e7d3ca2021-09-09 16:37:49 +010025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
36// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
38//
Paul Duffin973bedb2021-05-05 22:00:51 +010039// SOONG_SDK_SNAPSHOT_VERSION
40// This provides control over the version of the generated snapshot.
41//
42// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
43// versioned snapshot module. This is the default behavior. The zip file containing the
44// generated snapshot will be <sdk-name>-current.zip.
45//
46// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
47// file containing the generated snapshot will be <sdk-name>.zip.
48//
49// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
50// snapshot module only. The zip file containing the generated snapshot will be
51// <sdk-name>-<number>.zip.
52//
Paul Duffin24c545e2021-09-24 14:58:27 +010053// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
54// This allows the target build release (i.e. the release version of the build within which
55// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
56// to the current build release version. Otherwise, it must be the name of one of the build
57// releases defined in nameToBuildRelease, e.g. S, T, etc..
58//
59// The generated snapshot must only be used in the specified target release. If the target
60// build release is not the current build release then the generated Android.bp file not be
61// checked for compatibility.
62//
63// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
64// to be compatible with S.
65//
Paul Duffin64fb5262021-05-05 21:36:04 +010066
Jiyong Park9b409bc2019-10-11 14:59:13 +090067var pctx = android.NewPackageContext("android/soong/sdk")
68
Paul Duffin375058f2019-11-29 20:17:53 +000069var (
70 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
71 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000072 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000073 CommandDeps: []string{
74 "${config.Zip2ZipCmd}",
75 },
76 },
77 "destdir")
78
79 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
80 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070081 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000082 CommandDeps: []string{
83 "${config.SoongZipCmd}",
84 },
85 Rspfile: "$out.rsp",
86 RspfileContent: "$in",
87 },
88 "basedir")
89
90 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
91 blueprint.RuleParams{
92 Command: `${config.MergeZipsCmd} $out $in`,
93 CommandDeps: []string{
94 "${config.MergeZipsCmd}",
95 },
96 })
97)
98
Paul Duffin973bedb2021-05-05 22:00:51 +010099const (
100 soongSdkSnapshotVersionUnversioned = "unversioned"
101 soongSdkSnapshotVersionCurrent = "current"
102)
103
Paul Duffinb645ec82019-11-27 17:43:54 +0000104type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900105 content strings.Builder
106 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900107}
108
Paul Duffinb645ec82019-11-27 17:43:54 +0000109// generatedFile abstracts operations for writing contents into a file and emit a build rule
110// for the file.
111type generatedFile struct {
112 generatedContents
113 path android.OutputPath
114}
115
Jiyong Park232e7852019-11-04 12:23:40 +0900116func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900117 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000118 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900119 }
120}
121
Paul Duffinb645ec82019-11-27 17:43:54 +0000122func (gc *generatedContents) Indent() {
123 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900124}
125
Paul Duffinb645ec82019-11-27 17:43:54 +0000126func (gc *generatedContents) Dedent() {
127 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128}
129
Paul Duffinb645ec82019-11-27 17:43:54 +0000130func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +0100131 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900132}
133
134func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800135 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100136
137 content := gf.content.String()
138
139 // ninja consumes newline characters in rspfile_content. Prevent it by
140 // escaping the backslash in the newline character. The extra backslash
141 // is removed when the rspfile is written to the actual script file
142 content = strings.ReplaceAll(content, "\n", "\\n")
143
Jiyong Park9b409bc2019-10-11 14:59:13 +0900144 rb.Command().
145 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100146 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100147 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900148 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
149 rb.Command().
150 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800151 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900152}
153
Paul Duffin13879572019-11-28 14:31:38 +0000154// Collect all the members.
155//
Paul Duffina1aa7382021-04-29 21:50:40 +0100156// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
157// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000158func (s *sdk) collectMembers(ctx android.ModuleContext) {
159 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000160 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
161 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000162 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100163 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900164
Paul Duffinb3821fe2021-05-26 10:16:01 +0100165 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
166 if memberType == nil {
167 return false
168 }
169
Paul Duffin13879572019-11-28 14:31:38 +0000170 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000171 if !memberType.IsInstance(child) {
172 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900173 }
Paul Duffin13879572019-11-28 14:31:38 +0000174
Paul Duffin6a7e9532020-03-20 17:50:07 +0000175 // Keep track of which multilib variants are used by the sdk.
176 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
177
Paul Duffina1aa7382021-04-29 21:50:40 +0100178 var exportedComponentsInfo android.ExportedComponentsInfo
179 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
180 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
181 }
182
Paul Duffina7208112021-04-23 21:20:20 +0100183 export := memberTag.ExportMember()
Paul Duffina1aa7382021-04-29 21:50:40 +0100184 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
185 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
186 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000187
Paul Duffin2d3da312021-05-06 12:02:27 +0100188 // Recurse down into the member's dependencies as it may have dependencies that need to be
189 // automatically added to the sdk.
190 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900191 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000192
193 return false
Paul Duffin13879572019-11-28 14:31:38 +0000194 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000195}
196
Paul Duffincc3132e2021-04-24 01:10:30 +0100197// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
198// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000199//
Paul Duffincc3132e2021-04-24 01:10:30 +0100200// The sdkMember instances are then grouped into slices by member type. Within each such slice the
201// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000202//
Paul Duffincc3132e2021-04-24 01:10:30 +0100203// Finally, the member type slices are concatenated together to form a single slice. The order in
204// which they are concatenated is the order in which the member types were registered in the
205// android.SdkMemberTypesRegistry.
206func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000207 byType := make(map[android.SdkMemberType][]*sdkMember)
208 byName := make(map[string]*sdkMember)
209
Paul Duffin21827262021-04-24 12:16:36 +0100210 for _, memberVariantDep := range memberVariantDeps {
211 memberType := memberVariantDep.memberType
212 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000213
214 name := ctx.OtherModuleName(variant)
215 member := byName[name]
216 if member == nil {
217 member = &sdkMember{memberType: memberType, name: name}
218 byName[name] = member
219 byType[memberType] = append(byType[memberType], member)
220 }
221
Paul Duffin1356d8c2020-02-25 19:26:33 +0000222 // Only append new variants to the list. This is needed because a member can be both
223 // exported by the sdk and also be a transitive sdk member.
224 member.variants = appendUniqueVariants(member.variants, variant)
225 }
226
Paul Duffin13879572019-11-28 14:31:38 +0000227 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000228 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000229 membersOfType := byType[memberListProperty.memberType]
230 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900231 }
232
Paul Duffin6a7e9532020-03-20 17:50:07 +0000233 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900234}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900235
Paul Duffin72910952020-01-20 18:16:30 +0000236func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
237 for _, v := range variants {
238 if v == newVariant {
239 return variants
240 }
241 }
242 return append(variants, newVariant)
243}
244
Jiyong Park73c54ee2019-10-22 20:31:18 +0900245// SDK directory structure
246// <sdk_root>/
247// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
248// <api_ver>/ : below this directory are all auto-generated
249// Android.bp : definition of 'sdk_snapshot' module is here
250// aidl/
251// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
252// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900253// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900254// include/
255// bionic/libc/include/stdlib.h : an exported header file
256// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900257// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900258// <arch>/include/ : arch-specific exported headers
259// <arch>/include_gen/ : arch-specific generated headers
260// <arch>/lib/
261// libFoo.so : a stub library
262
Jiyong Park232e7852019-11-04 12:23:40 +0900263// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900264// This isn't visible to users, so could be changed in future.
265func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
266 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
267}
268
Jiyong Park232e7852019-11-04 12:23:40 +0900269// buildSnapshot is the main function in this source file. It creates rules to copy
270// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000271func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
272
Paul Duffina1aa7382021-04-29 21:50:40 +0100273 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100274 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100275 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000276 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100277 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffina1aa7382021-04-29 21:50:40 +0100278 }
Paul Duffin865171e2020-03-02 18:38:15 +0000279
Paul Duffina1aa7382021-04-29 21:50:40 +0100280 // Filter out any sdkMemberVariantDep that is a component of another.
281 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000282
Paul Duffina1aa7382021-04-29 21:50:40 +0100283 // Record the names of all the members, both explicitly specified and implicitly
284 // included.
285 allMembersByName := make(map[string]struct{})
286 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100287
Paul Duffina1aa7382021-04-29 21:50:40 +0100288 addMember := func(name string, export bool) {
289 allMembersByName[name] = struct{}{}
290 if export {
291 exportedMembersByName[name] = struct{}{}
292 }
293 }
294
295 for _, memberVariantDep := range memberVariantDeps {
296 name := memberVariantDep.variant.Name()
297 export := memberVariantDep.export
298
299 addMember(name, export)
300
301 // Add any components provided by the module.
302 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
303 addMember(component, export)
304 }
305
306 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
307 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000308 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000309 }
310
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000311 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900312
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000313 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000314
315 bpFile := &bpFile{
316 modules: make(map[string]*bpModule),
317 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000318
Paul Duffin973bedb2021-05-05 22:00:51 +0100319 config := ctx.Config()
320 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
321
322 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
323 generateVersioned := version != soongSdkSnapshotVersionUnversioned
324
325 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
326 //
327 // Unversioned modules are not required in that case because the numbered version will be a
328 // finalized version of the snapshot that is intended to be kept separate from the
329 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
330 snapshotZipFileSuffix := ""
331 if generateVersioned {
332 snapshotZipFileSuffix = "-" + version
333 }
334
Paul Duffin24c545e2021-09-24 14:58:27 +0100335 currentBuildRelease := latestBuildRelease()
336 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
337 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
338 if err != nil {
339 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
340 targetBuildRelease = currentBuildRelease
341 }
342
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000343 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000344 ctx: ctx,
345 sdk: s,
Paul Duffin973bedb2021-05-05 22:00:51 +0100346 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000347 snapshotDir: snapshotDir.OutputPath,
348 copies: make(map[string]string),
349 filesToZip: []android.Path{bp.path},
350 bpFile: bpFile,
351 prebuiltModules: make(map[string]*bpModule),
352 allMembersByName: allMembersByName,
353 exportedMembersByName: exportedMembersByName,
Paul Duffin24c545e2021-09-24 14:58:27 +0100354 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900355 }
Paul Duffinac37c502019-11-26 18:02:20 +0000356 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900357
Paul Duffin62131702021-05-07 01:10:01 +0100358 // If the sdk snapshot includes any license modules then add a package module which has a
359 // default_applicable_licenses property. That will prevent the LSC license process from updating
360 // the generated Android.bp file to add a package module that includes all licenses used by all
361 // the modules in that package. That would be unnecessary as every module in the sdk should have
362 // their own licenses property specified.
363 if hasLicenses {
364 pkg := bpFile.newModule("package")
365 property := "default_applicable_licenses"
366 pkg.AddCommentForProperty(property, `
367A default list here prevents the license LSC from adding its own list which would
368be unnecessary as every module in the sdk already has its own licenses property.
369`)
370 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
371 bpFile.AddModule(pkg)
372 }
373
Paul Duffin0df49682021-05-07 01:10:01 +0100374 // Group the variants for each member module together and then group the members of each member
375 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100376 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100377
378 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000379 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000380 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000381
Paul Duffina551a1c2020-03-17 21:04:24 +0000382 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000383
384 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100385 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900386 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900387
Paul Duffine6c0d842020-01-15 14:08:51 +0000388 // Create a transformer that will transform an unversioned module into a versioned module.
389 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
390
Paul Duffin72910952020-01-20 18:16:30 +0000391 // Create a transformer that will transform an unversioned module by replacing any references
392 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100393 unversionedTransformer := unversionedTransformation{
394 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100395 }
Paul Duffin72910952020-01-20 18:16:30 +0000396
Paul Duffinb645ec82019-11-27 17:43:54 +0000397 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000398 // Prune any empty property sets.
399 unversioned = unversioned.transform(pruneEmptySetTransformer{})
400
Paul Duffin973bedb2021-05-05 22:00:51 +0100401 if generateVersioned {
402 // Copy the unversioned module so it can be modified to make it versioned.
403 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000404
Paul Duffin973bedb2021-05-05 22:00:51 +0100405 // Transform the unversioned module into a versioned one.
406 versioned.transform(unversionedToVersionedTransformer)
407 bpFile.AddModule(versioned)
408 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000409
Paul Duffin973bedb2021-05-05 22:00:51 +0100410 if generateUnversioned {
411 // Transform the unversioned module to make it suitable for use in the snapshot.
412 unversioned.transform(unversionedTransformer)
413 bpFile.AddModule(unversioned)
414 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000415 }
416
Paul Duffin973bedb2021-05-05 22:00:51 +0100417 if generateVersioned {
418 // Add the sdk/module_exports_snapshot module to the bp file.
419 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
420 }
Paul Duffin26197a62021-04-24 00:34:10 +0100421
422 // generate Android.bp
423 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
424 generateBpContents(&bp.generatedContents, bpFile)
425
426 contents := bp.content.String()
Paul Duffin24c545e2021-09-24 14:58:27 +0100427 // If the snapshot is being generated for the current build release then check the syntax to make
428 // sure that it is compatible.
429 if targetBuildRelease == currentBuildRelease {
430 syntaxCheckSnapshotBpFile(ctx, contents)
431 }
Paul Duffin26197a62021-04-24 00:34:10 +0100432
433 bp.build(pctx, ctx, nil)
434
435 filesToZip := builder.filesToZip
436
437 // zip them all
Paul Duffin973bedb2021-05-05 22:00:51 +0100438 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
439 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100440 outputDesc := "Building snapshot for " + ctx.ModuleName()
441
442 // If there are no zips to merge then generate the output zip directly.
443 // Otherwise, generate an intermediate zip file into which other zips can be
444 // merged.
445 var zipFile android.OutputPath
446 var desc string
447 if len(builder.zipsToMerge) == 0 {
448 zipFile = outputZipFile
449 desc = outputDesc
450 } else {
Paul Duffin973bedb2021-05-05 22:00:51 +0100451 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
452 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100453 desc = "Building intermediate snapshot for " + ctx.ModuleName()
454 }
455
456 ctx.Build(pctx, android.BuildParams{
457 Description: desc,
458 Rule: zipFiles,
459 Inputs: filesToZip,
460 Output: zipFile,
461 Args: map[string]string{
462 "basedir": builder.snapshotDir.String(),
463 },
464 })
465
466 if len(builder.zipsToMerge) != 0 {
467 ctx.Build(pctx, android.BuildParams{
468 Description: outputDesc,
469 Rule: mergeZips,
470 Input: zipFile,
471 Inputs: builder.zipsToMerge,
472 Output: outputZipFile,
473 })
474 }
475
476 return outputZipFile
477}
478
Paul Duffina1aa7382021-04-29 21:50:40 +0100479// filterOutComponents removes any item from the deps list that is a component of another item in
480// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
481// then it will remove "foo.stubs" from the deps.
482func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
483 // Collate the set of components that all the modules added to the sdk provide.
484 components := map[string]*sdkMemberVariantDep{}
485 for i, _ := range deps {
486 dep := &deps[i]
487 for _, c := range dep.exportedComponentsInfo.Components {
488 components[c] = dep
489 }
490 }
491
492 // If no module provides components then return the input deps unfiltered.
493 if len(components) == 0 {
494 return deps
495 }
496
497 filtered := make([]sdkMemberVariantDep, 0, len(deps))
498 for _, dep := range deps {
499 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
500 if owner, ok := components[name]; ok {
501 // This is a component of another module that is a member of the sdk.
502
503 // If the component is exported but the owning module is not then the configuration is not
504 // supported.
505 if dep.export && !owner.export {
506 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
507 continue
508 }
509
510 // This module must not be added to the list of members of the sdk as that would result in a
511 // duplicate module in the sdk snapshot.
512 continue
513 }
514
515 filtered = append(filtered, dep)
516 }
517 return filtered
518}
519
Paul Duffin26197a62021-04-24 00:34:10 +0100520// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100521func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100522 bpFile := builder.bpFile
523
Paul Duffinb645ec82019-11-27 17:43:54 +0000524 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000525 var snapshotModuleType string
526 if s.properties.Module_exports {
527 snapshotModuleType = "module_exports_snapshot"
528 } else {
529 snapshotModuleType = "sdk_snapshot"
530 }
531 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000532 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000533
534 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100535 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000536 if len(visibility) != 0 {
537 snapshotModule.AddProperty("visibility", visibility)
538 }
539
Paul Duffin865171e2020-03-02 18:38:15 +0000540 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000541
Paul Duffincd064672021-04-24 00:47:29 +0100542 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100543 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000544
Paul Duffin2d1bb892021-04-24 11:32:59 +0100545 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100546
Paul Duffin6a7e9532020-03-20 17:50:07 +0000547 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100548
Paul Duffin2d1bb892021-04-24 11:32:59 +0100549 // Create a mapping from osType to combined properties.
550 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
551 for _, combined := range combinedPropertiesList {
552 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
553 }
554
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100555 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000556 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100557 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100558 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000559
Paul Duffin2d1bb892021-04-24 11:32:59 +0100560 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000561 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000562 }
Paul Duffin865171e2020-03-02 18:38:15 +0000563
Jiyong Park8fe14e62020-10-19 22:47:34 +0900564 // If host is supported and any member is host OS dependent then disable host
565 // by default, so that we can enable each host OS variant explicitly. This
566 // avoids problems with implicitly enabled OS variants when the snapshot is
567 // used, which might be different from this run (e.g. different build OS).
568 if s.HostSupported() {
569 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100570 for _, memberVariantDep := range memberVariantDeps {
571 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
572 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900573 if !android.InList(targetString, supportedHostTargets) {
574 supportedHostTargets = append(supportedHostTargets, targetString)
575 }
576 }
577 }
578 if len(supportedHostTargets) > 0 {
579 hostPropertySet := targetPropertySet.AddPropertySet("host")
580 hostPropertySet.AddProperty("enabled", false)
581 }
582 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
583 for _, hostTarget := range supportedHostTargets {
584 propertySet := targetPropertySet.AddPropertySet(hostTarget)
585 propertySet.AddProperty("enabled", true)
586 }
587 }
588
Paul Duffin865171e2020-03-02 18:38:15 +0000589 // Prune any empty property sets.
590 snapshotModule.transform(pruneEmptySetTransformer{})
591
Paul Duffinb645ec82019-11-27 17:43:54 +0000592 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900593}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000594
Paul Duffinf88d8e02020-05-07 20:21:34 +0100595// Check the syntax of the generated Android.bp file contents and if they are
596// invalid then log an error with the contents (tagged with line numbers) and the
597// errors that were found so that it is easy to see where the problem lies.
598func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
599 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
600 if len(errs) != 0 {
601 message := &strings.Builder{}
602 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
603
604Generated Android.bp contents
605========================================================================
606`)
607 for i, line := range strings.Split(contents, "\n") {
608 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
609 }
610
611 _, _ = fmt.Fprint(message, `
612========================================================================
613
614Errors found:
615`)
616
617 for _, err := range errs {
618 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
619 }
620
621 ctx.ModuleErrorf("%s", message.String())
622 }
623}
624
Paul Duffin4b8b7932020-05-06 12:35:38 +0100625func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
626 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
627 if err != nil {
628 ctx.ModuleErrorf("error extracting common properties: %s", err)
629 }
630}
631
Paul Duffinfbe470e2021-04-24 12:37:13 +0100632// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
633type snapshotModuleStaticProperties struct {
634 Compile_multilib string `android:"arch_variant"`
635}
636
Paul Duffin2d1bb892021-04-24 11:32:59 +0100637// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
638type combinedSnapshotModuleProperties struct {
639 // The sdk variant from which this information was collected.
640 sdkVariant *sdk
641
642 // Static snapshot module properties.
643 staticProperties *snapshotModuleStaticProperties
644
645 // The dynamically generated member list properties.
646 dynamicProperties interface{}
647}
648
649// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100650func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
651 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100652 var list []*combinedSnapshotModuleProperties
653 for _, sdkVariant := range sdkVariants {
654 staticProperties := &snapshotModuleStaticProperties{
655 Compile_multilib: sdkVariant.multilibUsages.String(),
656 }
Paul Duffincd064672021-04-24 00:47:29 +0100657 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100658
Paul Duffincd064672021-04-24 00:47:29 +0100659 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100660 sdkVariant: sdkVariant,
661 staticProperties: staticProperties,
662 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100663 }
664 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
665
666 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100667 }
Paul Duffincd064672021-04-24 00:47:29 +0100668
669 for _, memberVariantDep := range memberVariantDeps {
670 // If the member dependency is internal then do not add the dependency to the snapshot member
671 // list properties.
672 if !memberVariantDep.export {
673 continue
674 }
675
676 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100677 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100678 memberName := ctx.OtherModuleName(memberVariantDep.variant)
679
Paul Duffin13082052021-05-11 00:31:38 +0100680 if memberListProperty.getter == nil {
681 continue
682 }
683
Paul Duffincd064672021-04-24 00:47:29 +0100684 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100685 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100686 if !android.InList(memberName, memberList) {
687 memberList = append(memberList, memberName)
688 }
Paul Duffin13082052021-05-11 00:31:38 +0100689 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100690 }
691
Paul Duffin2d1bb892021-04-24 11:32:59 +0100692 return list
693}
694
695func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
696
697 // Extract the dynamic properties and add them to a list of propertiesContainer.
698 propertyContainers := []propertiesContainer{}
699 for _, i := range list {
700 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
701 sdkVariant: i.sdkVariant,
702 properties: i.dynamicProperties,
703 })
704 }
705
706 // Extract the common members, removing them from the original properties.
707 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
708 extractor := newCommonValueExtractor(commonDynamicProperties)
709 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
710
711 // Extract the static properties and add them to a list of propertiesContainer.
712 propertyContainers = []propertiesContainer{}
713 for _, i := range list {
714 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
715 sdkVariant: i.sdkVariant,
716 properties: i.staticProperties,
717 })
718 }
719
720 commonStaticProperties := &snapshotModuleStaticProperties{}
721 extractor = newCommonValueExtractor(commonStaticProperties)
722 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
723
724 return &combinedSnapshotModuleProperties{
725 sdkVariant: nil,
726 staticProperties: commonStaticProperties,
727 dynamicProperties: commonDynamicProperties,
728 }
729}
730
731func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
732 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100733 multilib := staticProperties.Compile_multilib
734 if multilib != "" && multilib != "both" {
735 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
736 propertySet.AddProperty("compile_multilib", multilib)
737 }
738
Paul Duffin2d1bb892021-04-24 11:32:59 +0100739 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000740 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100741 if memberListProperty.getter == nil {
742 continue
743 }
Paul Duffin865171e2020-03-02 18:38:15 +0000744 names := memberListProperty.getter(dynamicMemberTypeListProperties)
745 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000746 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000747 }
748 }
749}
750
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000751type propertyTag struct {
752 name string
753}
754
Paul Duffin0cb37b92020-03-04 14:52:46 +0000755// A BpPropertyTag to add to a property that contains references to other sdk members.
756//
757// This will cause the references to be rewritten to a versioned reference in the version
758// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000759var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000760var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000761
Paul Duffin0cb37b92020-03-04 14:52:46 +0000762// A BpPropertyTag that indicates the property should only be present in the versioned
763// module.
764//
765// This will cause the property to be removed from the unversioned instance of a
766// snapshot module.
767var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
768
Paul Duffine6c0d842020-01-15 14:08:51 +0000769type unversionedToVersionedTransformation struct {
770 identityTransformation
771 builder *snapshotBuilder
772}
773
Paul Duffine6c0d842020-01-15 14:08:51 +0000774func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
775 // Use a versioned name for the module but remember the original name for the
776 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100777 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000778 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000779 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100780 // Remove the prefer property if present as versioned modules never need marking with prefer.
781 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000782 return module
783}
784
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000785func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000786 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
787 required := tag == requiredSdkMemberReferencePropertyTag
788 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000789 } else {
790 return value, tag
791 }
792}
793
Paul Duffin72910952020-01-20 18:16:30 +0000794type unversionedTransformation struct {
795 identityTransformation
796 builder *snapshotBuilder
797}
798
799func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
800 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100801 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000802 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000803 return module
804}
805
806func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000807 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
808 required := tag == requiredSdkMemberReferencePropertyTag
809 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000810 } else if tag == sdkVersionedOnlyPropertyTag {
811 // The property is not allowed in the unversioned module so remove it.
812 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000813 } else {
814 return value, tag
815 }
816}
817
Paul Duffina78f3a72020-02-21 16:29:35 +0000818type pruneEmptySetTransformer struct {
819 identityTransformation
820}
821
822var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
823
824func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
825 if len(propertySet.properties) == 0 {
826 return nil, nil
827 } else {
828 return propertySet, tag
829 }
830}
831
Paul Duffinb645ec82019-11-27 17:43:54 +0000832func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000833 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
834 return true
835 })
836}
837
838func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000839 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
840 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000841 if moduleFilter(bpModule) {
842 contents.Printfln("")
843 contents.Printfln("%s {", bpModule.moduleType)
844 outputPropertySet(contents, bpModule.bpPropertySet)
845 contents.Printfln("}")
846 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000847 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000848}
849
850func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
851 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000852
Paul Duffin0df49682021-05-07 01:10:01 +0100853 addComment := func(name string) {
854 if text, ok := set.comments[name]; ok {
855 for _, line := range strings.Split(text, "\n") {
856 contents.Printfln("// %s", line)
857 }
858 }
859 }
860
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000861 // Output the properties first, followed by the nested sets. This ensures a
862 // consistent output irrespective of whether property sets are created before
863 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000864 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000865 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000866
Paul Duffin0df49682021-05-07 01:10:01 +0100867 // Do not write property sets in the properties phase.
868 if _, ok := value.(*bpPropertySet); ok {
869 continue
870 }
871
872 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000873 switch v := value.(type) {
874 case []string:
875 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000876 if length > 1 {
877 contents.Printfln("%s: [", name)
878 contents.Indent()
879 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000880 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000881 }
882 contents.Dedent()
883 contents.Printfln("],")
884 } else if length == 0 {
885 contents.Printfln("%s: [],", name)
886 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000887 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000888 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000889
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000890 case bool:
891 contents.Printfln("%s: %t,", name, v)
892
Paul Duffinb645ec82019-11-27 17:43:54 +0000893 default:
894 contents.Printfln("%s: %q,", name, value)
895 }
896 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000897
898 for _, name := range set.order {
899 value := set.getValue(name)
900
901 // Only write property sets in the sets phase.
902 switch v := value.(type) {
903 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100904 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000905 contents.Printfln("%s: {", name)
906 outputPropertySet(contents, v)
907 contents.Printfln("},")
908 }
909 }
910
Paul Duffinb645ec82019-11-27 17:43:54 +0000911 contents.Dedent()
912}
913
Paul Duffinac37c502019-11-26 18:02:20 +0000914func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000915 contents := &generatedContents{}
916 generateBpContents(contents, s.builderForTests.bpFile)
917 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000918}
919
Paul Duffind0759072021-02-17 11:23:00 +0000920func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
921 contents := &generatedContents{}
922 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100923 name := module.Name()
924 // Include modules that are either unversioned or have no name.
925 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000926 })
927 return contents.content.String()
928}
929
930func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
931 contents := &generatedContents{}
932 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100933 name := module.Name()
934 // Include modules that are either versioned or have no name.
935 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000936 })
937 return contents.content.String()
938}
939
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000940type snapshotBuilder struct {
Paul Duffin973bedb2021-05-05 22:00:51 +0100941 ctx android.ModuleContext
942 sdk *sdk
943
944 // The version of the generated snapshot.
945 //
946 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
947 // this field.
948 version string
949
Paul Duffinb645ec82019-11-27 17:43:54 +0000950 snapshotDir android.OutputPath
951 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000952
953 // Map from destination to source of each copy - used to eliminate duplicates and
954 // detect conflicts.
955 copies map[string]string
956
Paul Duffinb645ec82019-11-27 17:43:54 +0000957 filesToZip android.Paths
958 zipsToMerge android.Paths
959
960 prebuiltModules map[string]*bpModule
961 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000962
963 // The set of all members by name.
964 allMembersByName map[string]struct{}
965
966 // The set of exported members by name.
967 exportedMembersByName map[string]struct{}
Paul Duffin24c545e2021-09-24 14:58:27 +0100968
969 // The target build release for which the snapshot is to be generated.
970 targetBuildRelease *buildRelease
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000971}
972
973func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000974 if existing, ok := s.copies[dest]; ok {
975 if existing != src.String() {
976 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
977 return
978 }
979 } else {
980 path := s.snapshotDir.Join(s.ctx, dest)
981 s.ctx.Build(pctx, android.BuildParams{
982 Rule: android.Cp,
983 Input: src,
984 Output: path,
985 })
986 s.filesToZip = append(s.filesToZip, path)
987
988 s.copies[dest] = src.String()
989 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000990}
991
Paul Duffin91547182019-11-12 19:39:36 +0000992func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
993 ctx := s.ctx
994
995 // Repackage the zip file so that the entries are in the destDir directory.
996 // This will allow the zip file to be merged into the snapshot.
997 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000998
999 ctx.Build(pctx, android.BuildParams{
1000 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1001 Rule: repackageZip,
1002 Input: zipPath,
1003 Output: tmpZipPath,
1004 Args: map[string]string{
1005 "destdir": destDir,
1006 },
1007 })
Paul Duffin91547182019-11-12 19:39:36 +00001008
1009 // Add the repackaged zip file to the files to merge.
1010 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1011}
1012
Paul Duffin9d8d6092019-12-05 18:19:29 +00001013func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1014 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001015 if s.prebuiltModules[name] != nil {
1016 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1017 }
1018
1019 m := s.bpFile.newModule(moduleType)
1020 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001021
Paul Duffinbefa4b92020-03-04 14:22:45 +00001022 variant := member.Variants()[0]
1023
Paul Duffin13f02712020-03-06 12:30:43 +00001024 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001025 // An internal member is only referenced from the sdk snapshot which is in the
1026 // same package so can be marked as private.
1027 m.AddProperty("visibility", []string{"//visibility:private"})
1028 } else {
1029 // Extract visibility information from a member variant. All variants have the same
1030 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001031 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1032
1033 // Add any additional visibility rules needed for the prebuilts to reference each other.
1034 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1035 if err != nil {
1036 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1037 }
1038
1039 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001040 if len(visibility) != 0 {
1041 m.AddProperty("visibility", visibility)
1042 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001043 }
1044
Martin Stjernholm1e041092020-11-03 00:11:09 +00001045 // Where available copy apex_available properties from the member.
1046 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1047 apexAvailable := apexAware.ApexAvailable()
1048 if len(apexAvailable) == 0 {
1049 // //apex_available:platform is the default.
1050 apexAvailable = []string{android.AvailableToPlatform}
1051 }
1052
1053 // Add in any baseline apex available settings.
1054 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1055
1056 // Remove duplicates and sort.
1057 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1058 sort.Strings(apexAvailable)
1059
1060 m.AddProperty("apex_available", apexAvailable)
1061 }
1062
Paul Duffinb0bb3762021-05-06 16:48:05 +01001063 // The licenses are the same for all variants.
1064 mctx := s.ctx
1065 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1066 if len(licenseInfo.Licenses) > 0 {
1067 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1068 }
1069
Paul Duffin865171e2020-03-02 18:38:15 +00001070 deviceSupported := false
1071 hostSupported := false
1072
1073 for _, variant := range member.Variants() {
1074 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001075 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001076 hostSupported = true
1077 } else if osClass == android.Device {
1078 deviceSupported = true
1079 }
1080 }
1081
1082 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001083
Paul Duffin0cb37b92020-03-04 14:52:46 +00001084 // Disable installation in the versioned module of those modules that are ever installable.
1085 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1086 if installable.EverInstallable() {
1087 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1088 }
1089 }
1090
Paul Duffinb645ec82019-11-27 17:43:54 +00001091 s.prebuiltModules[name] = m
1092 s.prebuiltOrder = append(s.prebuiltOrder, m)
1093 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001094}
1095
Paul Duffin865171e2020-03-02 18:38:15 +00001096func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001097 // If neither device or host is supported then this module does not support either so will not
1098 // recognize the properties.
1099 if !deviceSupported && !hostSupported {
1100 return
1101 }
1102
Paul Duffin865171e2020-03-02 18:38:15 +00001103 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001104 bpModule.AddProperty("device_supported", false)
1105 }
Paul Duffin865171e2020-03-02 18:38:15 +00001106 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001107 bpModule.AddProperty("host_supported", true)
1108 }
1109}
1110
Paul Duffin13f02712020-03-06 12:30:43 +00001111func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1112 if required {
1113 return requiredSdkMemberReferencePropertyTag
1114 } else {
1115 return optionalSdkMemberReferencePropertyTag
1116 }
1117}
1118
1119func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1120 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001121}
1122
Paul Duffinb645ec82019-11-27 17:43:54 +00001123// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001124func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1125 if _, ok := s.allMembersByName[unversionedName]; !ok {
1126 if required {
1127 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1128 }
1129 return unversionedName
1130 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001131 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1132}
Paul Duffinb645ec82019-11-27 17:43:54 +00001133
Paul Duffin13f02712020-03-06 12:30:43 +00001134func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001135 var references []string = nil
1136 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001137 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001138 }
1139 return references
1140}
Paul Duffin13879572019-11-28 14:31:38 +00001141
Paul Duffin72910952020-01-20 18:16:30 +00001142// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001143func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1144 if _, ok := s.allMembersByName[unversionedName]; !ok {
1145 if required {
1146 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1147 }
1148 return unversionedName
1149 }
1150
1151 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001152 return s.ctx.ModuleName() + "_" + unversionedName
1153 } else {
1154 return unversionedName
1155 }
1156}
1157
Paul Duffin13f02712020-03-06 12:30:43 +00001158func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001159 var references []string = nil
1160 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001161 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001162 }
1163 return references
1164}
1165
Paul Duffin13f02712020-03-06 12:30:43 +00001166func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1167 _, ok := s.exportedMembersByName[memberName]
1168 return !ok
1169}
1170
Martin Stjernholm89238f42020-07-10 00:14:03 +01001171// Add the properties from the given SdkMemberProperties to the blueprint
1172// property set. This handles common properties in SdkMemberPropertiesBase and
1173// calls the member-specific AddToPropertySet for the rest.
1174func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1175 if memberProperties.Base().Compile_multilib != "" {
1176 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1177 }
1178
1179 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1180}
1181
Paul Duffin21827262021-04-24 12:16:36 +01001182// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1183type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001184 // The sdk variant that depends (possibly indirectly) on the member variant.
1185 sdkVariant *sdk
Paul Duffina1aa7382021-04-29 21:50:40 +01001186
1187 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001188 memberType android.SdkMemberType
Paul Duffina1aa7382021-04-29 21:50:40 +01001189
1190 // The variant that is added to the sdk.
1191 variant android.SdkAware
1192
1193 // True if the member should be exported, i.e. accessible, from outside the sdk.
1194 export bool
1195
1196 // The names of additional component modules provided by the variant.
1197 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001198}
1199
Paul Duffin13879572019-11-28 14:31:38 +00001200var _ android.SdkMember = (*sdkMember)(nil)
1201
Paul Duffin21827262021-04-24 12:16:36 +01001202// sdkMember groups all the variants of a specific member module together along with the name of the
1203// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001204type sdkMember struct {
1205 memberType android.SdkMemberType
1206 name string
1207 variants []android.SdkAware
1208}
1209
1210func (m *sdkMember) Name() string {
1211 return m.name
1212}
1213
1214func (m *sdkMember) Variants() []android.SdkAware {
1215 return m.variants
1216}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001217
Paul Duffin9c3760e2020-03-16 19:52:08 +00001218// Track usages of multilib variants.
1219type multilibUsage int
1220
1221const (
1222 multilibNone multilibUsage = 0
1223 multilib32 multilibUsage = 1
1224 multilib64 multilibUsage = 2
1225 multilibBoth = multilib32 | multilib64
1226)
1227
1228// Add the multilib that is used in the arch type.
1229func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1230 multilib := archType.Multilib
1231 switch multilib {
1232 case "":
1233 return m
1234 case "lib32":
1235 return m | multilib32
1236 case "lib64":
1237 return m | multilib64
1238 default:
1239 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1240 }
1241}
1242
1243func (m multilibUsage) String() string {
1244 switch m {
1245 case multilibNone:
1246 return ""
1247 case multilib32:
1248 return "32"
1249 case multilib64:
1250 return "64"
1251 case multilibBoth:
1252 return "both"
1253 default:
1254 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1255 m, multilibNone, multilib32, multilib64, multilibBoth))
1256 }
1257}
1258
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001259type baseInfo struct {
1260 Properties android.SdkMemberProperties
1261}
1262
Paul Duffinf34f6d82020-04-30 15:48:31 +01001263func (b *baseInfo) optimizableProperties() interface{} {
1264 return b.Properties
1265}
1266
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001267type osTypeSpecificInfo struct {
1268 baseInfo
1269
Paul Duffin00e46802020-03-12 20:40:35 +00001270 osType android.OsType
1271
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001272 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001273 //
1274 // Nil if there is one variant whose arch type is common
1275 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001276}
1277
Paul Duffin4b8b7932020-05-06 12:35:38 +01001278var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1279
Paul Duffinfc8dd232020-03-17 12:51:37 +00001280type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1281
Paul Duffin00e46802020-03-12 20:40:35 +00001282// Create a new osTypeSpecificInfo for the specified os type and its properties
1283// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001284func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001285 osInfo := &osTypeSpecificInfo{
1286 osType: osType,
1287 }
1288
1289 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1290 properties := variantPropertiesFactory()
1291 properties.Base().Os = osType
1292 return properties
1293 }
1294
1295 // Create a structure into which properties common across the architectures in
1296 // this os type will be stored.
1297 osInfo.Properties = osSpecificVariantPropertiesFactory()
1298
1299 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001300 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001301 var archTypes []android.ArchType
1302 for _, variant := range osTypeVariants {
1303 archType := variant.Target().Arch.ArchType
1304 archTypeName := archType.Name
1305 if _, ok := variantsByArchName[archTypeName]; !ok {
1306 archTypes = append(archTypes, archType)
1307 }
1308
1309 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1310 }
1311
1312 if commonVariants, ok := variantsByArchName["common"]; ok {
1313 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001314 panic(fmt.Errorf("Expected to only have 1 variant when arch type is common but found %d", len(osTypeVariants)))
Paul Duffin00e46802020-03-12 20:40:35 +00001315 }
1316
1317 // A common arch type only has one variant and its properties should be treated
1318 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001319 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001320 } else {
1321 // Create an arch specific info for each supported architecture type.
1322 for _, archType := range archTypes {
1323 archTypeName := archType.Name
1324
1325 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001326 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001327
1328 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1329 }
1330 }
1331
1332 return osInfo
1333}
1334
Paul Duffin24c545e2021-09-24 14:58:27 +01001335func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1336 if len(osInfo.archInfos) == 0 {
1337 pruner.pruneProperties(osInfo.Properties)
1338 } else {
1339 for _, archInfo := range osInfo.archInfos {
1340 archInfo.pruneUnsupportedProperties(pruner)
1341 }
1342 }
1343}
1344
Paul Duffin00e46802020-03-12 20:40:35 +00001345// Optimize the properties by extracting common properties from arch type specific
1346// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001347func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001348 // Nothing to do if there is only a single common architecture.
1349 if len(osInfo.archInfos) == 0 {
1350 return
1351 }
1352
Paul Duffin9c3760e2020-03-16 19:52:08 +00001353 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001354 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001355 multilib = multilib.addArchType(archInfo.archType)
1356
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001357 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001358 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001359 }
1360
Paul Duffin4b8b7932020-05-06 12:35:38 +01001361 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001362
1363 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001364 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001365}
1366
1367// Add the properties for an os to a property set.
1368//
1369// Maps the properties related to the os variants through to an appropriate
1370// module structure that will produce equivalent set of variants when it is
1371// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001372func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001373
1374 var osPropertySet android.BpPropertySet
1375 var archPropertySet android.BpPropertySet
1376 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001377 if osInfo.Properties.Base().Os_count == 1 &&
1378 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1379 // There is only one OS type present in the variants and it shouldn't have a
1380 // variant-specific target. The latter is the case if it's either for device
1381 // where there is only one OS (android), or for host and the member type
1382 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001383
1384 // Create a structure that looks like:
1385 // module_type {
1386 // name: "...",
1387 // ...
1388 // <common properties>
1389 // ...
1390 // <single os type specific properties>
1391 //
1392 // arch: {
1393 // <arch specific sections>
1394 // }
1395 //
1396 osPropertySet = bpModule
1397 archPropertySet = osPropertySet.AddPropertySet("arch")
1398
1399 // Arch specific properties need to be added to an arch specific section
1400 // within arch.
1401 archOsPrefix = ""
1402 } else {
1403 // Create a structure that looks like:
1404 // module_type {
1405 // name: "...",
1406 // ...
1407 // <common properties>
1408 // ...
1409 // target: {
1410 // <arch independent os specific sections, e.g. android>
1411 // ...
1412 // <arch and os specific sections, e.g. android_x86>
1413 // }
1414 //
1415 osType := osInfo.osType
1416 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1417 archPropertySet = targetPropertySet
1418
1419 // Arch specific properties need to be added to an os and arch specific
1420 // section prefixed with <os>_.
1421 archOsPrefix = osType.Name + "_"
1422 }
1423
1424 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001425 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001426
1427 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1428 // os) specific properties.
1429 //
1430 // The archInfos list will be empty if the os contains variants for the common
1431 // architecture.
1432 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001433 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001434 }
1435}
1436
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001437func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1438 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001439 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001440}
1441
1442var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1443
Paul Duffin4b8b7932020-05-06 12:35:38 +01001444func (osInfo *osTypeSpecificInfo) String() string {
1445 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1446}
1447
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001448type archTypeSpecificInfo struct {
1449 baseInfo
1450
1451 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001452 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001453
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001454 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001455}
1456
Paul Duffin4b8b7932020-05-06 12:35:38 +01001457var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1458
Paul Duffinfc8dd232020-03-17 12:51:37 +00001459// Create a new archTypeSpecificInfo for the specified arch type and its properties
1460// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001461func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001462
Paul Duffinfc8dd232020-03-17 12:51:37 +00001463 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001464 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001465
1466 // Create the properties into which the arch type specific properties will be
1467 // added.
1468 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001469
1470 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001471 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001472 } else {
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001473 // Group the variants by image type.
1474 variantsByImage := make(map[string][]android.Module)
1475 for _, variant := range archVariants {
1476 image := variant.ImageVariation().Variation
1477 variantsByImage[image] = append(variantsByImage[image], variant)
1478 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001479
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001480 // Create the image variant info in a fixed order.
1481 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1482 variants := variantsByImage[imageVariantName]
1483 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001484 }
1485 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001486
1487 return archInfo
1488}
1489
Paul Duffinf34f6d82020-04-30 15:48:31 +01001490func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1491 return archInfo.Properties
1492}
1493
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001494// Get the link type of the variant
1495//
1496// If the variant is not differentiated by link type then it returns "",
1497// otherwise it returns one of "static" or "shared".
1498func getLinkType(variant android.Module) string {
1499 linkType := ""
1500 if linkable, ok := variant.(cc.LinkableInterface); ok {
1501 if linkable.Shared() && linkable.Static() {
1502 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1503 } else if linkable.Shared() {
1504 linkType = "shared"
1505 } else if linkable.Static() {
1506 linkType = "static"
1507 } else {
1508 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1509 }
1510 }
1511 return linkType
1512}
1513
Paul Duffin24c545e2021-09-24 14:58:27 +01001514func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1515 if len(archInfo.imageVariantInfos) == 0 {
1516 pruner.pruneProperties(archInfo.Properties)
1517 } else {
1518 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1519 imageVariantInfo.pruneUnsupportedProperties(pruner)
1520 }
1521 }
1522}
1523
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001524// Optimize the properties by extracting common properties from link type specific
1525// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001526func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001527 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001528 return
1529 }
1530
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001531 // Optimize the image variant properties first.
1532 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1533 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1534 }
1535
1536 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001537}
1538
Paul Duffinfc8dd232020-03-17 12:51:37 +00001539// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001540func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001541 archTypeName := archInfo.archType.Name
1542 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001543 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1544 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1545 archTypePropertySet.AddProperty("enabled", true)
1546 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001547 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001548
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001549 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1550 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001551 }
1552}
1553
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001554// getPropertySetContents returns the string representation of the contents of a property set, after
1555// recursively pruning any empty nested property sets.
1556func getPropertySetContents(propertySet android.BpPropertySet) string {
1557 set := propertySet.(*bpPropertySet)
1558 set.transformContents(pruneEmptySetTransformer{})
1559 if len(set.properties) != 0 {
1560 contents := &generatedContents{}
1561 contents.Indent()
1562 outputPropertySet(contents, set)
1563 setAsString := contents.content.String()
1564 return setAsString
1565 }
1566 return ""
1567}
1568
Paul Duffin4b8b7932020-05-06 12:35:38 +01001569func (archInfo *archTypeSpecificInfo) String() string {
1570 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1571}
1572
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001573type imageVariantSpecificInfo struct {
1574 baseInfo
1575
1576 imageVariant string
1577
1578 linkInfos []*linkTypeSpecificInfo
1579}
1580
1581func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1582
1583 // Create an image variant specific info into which the variant properties can be copied.
1584 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1585
1586 // Create the properties into which the image variant specific properties will be added.
1587 imageInfo.Properties = variantPropertiesFactory()
1588
1589 if len(imageVariants) == 1 {
1590 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1591 } else {
1592 // There is more than one variant for this image variant which must be differentiated by link
1593 // type.
1594 for _, linkVariant := range imageVariants {
1595 linkType := getLinkType(linkVariant)
1596 if linkType == "" {
1597 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1598 } else {
1599 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1600
1601 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1602 }
1603 }
1604 }
1605
1606 return imageInfo
1607}
1608
Paul Duffin24c545e2021-09-24 14:58:27 +01001609func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1610 if len(imageInfo.linkInfos) == 0 {
1611 pruner.pruneProperties(imageInfo.Properties)
1612 } else {
1613 for _, linkInfo := range imageInfo.linkInfos {
1614 linkInfo.pruneUnsupportedProperties(pruner)
1615 }
1616 }
1617}
1618
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001619// Optimize the properties by extracting common properties from link type specific
1620// properties into arch type specific properties.
1621func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1622 if len(imageInfo.linkInfos) == 0 {
1623 return
1624 }
1625
1626 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1627}
1628
1629// Add the properties for an arch type to a property set.
1630func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1631 if imageInfo.imageVariant != android.CoreVariation {
1632 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1633 }
1634
1635 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1636
1637 for _, linkInfo := range imageInfo.linkInfos {
1638 linkInfo.addToPropertySet(ctx, propertySet)
1639 }
1640
1641 // If this is for a non-core image variant then make sure that the property set does not contain
1642 // any properties as providing non-core image variant specific properties for prebuilts is not
1643 // currently supported.
1644 if imageInfo.imageVariant != android.CoreVariation {
1645 propertySetContents := getPropertySetContents(propertySet)
1646 if propertySetContents != "" {
1647 ctx.SdkModuleContext().ModuleErrorf("Image variant %q of sdk member %q has properties distinct from other variants; this is not yet supported. The properties are:\n%s",
1648 imageInfo.imageVariant, ctx.name, propertySetContents)
1649 }
1650 }
1651}
1652
1653func (imageInfo *imageVariantSpecificInfo) String() string {
1654 return imageInfo.imageVariant
1655}
1656
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001657type linkTypeSpecificInfo struct {
1658 baseInfo
1659
1660 linkType string
1661}
1662
Paul Duffin4b8b7932020-05-06 12:35:38 +01001663var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1664
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001665// Create a new linkTypeSpecificInfo for the specified link type and its properties
1666// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001667func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001668 linkInfo := &linkTypeSpecificInfo{
1669 baseInfo: baseInfo{
1670 // Create the properties into which the link type specific properties will be
1671 // added.
1672 Properties: variantPropertiesFactory(),
1673 },
1674 linkType: linkType,
1675 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001676 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001677 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001678}
1679
Paul Duffinc5662552021-09-09 16:11:42 +01001680func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1681 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1682 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1683}
1684
Paul Duffin24c545e2021-09-24 14:58:27 +01001685func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1686 pruner.pruneProperties(l.Properties)
1687}
1688
Paul Duffin4b8b7932020-05-06 12:35:38 +01001689func (l *linkTypeSpecificInfo) String() string {
1690 return fmt.Sprintf("LinkType{%s}", l.linkType)
1691}
1692
Paul Duffin3a4eb502020-03-19 16:11:18 +00001693type memberContext struct {
1694 sdkMemberContext android.ModuleContext
1695 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001696 memberType android.SdkMemberType
1697 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001698}
1699
1700func (m *memberContext) SdkModuleContext() android.ModuleContext {
1701 return m.sdkMemberContext
1702}
1703
1704func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1705 return m.builder
1706}
1707
Paul Duffina551a1c2020-03-17 21:04:24 +00001708func (m *memberContext) MemberType() android.SdkMemberType {
1709 return m.memberType
1710}
1711
1712func (m *memberContext) Name() string {
1713 return m.name
1714}
1715
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001716func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001717
1718 memberType := member.memberType
1719
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001720 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin24c545e2021-09-24 14:58:27 +01001721 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001722 if !memberType.UsesSourceModuleTypeInSnapshot() {
1723 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1724 // snapshot to be created that sets prefer: true.
1725 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1726 // dynamically at build time not at snapshot generation time.
Paul Duffin24c545e2021-09-24 14:58:27 +01001727 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001728
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001729 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1730 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1731 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1732 // behavior is for the module.
1733 bpModule.insertAfter("name", "prefer", prefer)
1734 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001735
Paul Duffina04c1072020-03-02 10:16:35 +00001736 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001737 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001738 variants := member.Variants()
1739 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001740 osType := variant.Target().Os
1741 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001742 }
1743
Paul Duffina04c1072020-03-02 10:16:35 +00001744 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001745 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001746 properties := memberType.CreateVariantPropertiesStruct()
1747 base := properties.Base()
1748 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001749 return properties
1750 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001751
Paul Duffina04c1072020-03-02 10:16:35 +00001752 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001753
Paul Duffina04c1072020-03-02 10:16:35 +00001754 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001755 commonProperties := variantPropertiesFactory()
1756 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001757
Paul Duffin24c545e2021-09-24 14:58:27 +01001758 // Create a property pruner that will prune any properties unsupported by the target build
1759 // release.
1760 targetBuildRelease := ctx.builder.targetBuildRelease
1761 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1762
Paul Duffinc097e362020-03-10 22:50:03 +00001763 // Create common value extractor that can be used to optimize the properties.
1764 commonValueExtractor := newCommonValueExtractor(commonProperties)
1765
Paul Duffina04c1072020-03-02 10:16:35 +00001766 // The list of property structures which are os type specific but common across
1767 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001768 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001769
1770 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001771 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001772 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001773 // Add the os specific properties to a list of os type specific yet architecture
1774 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001775 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001776
Paul Duffin24c545e2021-09-24 14:58:27 +01001777 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
1778
Paul Duffin00e46802020-03-12 20:40:35 +00001779 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001780 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001781 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001782
Paul Duffina04c1072020-03-02 10:16:35 +00001783 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001784 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001785
Paul Duffina04c1072020-03-02 10:16:35 +00001786 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001787 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001788
Paul Duffina04c1072020-03-02 10:16:35 +00001789 // Create a target property set into which target specific properties can be
1790 // added.
1791 targetPropertySet := bpModule.AddPropertySet("target")
1792
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001793 // If the member is host OS dependent and has host_supported then disable by
1794 // default and enable each host OS variant explicitly. This avoids problems
1795 // with implicitly enabled OS variants when the snapshot is used, which might
1796 // be different from this run (e.g. different build OS).
1797 if ctx.memberType.IsHostOsDependent() {
1798 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1799 if hostSupported {
1800 hostPropertySet := targetPropertySet.AddPropertySet("host")
1801 hostPropertySet.AddProperty("enabled", false)
1802 }
1803 }
1804
Paul Duffina04c1072020-03-02 10:16:35 +00001805 // Iterate over the os types in a fixed order.
1806 for _, osType := range s.getPossibleOsTypes() {
1807 osInfo := osTypeToInfo[osType]
1808 if osInfo == nil {
1809 continue
1810 }
1811
Paul Duffin3a4eb502020-03-19 16:11:18 +00001812 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001813 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001814}
1815
Paul Duffina04c1072020-03-02 10:16:35 +00001816// Compute the list of possible os types that this sdk could support.
1817func (s *sdk) getPossibleOsTypes() []android.OsType {
1818 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001819 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001820 if s.DeviceSupported() {
1821 if osType.Class == android.Device && osType != android.Fuchsia {
1822 osTypes = append(osTypes, osType)
1823 }
1824 }
1825 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001826 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001827 osTypes = append(osTypes, osType)
1828 }
1829 }
1830 }
1831 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1832 return osTypes
1833}
1834
Paul Duffinb28369a2020-05-04 15:39:59 +01001835// Given a set of properties (struct value), return the value of the field within that
1836// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001837type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1838
Paul Duffinc459f892020-04-30 18:08:29 +01001839// Checks the metadata to determine whether the property should be ignored for the
1840// purposes of common value extraction or not.
1841type extractorMetadataPredicate func(metadata propertiesContainer) bool
1842
1843// Indicates whether optimizable properties are provided by a host variant or
1844// not.
1845type isHostVariant interface {
1846 isHostVariant() bool
1847}
1848
Paul Duffinb28369a2020-05-04 15:39:59 +01001849// A property that can be optimized by the commonValueExtractor.
1850type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001851 // The name of the field for this property. It is a "."-separated path for
1852 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001853 name string
1854
Paul Duffinc459f892020-04-30 18:08:29 +01001855 // Filter that can use metadata associated with the properties being optimized
1856 // to determine whether the field should be ignored during common value
1857 // optimization.
1858 filter extractorMetadataPredicate
1859
Paul Duffinb28369a2020-05-04 15:39:59 +01001860 // Retrieves the value on which common value optimization will be performed.
1861 getter fieldAccessorFunc
1862
1863 // The empty value for the field.
1864 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001865
1866 // True if the property can support arch variants false otherwise.
1867 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001868}
1869
Paul Duffin4b8b7932020-05-06 12:35:38 +01001870func (p extractorProperty) String() string {
1871 return p.name
1872}
1873
Paul Duffinc097e362020-03-10 22:50:03 +00001874// Supports extracting common values from a number of instances of a properties
1875// structure into a separate common set of properties.
1876type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001877 // The properties that the extractor can optimize.
1878 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001879}
1880
1881// Create a new common value extractor for the structure type for the supplied
1882// properties struct.
1883//
1884// The returned extractor can be used on any properties structure of the same type
1885// as the supplied set of properties.
1886func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1887 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1888 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001889 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001890 return extractor
1891}
1892
1893// Gather the fields from the supplied structure type from which common values will
1894// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001895//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001896// This is recursive function. If it encounters a struct then it will recurse
1897// into it, passing in the accessor for the field and the struct name as prefix
1898// for the nested fields. That will then be used in the accessors for the fields
1899// in the embedded struct.
1900func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001901 for f := 0; f < structType.NumField(); f++ {
1902 field := structType.Field(f)
1903 if field.PkgPath != "" {
1904 // Ignore unexported fields.
1905 continue
1906 }
1907
Paul Duffinb07fa512020-03-10 22:17:04 +00001908 // Ignore fields whose value should be kept.
1909 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001910 continue
1911 }
1912
Paul Duffinc459f892020-04-30 18:08:29 +01001913 var filter extractorMetadataPredicate
1914
1915 // Add a filter
1916 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1917 filter = func(metadata propertiesContainer) bool {
1918 if m, ok := metadata.(isHostVariant); ok {
1919 if m.isHostVariant() {
1920 return false
1921 }
1922 }
1923 return true
1924 }
1925 }
1926
Paul Duffinc097e362020-03-10 22:50:03 +00001927 // Save a copy of the field index for use in the function.
1928 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001929
Martin Stjernholmb0249572020-09-15 02:32:35 +01001930 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001931
Paul Duffinc097e362020-03-10 22:50:03 +00001932 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001933 if containingStructAccessor != nil {
1934 // This is an embedded structure so first access the field for the embedded
1935 // structure.
1936 value = containingStructAccessor(value)
1937 }
1938
Paul Duffinc097e362020-03-10 22:50:03 +00001939 // Skip through interface and pointer values to find the structure.
1940 value = getStructValue(value)
1941
Paul Duffin4b8b7932020-05-06 12:35:38 +01001942 defer func() {
1943 if r := recover(); r != nil {
1944 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1945 }
1946 }()
1947
Paul Duffinc097e362020-03-10 22:50:03 +00001948 // Return the field.
1949 return value.Field(fieldIndex)
1950 }
1951
Martin Stjernholmb0249572020-09-15 02:32:35 +01001952 if field.Type.Kind() == reflect.Struct {
1953 // Gather fields from the nested or embedded structure.
1954 var subNamePrefix string
1955 if field.Anonymous {
1956 subNamePrefix = namePrefix
1957 } else {
1958 subNamePrefix = name + "."
1959 }
1960 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001961 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001962 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001963 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001964 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001965 fieldGetter,
1966 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001967 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001968 }
1969 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001970 }
Paul Duffinc097e362020-03-10 22:50:03 +00001971 }
1972}
1973
1974func getStructValue(value reflect.Value) reflect.Value {
1975foundStruct:
1976 for {
1977 kind := value.Kind()
1978 switch kind {
1979 case reflect.Interface, reflect.Ptr:
1980 value = value.Elem()
1981 case reflect.Struct:
1982 break foundStruct
1983 default:
1984 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1985 }
1986 }
1987 return value
1988}
1989
Paul Duffinf34f6d82020-04-30 15:48:31 +01001990// A container of properties to be optimized.
1991//
1992// Allows additional information to be associated with the properties, e.g. for
1993// filtering.
1994type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001995 fmt.Stringer
1996
Paul Duffinf34f6d82020-04-30 15:48:31 +01001997 // Get the properties that need optimizing.
1998 optimizableProperties() interface{}
1999}
2000
Paul Duffin2d1bb892021-04-24 11:32:59 +01002001// A wrapper for sdk variant related properties to allow them to be optimized.
2002type sdkVariantPropertiesContainer struct {
2003 sdkVariant *sdk
2004 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002005}
2006
Paul Duffin2d1bb892021-04-24 11:32:59 +01002007func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2008 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002009}
2010
Paul Duffin2d1bb892021-04-24 11:32:59 +01002011func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002012 return c.sdkVariant.String()
2013}
2014
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002015// Extract common properties from a slice of property structures of the same type.
2016//
2017// All the property structures must be of the same type.
2018// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002019// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002020//
2021// Iterates over each exported field (capitalized name) and checks to see whether they
2022// have the same value (using DeepEquals) across all the input properties. If it does not then no
2023// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002024// and the field in each of the input properties structure is set to its default value. Nested
2025// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002026func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002027 commonPropertiesValue := reflect.ValueOf(commonProperties)
2028 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002029
Paul Duffinf34f6d82020-04-30 15:48:31 +01002030 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2031
Paul Duffinb28369a2020-05-04 15:39:59 +01002032 for _, property := range e.properties {
2033 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002034 filter := property.filter
2035 if filter == nil {
2036 filter = func(metadata propertiesContainer) bool {
2037 return true
2038 }
2039 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002040
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002041 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002042 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2043 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002044 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002045
Paul Duffin864e1b42020-05-06 10:23:19 +01002046 // Assume that all the values will be the same.
2047 //
2048 // While similar to this is not quite the same as commonValue == nil. If all the values
2049 // have been filtered out then this will be false but commonValue == nil will be true.
2050 valuesDiffer := false
2051
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002052 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002053 container := sliceValue.Index(i).Interface().(propertiesContainer)
2054 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002055 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002056
Paul Duffinc459f892020-04-30 18:08:29 +01002057 if !filter(container) {
2058 expectedValue := property.emptyValue.Interface()
2059 actualValue := fieldValue.Interface()
2060 if !reflect.DeepEqual(expectedValue, actualValue) {
2061 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2062 }
2063 continue
2064 }
2065
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002066 if commonValue == nil {
2067 // Use the first value as the commonProperties value.
2068 commonValue = &fieldValue
2069 } else {
2070 // If the value does not match the current common value then there is
2071 // no value in common so break out.
2072 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2073 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002074 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002075 break
2076 }
2077 }
2078 }
2079
Paul Duffin864e1b42020-05-06 10:23:19 +01002080 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002081 // and set the input struct's field to the empty value.
2082 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002083 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002084 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002085 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002086 container := sliceValue.Index(i).Interface().(propertiesContainer)
2087 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002088 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002089 fieldValue.Set(emptyValue)
2090 }
2091 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002092
2093 if valuesDiffer && !property.archVariant {
2094 // The values differ but the property does not support arch variants so it
2095 // is an error.
2096 var details strings.Builder
2097 for i := 0; i < sliceValue.Len(); i++ {
2098 container := sliceValue.Index(i).Interface().(propertiesContainer)
2099 itemValue := reflect.ValueOf(container.optimizableProperties())
2100 fieldValue := fieldGetter(itemValue)
2101
2102 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2103 }
2104
2105 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2106 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002107 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002108
2109 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002110}