blob: c3a426f8d0c3747d6e15a838efe07334a2fa6302 [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 (
Paul Duffinc6ba1822022-05-06 09:38:02 +000018 "bytes"
19 "encoding/json"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000021 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000022 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "strings"
24
Paul Duffin7d74e7b2020-03-06 12:30:13 +000025 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000026 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070027
Paul Duffin375058f2019-11-29 20:17:53 +000028 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029 "github.com/google/blueprint/proptools"
30
31 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090032)
33
Paul Duffin64fb5262021-05-05 21:36:04 +010034// Environment variables that affect the generated snapshot
35// ========================================================
36//
37// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000038// By default every unversioned module in the generated snapshot has prefer: false. Building it
39// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010040//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010041// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
42// If set this specifies the Soong config var that can be used to control whether the prebuilt
43// modules from the generated snapshot or the original source modules. Values must be a colon
44// separated pair of strings, the first of which is the Soong config namespace, and the second
45// is the name of the variable within that namespace.
46//
47// The config namespace and var name are used to set the `use_source_config_var` property. That
48// in turn will cause the generated prebuilts to use the soong config variable to select whether
49// source or the prebuilt is used.
50// e.g. If an sdk snapshot is built using:
51// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
52// Then the resulting snapshot will include:
53// use_source_config_var: {
54// config_namespace: "acme",
55// var_name: "build_from_source",
56// }
57//
58// Assuming that the config variable is defined in .mk using something like:
59// $(call add_soong_config_namespace,acme)
60// $(call add_soong_config_var_value,acme,build_from_source,true)
61//
62// Then when the snapshot is unpacked in the repository it will have the following behavior:
63// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
64// sources.
65// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
66// sources, if present. Otherwise, it will use the prebuilts.
67//
68// This is a temporary mechanism to control the prefer flags and will be removed once a more
69// maintainable solution has been implemented.
70// TODO(b/174997203): Remove when no longer necessary.
71//
Paul Duffin43f7bf02021-05-05 22:00:51 +010072// SOONG_SDK_SNAPSHOT_VERSION
73// This provides control over the version of the generated snapshot.
74//
75// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
76// versioned snapshot module. This is the default behavior. The zip file containing the
77// generated snapshot will be <sdk-name>-current.zip.
78//
79// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
80// file containing the generated snapshot will be <sdk-name>.zip.
81//
82// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
83// snapshot module only. The zip file containing the generated snapshot will be
84// <sdk-name>-<number>.zip.
85//
Paul Duffin39abf8f2021-09-24 14:58:27 +010086// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
87// This allows the target build release (i.e. the release version of the build within which
88// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
89// to the current build release version. Otherwise, it must be the name of one of the build
90// releases defined in nameToBuildRelease, e.g. S, T, etc..
91//
92// The generated snapshot must only be used in the specified target release. If the target
93// build release is not the current build release then the generated Android.bp file not be
94// checked for compatibility.
95//
96// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
97// to be compatible with S.
98//
Paul Duffin64fb5262021-05-05 21:36:04 +010099
Jiyong Park9b409bc2019-10-11 14:59:13 +0900100var pctx = android.NewPackageContext("android/soong/sdk")
101
Paul Duffin375058f2019-11-29 20:17:53 +0000102var (
103 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
104 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +0000105 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +0000106 CommandDeps: []string{
107 "${config.Zip2ZipCmd}",
108 },
109 },
110 "destdir")
111
112 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
113 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -0700114 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000115 CommandDeps: []string{
116 "${config.SoongZipCmd}",
117 },
118 Rspfile: "$out.rsp",
119 RspfileContent: "$in",
120 },
121 "basedir")
122
123 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
124 blueprint.RuleParams{
125 Command: `${config.MergeZipsCmd} $out $in`,
126 CommandDeps: []string{
127 "${config.MergeZipsCmd}",
128 },
129 })
130)
131
Paul Duffin43f7bf02021-05-05 22:00:51 +0100132const (
133 soongSdkSnapshotVersionUnversioned = "unversioned"
134 soongSdkSnapshotVersionCurrent = "current"
135)
136
Paul Duffinb645ec82019-11-27 17:43:54 +0000137type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900138 content strings.Builder
139 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900140}
141
Paul Duffinb645ec82019-11-27 17:43:54 +0000142// generatedFile abstracts operations for writing contents into a file and emit a build rule
143// for the file.
144type generatedFile struct {
145 generatedContents
146 path android.OutputPath
147}
148
Jiyong Park232e7852019-11-04 12:23:40 +0900149func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900150 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000151 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900152 }
153}
154
Paul Duffinb645ec82019-11-27 17:43:54 +0000155func (gc *generatedContents) Indent() {
156 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900157}
158
Paul Duffinb645ec82019-11-27 17:43:54 +0000159func (gc *generatedContents) Dedent() {
160 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900161}
162
Paul Duffina08e4dc2021-06-22 18:19:19 +0100163// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
164// arguments.
165func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
166 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
167}
168
169// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
170// the arguments.
171func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
172 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900173}
174
175func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800176 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100177
178 content := gf.content.String()
179
180 // ninja consumes newline characters in rspfile_content. Prevent it by
181 // escaping the backslash in the newline character. The extra backslash
182 // is removed when the rspfile is written to the actual script file
183 content = strings.ReplaceAll(content, "\n", "\\n")
184
Jiyong Park9b409bc2019-10-11 14:59:13 +0900185 rb.Command().
186 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100187 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100188 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900189 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
190 rb.Command().
191 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800192 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900193}
194
Paul Duffin13879572019-11-28 14:31:38 +0000195// Collect all the members.
196//
Paul Duffinb97b1572021-04-29 21:50:40 +0100197// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
198// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000199func (s *sdk) collectMembers(ctx android.ModuleContext) {
200 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000201 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
202 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100203 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100204 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900205
Paul Duffin5cca7c42021-05-26 10:16:01 +0100206 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
207 if memberType == nil {
208 return false
209 }
210
Paul Duffin13879572019-11-28 14:31:38 +0000211 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000212 if !memberType.IsInstance(child) {
213 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900214 }
Paul Duffin13879572019-11-28 14:31:38 +0000215
Paul Duffin6a7e9532020-03-20 17:50:07 +0000216 // Keep track of which multilib variants are used by the sdk.
217 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
218
Paul Duffinb97b1572021-04-29 21:50:40 +0100219 var exportedComponentsInfo android.ExportedComponentsInfo
220 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
221 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
222 }
223
Paul Duffinc6ba1822022-05-06 09:38:02 +0000224 var container android.SdkAware
225 if parent != ctx.Module() {
226 container = parent.(android.SdkAware)
227 }
228
Paul Duffina7208112021-04-23 21:20:20 +0100229 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100230 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000231 sdkVariant: s,
232 memberType: memberType,
233 variant: child.(android.SdkAware),
234 container: container,
235 export: export,
236 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100237 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000238
Paul Duffin2d3da312021-05-06 12:02:27 +0100239 // Recurse down into the member's dependencies as it may have dependencies that need to be
240 // automatically added to the sdk.
241 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900242 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000243
244 return false
Paul Duffin13879572019-11-28 14:31:38 +0000245 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000246}
247
Paul Duffincc3132e2021-04-24 01:10:30 +0100248// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
249// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000250//
Paul Duffincc3132e2021-04-24 01:10:30 +0100251// The sdkMember instances are then grouped into slices by member type. Within each such slice the
252// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000253//
Paul Duffincc3132e2021-04-24 01:10:30 +0100254// Finally, the member type slices are concatenated together to form a single slice. The order in
255// which they are concatenated is the order in which the member types were registered in the
256// android.SdkMemberTypesRegistry.
257func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000258 byType := make(map[android.SdkMemberType][]*sdkMember)
259 byName := make(map[string]*sdkMember)
260
Paul Duffin21827262021-04-24 12:16:36 +0100261 for _, memberVariantDep := range memberVariantDeps {
262 memberType := memberVariantDep.memberType
263 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000264
265 name := ctx.OtherModuleName(variant)
266 member := byName[name]
267 if member == nil {
268 member = &sdkMember{memberType: memberType, name: name}
269 byName[name] = member
270 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400271 } else if member.memberType != memberType {
272 // validate whether this is the same member type or and overriding member type
273 if memberType.Overrides(member.memberType) {
274 member.memberType = memberType
275 } else if !member.memberType.Overrides(memberType) {
276 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
277 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000278 }
279
Paul Duffin1356d8c2020-02-25 19:26:33 +0000280 // Only append new variants to the list. This is needed because a member can be both
281 // exported by the sdk and also be a transitive sdk member.
282 member.variants = appendUniqueVariants(member.variants, variant)
283 }
Paul Duffin13879572019-11-28 14:31:38 +0000284 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100285 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000286 membersOfType := byType[memberListProperty.memberType]
287 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900288 }
289
Paul Duffin6a7e9532020-03-20 17:50:07 +0000290 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900291}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900292
Paul Duffin72910952020-01-20 18:16:30 +0000293func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
294 for _, v := range variants {
295 if v == newVariant {
296 return variants
297 }
298 }
299 return append(variants, newVariant)
300}
301
Paul Duffin51509a12022-04-06 12:48:09 +0000302// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
303// the build from which the snapshot was produced.
304const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
305
Jiyong Park73c54ee2019-10-22 20:31:18 +0900306// SDK directory structure
307// <sdk_root>/
308// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
309// <api_ver>/ : below this directory are all auto-generated
310// Android.bp : definition of 'sdk_snapshot' module is here
311// aidl/
312// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
313// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900314// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900315// include/
316// bionic/libc/include/stdlib.h : an exported header file
317// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900318// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900319// <arch>/include/ : arch-specific exported headers
320// <arch>/include_gen/ : arch-specific generated headers
321// <arch>/lib/
322// libFoo.so : a stub library
323
Jiyong Park232e7852019-11-04 12:23:40 +0900324// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900325// This isn't visible to users, so could be changed in future.
326func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
327 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
328}
329
Jiyong Park232e7852019-11-04 12:23:40 +0900330// buildSnapshot is the main function in this source file. It creates rules to copy
331// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000332func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000333
Paul Duffinb97b1572021-04-29 21:50:40 +0100334 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100335 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100336 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000337 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100338 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100339 }
Paul Duffin865171e2020-03-02 18:38:15 +0000340
Paul Duffinb97b1572021-04-29 21:50:40 +0100341 // Filter out any sdkMemberVariantDep that is a component of another.
342 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000343
Paul Duffinb97b1572021-04-29 21:50:40 +0100344 // Record the names of all the members, both explicitly specified and implicitly
345 // included.
346 allMembersByName := make(map[string]struct{})
347 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100348
Paul Duffinb97b1572021-04-29 21:50:40 +0100349 addMember := func(name string, export bool) {
350 allMembersByName[name] = struct{}{}
351 if export {
352 exportedMembersByName[name] = struct{}{}
353 }
354 }
355
356 for _, memberVariantDep := range memberVariantDeps {
357 name := memberVariantDep.variant.Name()
358 export := memberVariantDep.export
359
360 addMember(name, export)
361
362 // Add any components provided by the module.
363 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
364 addMember(component, export)
365 }
366
367 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
368 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000369 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000370 }
371
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000372 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900373
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000374 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000375
376 bpFile := &bpFile{
377 modules: make(map[string]*bpModule),
378 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000379
Paul Duffin43f7bf02021-05-05 22:00:51 +0100380 config := ctx.Config()
381 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
382
383 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
384 generateVersioned := version != soongSdkSnapshotVersionUnversioned
385
386 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
387 //
388 // Unversioned modules are not required in that case because the numbered version will be a
389 // finalized version of the snapshot that is intended to be kept separate from the
390 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
Paul Duffinc6ba1822022-05-06 09:38:02 +0000391 snapshotFileSuffix := ""
Paul Duffin43f7bf02021-05-05 22:00:51 +0100392 if generateVersioned {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000393 snapshotFileSuffix = "-" + version
Paul Duffin43f7bf02021-05-05 22:00:51 +0100394 }
395
Paul Duffin39abf8f2021-09-24 14:58:27 +0100396 currentBuildRelease := latestBuildRelease()
397 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
398 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
399 if err != nil {
400 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
401 targetBuildRelease = currentBuildRelease
402 }
403
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000404 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000405 ctx: ctx,
406 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100407 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000408 snapshotDir: snapshotDir.OutputPath,
409 copies: make(map[string]string),
410 filesToZip: []android.Path{bp.path},
411 bpFile: bpFile,
412 prebuiltModules: make(map[string]*bpModule),
413 allMembersByName: allMembersByName,
414 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100415 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900416 }
Paul Duffinac37c502019-11-26 18:02:20 +0000417 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900418
Paul Duffin62131702021-05-07 01:10:01 +0100419 // If the sdk snapshot includes any license modules then add a package module which has a
420 // default_applicable_licenses property. That will prevent the LSC license process from updating
421 // the generated Android.bp file to add a package module that includes all licenses used by all
422 // the modules in that package. That would be unnecessary as every module in the sdk should have
423 // their own licenses property specified.
424 if hasLicenses {
425 pkg := bpFile.newModule("package")
426 property := "default_applicable_licenses"
427 pkg.AddCommentForProperty(property, `
428A default list here prevents the license LSC from adding its own list which would
429be unnecessary as every module in the sdk already has its own licenses property.
430`)
431 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
432 bpFile.AddModule(pkg)
433 }
434
Paul Duffin0df49682021-05-07 01:10:01 +0100435 // Group the variants for each member module together and then group the members of each member
436 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100437 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100438
439 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100440 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000441 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000442 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000443
Paul Duffind19f8942021-07-14 12:08:37 +0100444 name := member.name
445 requiredTraits := traits[name]
446 if requiredTraits == nil {
447 requiredTraits = android.EmptySdkMemberTraitSet()
448 }
449
450 // Create the snapshot for the member.
451 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000452
453 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100454 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900455 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900456
Paul Duffine6c0d842020-01-15 14:08:51 +0000457 // Create a transformer that will transform an unversioned module into a versioned module.
458 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
459
Paul Duffin72910952020-01-20 18:16:30 +0000460 // Create a transformer that will transform an unversioned module by replacing any references
461 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100462 unversionedTransformer := unversionedTransformation{
463 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100464 }
Paul Duffin72910952020-01-20 18:16:30 +0000465
Paul Duffinb645ec82019-11-27 17:43:54 +0000466 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000467 // Prune any empty property sets.
468 unversioned = unversioned.transform(pruneEmptySetTransformer{})
469
Paul Duffin43f7bf02021-05-05 22:00:51 +0100470 if generateVersioned {
471 // Copy the unversioned module so it can be modified to make it versioned.
472 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000473
Paul Duffin43f7bf02021-05-05 22:00:51 +0100474 // Transform the unversioned module into a versioned one.
475 versioned.transform(unversionedToVersionedTransformer)
476 bpFile.AddModule(versioned)
477 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000478
Paul Duffin43f7bf02021-05-05 22:00:51 +0100479 if generateUnversioned {
480 // Transform the unversioned module to make it suitable for use in the snapshot.
481 unversioned.transform(unversionedTransformer)
482 bpFile.AddModule(unversioned)
483 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000484 }
485
Paul Duffin43f7bf02021-05-05 22:00:51 +0100486 if generateVersioned {
487 // Add the sdk/module_exports_snapshot module to the bp file.
488 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
489 }
Paul Duffin26197a62021-04-24 00:34:10 +0100490
491 // generate Android.bp
492 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
493 generateBpContents(&bp.generatedContents, bpFile)
494
495 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100496 // If the snapshot is being generated for the current build release then check the syntax to make
497 // sure that it is compatible.
498 if targetBuildRelease == currentBuildRelease {
499 syntaxCheckSnapshotBpFile(ctx, contents)
500 }
Paul Duffin26197a62021-04-24 00:34:10 +0100501
502 bp.build(pctx, ctx, nil)
503
Paul Duffin51509a12022-04-06 12:48:09 +0000504 // Copy the build number file into the snapshot.
505 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
506
Paul Duffin26197a62021-04-24 00:34:10 +0100507 filesToZip := builder.filesToZip
508
509 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000510 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100511 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100512 outputDesc := "Building snapshot for " + ctx.ModuleName()
513
514 // If there are no zips to merge then generate the output zip directly.
515 // Otherwise, generate an intermediate zip file into which other zips can be
516 // merged.
517 var zipFile android.OutputPath
518 var desc string
519 if len(builder.zipsToMerge) == 0 {
520 zipFile = outputZipFile
521 desc = outputDesc
522 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000523 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100524 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100525 desc = "Building intermediate snapshot for " + ctx.ModuleName()
526 }
527
528 ctx.Build(pctx, android.BuildParams{
529 Description: desc,
530 Rule: zipFiles,
531 Inputs: filesToZip,
532 Output: zipFile,
533 Args: map[string]string{
534 "basedir": builder.snapshotDir.String(),
535 },
536 })
537
538 if len(builder.zipsToMerge) != 0 {
539 ctx.Build(pctx, android.BuildParams{
540 Description: outputDesc,
541 Rule: mergeZips,
542 Input: zipFile,
543 Inputs: builder.zipsToMerge,
544 Output: outputZipFile,
545 })
546 }
547
Paul Duffinc6ba1822022-05-06 09:38:02 +0000548 modules := s.generateInfoData(ctx, memberVariantDeps)
549
550 // Output the modules information as pretty printed JSON.
551 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
552 output, err := json.MarshalIndent(modules, "", " ")
553 if err != nil {
554 ctx.ModuleErrorf("error generating %q: %s", info, err)
555 }
556 builder.infoContents = string(output)
557 info.generatedContents.UnindentedPrintf("%s", output)
558 info.build(pctx, ctx, nil)
559 infoPath := info.path
560 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
561 s.infoFile = android.OptionalPathForPath(installedInfo)
562
563 // Install the zip, making sure that the info file has been installed as well.
564 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
565 s.snapshotFile = android.OptionalPathForPath(installedZip)
566}
567
568type moduleInfo struct {
569 // The type of the module, e.g. java_sdk_library
570 moduleType string
571 // The name of the module.
572 name string
573 // A list of additional dependencies of the module.
574 deps []string
575 // Additional dynamic properties.
576 dynamic map[string]interface{}
577}
578
579func (m *moduleInfo) MarshalJSON() ([]byte, error) {
580 buffer := bytes.Buffer{}
581
582 separator := ""
583 writeObjectPair := func(key string, value interface{}) {
584 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
585 b, err := json.Marshal(value)
586 if err != nil {
587 panic(err)
588 }
589 buffer.Write(b)
590 separator = ","
591 }
592
593 buffer.WriteString("{")
594 writeObjectPair("@type", m.moduleType)
595 writeObjectPair("@name", m.name)
596 if m.deps != nil {
597 writeObjectPair("@deps", m.deps)
598 }
599 for _, k := range android.SortedStringKeys(m.dynamic) {
600 v := m.dynamic[k]
601 writeObjectPair(k, v)
602 }
603 buffer.WriteString("}")
604 return buffer.Bytes(), nil
605}
606
607var _ json.Marshaler = (*moduleInfo)(nil)
608
609// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
610func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
611 modules := []*moduleInfo{}
612 sdkInfo := moduleInfo{
613 moduleType: "sdk",
614 name: ctx.ModuleName(),
615 dynamic: map[string]interface{}{},
616 }
617 modules = append(modules, &sdkInfo)
618
619 name2Info := map[string]*moduleInfo{}
620 getModuleInfo := func(module android.Module) *moduleInfo {
621 name := module.Name()
622 info := name2Info[name]
623 if info == nil {
624 moduleType := ctx.OtherModuleType(module)
625 // Remove any suffix added when creating modules dynamically.
626 moduleType = strings.Split(moduleType, "__")[0]
627 info = &moduleInfo{
628 moduleType: moduleType,
629 name: name,
630 }
631 name2Info[name] = info
632 }
633 return info
634 }
635
636 for _, memberVariantDep := range memberVariantDeps {
637 propertyName := memberVariantDep.memberType.SdkPropertyName()
638 var list []string
639 if v, ok := sdkInfo.dynamic[propertyName]; ok {
640 list = v.([]string)
641 }
642
643 memberName := memberVariantDep.variant.Name()
644 list = append(list, memberName)
645 sdkInfo.dynamic[propertyName] = android.SortedUniqueStrings(list)
646
647 if memberVariantDep.container != nil {
648 containerInfo := getModuleInfo(memberVariantDep.container)
649 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
650 }
651
652 // Make sure that the module info is created for each module.
653 getModuleInfo(memberVariantDep.variant)
654 }
655
656 for _, memberName := range android.SortedStringKeys(name2Info) {
657 info := name2Info[memberName]
658 modules = append(modules, info)
659 }
660
661 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100662}
663
Paul Duffinb97b1572021-04-29 21:50:40 +0100664// filterOutComponents removes any item from the deps list that is a component of another item in
665// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
666// then it will remove "foo.stubs" from the deps.
667func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
668 // Collate the set of components that all the modules added to the sdk provide.
669 components := map[string]*sdkMemberVariantDep{}
670 for i, _ := range deps {
671 dep := &deps[i]
672 for _, c := range dep.exportedComponentsInfo.Components {
673 components[c] = dep
674 }
675 }
676
677 // If no module provides components then return the input deps unfiltered.
678 if len(components) == 0 {
679 return deps
680 }
681
682 filtered := make([]sdkMemberVariantDep, 0, len(deps))
683 for _, dep := range deps {
684 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
685 if owner, ok := components[name]; ok {
686 // This is a component of another module that is a member of the sdk.
687
688 // If the component is exported but the owning module is not then the configuration is not
689 // supported.
690 if dep.export && !owner.export {
691 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
692 continue
693 }
694
695 // This module must not be added to the list of members of the sdk as that would result in a
696 // duplicate module in the sdk snapshot.
697 continue
698 }
699
700 filtered = append(filtered, dep)
701 }
702 return filtered
703}
704
Paul Duffin26197a62021-04-24 00:34:10 +0100705// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100706func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100707 bpFile := builder.bpFile
708
Paul Duffinb645ec82019-11-27 17:43:54 +0000709 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000710 var snapshotModuleType string
711 if s.properties.Module_exports {
712 snapshotModuleType = "module_exports_snapshot"
713 } else {
714 snapshotModuleType = "sdk_snapshot"
715 }
716 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000717 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000718
719 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100720 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000721 if len(visibility) != 0 {
722 snapshotModule.AddProperty("visibility", visibility)
723 }
724
Paul Duffin865171e2020-03-02 18:38:15 +0000725 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000726
Paul Duffincd064672021-04-24 00:47:29 +0100727 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100728 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000729
Paul Duffin2d1bb892021-04-24 11:32:59 +0100730 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100731
Paul Duffin6a7e9532020-03-20 17:50:07 +0000732 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100733
Paul Duffin2d1bb892021-04-24 11:32:59 +0100734 // Create a mapping from osType to combined properties.
735 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
736 for _, combined := range combinedPropertiesList {
737 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
738 }
739
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100740 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000741 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100742 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100743 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000744
Paul Duffin2d1bb892021-04-24 11:32:59 +0100745 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000746 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000747 }
Paul Duffin865171e2020-03-02 18:38:15 +0000748
Jiyong Park8fe14e62020-10-19 22:47:34 +0900749 // If host is supported and any member is host OS dependent then disable host
750 // by default, so that we can enable each host OS variant explicitly. This
751 // avoids problems with implicitly enabled OS variants when the snapshot is
752 // used, which might be different from this run (e.g. different build OS).
753 if s.HostSupported() {
754 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100755 for _, memberVariantDep := range memberVariantDeps {
756 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
757 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900758 if !android.InList(targetString, supportedHostTargets) {
759 supportedHostTargets = append(supportedHostTargets, targetString)
760 }
761 }
762 }
763 if len(supportedHostTargets) > 0 {
764 hostPropertySet := targetPropertySet.AddPropertySet("host")
765 hostPropertySet.AddProperty("enabled", false)
766 }
767 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
768 for _, hostTarget := range supportedHostTargets {
769 propertySet := targetPropertySet.AddPropertySet(hostTarget)
770 propertySet.AddProperty("enabled", true)
771 }
772 }
773
Paul Duffin865171e2020-03-02 18:38:15 +0000774 // Prune any empty property sets.
775 snapshotModule.transform(pruneEmptySetTransformer{})
776
Paul Duffinb645ec82019-11-27 17:43:54 +0000777 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900778}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000779
Paul Duffinf88d8e02020-05-07 20:21:34 +0100780// Check the syntax of the generated Android.bp file contents and if they are
781// invalid then log an error with the contents (tagged with line numbers) and the
782// errors that were found so that it is easy to see where the problem lies.
783func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
784 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
785 if len(errs) != 0 {
786 message := &strings.Builder{}
787 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
788
789Generated Android.bp contents
790========================================================================
791`)
792 for i, line := range strings.Split(contents, "\n") {
793 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
794 }
795
796 _, _ = fmt.Fprint(message, `
797========================================================================
798
799Errors found:
800`)
801
802 for _, err := range errs {
803 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
804 }
805
806 ctx.ModuleErrorf("%s", message.String())
807 }
808}
809
Paul Duffin4b8b7932020-05-06 12:35:38 +0100810func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
811 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
812 if err != nil {
813 ctx.ModuleErrorf("error extracting common properties: %s", err)
814 }
815}
816
Paul Duffinfbe470e2021-04-24 12:37:13 +0100817// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
818type snapshotModuleStaticProperties struct {
819 Compile_multilib string `android:"arch_variant"`
820}
821
Paul Duffin2d1bb892021-04-24 11:32:59 +0100822// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
823type combinedSnapshotModuleProperties struct {
824 // The sdk variant from which this information was collected.
825 sdkVariant *sdk
826
827 // Static snapshot module properties.
828 staticProperties *snapshotModuleStaticProperties
829
830 // The dynamically generated member list properties.
831 dynamicProperties interface{}
832}
833
834// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100835func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
836 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100837 var list []*combinedSnapshotModuleProperties
838 for _, sdkVariant := range sdkVariants {
839 staticProperties := &snapshotModuleStaticProperties{
840 Compile_multilib: sdkVariant.multilibUsages.String(),
841 }
Paul Duffin62782de2021-07-14 12:05:16 +0100842 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100843
Paul Duffincd064672021-04-24 00:47:29 +0100844 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100845 sdkVariant: sdkVariant,
846 staticProperties: staticProperties,
847 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100848 }
849 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
850
851 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100852 }
Paul Duffincd064672021-04-24 00:47:29 +0100853
854 for _, memberVariantDep := range memberVariantDeps {
855 // If the member dependency is internal then do not add the dependency to the snapshot member
856 // list properties.
857 if !memberVariantDep.export {
858 continue
859 }
860
861 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100862 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100863 memberName := ctx.OtherModuleName(memberVariantDep.variant)
864
Paul Duffin13082052021-05-11 00:31:38 +0100865 if memberListProperty.getter == nil {
866 continue
867 }
868
Paul Duffincd064672021-04-24 00:47:29 +0100869 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100870 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100871 if !android.InList(memberName, memberList) {
872 memberList = append(memberList, memberName)
873 }
Paul Duffin13082052021-05-11 00:31:38 +0100874 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100875 }
876
Paul Duffin2d1bb892021-04-24 11:32:59 +0100877 return list
878}
879
880func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
881
882 // Extract the dynamic properties and add them to a list of propertiesContainer.
883 propertyContainers := []propertiesContainer{}
884 for _, i := range list {
885 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
886 sdkVariant: i.sdkVariant,
887 properties: i.dynamicProperties,
888 })
889 }
890
891 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100892 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100893 extractor := newCommonValueExtractor(commonDynamicProperties)
894 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
895
896 // Extract the static properties and add them to a list of propertiesContainer.
897 propertyContainers = []propertiesContainer{}
898 for _, i := range list {
899 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
900 sdkVariant: i.sdkVariant,
901 properties: i.staticProperties,
902 })
903 }
904
905 commonStaticProperties := &snapshotModuleStaticProperties{}
906 extractor = newCommonValueExtractor(commonStaticProperties)
907 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
908
909 return &combinedSnapshotModuleProperties{
910 sdkVariant: nil,
911 staticProperties: commonStaticProperties,
912 dynamicProperties: commonDynamicProperties,
913 }
914}
915
916func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
917 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100918 multilib := staticProperties.Compile_multilib
919 if multilib != "" && multilib != "both" {
920 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
921 propertySet.AddProperty("compile_multilib", multilib)
922 }
923
Paul Duffin2d1bb892021-04-24 11:32:59 +0100924 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100925 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100926 if memberListProperty.getter == nil {
927 continue
928 }
Paul Duffin865171e2020-03-02 18:38:15 +0000929 names := memberListProperty.getter(dynamicMemberTypeListProperties)
930 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000931 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000932 }
933 }
934}
935
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000936type propertyTag struct {
937 name string
938}
939
Paul Duffin94289702021-09-09 15:38:32 +0100940var _ android.BpPropertyTag = propertyTag{}
941
Paul Duffin0cb37b92020-03-04 14:52:46 +0000942// A BpPropertyTag to add to a property that contains references to other sdk members.
943//
944// This will cause the references to be rewritten to a versioned reference in the version
945// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000946var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000947var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000948
Paul Duffin0cb37b92020-03-04 14:52:46 +0000949// A BpPropertyTag that indicates the property should only be present in the versioned
950// module.
951//
952// This will cause the property to be removed from the unversioned instance of a
953// snapshot module.
954var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
955
Paul Duffine6c0d842020-01-15 14:08:51 +0000956type unversionedToVersionedTransformation struct {
957 identityTransformation
958 builder *snapshotBuilder
959}
960
Paul Duffine6c0d842020-01-15 14:08:51 +0000961func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
962 // Use a versioned name for the module but remember the original name for the
963 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100964 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000965 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000966 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100967 // Remove the prefer property if present as versioned modules never need marking with prefer.
968 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100969 // Ditto for use_source_config_var
970 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000971 return module
972}
973
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000974func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000975 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
976 required := tag == requiredSdkMemberReferencePropertyTag
977 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000978 } else {
979 return value, tag
980 }
981}
982
Paul Duffin72910952020-01-20 18:16:30 +0000983type unversionedTransformation struct {
984 identityTransformation
985 builder *snapshotBuilder
986}
987
988func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
989 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100990 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000991 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000992 return module
993}
994
995func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000996 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
997 required := tag == requiredSdkMemberReferencePropertyTag
998 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000999 } else if tag == sdkVersionedOnlyPropertyTag {
1000 // The property is not allowed in the unversioned module so remove it.
1001 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +00001002 } else {
1003 return value, tag
1004 }
1005}
1006
Paul Duffina78f3a72020-02-21 16:29:35 +00001007type pruneEmptySetTransformer struct {
1008 identityTransformation
1009}
1010
1011var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
1012
1013func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
1014 if len(propertySet.properties) == 0 {
1015 return nil, nil
1016 } else {
1017 return propertySet, tag
1018 }
1019}
1020
Paul Duffinb645ec82019-11-27 17:43:54 +00001021func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +00001022 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
1023 return true
1024 })
1025}
1026
1027func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001028 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +00001029 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +00001030 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001031 contents.IndentedPrintf("\n")
1032 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +00001033 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001034 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +00001035 }
Paul Duffinb645ec82019-11-27 17:43:54 +00001036 }
Paul Duffinb645ec82019-11-27 17:43:54 +00001037}
1038
1039func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
1040 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001041
Paul Duffin0df49682021-05-07 01:10:01 +01001042 addComment := func(name string) {
1043 if text, ok := set.comments[name]; ok {
1044 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001045 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +01001046 }
1047 }
1048 }
1049
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001050 // Output the properties first, followed by the nested sets. This ensures a
1051 // consistent output irrespective of whether property sets are created before
1052 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +00001053 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +00001054 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +00001055
Paul Duffin0df49682021-05-07 01:10:01 +01001056 // Do not write property sets in the properties phase.
1057 if _, ok := value.(*bpPropertySet); ok {
1058 continue
1059 }
1060
1061 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001062 reflectValue := reflect.ValueOf(value)
1063 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +00001064 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001065
1066 for _, name := range set.order {
1067 value := set.getValue(name)
1068
1069 // Only write property sets in the sets phase.
1070 switch v := value.(type) {
1071 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +01001072 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001073 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001074 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001075 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001076 }
1077 }
1078
Paul Duffinb645ec82019-11-27 17:43:54 +00001079 contents.Dedent()
1080}
1081
Paul Duffina08e4dc2021-06-22 18:19:19 +01001082// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
1083// by the value and then followed by a , and a newline.
1084func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
1085 contents.IndentedPrintf("%s: ", name)
1086 outputUnnamedValue(contents, value)
1087 contents.UnindentedPrintf(",\n")
1088}
1089
1090// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
1091// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
1092// indented and all but the last line will end with a newline.
1093func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
1094 valueType := value.Type()
1095 switch valueType.Kind() {
1096 case reflect.Bool:
1097 contents.UnindentedPrintf("%t", value.Bool())
1098
1099 case reflect.String:
1100 contents.UnindentedPrintf("%q", value)
1101
Paul Duffin51227d82021-05-18 12:54:27 +01001102 case reflect.Ptr:
1103 outputUnnamedValue(contents, value.Elem())
1104
Paul Duffina08e4dc2021-06-22 18:19:19 +01001105 case reflect.Slice:
1106 length := value.Len()
1107 if length == 0 {
1108 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +01001109 } else {
Paul Duffin51227d82021-05-18 12:54:27 +01001110 firstValue := value.Index(0)
1111 if length == 1 && !multiLineValue(firstValue) {
1112 contents.UnindentedPrintf("[")
1113 outputUnnamedValue(contents, firstValue)
1114 contents.UnindentedPrintf("]")
1115 } else {
1116 contents.UnindentedPrintf("[\n")
1117 contents.Indent()
1118 for i := 0; i < length; i++ {
1119 itemValue := value.Index(i)
1120 contents.IndentedPrintf("")
1121 outputUnnamedValue(contents, itemValue)
1122 contents.UnindentedPrintf(",\n")
1123 }
1124 contents.Dedent()
1125 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +01001126 }
Paul Duffina08e4dc2021-06-22 18:19:19 +01001127 }
1128
Paul Duffin51227d82021-05-18 12:54:27 +01001129 case reflect.Struct:
1130 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
1131 v := value.Interface()
1132 if _, ok := v.(android.BpPrintable); !ok {
1133 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
1134 }
1135 contents.UnindentedPrintf("{\n")
1136 contents.Indent()
1137 for f := 0; f < valueType.NumField(); f++ {
1138 fieldType := valueType.Field(f)
1139 if fieldType.Anonymous {
1140 continue
1141 }
1142 fieldValue := value.Field(f)
1143 fieldName := fieldType.Name
1144 propertyName := proptools.PropertyNameForField(fieldName)
1145 outputNamedValue(contents, propertyName, fieldValue)
1146 }
1147 contents.Dedent()
1148 contents.IndentedPrintf("}")
1149
Paul Duffina08e4dc2021-06-22 18:19:19 +01001150 default:
1151 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1152 }
1153}
1154
Paul Duffin51227d82021-05-18 12:54:27 +01001155// multiLineValue returns true if the supplied value may require multiple lines in the output.
1156func multiLineValue(value reflect.Value) bool {
1157 kind := value.Kind()
1158 return kind == reflect.Slice || kind == reflect.Struct
1159}
1160
Paul Duffinac37c502019-11-26 18:02:20 +00001161func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001162 contents := &generatedContents{}
1163 generateBpContents(contents, s.builderForTests.bpFile)
1164 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001165}
1166
Paul Duffinc6ba1822022-05-06 09:38:02 +00001167func (s *sdk) GetInfoContentsForTests() string {
1168 return s.builderForTests.infoContents
1169}
1170
Paul Duffind0759072021-02-17 11:23:00 +00001171func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1172 contents := &generatedContents{}
1173 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001174 name := module.Name()
1175 // Include modules that are either unversioned or have no name.
1176 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001177 })
1178 return contents.content.String()
1179}
1180
1181func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1182 contents := &generatedContents{}
1183 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001184 name := module.Name()
1185 // Include modules that are either versioned or have no name.
1186 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001187 })
1188 return contents.content.String()
1189}
1190
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001191type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001192 ctx android.ModuleContext
1193 sdk *sdk
1194
1195 // The version of the generated snapshot.
1196 //
1197 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1198 // this field.
1199 version string
1200
Paul Duffinb645ec82019-11-27 17:43:54 +00001201 snapshotDir android.OutputPath
1202 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001203
1204 // Map from destination to source of each copy - used to eliminate duplicates and
1205 // detect conflicts.
1206 copies map[string]string
1207
Paul Duffinb645ec82019-11-27 17:43:54 +00001208 filesToZip android.Paths
1209 zipsToMerge android.Paths
1210
Paul Duffin5c211452021-07-15 12:42:44 +01001211 // The path to an empty file.
1212 emptyFile android.WritablePath
1213
Paul Duffinb645ec82019-11-27 17:43:54 +00001214 prebuiltModules map[string]*bpModule
1215 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001216
1217 // The set of all members by name.
1218 allMembersByName map[string]struct{}
1219
1220 // The set of exported members by name.
1221 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001222
1223 // The target build release for which the snapshot is to be generated.
1224 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001225
1226 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001227}
1228
1229func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001230 if existing, ok := s.copies[dest]; ok {
1231 if existing != src.String() {
1232 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1233 return
1234 }
1235 } else {
1236 path := s.snapshotDir.Join(s.ctx, dest)
1237 s.ctx.Build(pctx, android.BuildParams{
1238 Rule: android.Cp,
1239 Input: src,
1240 Output: path,
1241 })
1242 s.filesToZip = append(s.filesToZip, path)
1243
1244 s.copies[dest] = src.String()
1245 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001246}
1247
Paul Duffin91547182019-11-12 19:39:36 +00001248func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1249 ctx := s.ctx
1250
1251 // Repackage the zip file so that the entries are in the destDir directory.
1252 // This will allow the zip file to be merged into the snapshot.
1253 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001254
1255 ctx.Build(pctx, android.BuildParams{
1256 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1257 Rule: repackageZip,
1258 Input: zipPath,
1259 Output: tmpZipPath,
1260 Args: map[string]string{
1261 "destdir": destDir,
1262 },
1263 })
Paul Duffin91547182019-11-12 19:39:36 +00001264
1265 // Add the repackaged zip file to the files to merge.
1266 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1267}
1268
Paul Duffin5c211452021-07-15 12:42:44 +01001269func (s *snapshotBuilder) EmptyFile() android.Path {
1270 if s.emptyFile == nil {
1271 ctx := s.ctx
1272 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1273 s.ctx.Build(pctx, android.BuildParams{
1274 Rule: android.Touch,
1275 Output: s.emptyFile,
1276 })
1277 }
1278
1279 return s.emptyFile
1280}
1281
Paul Duffin9d8d6092019-12-05 18:19:29 +00001282func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1283 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001284 if s.prebuiltModules[name] != nil {
1285 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1286 }
1287
1288 m := s.bpFile.newModule(moduleType)
1289 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001290
Paul Duffinbefa4b92020-03-04 14:22:45 +00001291 variant := member.Variants()[0]
1292
Paul Duffin13f02712020-03-06 12:30:43 +00001293 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001294 // An internal member is only referenced from the sdk snapshot which is in the
1295 // same package so can be marked as private.
1296 m.AddProperty("visibility", []string{"//visibility:private"})
1297 } else {
1298 // Extract visibility information from a member variant. All variants have the same
1299 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001300 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1301
1302 // Add any additional visibility rules needed for the prebuilts to reference each other.
1303 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1304 if err != nil {
1305 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1306 }
1307
1308 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001309 if len(visibility) != 0 {
1310 m.AddProperty("visibility", visibility)
1311 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001312 }
1313
Martin Stjernholm1e041092020-11-03 00:11:09 +00001314 // Where available copy apex_available properties from the member.
1315 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1316 apexAvailable := apexAware.ApexAvailable()
1317 if len(apexAvailable) == 0 {
1318 // //apex_available:platform is the default.
1319 apexAvailable = []string{android.AvailableToPlatform}
1320 }
1321
1322 // Add in any baseline apex available settings.
1323 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1324
1325 // Remove duplicates and sort.
1326 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1327 sort.Strings(apexAvailable)
1328
1329 m.AddProperty("apex_available", apexAvailable)
1330 }
1331
Paul Duffinb0bb3762021-05-06 16:48:05 +01001332 // The licenses are the same for all variants.
1333 mctx := s.ctx
1334 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1335 if len(licenseInfo.Licenses) > 0 {
1336 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1337 }
1338
Paul Duffin865171e2020-03-02 18:38:15 +00001339 deviceSupported := false
1340 hostSupported := false
1341
1342 for _, variant := range member.Variants() {
1343 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001344 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001345 hostSupported = true
1346 } else if osClass == android.Device {
1347 deviceSupported = true
1348 }
1349 }
1350
1351 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001352
Paul Duffin0cb37b92020-03-04 14:52:46 +00001353 // Disable installation in the versioned module of those modules that are ever installable.
1354 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1355 if installable.EverInstallable() {
1356 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1357 }
1358 }
1359
Paul Duffinb645ec82019-11-27 17:43:54 +00001360 s.prebuiltModules[name] = m
1361 s.prebuiltOrder = append(s.prebuiltOrder, m)
1362 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001363}
1364
Paul Duffin865171e2020-03-02 18:38:15 +00001365func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001366 // If neither device or host is supported then this module does not support either so will not
1367 // recognize the properties.
1368 if !deviceSupported && !hostSupported {
1369 return
1370 }
1371
Paul Duffin865171e2020-03-02 18:38:15 +00001372 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001373 bpModule.AddProperty("device_supported", false)
1374 }
Paul Duffin865171e2020-03-02 18:38:15 +00001375 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001376 bpModule.AddProperty("host_supported", true)
1377 }
1378}
1379
Paul Duffin13f02712020-03-06 12:30:43 +00001380func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1381 if required {
1382 return requiredSdkMemberReferencePropertyTag
1383 } else {
1384 return optionalSdkMemberReferencePropertyTag
1385 }
1386}
1387
1388func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1389 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001390}
1391
Paul Duffinb645ec82019-11-27 17:43:54 +00001392// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001393func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1394 if _, ok := s.allMembersByName[unversionedName]; !ok {
1395 if required {
1396 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1397 }
1398 return unversionedName
1399 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001400 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1401}
Paul Duffinb645ec82019-11-27 17:43:54 +00001402
Paul Duffin13f02712020-03-06 12:30:43 +00001403func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001404 var references []string = nil
1405 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001406 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001407 }
1408 return references
1409}
Paul Duffin13879572019-11-28 14:31:38 +00001410
Paul Duffin72910952020-01-20 18:16:30 +00001411// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001412func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1413 if _, ok := s.allMembersByName[unversionedName]; !ok {
1414 if required {
1415 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1416 }
1417 return unversionedName
1418 }
1419
1420 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001421 return s.ctx.ModuleName() + "_" + unversionedName
1422 } else {
1423 return unversionedName
1424 }
1425}
1426
Paul Duffin13f02712020-03-06 12:30:43 +00001427func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001428 var references []string = nil
1429 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001430 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001431 }
1432 return references
1433}
1434
Paul Duffin13f02712020-03-06 12:30:43 +00001435func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1436 _, ok := s.exportedMembersByName[memberName]
1437 return !ok
1438}
1439
Martin Stjernholm89238f42020-07-10 00:14:03 +01001440// Add the properties from the given SdkMemberProperties to the blueprint
1441// property set. This handles common properties in SdkMemberPropertiesBase and
1442// calls the member-specific AddToPropertySet for the rest.
1443func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1444 if memberProperties.Base().Compile_multilib != "" {
1445 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1446 }
1447
1448 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1449}
1450
Paul Duffin21827262021-04-24 12:16:36 +01001451// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1452type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001453 // The sdk variant that depends (possibly indirectly) on the member variant.
1454 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001455
1456 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001457 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001458
1459 // The variant that is added to the sdk.
1460 variant android.SdkAware
1461
Paul Duffinc6ba1822022-05-06 09:38:02 +00001462 // The optional container of this member, i.e. the module that is depended upon by the sdk
1463 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1464 // Is nil if this a direct dependency of the sdk.
1465 container android.SdkAware
1466
Paul Duffinb97b1572021-04-29 21:50:40 +01001467 // True if the member should be exported, i.e. accessible, from outside the sdk.
1468 export bool
1469
1470 // The names of additional component modules provided by the variant.
1471 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001472}
1473
Paul Duffin13879572019-11-28 14:31:38 +00001474var _ android.SdkMember = (*sdkMember)(nil)
1475
Paul Duffin21827262021-04-24 12:16:36 +01001476// sdkMember groups all the variants of a specific member module together along with the name of the
1477// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001478type sdkMember struct {
1479 memberType android.SdkMemberType
1480 name string
1481 variants []android.SdkAware
1482}
1483
1484func (m *sdkMember) Name() string {
1485 return m.name
1486}
1487
1488func (m *sdkMember) Variants() []android.SdkAware {
1489 return m.variants
1490}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001491
Paul Duffin9c3760e2020-03-16 19:52:08 +00001492// Track usages of multilib variants.
1493type multilibUsage int
1494
1495const (
1496 multilibNone multilibUsage = 0
1497 multilib32 multilibUsage = 1
1498 multilib64 multilibUsage = 2
1499 multilibBoth = multilib32 | multilib64
1500)
1501
1502// Add the multilib that is used in the arch type.
1503func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1504 multilib := archType.Multilib
1505 switch multilib {
1506 case "":
1507 return m
1508 case "lib32":
1509 return m | multilib32
1510 case "lib64":
1511 return m | multilib64
1512 default:
1513 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1514 }
1515}
1516
1517func (m multilibUsage) String() string {
1518 switch m {
1519 case multilibNone:
1520 return ""
1521 case multilib32:
1522 return "32"
1523 case multilib64:
1524 return "64"
1525 case multilibBoth:
1526 return "both"
1527 default:
1528 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1529 m, multilibNone, multilib32, multilib64, multilibBoth))
1530 }
1531}
1532
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001533type baseInfo struct {
1534 Properties android.SdkMemberProperties
1535}
1536
Paul Duffinf34f6d82020-04-30 15:48:31 +01001537func (b *baseInfo) optimizableProperties() interface{} {
1538 return b.Properties
1539}
1540
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001541type osTypeSpecificInfo struct {
1542 baseInfo
1543
Paul Duffin00e46802020-03-12 20:40:35 +00001544 osType android.OsType
1545
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001546 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001547 //
1548 // Nil if there is one variant whose arch type is common
1549 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001550}
1551
Paul Duffin4b8b7932020-05-06 12:35:38 +01001552var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1553
Paul Duffinfc8dd232020-03-17 12:51:37 +00001554type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1555
Paul Duffin00e46802020-03-12 20:40:35 +00001556// Create a new osTypeSpecificInfo for the specified os type and its properties
1557// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001558func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001559 osInfo := &osTypeSpecificInfo{
1560 osType: osType,
1561 }
1562
1563 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1564 properties := variantPropertiesFactory()
1565 properties.Base().Os = osType
1566 return properties
1567 }
1568
1569 // Create a structure into which properties common across the architectures in
1570 // this os type will be stored.
1571 osInfo.Properties = osSpecificVariantPropertiesFactory()
1572
1573 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001574 var variantsByArchId = make(map[archId][]android.Module)
1575 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001576 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001577 target := variant.Target()
1578 id := archIdFromTarget(target)
1579 if _, ok := variantsByArchId[id]; !ok {
1580 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001581 }
1582
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001583 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001584 }
1585
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001586 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001587 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001588 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 +00001589 }
1590
1591 // A common arch type only has one variant and its properties should be treated
1592 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001593 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001594 } else {
1595 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001596 for _, id := range archIds {
1597 archVariants := variantsByArchId[id]
1598 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001599
1600 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1601 }
1602 }
1603
1604 return osInfo
1605}
1606
Paul Duffin39abf8f2021-09-24 14:58:27 +01001607func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1608 if len(osInfo.archInfos) == 0 {
1609 pruner.pruneProperties(osInfo.Properties)
1610 } else {
1611 for _, archInfo := range osInfo.archInfos {
1612 archInfo.pruneUnsupportedProperties(pruner)
1613 }
1614 }
1615}
1616
Paul Duffin00e46802020-03-12 20:40:35 +00001617// Optimize the properties by extracting common properties from arch type specific
1618// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001619func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001620 // Nothing to do if there is only a single common architecture.
1621 if len(osInfo.archInfos) == 0 {
1622 return
1623 }
1624
Paul Duffin9c3760e2020-03-16 19:52:08 +00001625 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001626 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001627 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001628
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001629 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001630 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001631 }
1632
Paul Duffin4b8b7932020-05-06 12:35:38 +01001633 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001634
1635 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001636 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001637}
1638
1639// Add the properties for an os to a property set.
1640//
1641// Maps the properties related to the os variants through to an appropriate
1642// module structure that will produce equivalent set of variants when it is
1643// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001644func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001645
1646 var osPropertySet android.BpPropertySet
1647 var archPropertySet android.BpPropertySet
1648 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001649 if osInfo.Properties.Base().Os_count == 1 &&
1650 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1651 // There is only one OS type present in the variants and it shouldn't have a
1652 // variant-specific target. The latter is the case if it's either for device
1653 // where there is only one OS (android), or for host and the member type
1654 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001655
1656 // Create a structure that looks like:
1657 // module_type {
1658 // name: "...",
1659 // ...
1660 // <common properties>
1661 // ...
1662 // <single os type specific properties>
1663 //
1664 // arch: {
1665 // <arch specific sections>
1666 // }
1667 //
1668 osPropertySet = bpModule
1669 archPropertySet = osPropertySet.AddPropertySet("arch")
1670
1671 // Arch specific properties need to be added to an arch specific section
1672 // within arch.
1673 archOsPrefix = ""
1674 } else {
1675 // Create a structure that looks like:
1676 // module_type {
1677 // name: "...",
1678 // ...
1679 // <common properties>
1680 // ...
1681 // target: {
1682 // <arch independent os specific sections, e.g. android>
1683 // ...
1684 // <arch and os specific sections, e.g. android_x86>
1685 // }
1686 //
1687 osType := osInfo.osType
1688 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1689 archPropertySet = targetPropertySet
1690
1691 // Arch specific properties need to be added to an os and arch specific
1692 // section prefixed with <os>_.
1693 archOsPrefix = osType.Name + "_"
1694 }
1695
1696 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001697 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001698
1699 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1700 // os) specific properties.
1701 //
1702 // The archInfos list will be empty if the os contains variants for the common
1703 // architecture.
1704 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001705 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001706 }
1707}
1708
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001709func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1710 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001711 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001712}
1713
1714var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1715
Paul Duffin4b8b7932020-05-06 12:35:38 +01001716func (osInfo *osTypeSpecificInfo) String() string {
1717 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1718}
1719
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001720// archId encapsulates the information needed to identify a combination of arch type and native
1721// bridge support.
1722//
1723// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1724// essentially using one android.Arch to implement another. However, in terms of the handling of
1725// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1726// on android.Target.
1727//
1728// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1729type archId struct {
1730 // The arch type of the variant's target.
1731 archType android.ArchType
1732
1733 // True if the variants is for the native bridge, false otherwise.
1734 nativeBridge bool
1735}
1736
1737// propertyName returns the name of the property corresponding to use for this arch id.
1738func (i *archId) propertyName() string {
1739 name := i.archType.Name
1740 if i.nativeBridge {
1741 // Note: This does not result in a valid property because there is no architecture specific
1742 // native bridge property, only a generic "native_bridge" property. However, this will be used
1743 // in error messages if there is an attempt to use this in a generated bp file.
1744 name += "_native_bridge"
1745 }
1746 return name
1747}
1748
1749func (i *archId) String() string {
1750 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1751}
1752
1753// archIdFromTarget returns an archId initialized from information in the supplied target.
1754func archIdFromTarget(target android.Target) archId {
1755 return archId{
1756 archType: target.Arch.ArchType,
1757 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1758 }
1759}
1760
1761// commonArchId is the archId for the common architecture.
1762var commonArchId = archId{archType: android.Common}
1763
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001764type archTypeSpecificInfo struct {
1765 baseInfo
1766
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001767 archId archId
1768 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001769
Paul Duffinb42fa672021-09-09 16:37:49 +01001770 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001771}
1772
Paul Duffin4b8b7932020-05-06 12:35:38 +01001773var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1774
Paul Duffinfc8dd232020-03-17 12:51:37 +00001775// Create a new archTypeSpecificInfo for the specified arch type and its properties
1776// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001777func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001778
Paul Duffinfc8dd232020-03-17 12:51:37 +00001779 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001780 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001781
1782 // Create the properties into which the arch type specific properties will be
1783 // added.
1784 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001785
Liz Kammer96320df2022-05-12 20:40:00 -04001786 // if there are multiple supported link variants, we want to nest based on linkage even if there
1787 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1788 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001789 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001790 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001791 // Group the variants by image type.
1792 variantsByImage := make(map[string][]android.Module)
1793 for _, variant := range archVariants {
1794 image := variant.ImageVariation().Variation
1795 variantsByImage[image] = append(variantsByImage[image], variant)
1796 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001797
Paul Duffinb42fa672021-09-09 16:37:49 +01001798 // Create the image variant info in a fixed order.
1799 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1800 variants := variantsByImage[imageVariantName]
1801 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001802 }
1803 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001804
1805 return archInfo
1806}
1807
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001808// Get the link type of the variant
1809//
1810// If the variant is not differentiated by link type then it returns "",
1811// otherwise it returns one of "static" or "shared".
1812func getLinkType(variant android.Module) string {
1813 linkType := ""
1814 if linkable, ok := variant.(cc.LinkableInterface); ok {
1815 if linkable.Shared() && linkable.Static() {
1816 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1817 } else if linkable.Shared() {
1818 linkType = "shared"
1819 } else if linkable.Static() {
1820 linkType = "static"
1821 } else {
1822 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1823 }
1824 }
1825 return linkType
1826}
1827
Paul Duffin39abf8f2021-09-24 14:58:27 +01001828func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1829 if len(archInfo.imageVariantInfos) == 0 {
1830 pruner.pruneProperties(archInfo.Properties)
1831 } else {
1832 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1833 imageVariantInfo.pruneUnsupportedProperties(pruner)
1834 }
1835 }
1836}
1837
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001838// Optimize the properties by extracting common properties from link type specific
1839// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001840func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001841 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001842 return
1843 }
1844
Paul Duffinb42fa672021-09-09 16:37:49 +01001845 // Optimize the image variant properties first.
1846 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1847 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1848 }
1849
1850 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001851}
1852
Paul Duffinfc8dd232020-03-17 12:51:37 +00001853// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001854func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001855 archPropertySuffix := archInfo.archId.propertyName()
1856 propertySetName := archOsPrefix + archPropertySuffix
1857 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001858 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1859 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1860 archTypePropertySet.AddProperty("enabled", true)
1861 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001862 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001863
Paul Duffinb42fa672021-09-09 16:37:49 +01001864 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1865 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001866 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001867
1868 // If this is for a native bridge architecture then make sure that the property set does not
1869 // contain any properties as providing native bridge specific properties is not currently
1870 // supported.
1871 if archInfo.archId.nativeBridge {
1872 propertySetContents := getPropertySetContents(archTypePropertySet)
1873 if propertySetContents != "" {
1874 ctx.SdkModuleContext().ModuleErrorf("Architecture variant %q of sdk member %q has properties distinct from other variants; this is not yet supported. The properties are:\n%s",
1875 propertySetName, ctx.name, propertySetContents)
1876 }
1877 }
1878}
1879
1880// getPropertySetContents returns the string representation of the contents of a property set, after
1881// recursively pruning any empty nested property sets.
1882func getPropertySetContents(propertySet android.BpPropertySet) string {
1883 set := propertySet.(*bpPropertySet)
1884 set.transformContents(pruneEmptySetTransformer{})
1885 if len(set.properties) != 0 {
1886 contents := &generatedContents{}
1887 contents.Indent()
1888 outputPropertySet(contents, set)
1889 setAsString := contents.content.String()
1890 return setAsString
1891 }
1892 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001893}
1894
Paul Duffin4b8b7932020-05-06 12:35:38 +01001895func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001896 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001897}
1898
Paul Duffinb42fa672021-09-09 16:37:49 +01001899type imageVariantSpecificInfo struct {
1900 baseInfo
1901
1902 imageVariant string
1903
1904 linkInfos []*linkTypeSpecificInfo
1905}
1906
1907func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1908
1909 // Create an image variant specific info into which the variant properties can be copied.
1910 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1911
1912 // Create the properties into which the image variant specific properties will be added.
1913 imageInfo.Properties = variantPropertiesFactory()
1914
Liz Kammer96320df2022-05-12 20:40:00 -04001915 // if there are multiple supported link variants, we want to nest even if there is only one
1916 // variant, otherwise, if there is only one variant we can populate based on the image
1917 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001918 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1919 } else {
1920 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001921 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001922 for _, linkVariant := range imageVariants {
1923 linkType := getLinkType(linkVariant)
1924 if linkType == "" {
1925 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1926 } else {
1927 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1928
1929 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1930 }
1931 }
1932 }
1933
1934 return imageInfo
1935}
1936
Paul Duffin39abf8f2021-09-24 14:58:27 +01001937func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1938 if len(imageInfo.linkInfos) == 0 {
1939 pruner.pruneProperties(imageInfo.Properties)
1940 } else {
1941 for _, linkInfo := range imageInfo.linkInfos {
1942 linkInfo.pruneUnsupportedProperties(pruner)
1943 }
1944 }
1945}
1946
Paul Duffinb42fa672021-09-09 16:37:49 +01001947// Optimize the properties by extracting common properties from link type specific
1948// properties into arch type specific properties.
1949func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1950 if len(imageInfo.linkInfos) == 0 {
1951 return
1952 }
1953
1954 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1955}
1956
1957// Add the properties for an arch type to a property set.
1958func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1959 if imageInfo.imageVariant != android.CoreVariation {
1960 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1961 }
1962
1963 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1964
Liz Kammer96320df2022-05-12 20:40:00 -04001965 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001966 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001967 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001968 linkInfo.addToPropertySet(ctx, propertySet)
1969 }
1970
Liz Kammer96320df2022-05-12 20:40:00 -04001971 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1972 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1973 for _, l := range ctx.MemberType().SupportedLinkages() {
1974 if _, ok := usedLinkages[l]; !ok {
1975 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1976 otherLinkagePropertySet.AddProperty("enabled", false)
1977 }
1978 }
1979 }
1980
Paul Duffinb42fa672021-09-09 16:37:49 +01001981 // If this is for a non-core image variant then make sure that the property set does not contain
1982 // any properties as providing non-core image variant specific properties for prebuilts is not
1983 // currently supported.
1984 if imageInfo.imageVariant != android.CoreVariation {
1985 propertySetContents := getPropertySetContents(propertySet)
1986 if propertySetContents != "" {
1987 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",
1988 imageInfo.imageVariant, ctx.name, propertySetContents)
1989 }
1990 }
1991}
1992
1993func (imageInfo *imageVariantSpecificInfo) String() string {
1994 return imageInfo.imageVariant
1995}
1996
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001997type linkTypeSpecificInfo struct {
1998 baseInfo
1999
2000 linkType string
2001}
2002
Paul Duffin4b8b7932020-05-06 12:35:38 +01002003var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
2004
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002005// Create a new linkTypeSpecificInfo for the specified link type and its properties
2006// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002007func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002008 linkInfo := &linkTypeSpecificInfo{
2009 baseInfo: baseInfo{
2010 // Create the properties into which the link type specific properties will be
2011 // added.
2012 Properties: variantPropertiesFactory(),
2013 },
2014 linkType: linkType,
2015 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00002016 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002017 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00002018}
2019
Paul Duffinf68f85a2021-09-09 16:11:42 +01002020func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
2021 linkPropertySet := propertySet.AddPropertySet(l.linkType)
2022 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
2023}
2024
Paul Duffin39abf8f2021-09-24 14:58:27 +01002025func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
2026 pruner.pruneProperties(l.Properties)
2027}
2028
Paul Duffin4b8b7932020-05-06 12:35:38 +01002029func (l *linkTypeSpecificInfo) String() string {
2030 return fmt.Sprintf("LinkType{%s}", l.linkType)
2031}
2032
Paul Duffin3a4eb502020-03-19 16:11:18 +00002033type memberContext struct {
2034 sdkMemberContext android.ModuleContext
2035 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00002036 memberType android.SdkMemberType
2037 name string
Paul Duffind19f8942021-07-14 12:08:37 +01002038
2039 // The set of traits required of this member.
2040 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00002041}
2042
2043func (m *memberContext) SdkModuleContext() android.ModuleContext {
2044 return m.sdkMemberContext
2045}
2046
2047func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
2048 return m.builder
2049}
2050
Paul Duffina551a1c2020-03-17 21:04:24 +00002051func (m *memberContext) MemberType() android.SdkMemberType {
2052 return m.memberType
2053}
2054
2055func (m *memberContext) Name() string {
2056 return m.name
2057}
2058
Paul Duffind19f8942021-07-14 12:08:37 +01002059func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
2060 return m.requiredTraits.Contains(trait)
2061}
2062
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002063func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002064
2065 memberType := member.memberType
2066
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002067 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01002068 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002069 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00002070 // Set the prefer based on the environment variable. This is a temporary work around to allow a
2071 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002072 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
2073 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002074 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01002075
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002076 // Set prefer. Setting this to false is not strictly required as that is the default but it does
2077 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
2078 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
2079 // behavior is for the module.
2080 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002081
2082 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
2083 if configVar != "" {
2084 parts := strings.Split(configVar, ":")
2085 cfp := android.ConfigVarProperties{
2086 Config_namespace: proptools.StringPtr(parts[0]),
2087 Var_name: proptools.StringPtr(parts[1]),
2088 }
2089 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
2090 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002091 }
Paul Duffin83ad9562021-05-10 23:49:04 +01002092
Paul Duffina04c1072020-03-02 10:16:35 +00002093 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002094 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002095 variants := member.Variants()
2096 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00002097 osType := variant.Target().Os
2098 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002099 }
2100
Paul Duffina04c1072020-03-02 10:16:35 +00002101 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002102 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002103 properties := memberType.CreateVariantPropertiesStruct()
2104 base := properties.Base()
2105 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002106 return properties
2107 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002108
Paul Duffina04c1072020-03-02 10:16:35 +00002109 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002110
Paul Duffina04c1072020-03-02 10:16:35 +00002111 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002112 commonProperties := variantPropertiesFactory()
2113 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002114
Paul Duffin39abf8f2021-09-24 14:58:27 +01002115 // Create a property pruner that will prune any properties unsupported by the target build
2116 // release.
2117 targetBuildRelease := ctx.builder.targetBuildRelease
2118 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2119
Paul Duffinc097e362020-03-10 22:50:03 +00002120 // Create common value extractor that can be used to optimize the properties.
2121 commonValueExtractor := newCommonValueExtractor(commonProperties)
2122
Paul Duffina04c1072020-03-02 10:16:35 +00002123 // The list of property structures which are os type specific but common across
2124 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002125 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002126
2127 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002128 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002129 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002130 // Add the os specific properties to a list of os type specific yet architecture
2131 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002132 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002133
Paul Duffin39abf8f2021-09-24 14:58:27 +01002134 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2135
Paul Duffin00e46802020-03-12 20:40:35 +00002136 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002137 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002138 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002139
Paul Duffina04c1072020-03-02 10:16:35 +00002140 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002141 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002142
Paul Duffina04c1072020-03-02 10:16:35 +00002143 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002144 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002145
Paul Duffina04c1072020-03-02 10:16:35 +00002146 // Create a target property set into which target specific properties can be
2147 // added.
2148 targetPropertySet := bpModule.AddPropertySet("target")
2149
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002150 // If the member is host OS dependent and has host_supported then disable by
2151 // default and enable each host OS variant explicitly. This avoids problems
2152 // with implicitly enabled OS variants when the snapshot is used, which might
2153 // be different from this run (e.g. different build OS).
2154 if ctx.memberType.IsHostOsDependent() {
2155 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2156 if hostSupported {
2157 hostPropertySet := targetPropertySet.AddPropertySet("host")
2158 hostPropertySet.AddProperty("enabled", false)
2159 }
2160 }
2161
Paul Duffina04c1072020-03-02 10:16:35 +00002162 // Iterate over the os types in a fixed order.
2163 for _, osType := range s.getPossibleOsTypes() {
2164 osInfo := osTypeToInfo[osType]
2165 if osInfo == nil {
2166 continue
2167 }
2168
Paul Duffin3a4eb502020-03-19 16:11:18 +00002169 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002170 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002171}
2172
Paul Duffina04c1072020-03-02 10:16:35 +00002173// Compute the list of possible os types that this sdk could support.
2174func (s *sdk) getPossibleOsTypes() []android.OsType {
2175 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002176 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002177 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002178 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002179 osTypes = append(osTypes, osType)
2180 }
2181 }
2182 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002183 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002184 osTypes = append(osTypes, osType)
2185 }
2186 }
2187 }
2188 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2189 return osTypes
2190}
2191
Paul Duffinb28369a2020-05-04 15:39:59 +01002192// Given a set of properties (struct value), return the value of the field within that
2193// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002194type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2195
Paul Duffinc459f892020-04-30 18:08:29 +01002196// Checks the metadata to determine whether the property should be ignored for the
2197// purposes of common value extraction or not.
2198type extractorMetadataPredicate func(metadata propertiesContainer) bool
2199
2200// Indicates whether optimizable properties are provided by a host variant or
2201// not.
2202type isHostVariant interface {
2203 isHostVariant() bool
2204}
2205
Paul Duffinb28369a2020-05-04 15:39:59 +01002206// A property that can be optimized by the commonValueExtractor.
2207type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002208 // The name of the field for this property. It is a "."-separated path for
2209 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002210 name string
2211
Paul Duffinc459f892020-04-30 18:08:29 +01002212 // Filter that can use metadata associated with the properties being optimized
2213 // to determine whether the field should be ignored during common value
2214 // optimization.
2215 filter extractorMetadataPredicate
2216
Paul Duffinb28369a2020-05-04 15:39:59 +01002217 // Retrieves the value on which common value optimization will be performed.
2218 getter fieldAccessorFunc
2219
2220 // The empty value for the field.
2221 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002222
2223 // True if the property can support arch variants false otherwise.
2224 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002225}
2226
Paul Duffin4b8b7932020-05-06 12:35:38 +01002227func (p extractorProperty) String() string {
2228 return p.name
2229}
2230
Paul Duffinc097e362020-03-10 22:50:03 +00002231// Supports extracting common values from a number of instances of a properties
2232// structure into a separate common set of properties.
2233type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002234 // The properties that the extractor can optimize.
2235 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002236}
2237
2238// Create a new common value extractor for the structure type for the supplied
2239// properties struct.
2240//
2241// The returned extractor can be used on any properties structure of the same type
2242// as the supplied set of properties.
2243func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2244 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2245 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002246 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002247 return extractor
2248}
2249
2250// Gather the fields from the supplied structure type from which common values will
2251// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002252//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002253// This is recursive function. If it encounters a struct then it will recurse
2254// into it, passing in the accessor for the field and the struct name as prefix
2255// for the nested fields. That will then be used in the accessors for the fields
2256// in the embedded struct.
2257func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002258 for f := 0; f < structType.NumField(); f++ {
2259 field := structType.Field(f)
2260 if field.PkgPath != "" {
2261 // Ignore unexported fields.
2262 continue
2263 }
2264
Paul Duffinb07fa512020-03-10 22:17:04 +00002265 // Ignore fields whose value should be kept.
2266 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002267 continue
2268 }
2269
Paul Duffinc459f892020-04-30 18:08:29 +01002270 var filter extractorMetadataPredicate
2271
2272 // Add a filter
2273 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2274 filter = func(metadata propertiesContainer) bool {
2275 if m, ok := metadata.(isHostVariant); ok {
2276 if m.isHostVariant() {
2277 return false
2278 }
2279 }
2280 return true
2281 }
2282 }
2283
Paul Duffinc097e362020-03-10 22:50:03 +00002284 // Save a copy of the field index for use in the function.
2285 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002286
Martin Stjernholmb0249572020-09-15 02:32:35 +01002287 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002288
Paul Duffinc097e362020-03-10 22:50:03 +00002289 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002290 if containingStructAccessor != nil {
2291 // This is an embedded structure so first access the field for the embedded
2292 // structure.
2293 value = containingStructAccessor(value)
2294 }
2295
Paul Duffinc097e362020-03-10 22:50:03 +00002296 // Skip through interface and pointer values to find the structure.
2297 value = getStructValue(value)
2298
Paul Duffin4b8b7932020-05-06 12:35:38 +01002299 defer func() {
2300 if r := recover(); r != nil {
2301 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2302 }
2303 }()
2304
Paul Duffinc097e362020-03-10 22:50:03 +00002305 // Return the field.
2306 return value.Field(fieldIndex)
2307 }
2308
Martin Stjernholmb0249572020-09-15 02:32:35 +01002309 if field.Type.Kind() == reflect.Struct {
2310 // Gather fields from the nested or embedded structure.
2311 var subNamePrefix string
2312 if field.Anonymous {
2313 subNamePrefix = namePrefix
2314 } else {
2315 subNamePrefix = name + "."
2316 }
2317 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002318 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002319 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002320 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002321 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002322 fieldGetter,
2323 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002324 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002325 }
2326 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002327 }
Paul Duffinc097e362020-03-10 22:50:03 +00002328 }
2329}
2330
2331func getStructValue(value reflect.Value) reflect.Value {
2332foundStruct:
2333 for {
2334 kind := value.Kind()
2335 switch kind {
2336 case reflect.Interface, reflect.Ptr:
2337 value = value.Elem()
2338 case reflect.Struct:
2339 break foundStruct
2340 default:
2341 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2342 }
2343 }
2344 return value
2345}
2346
Paul Duffinf34f6d82020-04-30 15:48:31 +01002347// A container of properties to be optimized.
2348//
2349// Allows additional information to be associated with the properties, e.g. for
2350// filtering.
2351type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002352 fmt.Stringer
2353
Paul Duffinf34f6d82020-04-30 15:48:31 +01002354 // Get the properties that need optimizing.
2355 optimizableProperties() interface{}
2356}
2357
Paul Duffin2d1bb892021-04-24 11:32:59 +01002358// A wrapper for sdk variant related properties to allow them to be optimized.
2359type sdkVariantPropertiesContainer struct {
2360 sdkVariant *sdk
2361 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002362}
2363
Paul Duffin2d1bb892021-04-24 11:32:59 +01002364func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2365 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002366}
2367
Paul Duffin2d1bb892021-04-24 11:32:59 +01002368func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002369 return c.sdkVariant.String()
2370}
2371
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002372// Extract common properties from a slice of property structures of the same type.
2373//
2374// All the property structures must be of the same type.
2375// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002376// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002377//
2378// Iterates over each exported field (capitalized name) and checks to see whether they
2379// have the same value (using DeepEquals) across all the input properties. If it does not then no
2380// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002381// and the field in each of the input properties structure is set to its default value. Nested
2382// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002383func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002384 commonPropertiesValue := reflect.ValueOf(commonProperties)
2385 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002386
Paul Duffinf34f6d82020-04-30 15:48:31 +01002387 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2388
Paul Duffinb28369a2020-05-04 15:39:59 +01002389 for _, property := range e.properties {
2390 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002391 filter := property.filter
2392 if filter == nil {
2393 filter = func(metadata propertiesContainer) bool {
2394 return true
2395 }
2396 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002397
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002398 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002399 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2400 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002401 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002402
Paul Duffin864e1b42020-05-06 10:23:19 +01002403 // Assume that all the values will be the same.
2404 //
2405 // While similar to this is not quite the same as commonValue == nil. If all the values
2406 // have been filtered out then this will be false but commonValue == nil will be true.
2407 valuesDiffer := false
2408
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002409 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002410 container := sliceValue.Index(i).Interface().(propertiesContainer)
2411 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002412 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002413
Paul Duffinc459f892020-04-30 18:08:29 +01002414 if !filter(container) {
2415 expectedValue := property.emptyValue.Interface()
2416 actualValue := fieldValue.Interface()
2417 if !reflect.DeepEqual(expectedValue, actualValue) {
2418 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2419 }
2420 continue
2421 }
2422
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002423 if commonValue == nil {
2424 // Use the first value as the commonProperties value.
2425 commonValue = &fieldValue
2426 } else {
2427 // If the value does not match the current common value then there is
2428 // no value in common so break out.
2429 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2430 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002431 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002432 break
2433 }
2434 }
2435 }
2436
Paul Duffin864e1b42020-05-06 10:23:19 +01002437 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002438 // and set the input struct's field to the empty value.
2439 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002440 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002441 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002442 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002443 container := sliceValue.Index(i).Interface().(propertiesContainer)
2444 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002445 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002446 fieldValue.Set(emptyValue)
2447 }
2448 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002449
2450 if valuesDiffer && !property.archVariant {
2451 // The values differ but the property does not support arch variants so it
2452 // is an error.
2453 var details strings.Builder
2454 for i := 0; i < sliceValue.Len(); i++ {
2455 container := sliceValue.Index(i).Interface().(propertiesContainer)
2456 itemValue := reflect.ValueOf(container.optimizableProperties())
2457 fieldValue := fieldGetter(itemValue)
2458
2459 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2460 }
2461
2462 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2463 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002464 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002465
2466 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002467}