blob: af2b247b4703db9187aeff43e58589c0dcaf25ab [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 Duffin1a44a992022-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 Duffin1a44a992022-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 Duffin1a44a992022-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.
Paul Duffinb0c28d62022-07-01 15:56:06 +0000257func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, 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)
271 }
272
Paul Duffin1356d8c2020-02-25 19:26:33 +0000273 // Only append new variants to the list. This is needed because a member can be both
274 // exported by the sdk and also be a transitive sdk member.
275 member.variants = appendUniqueVariants(member.variants, variant)
276 }
277
Paul Duffin13879572019-11-28 14:31:38 +0000278 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100279 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinb0c28d62022-07-01 15:56:06 +0000280 memberType := memberListProperty.memberType
281
282 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
283 continue
284 }
285
286 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000287 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 Duffinb0c28d62022-07-01 15:56:06 +0000293// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
294// target build release.
295func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
296 supportedByTargetBuildRelease := true
297 supportedBuildReleases := memberType.SupportedBuildReleases()
298 if supportedBuildReleases == "" {
299 supportedBuildReleases = "S+"
300 }
301
302 set, err := parseBuildReleaseSet(supportedBuildReleases)
303 if err != nil {
304 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
305 memberType.SdkPropertyName(), supportedBuildReleases, err))
306 }
307 if !set.contains(targetBuildRelease) {
308 supportedByTargetBuildRelease = false
309 }
310 return supportedByTargetBuildRelease
311}
312
Paul Duffin72910952020-01-20 18:16:30 +0000313func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
314 for _, v := range variants {
315 if v == newVariant {
316 return variants
317 }
318 }
319 return append(variants, newVariant)
320}
321
Paul Duffin51509a12022-04-06 12:48:09 +0000322// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
323// the build from which the snapshot was produced.
324const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
325
Jiyong Park73c54ee2019-10-22 20:31:18 +0900326// SDK directory structure
327// <sdk_root>/
328// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
329// <api_ver>/ : below this directory are all auto-generated
330// Android.bp : definition of 'sdk_snapshot' module is here
331// aidl/
332// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
333// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900334// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900335// include/
336// bionic/libc/include/stdlib.h : an exported header file
337// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900338// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900339// <arch>/include/ : arch-specific exported headers
340// <arch>/include_gen/ : arch-specific generated headers
341// <arch>/lib/
342// libFoo.so : a stub library
343
Jiyong Park232e7852019-11-04 12:23:40 +0900344// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900345// This isn't visible to users, so could be changed in future.
346func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
347 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
348}
349
Jiyong Park232e7852019-11-04 12:23:40 +0900350// buildSnapshot is the main function in this source file. It creates rules to copy
351// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1a44a992022-05-06 09:38:02 +0000352func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000353
Paul Duffinb97b1572021-04-29 21:50:40 +0100354 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100355 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100356 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000357 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100358 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100359 }
Paul Duffin865171e2020-03-02 18:38:15 +0000360
Paul Duffinb97b1572021-04-29 21:50:40 +0100361 // Filter out any sdkMemberVariantDep that is a component of another.
362 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000363
Paul Duffinb97b1572021-04-29 21:50:40 +0100364 // Record the names of all the members, both explicitly specified and implicitly
365 // included.
366 allMembersByName := make(map[string]struct{})
367 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100368
Paul Duffinb97b1572021-04-29 21:50:40 +0100369 addMember := func(name string, export bool) {
370 allMembersByName[name] = struct{}{}
371 if export {
372 exportedMembersByName[name] = struct{}{}
373 }
374 }
375
376 for _, memberVariantDep := range memberVariantDeps {
377 name := memberVariantDep.variant.Name()
378 export := memberVariantDep.export
379
380 addMember(name, export)
381
382 // Add any components provided by the module.
383 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
384 addMember(component, export)
385 }
386
387 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
388 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000389 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000390 }
391
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000392 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900393
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000394 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000395
396 bpFile := &bpFile{
397 modules: make(map[string]*bpModule),
398 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000399
Paul Duffin43f7bf02021-05-05 22:00:51 +0100400 config := ctx.Config()
401 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
402
403 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
404 generateVersioned := version != soongSdkSnapshotVersionUnversioned
405
406 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
407 //
408 // Unversioned modules are not required in that case because the numbered version will be a
409 // finalized version of the snapshot that is intended to be kept separate from the
410 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
Paul Duffin1a44a992022-05-06 09:38:02 +0000411 snapshotFileSuffix := ""
Paul Duffin43f7bf02021-05-05 22:00:51 +0100412 if generateVersioned {
Paul Duffin1a44a992022-05-06 09:38:02 +0000413 snapshotFileSuffix = "-" + version
Paul Duffin43f7bf02021-05-05 22:00:51 +0100414 }
415
Paul Duffin39abf8f2021-09-24 14:58:27 +0100416 currentBuildRelease := latestBuildRelease()
417 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
418 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
419 if err != nil {
420 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
421 targetBuildRelease = currentBuildRelease
422 }
423
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000424 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000425 ctx: ctx,
426 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100427 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000428 snapshotDir: snapshotDir.OutputPath,
429 copies: make(map[string]string),
430 filesToZip: []android.Path{bp.path},
431 bpFile: bpFile,
432 prebuiltModules: make(map[string]*bpModule),
433 allMembersByName: allMembersByName,
434 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100435 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900436 }
Paul Duffinac37c502019-11-26 18:02:20 +0000437 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900438
Paul Duffin62131702021-05-07 01:10:01 +0100439 // If the sdk snapshot includes any license modules then add a package module which has a
440 // default_applicable_licenses property. That will prevent the LSC license process from updating
441 // the generated Android.bp file to add a package module that includes all licenses used by all
442 // the modules in that package. That would be unnecessary as every module in the sdk should have
443 // their own licenses property specified.
444 if hasLicenses {
445 pkg := bpFile.newModule("package")
446 property := "default_applicable_licenses"
447 pkg.AddCommentForProperty(property, `
448A default list here prevents the license LSC from adding its own list which would
449be unnecessary as every module in the sdk already has its own licenses property.
450`)
451 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
452 bpFile.AddModule(pkg)
453 }
454
Paul Duffin0df49682021-05-07 01:10:01 +0100455 // Group the variants for each member module together and then group the members of each member
456 // type together.
Paul Duffinb0c28d62022-07-01 15:56:06 +0000457 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100458
459 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100460 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000461 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000462 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000463
Paul Duffind19f8942021-07-14 12:08:37 +0100464 name := member.name
465 requiredTraits := traits[name]
466 if requiredTraits == nil {
467 requiredTraits = android.EmptySdkMemberTraitSet()
468 }
469
470 // Create the snapshot for the member.
471 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000472
473 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100474 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900475 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900476
Paul Duffine6c0d842020-01-15 14:08:51 +0000477 // Create a transformer that will transform an unversioned module into a versioned module.
478 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
479
Paul Duffin72910952020-01-20 18:16:30 +0000480 // Create a transformer that will transform an unversioned module by replacing any references
481 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100482 unversionedTransformer := unversionedTransformation{
483 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100484 }
Paul Duffin72910952020-01-20 18:16:30 +0000485
Paul Duffinb645ec82019-11-27 17:43:54 +0000486 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000487 // Prune any empty property sets.
488 unversioned = unversioned.transform(pruneEmptySetTransformer{})
489
Paul Duffin43f7bf02021-05-05 22:00:51 +0100490 if generateVersioned {
491 // Copy the unversioned module so it can be modified to make it versioned.
492 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000493
Paul Duffin43f7bf02021-05-05 22:00:51 +0100494 // Transform the unversioned module into a versioned one.
495 versioned.transform(unversionedToVersionedTransformer)
496 bpFile.AddModule(versioned)
497 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000498
Paul Duffin43f7bf02021-05-05 22:00:51 +0100499 if generateUnversioned {
500 // Transform the unversioned module to make it suitable for use in the snapshot.
501 unversioned.transform(unversionedTransformer)
502 bpFile.AddModule(unversioned)
503 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000504 }
505
Paul Duffin43f7bf02021-05-05 22:00:51 +0100506 if generateVersioned {
507 // Add the sdk/module_exports_snapshot module to the bp file.
508 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
509 }
Paul Duffin26197a62021-04-24 00:34:10 +0100510
511 // generate Android.bp
512 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
513 generateBpContents(&bp.generatedContents, bpFile)
514
515 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100516 // If the snapshot is being generated for the current build release then check the syntax to make
517 // sure that it is compatible.
518 if targetBuildRelease == currentBuildRelease {
519 syntaxCheckSnapshotBpFile(ctx, contents)
520 }
Paul Duffin26197a62021-04-24 00:34:10 +0100521
522 bp.build(pctx, ctx, nil)
523
Paul Duffin51509a12022-04-06 12:48:09 +0000524 // Copy the build number file into the snapshot.
525 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
526
Paul Duffin26197a62021-04-24 00:34:10 +0100527 filesToZip := builder.filesToZip
528
529 // zip them all
Paul Duffin1a44a992022-05-06 09:38:02 +0000530 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100531 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100532 outputDesc := "Building snapshot for " + ctx.ModuleName()
533
534 // If there are no zips to merge then generate the output zip directly.
535 // Otherwise, generate an intermediate zip file into which other zips can be
536 // merged.
537 var zipFile android.OutputPath
538 var desc string
539 if len(builder.zipsToMerge) == 0 {
540 zipFile = outputZipFile
541 desc = outputDesc
542 } else {
Paul Duffin1a44a992022-05-06 09:38:02 +0000543 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100544 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100545 desc = "Building intermediate snapshot for " + ctx.ModuleName()
546 }
547
548 ctx.Build(pctx, android.BuildParams{
549 Description: desc,
550 Rule: zipFiles,
551 Inputs: filesToZip,
552 Output: zipFile,
553 Args: map[string]string{
554 "basedir": builder.snapshotDir.String(),
555 },
556 })
557
558 if len(builder.zipsToMerge) != 0 {
559 ctx.Build(pctx, android.BuildParams{
560 Description: outputDesc,
561 Rule: mergeZips,
562 Input: zipFile,
563 Inputs: builder.zipsToMerge,
564 Output: outputZipFile,
565 })
566 }
567
Paul Duffin1a44a992022-05-06 09:38:02 +0000568 modules := s.generateInfoData(ctx, memberVariantDeps)
569
570 // Output the modules information as pretty printed JSON.
571 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
572 output, err := json.MarshalIndent(modules, "", " ")
573 if err != nil {
574 ctx.ModuleErrorf("error generating %q: %s", info, err)
575 }
576 builder.infoContents = string(output)
577 info.generatedContents.UnindentedPrintf("%s", output)
578 info.build(pctx, ctx, nil)
579 infoPath := info.path
580 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
581 s.infoFile = android.OptionalPathForPath(installedInfo)
582
583 // Install the zip, making sure that the info file has been installed as well.
584 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
585 s.snapshotFile = android.OptionalPathForPath(installedZip)
586}
587
588type moduleInfo struct {
589 // The type of the module, e.g. java_sdk_library
590 moduleType string
591 // The name of the module.
592 name string
593 // A list of additional dependencies of the module.
594 deps []string
Paul Duffindec81382022-05-16 13:10:47 +0000595 // Additional member specific properties.
596 // These will be added into the generated JSON alongside the above properties.
597 memberSpecific map[string]interface{}
Paul Duffin1a44a992022-05-06 09:38:02 +0000598}
599
600func (m *moduleInfo) MarshalJSON() ([]byte, error) {
601 buffer := bytes.Buffer{}
602
603 separator := ""
604 writeObjectPair := func(key string, value interface{}) {
605 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
606 b, err := json.Marshal(value)
607 if err != nil {
608 panic(err)
609 }
610 buffer.Write(b)
611 separator = ","
612 }
613
614 buffer.WriteString("{")
615 writeObjectPair("@type", m.moduleType)
616 writeObjectPair("@name", m.name)
617 if m.deps != nil {
618 writeObjectPair("@deps", m.deps)
619 }
Paul Duffindec81382022-05-16 13:10:47 +0000620 for _, k := range android.SortedStringKeys(m.memberSpecific) {
621 v := m.memberSpecific[k]
Paul Duffin1a44a992022-05-06 09:38:02 +0000622 writeObjectPair(k, v)
623 }
624 buffer.WriteString("}")
625 return buffer.Bytes(), nil
626}
627
628var _ json.Marshaler = (*moduleInfo)(nil)
629
630// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
631func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
632 modules := []*moduleInfo{}
633 sdkInfo := moduleInfo{
Paul Duffindec81382022-05-16 13:10:47 +0000634 moduleType: "sdk",
635 name: ctx.ModuleName(),
636 memberSpecific: map[string]interface{}{},
Paul Duffin1a44a992022-05-06 09:38:02 +0000637 }
638 modules = append(modules, &sdkInfo)
639
640 name2Info := map[string]*moduleInfo{}
641 getModuleInfo := func(module android.Module) *moduleInfo {
642 name := module.Name()
643 info := name2Info[name]
644 if info == nil {
645 moduleType := ctx.OtherModuleType(module)
646 // Remove any suffix added when creating modules dynamically.
647 moduleType = strings.Split(moduleType, "__")[0]
648 info = &moduleInfo{
649 moduleType: moduleType,
650 name: name,
651 }
Paul Duffindec81382022-05-16 13:10:47 +0000652
653 additionalSdkInfo := ctx.OtherModuleProvider(module, android.AdditionalSdkInfoProvider).(android.AdditionalSdkInfo)
654 info.memberSpecific = additionalSdkInfo.Properties
655
Paul Duffin1a44a992022-05-06 09:38:02 +0000656 name2Info[name] = info
657 }
658 return info
659 }
660
661 for _, memberVariantDep := range memberVariantDeps {
662 propertyName := memberVariantDep.memberType.SdkPropertyName()
663 var list []string
Paul Duffindec81382022-05-16 13:10:47 +0000664 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffin1a44a992022-05-06 09:38:02 +0000665 list = v.([]string)
666 }
667
668 memberName := memberVariantDep.variant.Name()
669 list = append(list, memberName)
Paul Duffindec81382022-05-16 13:10:47 +0000670 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffin1a44a992022-05-06 09:38:02 +0000671
672 if memberVariantDep.container != nil {
673 containerInfo := getModuleInfo(memberVariantDep.container)
674 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
675 }
676
677 // Make sure that the module info is created for each module.
678 getModuleInfo(memberVariantDep.variant)
679 }
680
681 for _, memberName := range android.SortedStringKeys(name2Info) {
682 info := name2Info[memberName]
683 modules = append(modules, info)
684 }
685
686 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100687}
688
Paul Duffinb97b1572021-04-29 21:50:40 +0100689// filterOutComponents removes any item from the deps list that is a component of another item in
690// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
691// then it will remove "foo.stubs" from the deps.
692func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
693 // Collate the set of components that all the modules added to the sdk provide.
694 components := map[string]*sdkMemberVariantDep{}
695 for i, _ := range deps {
696 dep := &deps[i]
697 for _, c := range dep.exportedComponentsInfo.Components {
698 components[c] = dep
699 }
700 }
701
702 // If no module provides components then return the input deps unfiltered.
703 if len(components) == 0 {
704 return deps
705 }
706
707 filtered := make([]sdkMemberVariantDep, 0, len(deps))
708 for _, dep := range deps {
709 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
710 if owner, ok := components[name]; ok {
711 // This is a component of another module that is a member of the sdk.
712
713 // If the component is exported but the owning module is not then the configuration is not
714 // supported.
715 if dep.export && !owner.export {
716 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
717 continue
718 }
719
720 // This module must not be added to the list of members of the sdk as that would result in a
721 // duplicate module in the sdk snapshot.
722 continue
723 }
724
725 filtered = append(filtered, dep)
726 }
727 return filtered
728}
729
Paul Duffin26197a62021-04-24 00:34:10 +0100730// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100731func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100732 bpFile := builder.bpFile
733
Paul Duffinb645ec82019-11-27 17:43:54 +0000734 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000735 var snapshotModuleType string
736 if s.properties.Module_exports {
737 snapshotModuleType = "module_exports_snapshot"
738 } else {
739 snapshotModuleType = "sdk_snapshot"
740 }
741 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000742 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000743
744 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100745 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000746 if len(visibility) != 0 {
747 snapshotModule.AddProperty("visibility", visibility)
748 }
749
Paul Duffin865171e2020-03-02 18:38:15 +0000750 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000751
Paul Duffincd064672021-04-24 00:47:29 +0100752 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100753 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000754
Paul Duffin2d1bb892021-04-24 11:32:59 +0100755 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100756
Paul Duffin6a7e9532020-03-20 17:50:07 +0000757 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100758
Paul Duffin2d1bb892021-04-24 11:32:59 +0100759 // Create a mapping from osType to combined properties.
760 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
761 for _, combined := range combinedPropertiesList {
762 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
763 }
764
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100765 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000766 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100767 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100768 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000769
Paul Duffin2d1bb892021-04-24 11:32:59 +0100770 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000771 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000772 }
Paul Duffin865171e2020-03-02 18:38:15 +0000773
Jiyong Park8fe14e62020-10-19 22:47:34 +0900774 // If host is supported and any member is host OS dependent then disable host
775 // by default, so that we can enable each host OS variant explicitly. This
776 // avoids problems with implicitly enabled OS variants when the snapshot is
777 // used, which might be different from this run (e.g. different build OS).
778 if s.HostSupported() {
779 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100780 for _, memberVariantDep := range memberVariantDeps {
781 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
782 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900783 if !android.InList(targetString, supportedHostTargets) {
784 supportedHostTargets = append(supportedHostTargets, targetString)
785 }
786 }
787 }
788 if len(supportedHostTargets) > 0 {
789 hostPropertySet := targetPropertySet.AddPropertySet("host")
790 hostPropertySet.AddProperty("enabled", false)
791 }
792 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
793 for _, hostTarget := range supportedHostTargets {
794 propertySet := targetPropertySet.AddPropertySet(hostTarget)
795 propertySet.AddProperty("enabled", true)
796 }
797 }
798
Paul Duffin865171e2020-03-02 18:38:15 +0000799 // Prune any empty property sets.
800 snapshotModule.transform(pruneEmptySetTransformer{})
801
Paul Duffinb645ec82019-11-27 17:43:54 +0000802 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900803}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000804
Paul Duffinf88d8e02020-05-07 20:21:34 +0100805// Check the syntax of the generated Android.bp file contents and if they are
806// invalid then log an error with the contents (tagged with line numbers) and the
807// errors that were found so that it is easy to see where the problem lies.
808func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
809 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
810 if len(errs) != 0 {
811 message := &strings.Builder{}
812 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
813
814Generated Android.bp contents
815========================================================================
816`)
817 for i, line := range strings.Split(contents, "\n") {
818 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
819 }
820
821 _, _ = fmt.Fprint(message, `
822========================================================================
823
824Errors found:
825`)
826
827 for _, err := range errs {
828 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
829 }
830
831 ctx.ModuleErrorf("%s", message.String())
832 }
833}
834
Paul Duffin4b8b7932020-05-06 12:35:38 +0100835func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
836 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
837 if err != nil {
838 ctx.ModuleErrorf("error extracting common properties: %s", err)
839 }
840}
841
Paul Duffinfbe470e2021-04-24 12:37:13 +0100842// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
843type snapshotModuleStaticProperties struct {
844 Compile_multilib string `android:"arch_variant"`
845}
846
Paul Duffin2d1bb892021-04-24 11:32:59 +0100847// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
848type combinedSnapshotModuleProperties struct {
849 // The sdk variant from which this information was collected.
850 sdkVariant *sdk
851
852 // Static snapshot module properties.
853 staticProperties *snapshotModuleStaticProperties
854
855 // The dynamically generated member list properties.
856 dynamicProperties interface{}
857}
858
859// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100860func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
861 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100862 var list []*combinedSnapshotModuleProperties
863 for _, sdkVariant := range sdkVariants {
864 staticProperties := &snapshotModuleStaticProperties{
865 Compile_multilib: sdkVariant.multilibUsages.String(),
866 }
Paul Duffin62782de2021-07-14 12:05:16 +0100867 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100868
Paul Duffincd064672021-04-24 00:47:29 +0100869 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100870 sdkVariant: sdkVariant,
871 staticProperties: staticProperties,
872 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100873 }
874 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
875
876 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100877 }
Paul Duffincd064672021-04-24 00:47:29 +0100878
879 for _, memberVariantDep := range memberVariantDeps {
880 // If the member dependency is internal then do not add the dependency to the snapshot member
881 // list properties.
882 if !memberVariantDep.export {
883 continue
884 }
885
886 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100887 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100888 memberName := ctx.OtherModuleName(memberVariantDep.variant)
889
Paul Duffin13082052021-05-11 00:31:38 +0100890 if memberListProperty.getter == nil {
891 continue
892 }
893
Paul Duffincd064672021-04-24 00:47:29 +0100894 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100895 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100896 if !android.InList(memberName, memberList) {
897 memberList = append(memberList, memberName)
898 }
Paul Duffin13082052021-05-11 00:31:38 +0100899 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100900 }
901
Paul Duffin2d1bb892021-04-24 11:32:59 +0100902 return list
903}
904
905func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
906
907 // Extract the dynamic properties and add them to a list of propertiesContainer.
908 propertyContainers := []propertiesContainer{}
909 for _, i := range list {
910 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
911 sdkVariant: i.sdkVariant,
912 properties: i.dynamicProperties,
913 })
914 }
915
916 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100917 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100918 extractor := newCommonValueExtractor(commonDynamicProperties)
919 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
920
921 // Extract the static properties and add them to a list of propertiesContainer.
922 propertyContainers = []propertiesContainer{}
923 for _, i := range list {
924 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
925 sdkVariant: i.sdkVariant,
926 properties: i.staticProperties,
927 })
928 }
929
930 commonStaticProperties := &snapshotModuleStaticProperties{}
931 extractor = newCommonValueExtractor(commonStaticProperties)
932 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
933
934 return &combinedSnapshotModuleProperties{
935 sdkVariant: nil,
936 staticProperties: commonStaticProperties,
937 dynamicProperties: commonDynamicProperties,
938 }
939}
940
941func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
942 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100943 multilib := staticProperties.Compile_multilib
944 if multilib != "" && multilib != "both" {
945 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
946 propertySet.AddProperty("compile_multilib", multilib)
947 }
948
Paul Duffin2d1bb892021-04-24 11:32:59 +0100949 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100950 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100951 if memberListProperty.getter == nil {
952 continue
953 }
Paul Duffinb0c28d62022-07-01 15:56:06 +0000954 if !isMemberTypeSupportedByTargetBuildRelease(memberListProperty.memberType, builder.targetBuildRelease) {
955 continue
956 }
Paul Duffin865171e2020-03-02 18:38:15 +0000957 names := memberListProperty.getter(dynamicMemberTypeListProperties)
958 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000959 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000960 }
961 }
962}
963
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000964type propertyTag struct {
965 name string
966}
967
Paul Duffin94289702021-09-09 15:38:32 +0100968var _ android.BpPropertyTag = propertyTag{}
969
Paul Duffin0cb37b92020-03-04 14:52:46 +0000970// A BpPropertyTag to add to a property that contains references to other sdk members.
971//
972// This will cause the references to be rewritten to a versioned reference in the version
973// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000974var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000975var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000976
Paul Duffin0cb37b92020-03-04 14:52:46 +0000977// A BpPropertyTag that indicates the property should only be present in the versioned
978// module.
979//
980// This will cause the property to be removed from the unversioned instance of a
981// snapshot module.
982var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
983
Paul Duffine6c0d842020-01-15 14:08:51 +0000984type unversionedToVersionedTransformation struct {
985 identityTransformation
986 builder *snapshotBuilder
987}
988
Paul Duffine6c0d842020-01-15 14:08:51 +0000989func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
990 // Use a versioned name for the module but remember the original name for the
991 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100992 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000993 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000994 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100995 // Remove the prefer property if present as versioned modules never need marking with prefer.
996 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100997 // Ditto for use_source_config_var
998 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000999 return module
1000}
1001
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001002func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +00001003 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
1004 required := tag == requiredSdkMemberReferencePropertyTag
1005 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001006 } else {
1007 return value, tag
1008 }
1009}
1010
Paul Duffin72910952020-01-20 18:16:30 +00001011type unversionedTransformation struct {
1012 identityTransformation
1013 builder *snapshotBuilder
1014}
1015
1016func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
1017 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +01001018 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +00001019 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +00001020 return module
1021}
1022
1023func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +00001024 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
1025 required := tag == requiredSdkMemberReferencePropertyTag
1026 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +00001027 } else if tag == sdkVersionedOnlyPropertyTag {
1028 // The property is not allowed in the unversioned module so remove it.
1029 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +00001030 } else {
1031 return value, tag
1032 }
1033}
1034
Paul Duffina78f3a72020-02-21 16:29:35 +00001035type pruneEmptySetTransformer struct {
1036 identityTransformation
1037}
1038
1039var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
1040
1041func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
1042 if len(propertySet.properties) == 0 {
1043 return nil, nil
1044 } else {
1045 return propertySet, tag
1046 }
1047}
1048
Paul Duffinb645ec82019-11-27 17:43:54 +00001049func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +00001050 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
1051 return true
1052 })
1053}
1054
1055func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001056 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +00001057 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +00001058 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001059 contents.IndentedPrintf("\n")
1060 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +00001061 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001062 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +00001063 }
Paul Duffinb645ec82019-11-27 17:43:54 +00001064 }
Paul Duffinb645ec82019-11-27 17:43:54 +00001065}
1066
1067func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
1068 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001069
Paul Duffin0df49682021-05-07 01:10:01 +01001070 addComment := func(name string) {
1071 if text, ok := set.comments[name]; ok {
1072 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001073 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +01001074 }
1075 }
1076 }
1077
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001078 // Output the properties first, followed by the nested sets. This ensures a
1079 // consistent output irrespective of whether property sets are created before
1080 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +00001081 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +00001082 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +00001083
Paul Duffin0df49682021-05-07 01:10:01 +01001084 // Do not write property sets in the properties phase.
1085 if _, ok := value.(*bpPropertySet); ok {
1086 continue
1087 }
1088
1089 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001090 reflectValue := reflect.ValueOf(value)
1091 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +00001092 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001093
1094 for _, name := range set.order {
1095 value := set.getValue(name)
1096
1097 // Only write property sets in the sets phase.
1098 switch v := value.(type) {
1099 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +01001100 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001101 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001102 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001103 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001104 }
1105 }
1106
Paul Duffinb645ec82019-11-27 17:43:54 +00001107 contents.Dedent()
1108}
1109
Paul Duffina08e4dc2021-06-22 18:19:19 +01001110// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
1111// by the value and then followed by a , and a newline.
1112func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
1113 contents.IndentedPrintf("%s: ", name)
1114 outputUnnamedValue(contents, value)
1115 contents.UnindentedPrintf(",\n")
1116}
1117
1118// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
1119// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
1120// indented and all but the last line will end with a newline.
1121func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
1122 valueType := value.Type()
1123 switch valueType.Kind() {
1124 case reflect.Bool:
1125 contents.UnindentedPrintf("%t", value.Bool())
1126
1127 case reflect.String:
1128 contents.UnindentedPrintf("%q", value)
1129
Paul Duffin51227d82021-05-18 12:54:27 +01001130 case reflect.Ptr:
1131 outputUnnamedValue(contents, value.Elem())
1132
Paul Duffina08e4dc2021-06-22 18:19:19 +01001133 case reflect.Slice:
1134 length := value.Len()
1135 if length == 0 {
1136 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +01001137 } else {
Paul Duffin51227d82021-05-18 12:54:27 +01001138 firstValue := value.Index(0)
1139 if length == 1 && !multiLineValue(firstValue) {
1140 contents.UnindentedPrintf("[")
1141 outputUnnamedValue(contents, firstValue)
1142 contents.UnindentedPrintf("]")
1143 } else {
1144 contents.UnindentedPrintf("[\n")
1145 contents.Indent()
1146 for i := 0; i < length; i++ {
1147 itemValue := value.Index(i)
1148 contents.IndentedPrintf("")
1149 outputUnnamedValue(contents, itemValue)
1150 contents.UnindentedPrintf(",\n")
1151 }
1152 contents.Dedent()
1153 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +01001154 }
Paul Duffina08e4dc2021-06-22 18:19:19 +01001155 }
1156
Paul Duffin51227d82021-05-18 12:54:27 +01001157 case reflect.Struct:
1158 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
1159 v := value.Interface()
1160 if _, ok := v.(android.BpPrintable); !ok {
1161 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
1162 }
1163 contents.UnindentedPrintf("{\n")
1164 contents.Indent()
1165 for f := 0; f < valueType.NumField(); f++ {
1166 fieldType := valueType.Field(f)
1167 if fieldType.Anonymous {
1168 continue
1169 }
1170 fieldValue := value.Field(f)
1171 fieldName := fieldType.Name
1172 propertyName := proptools.PropertyNameForField(fieldName)
1173 outputNamedValue(contents, propertyName, fieldValue)
1174 }
1175 contents.Dedent()
1176 contents.IndentedPrintf("}")
1177
Paul Duffina08e4dc2021-06-22 18:19:19 +01001178 default:
1179 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1180 }
1181}
1182
Paul Duffin51227d82021-05-18 12:54:27 +01001183// multiLineValue returns true if the supplied value may require multiple lines in the output.
1184func multiLineValue(value reflect.Value) bool {
1185 kind := value.Kind()
1186 return kind == reflect.Slice || kind == reflect.Struct
1187}
1188
Paul Duffinac37c502019-11-26 18:02:20 +00001189func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001190 contents := &generatedContents{}
1191 generateBpContents(contents, s.builderForTests.bpFile)
1192 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001193}
1194
Paul Duffin1a44a992022-05-06 09:38:02 +00001195func (s *sdk) GetInfoContentsForTests() string {
1196 return s.builderForTests.infoContents
1197}
1198
Paul Duffind0759072021-02-17 11:23:00 +00001199func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1200 contents := &generatedContents{}
1201 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001202 name := module.Name()
1203 // Include modules that are either unversioned or have no name.
1204 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001205 })
1206 return contents.content.String()
1207}
1208
1209func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1210 contents := &generatedContents{}
1211 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001212 name := module.Name()
1213 // Include modules that are either versioned or have no name.
1214 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001215 })
1216 return contents.content.String()
1217}
1218
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001219type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001220 ctx android.ModuleContext
1221 sdk *sdk
1222
1223 // The version of the generated snapshot.
1224 //
1225 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1226 // this field.
1227 version string
1228
Paul Duffinb645ec82019-11-27 17:43:54 +00001229 snapshotDir android.OutputPath
1230 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001231
1232 // Map from destination to source of each copy - used to eliminate duplicates and
1233 // detect conflicts.
1234 copies map[string]string
1235
Paul Duffinb645ec82019-11-27 17:43:54 +00001236 filesToZip android.Paths
1237 zipsToMerge android.Paths
1238
Paul Duffin5c211452021-07-15 12:42:44 +01001239 // The path to an empty file.
1240 emptyFile android.WritablePath
1241
Paul Duffinb645ec82019-11-27 17:43:54 +00001242 prebuiltModules map[string]*bpModule
1243 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001244
1245 // The set of all members by name.
1246 allMembersByName map[string]struct{}
1247
1248 // The set of exported members by name.
1249 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001250
1251 // The target build release for which the snapshot is to be generated.
1252 targetBuildRelease *buildRelease
Paul Duffin1a44a992022-05-06 09:38:02 +00001253
Paul Duffindec81382022-05-16 13:10:47 +00001254 // The contents of the .info file that describes the sdk contents.
Paul Duffin1a44a992022-05-06 09:38:02 +00001255 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001256}
1257
1258func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001259 if existing, ok := s.copies[dest]; ok {
1260 if existing != src.String() {
1261 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1262 return
1263 }
1264 } else {
1265 path := s.snapshotDir.Join(s.ctx, dest)
1266 s.ctx.Build(pctx, android.BuildParams{
1267 Rule: android.Cp,
1268 Input: src,
1269 Output: path,
1270 })
1271 s.filesToZip = append(s.filesToZip, path)
1272
1273 s.copies[dest] = src.String()
1274 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001275}
1276
Paul Duffin91547182019-11-12 19:39:36 +00001277func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1278 ctx := s.ctx
1279
1280 // Repackage the zip file so that the entries are in the destDir directory.
1281 // This will allow the zip file to be merged into the snapshot.
1282 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001283
1284 ctx.Build(pctx, android.BuildParams{
1285 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1286 Rule: repackageZip,
1287 Input: zipPath,
1288 Output: tmpZipPath,
1289 Args: map[string]string{
1290 "destdir": destDir,
1291 },
1292 })
Paul Duffin91547182019-11-12 19:39:36 +00001293
1294 // Add the repackaged zip file to the files to merge.
1295 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1296}
1297
Paul Duffin5c211452021-07-15 12:42:44 +01001298func (s *snapshotBuilder) EmptyFile() android.Path {
1299 if s.emptyFile == nil {
1300 ctx := s.ctx
1301 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1302 s.ctx.Build(pctx, android.BuildParams{
1303 Rule: android.Touch,
1304 Output: s.emptyFile,
1305 })
1306 }
1307
1308 return s.emptyFile
1309}
1310
Paul Duffin9d8d6092019-12-05 18:19:29 +00001311func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1312 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001313 if s.prebuiltModules[name] != nil {
1314 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1315 }
1316
1317 m := s.bpFile.newModule(moduleType)
1318 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001319
Paul Duffinbefa4b92020-03-04 14:22:45 +00001320 variant := member.Variants()[0]
1321
Paul Duffin13f02712020-03-06 12:30:43 +00001322 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001323 // An internal member is only referenced from the sdk snapshot which is in the
1324 // same package so can be marked as private.
1325 m.AddProperty("visibility", []string{"//visibility:private"})
1326 } else {
1327 // Extract visibility information from a member variant. All variants have the same
1328 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001329 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1330
1331 // Add any additional visibility rules needed for the prebuilts to reference each other.
1332 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1333 if err != nil {
1334 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1335 }
1336
1337 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001338 if len(visibility) != 0 {
1339 m.AddProperty("visibility", visibility)
1340 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001341 }
1342
Martin Stjernholm1e041092020-11-03 00:11:09 +00001343 // Where available copy apex_available properties from the member.
1344 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1345 apexAvailable := apexAware.ApexAvailable()
1346 if len(apexAvailable) == 0 {
1347 // //apex_available:platform is the default.
1348 apexAvailable = []string{android.AvailableToPlatform}
1349 }
1350
1351 // Add in any baseline apex available settings.
1352 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1353
1354 // Remove duplicates and sort.
1355 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1356 sort.Strings(apexAvailable)
1357
1358 m.AddProperty("apex_available", apexAvailable)
1359 }
1360
Paul Duffinb0bb3762021-05-06 16:48:05 +01001361 // The licenses are the same for all variants.
1362 mctx := s.ctx
1363 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1364 if len(licenseInfo.Licenses) > 0 {
1365 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1366 }
1367
Paul Duffin865171e2020-03-02 18:38:15 +00001368 deviceSupported := false
1369 hostSupported := false
1370
1371 for _, variant := range member.Variants() {
1372 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001373 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001374 hostSupported = true
1375 } else if osClass == android.Device {
1376 deviceSupported = true
1377 }
1378 }
1379
1380 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001381
Paul Duffin0cb37b92020-03-04 14:52:46 +00001382 // Disable installation in the versioned module of those modules that are ever installable.
1383 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1384 if installable.EverInstallable() {
1385 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1386 }
1387 }
1388
Paul Duffinb645ec82019-11-27 17:43:54 +00001389 s.prebuiltModules[name] = m
1390 s.prebuiltOrder = append(s.prebuiltOrder, m)
1391 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001392}
1393
Paul Duffin865171e2020-03-02 18:38:15 +00001394func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001395 // If neither device or host is supported then this module does not support either so will not
1396 // recognize the properties.
1397 if !deviceSupported && !hostSupported {
1398 return
1399 }
1400
Paul Duffin865171e2020-03-02 18:38:15 +00001401 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001402 bpModule.AddProperty("device_supported", false)
1403 }
Paul Duffin865171e2020-03-02 18:38:15 +00001404 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001405 bpModule.AddProperty("host_supported", true)
1406 }
1407}
1408
Paul Duffin13f02712020-03-06 12:30:43 +00001409func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1410 if required {
1411 return requiredSdkMemberReferencePropertyTag
1412 } else {
1413 return optionalSdkMemberReferencePropertyTag
1414 }
1415}
1416
1417func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1418 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001419}
1420
Paul Duffinb645ec82019-11-27 17:43:54 +00001421// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001422func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1423 if _, ok := s.allMembersByName[unversionedName]; !ok {
1424 if required {
1425 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1426 }
1427 return unversionedName
1428 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001429 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1430}
Paul Duffinb645ec82019-11-27 17:43:54 +00001431
Paul Duffin13f02712020-03-06 12:30:43 +00001432func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001433 var references []string = nil
1434 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001435 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001436 }
1437 return references
1438}
Paul Duffin13879572019-11-28 14:31:38 +00001439
Paul Duffin72910952020-01-20 18:16:30 +00001440// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001441func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1442 if _, ok := s.allMembersByName[unversionedName]; !ok {
1443 if required {
1444 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1445 }
1446 return unversionedName
1447 }
1448
1449 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001450 return s.ctx.ModuleName() + "_" + unversionedName
1451 } else {
1452 return unversionedName
1453 }
1454}
1455
Paul Duffin13f02712020-03-06 12:30:43 +00001456func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001457 var references []string = nil
1458 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001459 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001460 }
1461 return references
1462}
1463
Paul Duffin13f02712020-03-06 12:30:43 +00001464func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1465 _, ok := s.exportedMembersByName[memberName]
1466 return !ok
1467}
1468
Martin Stjernholm89238f42020-07-10 00:14:03 +01001469// Add the properties from the given SdkMemberProperties to the blueprint
1470// property set. This handles common properties in SdkMemberPropertiesBase and
1471// calls the member-specific AddToPropertySet for the rest.
1472func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1473 if memberProperties.Base().Compile_multilib != "" {
1474 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1475 }
1476
1477 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1478}
1479
Paul Duffin21827262021-04-24 12:16:36 +01001480// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1481type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001482 // The sdk variant that depends (possibly indirectly) on the member variant.
1483 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001484
1485 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001486 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001487
1488 // The variant that is added to the sdk.
1489 variant android.SdkAware
1490
Paul Duffin1a44a992022-05-06 09:38:02 +00001491 // The optional container of this member, i.e. the module that is depended upon by the sdk
1492 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1493 // Is nil if this a direct dependency of the sdk.
1494 container android.SdkAware
1495
Paul Duffinb97b1572021-04-29 21:50:40 +01001496 // True if the member should be exported, i.e. accessible, from outside the sdk.
1497 export bool
1498
1499 // The names of additional component modules provided by the variant.
1500 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001501}
1502
Paul Duffin13879572019-11-28 14:31:38 +00001503var _ android.SdkMember = (*sdkMember)(nil)
1504
Paul Duffin21827262021-04-24 12:16:36 +01001505// sdkMember groups all the variants of a specific member module together along with the name of the
1506// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001507type sdkMember struct {
1508 memberType android.SdkMemberType
1509 name string
1510 variants []android.SdkAware
1511}
1512
1513func (m *sdkMember) Name() string {
1514 return m.name
1515}
1516
1517func (m *sdkMember) Variants() []android.SdkAware {
1518 return m.variants
1519}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001520
Paul Duffin9c3760e2020-03-16 19:52:08 +00001521// Track usages of multilib variants.
1522type multilibUsage int
1523
1524const (
1525 multilibNone multilibUsage = 0
1526 multilib32 multilibUsage = 1
1527 multilib64 multilibUsage = 2
1528 multilibBoth = multilib32 | multilib64
1529)
1530
1531// Add the multilib that is used in the arch type.
1532func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1533 multilib := archType.Multilib
1534 switch multilib {
1535 case "":
1536 return m
1537 case "lib32":
1538 return m | multilib32
1539 case "lib64":
1540 return m | multilib64
1541 default:
1542 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1543 }
1544}
1545
1546func (m multilibUsage) String() string {
1547 switch m {
1548 case multilibNone:
1549 return ""
1550 case multilib32:
1551 return "32"
1552 case multilib64:
1553 return "64"
1554 case multilibBoth:
1555 return "both"
1556 default:
1557 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1558 m, multilibNone, multilib32, multilib64, multilibBoth))
1559 }
1560}
1561
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001562type baseInfo struct {
1563 Properties android.SdkMemberProperties
1564}
1565
Paul Duffinf34f6d82020-04-30 15:48:31 +01001566func (b *baseInfo) optimizableProperties() interface{} {
1567 return b.Properties
1568}
1569
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001570type osTypeSpecificInfo struct {
1571 baseInfo
1572
Paul Duffin00e46802020-03-12 20:40:35 +00001573 osType android.OsType
1574
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001575 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001576 //
1577 // Nil if there is one variant whose arch type is common
1578 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001579}
1580
Paul Duffin4b8b7932020-05-06 12:35:38 +01001581var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1582
Paul Duffinfc8dd232020-03-17 12:51:37 +00001583type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1584
Paul Duffin00e46802020-03-12 20:40:35 +00001585// Create a new osTypeSpecificInfo for the specified os type and its properties
1586// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001587func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001588 osInfo := &osTypeSpecificInfo{
1589 osType: osType,
1590 }
1591
1592 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1593 properties := variantPropertiesFactory()
1594 properties.Base().Os = osType
1595 return properties
1596 }
1597
1598 // Create a structure into which properties common across the architectures in
1599 // this os type will be stored.
1600 osInfo.Properties = osSpecificVariantPropertiesFactory()
1601
1602 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001603 var variantsByArchId = make(map[archId][]android.Module)
1604 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001605 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001606 target := variant.Target()
1607 id := archIdFromTarget(target)
1608 if _, ok := variantsByArchId[id]; !ok {
1609 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001610 }
1611
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001612 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001613 }
1614
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001615 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001616 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001617 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 +00001618 }
1619
1620 // A common arch type only has one variant and its properties should be treated
1621 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001622 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001623 } else {
1624 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001625 for _, id := range archIds {
1626 archVariants := variantsByArchId[id]
1627 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001628
1629 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1630 }
1631 }
1632
1633 return osInfo
1634}
1635
Paul Duffin39abf8f2021-09-24 14:58:27 +01001636func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1637 if len(osInfo.archInfos) == 0 {
1638 pruner.pruneProperties(osInfo.Properties)
1639 } else {
1640 for _, archInfo := range osInfo.archInfos {
1641 archInfo.pruneUnsupportedProperties(pruner)
1642 }
1643 }
1644}
1645
Paul Duffin00e46802020-03-12 20:40:35 +00001646// Optimize the properties by extracting common properties from arch type specific
1647// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001648func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001649 // Nothing to do if there is only a single common architecture.
1650 if len(osInfo.archInfos) == 0 {
1651 return
1652 }
1653
Paul Duffin9c3760e2020-03-16 19:52:08 +00001654 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001655 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001656 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001657
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001658 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001659 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001660 }
1661
Paul Duffin4b8b7932020-05-06 12:35:38 +01001662 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001663
1664 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001665 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001666}
1667
1668// Add the properties for an os to a property set.
1669//
1670// Maps the properties related to the os variants through to an appropriate
1671// module structure that will produce equivalent set of variants when it is
1672// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001673func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001674
1675 var osPropertySet android.BpPropertySet
1676 var archPropertySet android.BpPropertySet
1677 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001678 if osInfo.Properties.Base().Os_count == 1 &&
1679 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1680 // There is only one OS type present in the variants and it shouldn't have a
1681 // variant-specific target. The latter is the case if it's either for device
1682 // where there is only one OS (android), or for host and the member type
1683 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001684
1685 // Create a structure that looks like:
1686 // module_type {
1687 // name: "...",
1688 // ...
1689 // <common properties>
1690 // ...
1691 // <single os type specific properties>
1692 //
1693 // arch: {
1694 // <arch specific sections>
1695 // }
1696 //
1697 osPropertySet = bpModule
1698 archPropertySet = osPropertySet.AddPropertySet("arch")
1699
1700 // Arch specific properties need to be added to an arch specific section
1701 // within arch.
1702 archOsPrefix = ""
1703 } else {
1704 // Create a structure that looks like:
1705 // module_type {
1706 // name: "...",
1707 // ...
1708 // <common properties>
1709 // ...
1710 // target: {
1711 // <arch independent os specific sections, e.g. android>
1712 // ...
1713 // <arch and os specific sections, e.g. android_x86>
1714 // }
1715 //
1716 osType := osInfo.osType
1717 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1718 archPropertySet = targetPropertySet
1719
1720 // Arch specific properties need to be added to an os and arch specific
1721 // section prefixed with <os>_.
1722 archOsPrefix = osType.Name + "_"
1723 }
1724
1725 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001726 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001727
1728 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1729 // os) specific properties.
1730 //
1731 // The archInfos list will be empty if the os contains variants for the common
1732 // architecture.
1733 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001734 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001735 }
1736}
1737
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001738func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1739 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001740 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001741}
1742
1743var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1744
Paul Duffin4b8b7932020-05-06 12:35:38 +01001745func (osInfo *osTypeSpecificInfo) String() string {
1746 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1747}
1748
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001749// archId encapsulates the information needed to identify a combination of arch type and native
1750// bridge support.
1751//
1752// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1753// essentially using one android.Arch to implement another. However, in terms of the handling of
1754// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1755// on android.Target.
1756//
1757// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1758type archId struct {
1759 // The arch type of the variant's target.
1760 archType android.ArchType
1761
1762 // True if the variants is for the native bridge, false otherwise.
1763 nativeBridge bool
1764}
1765
1766// propertyName returns the name of the property corresponding to use for this arch id.
1767func (i *archId) propertyName() string {
1768 name := i.archType.Name
1769 if i.nativeBridge {
1770 // Note: This does not result in a valid property because there is no architecture specific
1771 // native bridge property, only a generic "native_bridge" property. However, this will be used
1772 // in error messages if there is an attempt to use this in a generated bp file.
1773 name += "_native_bridge"
1774 }
1775 return name
1776}
1777
1778func (i *archId) String() string {
1779 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1780}
1781
1782// archIdFromTarget returns an archId initialized from information in the supplied target.
1783func archIdFromTarget(target android.Target) archId {
1784 return archId{
1785 archType: target.Arch.ArchType,
1786 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1787 }
1788}
1789
1790// commonArchId is the archId for the common architecture.
1791var commonArchId = archId{archType: android.Common}
1792
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001793type archTypeSpecificInfo struct {
1794 baseInfo
1795
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001796 archId archId
1797 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001798
Paul Duffinb42fa672021-09-09 16:37:49 +01001799 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001800}
1801
Paul Duffin4b8b7932020-05-06 12:35:38 +01001802var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1803
Paul Duffinfc8dd232020-03-17 12:51:37 +00001804// Create a new archTypeSpecificInfo for the specified arch type and its properties
1805// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001806func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001807
Paul Duffinfc8dd232020-03-17 12:51:37 +00001808 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001809 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001810
1811 // Create the properties into which the arch type specific properties will be
1812 // added.
1813 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001814
1815 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001816 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001817 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001818 // Group the variants by image type.
1819 variantsByImage := make(map[string][]android.Module)
1820 for _, variant := range archVariants {
1821 image := variant.ImageVariation().Variation
1822 variantsByImage[image] = append(variantsByImage[image], variant)
1823 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001824
Paul Duffinb42fa672021-09-09 16:37:49 +01001825 // Create the image variant info in a fixed order.
1826 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1827 variants := variantsByImage[imageVariantName]
1828 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001829 }
1830 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001831
1832 return archInfo
1833}
1834
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001835// Get the link type of the variant
1836//
1837// If the variant is not differentiated by link type then it returns "",
1838// otherwise it returns one of "static" or "shared".
1839func getLinkType(variant android.Module) string {
1840 linkType := ""
1841 if linkable, ok := variant.(cc.LinkableInterface); ok {
1842 if linkable.Shared() && linkable.Static() {
1843 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1844 } else if linkable.Shared() {
1845 linkType = "shared"
1846 } else if linkable.Static() {
1847 linkType = "static"
1848 } else {
1849 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1850 }
1851 }
1852 return linkType
1853}
1854
Paul Duffin39abf8f2021-09-24 14:58:27 +01001855func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1856 if len(archInfo.imageVariantInfos) == 0 {
1857 pruner.pruneProperties(archInfo.Properties)
1858 } else {
1859 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1860 imageVariantInfo.pruneUnsupportedProperties(pruner)
1861 }
1862 }
1863}
1864
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001865// Optimize the properties by extracting common properties from link type specific
1866// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001867func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001868 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001869 return
1870 }
1871
Paul Duffinb42fa672021-09-09 16:37:49 +01001872 // Optimize the image variant properties first.
1873 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1874 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1875 }
1876
1877 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001878}
1879
Paul Duffinfc8dd232020-03-17 12:51:37 +00001880// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001881func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001882 archPropertySuffix := archInfo.archId.propertyName()
1883 propertySetName := archOsPrefix + archPropertySuffix
1884 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001885 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1886 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1887 archTypePropertySet.AddProperty("enabled", true)
1888 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001889 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001890
Paul Duffinb42fa672021-09-09 16:37:49 +01001891 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1892 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001893 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001894
1895 // If this is for a native bridge architecture then make sure that the property set does not
1896 // contain any properties as providing native bridge specific properties is not currently
1897 // supported.
1898 if archInfo.archId.nativeBridge {
1899 propertySetContents := getPropertySetContents(archTypePropertySet)
1900 if propertySetContents != "" {
1901 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",
1902 propertySetName, ctx.name, propertySetContents)
1903 }
1904 }
1905}
1906
1907// getPropertySetContents returns the string representation of the contents of a property set, after
1908// recursively pruning any empty nested property sets.
1909func getPropertySetContents(propertySet android.BpPropertySet) string {
1910 set := propertySet.(*bpPropertySet)
1911 set.transformContents(pruneEmptySetTransformer{})
1912 if len(set.properties) != 0 {
1913 contents := &generatedContents{}
1914 contents.Indent()
1915 outputPropertySet(contents, set)
1916 setAsString := contents.content.String()
1917 return setAsString
1918 }
1919 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001920}
1921
Paul Duffin4b8b7932020-05-06 12:35:38 +01001922func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001923 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001924}
1925
Paul Duffinb42fa672021-09-09 16:37:49 +01001926type imageVariantSpecificInfo struct {
1927 baseInfo
1928
1929 imageVariant string
1930
1931 linkInfos []*linkTypeSpecificInfo
1932}
1933
1934func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1935
1936 // Create an image variant specific info into which the variant properties can be copied.
1937 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1938
1939 // Create the properties into which the image variant specific properties will be added.
1940 imageInfo.Properties = variantPropertiesFactory()
1941
1942 if len(imageVariants) == 1 {
1943 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1944 } else {
1945 // There is more than one variant for this image variant which must be differentiated by link
1946 // type.
1947 for _, linkVariant := range imageVariants {
1948 linkType := getLinkType(linkVariant)
1949 if linkType == "" {
1950 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1951 } else {
1952 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1953
1954 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1955 }
1956 }
1957 }
1958
1959 return imageInfo
1960}
1961
Paul Duffin39abf8f2021-09-24 14:58:27 +01001962func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1963 if len(imageInfo.linkInfos) == 0 {
1964 pruner.pruneProperties(imageInfo.Properties)
1965 } else {
1966 for _, linkInfo := range imageInfo.linkInfos {
1967 linkInfo.pruneUnsupportedProperties(pruner)
1968 }
1969 }
1970}
1971
Paul Duffinb42fa672021-09-09 16:37:49 +01001972// Optimize the properties by extracting common properties from link type specific
1973// properties into arch type specific properties.
1974func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1975 if len(imageInfo.linkInfos) == 0 {
1976 return
1977 }
1978
1979 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1980}
1981
1982// Add the properties for an arch type to a property set.
1983func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1984 if imageInfo.imageVariant != android.CoreVariation {
1985 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1986 }
1987
1988 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1989
1990 for _, linkInfo := range imageInfo.linkInfos {
1991 linkInfo.addToPropertySet(ctx, propertySet)
1992 }
1993
1994 // If this is for a non-core image variant then make sure that the property set does not contain
1995 // any properties as providing non-core image variant specific properties for prebuilts is not
1996 // currently supported.
1997 if imageInfo.imageVariant != android.CoreVariation {
1998 propertySetContents := getPropertySetContents(propertySet)
1999 if propertySetContents != "" {
2000 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",
2001 imageInfo.imageVariant, ctx.name, propertySetContents)
2002 }
2003 }
2004}
2005
2006func (imageInfo *imageVariantSpecificInfo) String() string {
2007 return imageInfo.imageVariant
2008}
2009
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002010type linkTypeSpecificInfo struct {
2011 baseInfo
2012
2013 linkType string
2014}
2015
Paul Duffin4b8b7932020-05-06 12:35:38 +01002016var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
2017
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002018// Create a new linkTypeSpecificInfo for the specified link type and its properties
2019// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002020func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002021 linkInfo := &linkTypeSpecificInfo{
2022 baseInfo: baseInfo{
2023 // Create the properties into which the link type specific properties will be
2024 // added.
2025 Properties: variantPropertiesFactory(),
2026 },
2027 linkType: linkType,
2028 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00002029 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002030 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00002031}
2032
Paul Duffinf68f85a2021-09-09 16:11:42 +01002033func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
2034 linkPropertySet := propertySet.AddPropertySet(l.linkType)
2035 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
2036}
2037
Paul Duffin39abf8f2021-09-24 14:58:27 +01002038func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
2039 pruner.pruneProperties(l.Properties)
2040}
2041
Paul Duffin4b8b7932020-05-06 12:35:38 +01002042func (l *linkTypeSpecificInfo) String() string {
2043 return fmt.Sprintf("LinkType{%s}", l.linkType)
2044}
2045
Paul Duffin3a4eb502020-03-19 16:11:18 +00002046type memberContext struct {
2047 sdkMemberContext android.ModuleContext
2048 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00002049 memberType android.SdkMemberType
2050 name string
Paul Duffind19f8942021-07-14 12:08:37 +01002051
2052 // The set of traits required of this member.
2053 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00002054}
2055
2056func (m *memberContext) SdkModuleContext() android.ModuleContext {
2057 return m.sdkMemberContext
2058}
2059
2060func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
2061 return m.builder
2062}
2063
Paul Duffina551a1c2020-03-17 21:04:24 +00002064func (m *memberContext) MemberType() android.SdkMemberType {
2065 return m.memberType
2066}
2067
2068func (m *memberContext) Name() string {
2069 return m.name
2070}
2071
Paul Duffind19f8942021-07-14 12:08:37 +01002072func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
2073 return m.requiredTraits.Contains(trait)
2074}
2075
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002076func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002077
2078 memberType := member.memberType
2079
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002080 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01002081 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002082 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00002083 // Set the prefer based on the environment variable. This is a temporary work around to allow a
2084 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002085 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
2086 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002087 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01002088
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002089 // Set prefer. Setting this to false is not strictly required as that is the default but it does
2090 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
2091 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
2092 // behavior is for the module.
2093 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002094
2095 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
2096 if configVar != "" {
2097 parts := strings.Split(configVar, ":")
2098 cfp := android.ConfigVarProperties{
2099 Config_namespace: proptools.StringPtr(parts[0]),
2100 Var_name: proptools.StringPtr(parts[1]),
2101 }
2102 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
2103 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002104 }
Paul Duffin83ad9562021-05-10 23:49:04 +01002105
Paul Duffina04c1072020-03-02 10:16:35 +00002106 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002107 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002108 variants := member.Variants()
2109 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00002110 osType := variant.Target().Os
2111 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002112 }
2113
Paul Duffina04c1072020-03-02 10:16:35 +00002114 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002115 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002116 properties := memberType.CreateVariantPropertiesStruct()
2117 base := properties.Base()
2118 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002119 return properties
2120 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002121
Paul Duffina04c1072020-03-02 10:16:35 +00002122 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002123
Paul Duffina04c1072020-03-02 10:16:35 +00002124 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002125 commonProperties := variantPropertiesFactory()
2126 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002127
Paul Duffin39abf8f2021-09-24 14:58:27 +01002128 // Create a property pruner that will prune any properties unsupported by the target build
2129 // release.
2130 targetBuildRelease := ctx.builder.targetBuildRelease
2131 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2132
Paul Duffinc097e362020-03-10 22:50:03 +00002133 // Create common value extractor that can be used to optimize the properties.
2134 commonValueExtractor := newCommonValueExtractor(commonProperties)
2135
Paul Duffina04c1072020-03-02 10:16:35 +00002136 // The list of property structures which are os type specific but common across
2137 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002138 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002139
2140 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002141 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002142 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002143 // Add the os specific properties to a list of os type specific yet architecture
2144 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002145 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002146
Paul Duffin39abf8f2021-09-24 14:58:27 +01002147 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2148
Paul Duffin00e46802020-03-12 20:40:35 +00002149 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002150 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002151 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002152
Paul Duffina04c1072020-03-02 10:16:35 +00002153 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002154 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002155
Paul Duffina04c1072020-03-02 10:16:35 +00002156 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002157 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002158
Paul Duffina04c1072020-03-02 10:16:35 +00002159 // Create a target property set into which target specific properties can be
2160 // added.
2161 targetPropertySet := bpModule.AddPropertySet("target")
2162
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002163 // If the member is host OS dependent and has host_supported then disable by
2164 // default and enable each host OS variant explicitly. This avoids problems
2165 // with implicitly enabled OS variants when the snapshot is used, which might
2166 // be different from this run (e.g. different build OS).
2167 if ctx.memberType.IsHostOsDependent() {
2168 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2169 if hostSupported {
2170 hostPropertySet := targetPropertySet.AddPropertySet("host")
2171 hostPropertySet.AddProperty("enabled", false)
2172 }
2173 }
2174
Paul Duffina04c1072020-03-02 10:16:35 +00002175 // Iterate over the os types in a fixed order.
2176 for _, osType := range s.getPossibleOsTypes() {
2177 osInfo := osTypeToInfo[osType]
2178 if osInfo == nil {
2179 continue
2180 }
2181
Paul Duffin3a4eb502020-03-19 16:11:18 +00002182 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002183 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002184}
2185
Paul Duffina04c1072020-03-02 10:16:35 +00002186// Compute the list of possible os types that this sdk could support.
2187func (s *sdk) getPossibleOsTypes() []android.OsType {
2188 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002189 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002190 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002191 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002192 osTypes = append(osTypes, osType)
2193 }
2194 }
2195 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002196 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002197 osTypes = append(osTypes, osType)
2198 }
2199 }
2200 }
2201 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2202 return osTypes
2203}
2204
Paul Duffinb28369a2020-05-04 15:39:59 +01002205// Given a set of properties (struct value), return the value of the field within that
2206// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002207type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2208
Paul Duffinc459f892020-04-30 18:08:29 +01002209// Checks the metadata to determine whether the property should be ignored for the
2210// purposes of common value extraction or not.
2211type extractorMetadataPredicate func(metadata propertiesContainer) bool
2212
2213// Indicates whether optimizable properties are provided by a host variant or
2214// not.
2215type isHostVariant interface {
2216 isHostVariant() bool
2217}
2218
Paul Duffinb28369a2020-05-04 15:39:59 +01002219// A property that can be optimized by the commonValueExtractor.
2220type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002221 // The name of the field for this property. It is a "."-separated path for
2222 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002223 name string
2224
Paul Duffinc459f892020-04-30 18:08:29 +01002225 // Filter that can use metadata associated with the properties being optimized
2226 // to determine whether the field should be ignored during common value
2227 // optimization.
2228 filter extractorMetadataPredicate
2229
Paul Duffinb28369a2020-05-04 15:39:59 +01002230 // Retrieves the value on which common value optimization will be performed.
2231 getter fieldAccessorFunc
2232
2233 // The empty value for the field.
2234 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002235
2236 // True if the property can support arch variants false otherwise.
2237 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002238}
2239
Paul Duffin4b8b7932020-05-06 12:35:38 +01002240func (p extractorProperty) String() string {
2241 return p.name
2242}
2243
Paul Duffinc097e362020-03-10 22:50:03 +00002244// Supports extracting common values from a number of instances of a properties
2245// structure into a separate common set of properties.
2246type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002247 // The properties that the extractor can optimize.
2248 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002249}
2250
2251// Create a new common value extractor for the structure type for the supplied
2252// properties struct.
2253//
2254// The returned extractor can be used on any properties structure of the same type
2255// as the supplied set of properties.
2256func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2257 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2258 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002259 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002260 return extractor
2261}
2262
2263// Gather the fields from the supplied structure type from which common values will
2264// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002265//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002266// This is recursive function. If it encounters a struct then it will recurse
2267// into it, passing in the accessor for the field and the struct name as prefix
2268// for the nested fields. That will then be used in the accessors for the fields
2269// in the embedded struct.
2270func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002271 for f := 0; f < structType.NumField(); f++ {
2272 field := structType.Field(f)
2273 if field.PkgPath != "" {
2274 // Ignore unexported fields.
2275 continue
2276 }
2277
Paul Duffinb07fa512020-03-10 22:17:04 +00002278 // Ignore fields whose value should be kept.
2279 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002280 continue
2281 }
2282
Paul Duffinc459f892020-04-30 18:08:29 +01002283 var filter extractorMetadataPredicate
2284
2285 // Add a filter
2286 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2287 filter = func(metadata propertiesContainer) bool {
2288 if m, ok := metadata.(isHostVariant); ok {
2289 if m.isHostVariant() {
2290 return false
2291 }
2292 }
2293 return true
2294 }
2295 }
2296
Paul Duffinc097e362020-03-10 22:50:03 +00002297 // Save a copy of the field index for use in the function.
2298 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002299
Martin Stjernholmb0249572020-09-15 02:32:35 +01002300 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002301
Paul Duffinc097e362020-03-10 22:50:03 +00002302 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002303 if containingStructAccessor != nil {
2304 // This is an embedded structure so first access the field for the embedded
2305 // structure.
2306 value = containingStructAccessor(value)
2307 }
2308
Paul Duffinc097e362020-03-10 22:50:03 +00002309 // Skip through interface and pointer values to find the structure.
2310 value = getStructValue(value)
2311
Paul Duffin4b8b7932020-05-06 12:35:38 +01002312 defer func() {
2313 if r := recover(); r != nil {
2314 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2315 }
2316 }()
2317
Paul Duffinc097e362020-03-10 22:50:03 +00002318 // Return the field.
2319 return value.Field(fieldIndex)
2320 }
2321
Martin Stjernholmb0249572020-09-15 02:32:35 +01002322 if field.Type.Kind() == reflect.Struct {
2323 // Gather fields from the nested or embedded structure.
2324 var subNamePrefix string
2325 if field.Anonymous {
2326 subNamePrefix = namePrefix
2327 } else {
2328 subNamePrefix = name + "."
2329 }
2330 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002331 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002332 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002333 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002334 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002335 fieldGetter,
2336 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002337 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002338 }
2339 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002340 }
Paul Duffinc097e362020-03-10 22:50:03 +00002341 }
2342}
2343
2344func getStructValue(value reflect.Value) reflect.Value {
2345foundStruct:
2346 for {
2347 kind := value.Kind()
2348 switch kind {
2349 case reflect.Interface, reflect.Ptr:
2350 value = value.Elem()
2351 case reflect.Struct:
2352 break foundStruct
2353 default:
2354 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2355 }
2356 }
2357 return value
2358}
2359
Paul Duffinf34f6d82020-04-30 15:48:31 +01002360// A container of properties to be optimized.
2361//
2362// Allows additional information to be associated with the properties, e.g. for
2363// filtering.
2364type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002365 fmt.Stringer
2366
Paul Duffinf34f6d82020-04-30 15:48:31 +01002367 // Get the properties that need optimizing.
2368 optimizableProperties() interface{}
2369}
2370
Paul Duffin2d1bb892021-04-24 11:32:59 +01002371// A wrapper for sdk variant related properties to allow them to be optimized.
2372type sdkVariantPropertiesContainer struct {
2373 sdkVariant *sdk
2374 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002375}
2376
Paul Duffin2d1bb892021-04-24 11:32:59 +01002377func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2378 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002379}
2380
Paul Duffin2d1bb892021-04-24 11:32:59 +01002381func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002382 return c.sdkVariant.String()
2383}
2384
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002385// Extract common properties from a slice of property structures of the same type.
2386//
2387// All the property structures must be of the same type.
2388// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002389// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002390//
2391// Iterates over each exported field (capitalized name) and checks to see whether they
2392// have the same value (using DeepEquals) across all the input properties. If it does not then no
2393// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002394// and the field in each of the input properties structure is set to its default value. Nested
2395// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002396func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002397 commonPropertiesValue := reflect.ValueOf(commonProperties)
2398 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002399
Paul Duffinf34f6d82020-04-30 15:48:31 +01002400 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2401
Paul Duffinb28369a2020-05-04 15:39:59 +01002402 for _, property := range e.properties {
2403 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002404 filter := property.filter
2405 if filter == nil {
2406 filter = func(metadata propertiesContainer) bool {
2407 return true
2408 }
2409 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002410
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002411 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002412 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2413 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002414 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002415
Paul Duffin864e1b42020-05-06 10:23:19 +01002416 // Assume that all the values will be the same.
2417 //
2418 // While similar to this is not quite the same as commonValue == nil. If all the values
2419 // have been filtered out then this will be false but commonValue == nil will be true.
2420 valuesDiffer := false
2421
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002422 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002423 container := sliceValue.Index(i).Interface().(propertiesContainer)
2424 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002425 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002426
Paul Duffinc459f892020-04-30 18:08:29 +01002427 if !filter(container) {
2428 expectedValue := property.emptyValue.Interface()
2429 actualValue := fieldValue.Interface()
2430 if !reflect.DeepEqual(expectedValue, actualValue) {
2431 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2432 }
2433 continue
2434 }
2435
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002436 if commonValue == nil {
2437 // Use the first value as the commonProperties value.
2438 commonValue = &fieldValue
2439 } else {
2440 // If the value does not match the current common value then there is
2441 // no value in common so break out.
2442 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2443 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002444 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002445 break
2446 }
2447 }
2448 }
2449
Paul Duffin864e1b42020-05-06 10:23:19 +01002450 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002451 // and set the input struct's field to the empty value.
2452 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002453 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002454 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002455 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002456 container := sliceValue.Index(i).Interface().(propertiesContainer)
2457 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002458 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002459 fieldValue.Set(emptyValue)
2460 }
2461 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002462
2463 if valuesDiffer && !property.archVariant {
2464 // The values differ but the property does not support arch variants so it
2465 // is an error.
2466 var details strings.Builder
2467 for i := 0; i < sliceValue.Len(); i++ {
2468 container := sliceValue.Index(i).Interface().(propertiesContainer)
2469 itemValue := reflect.ValueOf(container.optimizableProperties())
2470 fieldValue := fieldGetter(itemValue)
2471
2472 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2473 }
2474
2475 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2476 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002477 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002478
2479 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002480}