blob: 5db604b7cc8b461c98da7dd4e1907429d2e2e6f3 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000036// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010038//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010039// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
40// If set this specifies the Soong config var that can be used to control whether the prebuilt
41// modules from the generated snapshot or the original source modules. Values must be a colon
42// separated pair of strings, the first of which is the Soong config namespace, and the second
43// is the name of the variable within that namespace.
44//
45// The config namespace and var name are used to set the `use_source_config_var` property. That
46// in turn will cause the generated prebuilts to use the soong config variable to select whether
47// source or the prebuilt is used.
48// e.g. If an sdk snapshot is built using:
49// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
50// Then the resulting snapshot will include:
51// use_source_config_var: {
52// config_namespace: "acme",
53// var_name: "build_from_source",
54// }
55//
56// Assuming that the config variable is defined in .mk using something like:
57// $(call add_soong_config_namespace,acme)
58// $(call add_soong_config_var_value,acme,build_from_source,true)
59//
60// Then when the snapshot is unpacked in the repository it will have the following behavior:
61// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
62// sources.
63// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
64// sources, if present. Otherwise, it will use the prebuilts.
65//
66// This is a temporary mechanism to control the prefer flags and will be removed once a more
67// maintainable solution has been implemented.
68// TODO(b/174997203): Remove when no longer necessary.
69//
Paul Duffin43f7bf02021-05-05 22:00:51 +010070// SOONG_SDK_SNAPSHOT_VERSION
71// This provides control over the version of the generated snapshot.
72//
73// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
74// versioned snapshot module. This is the default behavior. The zip file containing the
75// generated snapshot will be <sdk-name>-current.zip.
76//
77// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
78// file containing the generated snapshot will be <sdk-name>.zip.
79//
80// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
81// snapshot module only. The zip file containing the generated snapshot will be
82// <sdk-name>-<number>.zip.
83//
Paul Duffin39abf8f2021-09-24 14:58:27 +010084// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
85// This allows the target build release (i.e. the release version of the build within which
86// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
87// to the current build release version. Otherwise, it must be the name of one of the build
88// releases defined in nameToBuildRelease, e.g. S, T, etc..
89//
90// The generated snapshot must only be used in the specified target release. If the target
91// build release is not the current build release then the generated Android.bp file not be
92// checked for compatibility.
93//
94// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
95// to be compatible with S.
96//
Paul Duffin64fb5262021-05-05 21:36:04 +010097
Jiyong Park9b409bc2019-10-11 14:59:13 +090098var pctx = android.NewPackageContext("android/soong/sdk")
99
Paul Duffin375058f2019-11-29 20:17:53 +0000100var (
101 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
102 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +0000103 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +0000104 CommandDeps: []string{
105 "${config.Zip2ZipCmd}",
106 },
107 },
108 "destdir")
109
110 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
111 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -0700112 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000113 CommandDeps: []string{
114 "${config.SoongZipCmd}",
115 },
116 Rspfile: "$out.rsp",
117 RspfileContent: "$in",
118 },
119 "basedir")
120
121 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
122 blueprint.RuleParams{
123 Command: `${config.MergeZipsCmd} $out $in`,
124 CommandDeps: []string{
125 "${config.MergeZipsCmd}",
126 },
127 })
128)
129
Paul Duffin43f7bf02021-05-05 22:00:51 +0100130const (
131 soongSdkSnapshotVersionUnversioned = "unversioned"
132 soongSdkSnapshotVersionCurrent = "current"
133)
134
Paul Duffinb645ec82019-11-27 17:43:54 +0000135type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900136 content strings.Builder
137 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900138}
139
Paul Duffinb645ec82019-11-27 17:43:54 +0000140// generatedFile abstracts operations for writing contents into a file and emit a build rule
141// for the file.
142type generatedFile struct {
143 generatedContents
144 path android.OutputPath
145}
146
Jiyong Park232e7852019-11-04 12:23:40 +0900147func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900148 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000149 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900150 }
151}
152
Paul Duffinb645ec82019-11-27 17:43:54 +0000153func (gc *generatedContents) Indent() {
154 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900155}
156
Paul Duffinb645ec82019-11-27 17:43:54 +0000157func (gc *generatedContents) Dedent() {
158 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900159}
160
Paul Duffina08e4dc2021-06-22 18:19:19 +0100161// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
162// arguments.
163func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
164 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
165}
166
167// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
168// the arguments.
169func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
170 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900171}
172
173func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800174 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100175
176 content := gf.content.String()
177
178 // ninja consumes newline characters in rspfile_content. Prevent it by
179 // escaping the backslash in the newline character. The extra backslash
180 // is removed when the rspfile is written to the actual script file
181 content = strings.ReplaceAll(content, "\n", "\\n")
182
Jiyong Park9b409bc2019-10-11 14:59:13 +0900183 rb.Command().
184 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100185 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100186 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900187 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
188 rb.Command().
189 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800190 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900191}
192
Paul Duffin13879572019-11-28 14:31:38 +0000193// Collect all the members.
194//
Paul Duffinb97b1572021-04-29 21:50:40 +0100195// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
196// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000197func (s *sdk) collectMembers(ctx android.ModuleContext) {
198 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000199 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
200 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100201 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100202 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900203
Paul Duffin5cca7c42021-05-26 10:16:01 +0100204 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
205 if memberType == nil {
206 return false
207 }
208
Paul Duffin13879572019-11-28 14:31:38 +0000209 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000210 if !memberType.IsInstance(child) {
211 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900212 }
Paul Duffin13879572019-11-28 14:31:38 +0000213
Paul Duffin6a7e9532020-03-20 17:50:07 +0000214 // Keep track of which multilib variants are used by the sdk.
215 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
216
Paul Duffinb97b1572021-04-29 21:50:40 +0100217 var exportedComponentsInfo android.ExportedComponentsInfo
218 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
219 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
220 }
221
Paul Duffina7208112021-04-23 21:20:20 +0100222 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100223 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
224 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
225 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000226
Paul Duffin2d3da312021-05-06 12:02:27 +0100227 // Recurse down into the member's dependencies as it may have dependencies that need to be
228 // automatically added to the sdk.
229 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900230 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000231
232 return false
Paul Duffin13879572019-11-28 14:31:38 +0000233 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000234}
235
Paul Duffincc3132e2021-04-24 01:10:30 +0100236// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
237// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000238//
Paul Duffincc3132e2021-04-24 01:10:30 +0100239// The sdkMember instances are then grouped into slices by member type. Within each such slice the
240// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000241//
Paul Duffincc3132e2021-04-24 01:10:30 +0100242// Finally, the member type slices are concatenated together to form a single slice. The order in
243// which they are concatenated is the order in which the member types were registered in the
244// android.SdkMemberTypesRegistry.
245func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000246 byType := make(map[android.SdkMemberType][]*sdkMember)
247 byName := make(map[string]*sdkMember)
248
Paul Duffin21827262021-04-24 12:16:36 +0100249 for _, memberVariantDep := range memberVariantDeps {
250 memberType := memberVariantDep.memberType
251 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000252
253 name := ctx.OtherModuleName(variant)
254 member := byName[name]
255 if member == nil {
256 member = &sdkMember{memberType: memberType, name: name}
257 byName[name] = member
258 byType[memberType] = append(byType[memberType], member)
259 }
260
Paul Duffin1356d8c2020-02-25 19:26:33 +0000261 // Only append new variants to the list. This is needed because a member can be both
262 // exported by the sdk and also be a transitive sdk member.
263 member.variants = appendUniqueVariants(member.variants, variant)
264 }
265
Paul Duffin13879572019-11-28 14:31:38 +0000266 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100267 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000268 membersOfType := byType[memberListProperty.memberType]
269 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900270 }
271
Paul Duffin6a7e9532020-03-20 17:50:07 +0000272 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900273}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900274
Paul Duffin72910952020-01-20 18:16:30 +0000275func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
276 for _, v := range variants {
277 if v == newVariant {
278 return variants
279 }
280 }
281 return append(variants, newVariant)
282}
283
Paul Duffin51509a12022-04-06 12:48:09 +0000284// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
285// the build from which the snapshot was produced.
286const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
287
Jiyong Park73c54ee2019-10-22 20:31:18 +0900288// SDK directory structure
289// <sdk_root>/
290// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
291// <api_ver>/ : below this directory are all auto-generated
292// Android.bp : definition of 'sdk_snapshot' module is here
293// aidl/
294// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
295// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900296// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900297// include/
298// bionic/libc/include/stdlib.h : an exported header file
299// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900300// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900301// <arch>/include/ : arch-specific exported headers
302// <arch>/include_gen/ : arch-specific generated headers
303// <arch>/lib/
304// libFoo.so : a stub library
305
Jiyong Park232e7852019-11-04 12:23:40 +0900306// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900307// This isn't visible to users, so could be changed in future.
308func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
309 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
310}
311
Jiyong Park232e7852019-11-04 12:23:40 +0900312// buildSnapshot is the main function in this source file. It creates rules to copy
313// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000314func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
315
Paul Duffinb97b1572021-04-29 21:50:40 +0100316 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100317 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100318 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000319 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100320 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100321 }
Paul Duffin865171e2020-03-02 18:38:15 +0000322
Paul Duffinb97b1572021-04-29 21:50:40 +0100323 // Filter out any sdkMemberVariantDep that is a component of another.
324 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000325
Paul Duffinb97b1572021-04-29 21:50:40 +0100326 // Record the names of all the members, both explicitly specified and implicitly
327 // included.
328 allMembersByName := make(map[string]struct{})
329 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100330
Paul Duffinb97b1572021-04-29 21:50:40 +0100331 addMember := func(name string, export bool) {
332 allMembersByName[name] = struct{}{}
333 if export {
334 exportedMembersByName[name] = struct{}{}
335 }
336 }
337
338 for _, memberVariantDep := range memberVariantDeps {
339 name := memberVariantDep.variant.Name()
340 export := memberVariantDep.export
341
342 addMember(name, export)
343
344 // Add any components provided by the module.
345 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
346 addMember(component, export)
347 }
348
349 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
350 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000351 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000352 }
353
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000354 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900355
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000356 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000357
358 bpFile := &bpFile{
359 modules: make(map[string]*bpModule),
360 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000361
Paul Duffin43f7bf02021-05-05 22:00:51 +0100362 config := ctx.Config()
363 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
364
365 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
366 generateVersioned := version != soongSdkSnapshotVersionUnversioned
367
368 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
369 //
370 // Unversioned modules are not required in that case because the numbered version will be a
371 // finalized version of the snapshot that is intended to be kept separate from the
372 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
373 snapshotZipFileSuffix := ""
374 if generateVersioned {
375 snapshotZipFileSuffix = "-" + version
376 }
377
Paul Duffin39abf8f2021-09-24 14:58:27 +0100378 currentBuildRelease := latestBuildRelease()
379 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
380 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
381 if err != nil {
382 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
383 targetBuildRelease = currentBuildRelease
384 }
385
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000386 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000387 ctx: ctx,
388 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100389 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000390 snapshotDir: snapshotDir.OutputPath,
391 copies: make(map[string]string),
392 filesToZip: []android.Path{bp.path},
393 bpFile: bpFile,
394 prebuiltModules: make(map[string]*bpModule),
395 allMembersByName: allMembersByName,
396 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100397 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900398 }
Paul Duffinac37c502019-11-26 18:02:20 +0000399 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900400
Paul Duffin62131702021-05-07 01:10:01 +0100401 // If the sdk snapshot includes any license modules then add a package module which has a
402 // default_applicable_licenses property. That will prevent the LSC license process from updating
403 // the generated Android.bp file to add a package module that includes all licenses used by all
404 // the modules in that package. That would be unnecessary as every module in the sdk should have
405 // their own licenses property specified.
406 if hasLicenses {
407 pkg := bpFile.newModule("package")
408 property := "default_applicable_licenses"
409 pkg.AddCommentForProperty(property, `
410A default list here prevents the license LSC from adding its own list which would
411be unnecessary as every module in the sdk already has its own licenses property.
412`)
413 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
414 bpFile.AddModule(pkg)
415 }
416
Paul Duffin0df49682021-05-07 01:10:01 +0100417 // Group the variants for each member module together and then group the members of each member
418 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100419 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100420
421 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100422 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000423 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000424 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000425
Paul Duffind19f8942021-07-14 12:08:37 +0100426 name := member.name
427 requiredTraits := traits[name]
428 if requiredTraits == nil {
429 requiredTraits = android.EmptySdkMemberTraitSet()
430 }
431
432 // Create the snapshot for the member.
433 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000434
435 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100436 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900437 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900438
Paul Duffine6c0d842020-01-15 14:08:51 +0000439 // Create a transformer that will transform an unversioned module into a versioned module.
440 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
441
Paul Duffin72910952020-01-20 18:16:30 +0000442 // Create a transformer that will transform an unversioned module by replacing any references
443 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100444 unversionedTransformer := unversionedTransformation{
445 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100446 }
Paul Duffin72910952020-01-20 18:16:30 +0000447
Paul Duffinb645ec82019-11-27 17:43:54 +0000448 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000449 // Prune any empty property sets.
450 unversioned = unversioned.transform(pruneEmptySetTransformer{})
451
Paul Duffin43f7bf02021-05-05 22:00:51 +0100452 if generateVersioned {
453 // Copy the unversioned module so it can be modified to make it versioned.
454 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000455
Paul Duffin43f7bf02021-05-05 22:00:51 +0100456 // Transform the unversioned module into a versioned one.
457 versioned.transform(unversionedToVersionedTransformer)
458 bpFile.AddModule(versioned)
459 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000460
Paul Duffin43f7bf02021-05-05 22:00:51 +0100461 if generateUnversioned {
462 // Transform the unversioned module to make it suitable for use in the snapshot.
463 unversioned.transform(unversionedTransformer)
464 bpFile.AddModule(unversioned)
465 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000466 }
467
Paul Duffin43f7bf02021-05-05 22:00:51 +0100468 if generateVersioned {
469 // Add the sdk/module_exports_snapshot module to the bp file.
470 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
471 }
Paul Duffin26197a62021-04-24 00:34:10 +0100472
473 // generate Android.bp
474 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
475 generateBpContents(&bp.generatedContents, bpFile)
476
477 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100478 // If the snapshot is being generated for the current build release then check the syntax to make
479 // sure that it is compatible.
480 if targetBuildRelease == currentBuildRelease {
481 syntaxCheckSnapshotBpFile(ctx, contents)
482 }
Paul Duffin26197a62021-04-24 00:34:10 +0100483
484 bp.build(pctx, ctx, nil)
485
Paul Duffin51509a12022-04-06 12:48:09 +0000486 // Copy the build number file into the snapshot.
487 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
488
Paul Duffin26197a62021-04-24 00:34:10 +0100489 filesToZip := builder.filesToZip
490
491 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100492 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
493 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100494 outputDesc := "Building snapshot for " + ctx.ModuleName()
495
496 // If there are no zips to merge then generate the output zip directly.
497 // Otherwise, generate an intermediate zip file into which other zips can be
498 // merged.
499 var zipFile android.OutputPath
500 var desc string
501 if len(builder.zipsToMerge) == 0 {
502 zipFile = outputZipFile
503 desc = outputDesc
504 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100505 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
506 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100507 desc = "Building intermediate snapshot for " + ctx.ModuleName()
508 }
509
510 ctx.Build(pctx, android.BuildParams{
511 Description: desc,
512 Rule: zipFiles,
513 Inputs: filesToZip,
514 Output: zipFile,
515 Args: map[string]string{
516 "basedir": builder.snapshotDir.String(),
517 },
518 })
519
520 if len(builder.zipsToMerge) != 0 {
521 ctx.Build(pctx, android.BuildParams{
522 Description: outputDesc,
523 Rule: mergeZips,
524 Input: zipFile,
525 Inputs: builder.zipsToMerge,
526 Output: outputZipFile,
527 })
528 }
529
530 return outputZipFile
531}
532
Paul Duffinb97b1572021-04-29 21:50:40 +0100533// filterOutComponents removes any item from the deps list that is a component of another item in
534// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
535// then it will remove "foo.stubs" from the deps.
536func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
537 // Collate the set of components that all the modules added to the sdk provide.
538 components := map[string]*sdkMemberVariantDep{}
539 for i, _ := range deps {
540 dep := &deps[i]
541 for _, c := range dep.exportedComponentsInfo.Components {
542 components[c] = dep
543 }
544 }
545
546 // If no module provides components then return the input deps unfiltered.
547 if len(components) == 0 {
548 return deps
549 }
550
551 filtered := make([]sdkMemberVariantDep, 0, len(deps))
552 for _, dep := range deps {
553 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
554 if owner, ok := components[name]; ok {
555 // This is a component of another module that is a member of the sdk.
556
557 // If the component is exported but the owning module is not then the configuration is not
558 // supported.
559 if dep.export && !owner.export {
560 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
561 continue
562 }
563
564 // This module must not be added to the list of members of the sdk as that would result in a
565 // duplicate module in the sdk snapshot.
566 continue
567 }
568
569 filtered = append(filtered, dep)
570 }
571 return filtered
572}
573
Paul Duffin26197a62021-04-24 00:34:10 +0100574// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100575func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100576 bpFile := builder.bpFile
577
Paul Duffinb645ec82019-11-27 17:43:54 +0000578 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000579 var snapshotModuleType string
580 if s.properties.Module_exports {
581 snapshotModuleType = "module_exports_snapshot"
582 } else {
583 snapshotModuleType = "sdk_snapshot"
584 }
585 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000586 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000587
588 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100589 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000590 if len(visibility) != 0 {
591 snapshotModule.AddProperty("visibility", visibility)
592 }
593
Paul Duffin865171e2020-03-02 18:38:15 +0000594 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000595
Paul Duffincd064672021-04-24 00:47:29 +0100596 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100597 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000598
Paul Duffin2d1bb892021-04-24 11:32:59 +0100599 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100600
Paul Duffin6a7e9532020-03-20 17:50:07 +0000601 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100602
Paul Duffin2d1bb892021-04-24 11:32:59 +0100603 // Create a mapping from osType to combined properties.
604 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
605 for _, combined := range combinedPropertiesList {
606 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
607 }
608
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100609 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000610 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100611 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100612 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000613
Paul Duffin2d1bb892021-04-24 11:32:59 +0100614 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000615 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000616 }
Paul Duffin865171e2020-03-02 18:38:15 +0000617
Jiyong Park8fe14e62020-10-19 22:47:34 +0900618 // If host is supported and any member is host OS dependent then disable host
619 // by default, so that we can enable each host OS variant explicitly. This
620 // avoids problems with implicitly enabled OS variants when the snapshot is
621 // used, which might be different from this run (e.g. different build OS).
622 if s.HostSupported() {
623 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100624 for _, memberVariantDep := range memberVariantDeps {
625 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
626 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900627 if !android.InList(targetString, supportedHostTargets) {
628 supportedHostTargets = append(supportedHostTargets, targetString)
629 }
630 }
631 }
632 if len(supportedHostTargets) > 0 {
633 hostPropertySet := targetPropertySet.AddPropertySet("host")
634 hostPropertySet.AddProperty("enabled", false)
635 }
636 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
637 for _, hostTarget := range supportedHostTargets {
638 propertySet := targetPropertySet.AddPropertySet(hostTarget)
639 propertySet.AddProperty("enabled", true)
640 }
641 }
642
Paul Duffin865171e2020-03-02 18:38:15 +0000643 // Prune any empty property sets.
644 snapshotModule.transform(pruneEmptySetTransformer{})
645
Paul Duffinb645ec82019-11-27 17:43:54 +0000646 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900647}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000648
Paul Duffinf88d8e02020-05-07 20:21:34 +0100649// Check the syntax of the generated Android.bp file contents and if they are
650// invalid then log an error with the contents (tagged with line numbers) and the
651// errors that were found so that it is easy to see where the problem lies.
652func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
653 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
654 if len(errs) != 0 {
655 message := &strings.Builder{}
656 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
657
658Generated Android.bp contents
659========================================================================
660`)
661 for i, line := range strings.Split(contents, "\n") {
662 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
663 }
664
665 _, _ = fmt.Fprint(message, `
666========================================================================
667
668Errors found:
669`)
670
671 for _, err := range errs {
672 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
673 }
674
675 ctx.ModuleErrorf("%s", message.String())
676 }
677}
678
Paul Duffin4b8b7932020-05-06 12:35:38 +0100679func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
680 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
681 if err != nil {
682 ctx.ModuleErrorf("error extracting common properties: %s", err)
683 }
684}
685
Paul Duffinfbe470e2021-04-24 12:37:13 +0100686// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
687type snapshotModuleStaticProperties struct {
688 Compile_multilib string `android:"arch_variant"`
689}
690
Paul Duffin2d1bb892021-04-24 11:32:59 +0100691// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
692type combinedSnapshotModuleProperties struct {
693 // The sdk variant from which this information was collected.
694 sdkVariant *sdk
695
696 // Static snapshot module properties.
697 staticProperties *snapshotModuleStaticProperties
698
699 // The dynamically generated member list properties.
700 dynamicProperties interface{}
701}
702
703// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100704func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
705 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100706 var list []*combinedSnapshotModuleProperties
707 for _, sdkVariant := range sdkVariants {
708 staticProperties := &snapshotModuleStaticProperties{
709 Compile_multilib: sdkVariant.multilibUsages.String(),
710 }
Paul Duffin62782de2021-07-14 12:05:16 +0100711 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100712
Paul Duffincd064672021-04-24 00:47:29 +0100713 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100714 sdkVariant: sdkVariant,
715 staticProperties: staticProperties,
716 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100717 }
718 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
719
720 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100721 }
Paul Duffincd064672021-04-24 00:47:29 +0100722
723 for _, memberVariantDep := range memberVariantDeps {
724 // If the member dependency is internal then do not add the dependency to the snapshot member
725 // list properties.
726 if !memberVariantDep.export {
727 continue
728 }
729
730 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100731 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100732 memberName := ctx.OtherModuleName(memberVariantDep.variant)
733
Paul Duffin13082052021-05-11 00:31:38 +0100734 if memberListProperty.getter == nil {
735 continue
736 }
737
Paul Duffincd064672021-04-24 00:47:29 +0100738 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100739 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100740 if !android.InList(memberName, memberList) {
741 memberList = append(memberList, memberName)
742 }
Paul Duffin13082052021-05-11 00:31:38 +0100743 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100744 }
745
Paul Duffin2d1bb892021-04-24 11:32:59 +0100746 return list
747}
748
749func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
750
751 // Extract the dynamic properties and add them to a list of propertiesContainer.
752 propertyContainers := []propertiesContainer{}
753 for _, i := range list {
754 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
755 sdkVariant: i.sdkVariant,
756 properties: i.dynamicProperties,
757 })
758 }
759
760 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100761 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100762 extractor := newCommonValueExtractor(commonDynamicProperties)
763 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
764
765 // Extract the static properties and add them to a list of propertiesContainer.
766 propertyContainers = []propertiesContainer{}
767 for _, i := range list {
768 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
769 sdkVariant: i.sdkVariant,
770 properties: i.staticProperties,
771 })
772 }
773
774 commonStaticProperties := &snapshotModuleStaticProperties{}
775 extractor = newCommonValueExtractor(commonStaticProperties)
776 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
777
778 return &combinedSnapshotModuleProperties{
779 sdkVariant: nil,
780 staticProperties: commonStaticProperties,
781 dynamicProperties: commonDynamicProperties,
782 }
783}
784
785func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
786 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100787 multilib := staticProperties.Compile_multilib
788 if multilib != "" && multilib != "both" {
789 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
790 propertySet.AddProperty("compile_multilib", multilib)
791 }
792
Paul Duffin2d1bb892021-04-24 11:32:59 +0100793 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100794 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100795 if memberListProperty.getter == nil {
796 continue
797 }
Paul Duffin865171e2020-03-02 18:38:15 +0000798 names := memberListProperty.getter(dynamicMemberTypeListProperties)
799 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000800 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000801 }
802 }
803}
804
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000805type propertyTag struct {
806 name string
807}
808
Paul Duffin94289702021-09-09 15:38:32 +0100809var _ android.BpPropertyTag = propertyTag{}
810
Paul Duffin0cb37b92020-03-04 14:52:46 +0000811// A BpPropertyTag to add to a property that contains references to other sdk members.
812//
813// This will cause the references to be rewritten to a versioned reference in the version
814// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000815var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000816var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000817
Paul Duffin0cb37b92020-03-04 14:52:46 +0000818// A BpPropertyTag that indicates the property should only be present in the versioned
819// module.
820//
821// This will cause the property to be removed from the unversioned instance of a
822// snapshot module.
823var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
824
Paul Duffine6c0d842020-01-15 14:08:51 +0000825type unversionedToVersionedTransformation struct {
826 identityTransformation
827 builder *snapshotBuilder
828}
829
Paul Duffine6c0d842020-01-15 14:08:51 +0000830func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
831 // Use a versioned name for the module but remember the original name for the
832 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100833 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000834 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000835 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100836 // Remove the prefer property if present as versioned modules never need marking with prefer.
837 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100838 // Ditto for use_source_config_var
839 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000840 return module
841}
842
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000843func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000844 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
845 required := tag == requiredSdkMemberReferencePropertyTag
846 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000847 } else {
848 return value, tag
849 }
850}
851
Paul Duffin72910952020-01-20 18:16:30 +0000852type unversionedTransformation struct {
853 identityTransformation
854 builder *snapshotBuilder
855}
856
857func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
858 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100859 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000860 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000861 return module
862}
863
864func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000865 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
866 required := tag == requiredSdkMemberReferencePropertyTag
867 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000868 } else if tag == sdkVersionedOnlyPropertyTag {
869 // The property is not allowed in the unversioned module so remove it.
870 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000871 } else {
872 return value, tag
873 }
874}
875
Paul Duffina78f3a72020-02-21 16:29:35 +0000876type pruneEmptySetTransformer struct {
877 identityTransformation
878}
879
880var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
881
882func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
883 if len(propertySet.properties) == 0 {
884 return nil, nil
885 } else {
886 return propertySet, tag
887 }
888}
889
Paul Duffinb645ec82019-11-27 17:43:54 +0000890func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000891 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
892 return true
893 })
894}
895
896func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100897 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000898 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000899 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100900 contents.IndentedPrintf("\n")
901 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000902 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100903 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000904 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000905 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000906}
907
908func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
909 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000910
Paul Duffin0df49682021-05-07 01:10:01 +0100911 addComment := func(name string) {
912 if text, ok := set.comments[name]; ok {
913 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100914 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100915 }
916 }
917 }
918
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000919 // Output the properties first, followed by the nested sets. This ensures a
920 // consistent output irrespective of whether property sets are created before
921 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000922 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000923 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000924
Paul Duffin0df49682021-05-07 01:10:01 +0100925 // Do not write property sets in the properties phase.
926 if _, ok := value.(*bpPropertySet); ok {
927 continue
928 }
929
930 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100931 reflectValue := reflect.ValueOf(value)
932 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000933 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000934
935 for _, name := range set.order {
936 value := set.getValue(name)
937
938 // Only write property sets in the sets phase.
939 switch v := value.(type) {
940 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100941 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100942 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000943 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100944 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000945 }
946 }
947
Paul Duffinb645ec82019-11-27 17:43:54 +0000948 contents.Dedent()
949}
950
Paul Duffina08e4dc2021-06-22 18:19:19 +0100951// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
952// by the value and then followed by a , and a newline.
953func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
954 contents.IndentedPrintf("%s: ", name)
955 outputUnnamedValue(contents, value)
956 contents.UnindentedPrintf(",\n")
957}
958
959// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
960// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
961// indented and all but the last line will end with a newline.
962func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
963 valueType := value.Type()
964 switch valueType.Kind() {
965 case reflect.Bool:
966 contents.UnindentedPrintf("%t", value.Bool())
967
968 case reflect.String:
969 contents.UnindentedPrintf("%q", value)
970
Paul Duffin51227d82021-05-18 12:54:27 +0100971 case reflect.Ptr:
972 outputUnnamedValue(contents, value.Elem())
973
Paul Duffina08e4dc2021-06-22 18:19:19 +0100974 case reflect.Slice:
975 length := value.Len()
976 if length == 0 {
977 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100978 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100979 firstValue := value.Index(0)
980 if length == 1 && !multiLineValue(firstValue) {
981 contents.UnindentedPrintf("[")
982 outputUnnamedValue(contents, firstValue)
983 contents.UnindentedPrintf("]")
984 } else {
985 contents.UnindentedPrintf("[\n")
986 contents.Indent()
987 for i := 0; i < length; i++ {
988 itemValue := value.Index(i)
989 contents.IndentedPrintf("")
990 outputUnnamedValue(contents, itemValue)
991 contents.UnindentedPrintf(",\n")
992 }
993 contents.Dedent()
994 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100995 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100996 }
997
Paul Duffin51227d82021-05-18 12:54:27 +0100998 case reflect.Struct:
999 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
1000 v := value.Interface()
1001 if _, ok := v.(android.BpPrintable); !ok {
1002 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
1003 }
1004 contents.UnindentedPrintf("{\n")
1005 contents.Indent()
1006 for f := 0; f < valueType.NumField(); f++ {
1007 fieldType := valueType.Field(f)
1008 if fieldType.Anonymous {
1009 continue
1010 }
1011 fieldValue := value.Field(f)
1012 fieldName := fieldType.Name
1013 propertyName := proptools.PropertyNameForField(fieldName)
1014 outputNamedValue(contents, propertyName, fieldValue)
1015 }
1016 contents.Dedent()
1017 contents.IndentedPrintf("}")
1018
Paul Duffina08e4dc2021-06-22 18:19:19 +01001019 default:
1020 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1021 }
1022}
1023
Paul Duffin51227d82021-05-18 12:54:27 +01001024// multiLineValue returns true if the supplied value may require multiple lines in the output.
1025func multiLineValue(value reflect.Value) bool {
1026 kind := value.Kind()
1027 return kind == reflect.Slice || kind == reflect.Struct
1028}
1029
Paul Duffinac37c502019-11-26 18:02:20 +00001030func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001031 contents := &generatedContents{}
1032 generateBpContents(contents, s.builderForTests.bpFile)
1033 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001034}
1035
Paul Duffind0759072021-02-17 11:23:00 +00001036func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1037 contents := &generatedContents{}
1038 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001039 name := module.Name()
1040 // Include modules that are either unversioned or have no name.
1041 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001042 })
1043 return contents.content.String()
1044}
1045
1046func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1047 contents := &generatedContents{}
1048 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001049 name := module.Name()
1050 // Include modules that are either versioned or have no name.
1051 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001052 })
1053 return contents.content.String()
1054}
1055
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001056type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001057 ctx android.ModuleContext
1058 sdk *sdk
1059
1060 // The version of the generated snapshot.
1061 //
1062 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1063 // this field.
1064 version string
1065
Paul Duffinb645ec82019-11-27 17:43:54 +00001066 snapshotDir android.OutputPath
1067 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001068
1069 // Map from destination to source of each copy - used to eliminate duplicates and
1070 // detect conflicts.
1071 copies map[string]string
1072
Paul Duffinb645ec82019-11-27 17:43:54 +00001073 filesToZip android.Paths
1074 zipsToMerge android.Paths
1075
Paul Duffin5c211452021-07-15 12:42:44 +01001076 // The path to an empty file.
1077 emptyFile android.WritablePath
1078
Paul Duffinb645ec82019-11-27 17:43:54 +00001079 prebuiltModules map[string]*bpModule
1080 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001081
1082 // The set of all members by name.
1083 allMembersByName map[string]struct{}
1084
1085 // The set of exported members by name.
1086 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001087
1088 // The target build release for which the snapshot is to be generated.
1089 targetBuildRelease *buildRelease
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001090}
1091
1092func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001093 if existing, ok := s.copies[dest]; ok {
1094 if existing != src.String() {
1095 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1096 return
1097 }
1098 } else {
1099 path := s.snapshotDir.Join(s.ctx, dest)
1100 s.ctx.Build(pctx, android.BuildParams{
1101 Rule: android.Cp,
1102 Input: src,
1103 Output: path,
1104 })
1105 s.filesToZip = append(s.filesToZip, path)
1106
1107 s.copies[dest] = src.String()
1108 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001109}
1110
Paul Duffin91547182019-11-12 19:39:36 +00001111func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1112 ctx := s.ctx
1113
1114 // Repackage the zip file so that the entries are in the destDir directory.
1115 // This will allow the zip file to be merged into the snapshot.
1116 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001117
1118 ctx.Build(pctx, android.BuildParams{
1119 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1120 Rule: repackageZip,
1121 Input: zipPath,
1122 Output: tmpZipPath,
1123 Args: map[string]string{
1124 "destdir": destDir,
1125 },
1126 })
Paul Duffin91547182019-11-12 19:39:36 +00001127
1128 // Add the repackaged zip file to the files to merge.
1129 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1130}
1131
Paul Duffin5c211452021-07-15 12:42:44 +01001132func (s *snapshotBuilder) EmptyFile() android.Path {
1133 if s.emptyFile == nil {
1134 ctx := s.ctx
1135 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1136 s.ctx.Build(pctx, android.BuildParams{
1137 Rule: android.Touch,
1138 Output: s.emptyFile,
1139 })
1140 }
1141
1142 return s.emptyFile
1143}
1144
Paul Duffin9d8d6092019-12-05 18:19:29 +00001145func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1146 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001147 if s.prebuiltModules[name] != nil {
1148 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1149 }
1150
1151 m := s.bpFile.newModule(moduleType)
1152 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001153
Paul Duffinbefa4b92020-03-04 14:22:45 +00001154 variant := member.Variants()[0]
1155
Paul Duffin13f02712020-03-06 12:30:43 +00001156 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001157 // An internal member is only referenced from the sdk snapshot which is in the
1158 // same package so can be marked as private.
1159 m.AddProperty("visibility", []string{"//visibility:private"})
1160 } else {
1161 // Extract visibility information from a member variant. All variants have the same
1162 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001163 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1164
1165 // Add any additional visibility rules needed for the prebuilts to reference each other.
1166 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1167 if err != nil {
1168 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1169 }
1170
1171 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001172 if len(visibility) != 0 {
1173 m.AddProperty("visibility", visibility)
1174 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001175 }
1176
Martin Stjernholm1e041092020-11-03 00:11:09 +00001177 // Where available copy apex_available properties from the member.
1178 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1179 apexAvailable := apexAware.ApexAvailable()
1180 if len(apexAvailable) == 0 {
1181 // //apex_available:platform is the default.
1182 apexAvailable = []string{android.AvailableToPlatform}
1183 }
1184
1185 // Add in any baseline apex available settings.
1186 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1187
1188 // Remove duplicates and sort.
1189 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1190 sort.Strings(apexAvailable)
1191
1192 m.AddProperty("apex_available", apexAvailable)
1193 }
1194
Paul Duffinb0bb3762021-05-06 16:48:05 +01001195 // The licenses are the same for all variants.
1196 mctx := s.ctx
1197 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1198 if len(licenseInfo.Licenses) > 0 {
1199 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1200 }
1201
Paul Duffin865171e2020-03-02 18:38:15 +00001202 deviceSupported := false
1203 hostSupported := false
1204
1205 for _, variant := range member.Variants() {
1206 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001207 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001208 hostSupported = true
1209 } else if osClass == android.Device {
1210 deviceSupported = true
1211 }
1212 }
1213
1214 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001215
Paul Duffin0cb37b92020-03-04 14:52:46 +00001216 // Disable installation in the versioned module of those modules that are ever installable.
1217 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1218 if installable.EverInstallable() {
1219 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1220 }
1221 }
1222
Paul Duffinb645ec82019-11-27 17:43:54 +00001223 s.prebuiltModules[name] = m
1224 s.prebuiltOrder = append(s.prebuiltOrder, m)
1225 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001226}
1227
Paul Duffin865171e2020-03-02 18:38:15 +00001228func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001229 // If neither device or host is supported then this module does not support either so will not
1230 // recognize the properties.
1231 if !deviceSupported && !hostSupported {
1232 return
1233 }
1234
Paul Duffin865171e2020-03-02 18:38:15 +00001235 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001236 bpModule.AddProperty("device_supported", false)
1237 }
Paul Duffin865171e2020-03-02 18:38:15 +00001238 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001239 bpModule.AddProperty("host_supported", true)
1240 }
1241}
1242
Paul Duffin13f02712020-03-06 12:30:43 +00001243func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1244 if required {
1245 return requiredSdkMemberReferencePropertyTag
1246 } else {
1247 return optionalSdkMemberReferencePropertyTag
1248 }
1249}
1250
1251func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1252 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001253}
1254
Paul Duffinb645ec82019-11-27 17:43:54 +00001255// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001256func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1257 if _, ok := s.allMembersByName[unversionedName]; !ok {
1258 if required {
1259 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1260 }
1261 return unversionedName
1262 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001263 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1264}
Paul Duffinb645ec82019-11-27 17:43:54 +00001265
Paul Duffin13f02712020-03-06 12:30:43 +00001266func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001267 var references []string = nil
1268 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001269 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001270 }
1271 return references
1272}
Paul Duffin13879572019-11-28 14:31:38 +00001273
Paul Duffin72910952020-01-20 18:16:30 +00001274// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001275func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1276 if _, ok := s.allMembersByName[unversionedName]; !ok {
1277 if required {
1278 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1279 }
1280 return unversionedName
1281 }
1282
1283 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001284 return s.ctx.ModuleName() + "_" + unversionedName
1285 } else {
1286 return unversionedName
1287 }
1288}
1289
Paul Duffin13f02712020-03-06 12:30:43 +00001290func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001291 var references []string = nil
1292 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001293 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001294 }
1295 return references
1296}
1297
Paul Duffin13f02712020-03-06 12:30:43 +00001298func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1299 _, ok := s.exportedMembersByName[memberName]
1300 return !ok
1301}
1302
Martin Stjernholm89238f42020-07-10 00:14:03 +01001303// Add the properties from the given SdkMemberProperties to the blueprint
1304// property set. This handles common properties in SdkMemberPropertiesBase and
1305// calls the member-specific AddToPropertySet for the rest.
1306func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1307 if memberProperties.Base().Compile_multilib != "" {
1308 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1309 }
1310
1311 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1312}
1313
Paul Duffin21827262021-04-24 12:16:36 +01001314// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1315type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001316 // The sdk variant that depends (possibly indirectly) on the member variant.
1317 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001318
1319 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001320 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001321
1322 // The variant that is added to the sdk.
1323 variant android.SdkAware
1324
1325 // True if the member should be exported, i.e. accessible, from outside the sdk.
1326 export bool
1327
1328 // The names of additional component modules provided by the variant.
1329 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001330}
1331
Paul Duffin13879572019-11-28 14:31:38 +00001332var _ android.SdkMember = (*sdkMember)(nil)
1333
Paul Duffin21827262021-04-24 12:16:36 +01001334// sdkMember groups all the variants of a specific member module together along with the name of the
1335// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001336type sdkMember struct {
1337 memberType android.SdkMemberType
1338 name string
1339 variants []android.SdkAware
1340}
1341
1342func (m *sdkMember) Name() string {
1343 return m.name
1344}
1345
1346func (m *sdkMember) Variants() []android.SdkAware {
1347 return m.variants
1348}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001349
Paul Duffin9c3760e2020-03-16 19:52:08 +00001350// Track usages of multilib variants.
1351type multilibUsage int
1352
1353const (
1354 multilibNone multilibUsage = 0
1355 multilib32 multilibUsage = 1
1356 multilib64 multilibUsage = 2
1357 multilibBoth = multilib32 | multilib64
1358)
1359
1360// Add the multilib that is used in the arch type.
1361func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1362 multilib := archType.Multilib
1363 switch multilib {
1364 case "":
1365 return m
1366 case "lib32":
1367 return m | multilib32
1368 case "lib64":
1369 return m | multilib64
1370 default:
1371 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1372 }
1373}
1374
1375func (m multilibUsage) String() string {
1376 switch m {
1377 case multilibNone:
1378 return ""
1379 case multilib32:
1380 return "32"
1381 case multilib64:
1382 return "64"
1383 case multilibBoth:
1384 return "both"
1385 default:
1386 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1387 m, multilibNone, multilib32, multilib64, multilibBoth))
1388 }
1389}
1390
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001391type baseInfo struct {
1392 Properties android.SdkMemberProperties
1393}
1394
Paul Duffinf34f6d82020-04-30 15:48:31 +01001395func (b *baseInfo) optimizableProperties() interface{} {
1396 return b.Properties
1397}
1398
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001399type osTypeSpecificInfo struct {
1400 baseInfo
1401
Paul Duffin00e46802020-03-12 20:40:35 +00001402 osType android.OsType
1403
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001404 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001405 //
1406 // Nil if there is one variant whose arch type is common
1407 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001408}
1409
Paul Duffin4b8b7932020-05-06 12:35:38 +01001410var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1411
Paul Duffinfc8dd232020-03-17 12:51:37 +00001412type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1413
Paul Duffin00e46802020-03-12 20:40:35 +00001414// Create a new osTypeSpecificInfo for the specified os type and its properties
1415// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001416func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001417 osInfo := &osTypeSpecificInfo{
1418 osType: osType,
1419 }
1420
1421 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1422 properties := variantPropertiesFactory()
1423 properties.Base().Os = osType
1424 return properties
1425 }
1426
1427 // Create a structure into which properties common across the architectures in
1428 // this os type will be stored.
1429 osInfo.Properties = osSpecificVariantPropertiesFactory()
1430
1431 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001432 var variantsByArchId = make(map[archId][]android.Module)
1433 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001434 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001435 target := variant.Target()
1436 id := archIdFromTarget(target)
1437 if _, ok := variantsByArchId[id]; !ok {
1438 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001439 }
1440
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001441 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001442 }
1443
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001444 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001445 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001446 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 +00001447 }
1448
1449 // A common arch type only has one variant and its properties should be treated
1450 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001451 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001452 } else {
1453 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001454 for _, id := range archIds {
1455 archVariants := variantsByArchId[id]
1456 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001457
1458 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1459 }
1460 }
1461
1462 return osInfo
1463}
1464
Paul Duffin39abf8f2021-09-24 14:58:27 +01001465func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1466 if len(osInfo.archInfos) == 0 {
1467 pruner.pruneProperties(osInfo.Properties)
1468 } else {
1469 for _, archInfo := range osInfo.archInfos {
1470 archInfo.pruneUnsupportedProperties(pruner)
1471 }
1472 }
1473}
1474
Paul Duffin00e46802020-03-12 20:40:35 +00001475// Optimize the properties by extracting common properties from arch type specific
1476// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001477func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001478 // Nothing to do if there is only a single common architecture.
1479 if len(osInfo.archInfos) == 0 {
1480 return
1481 }
1482
Paul Duffin9c3760e2020-03-16 19:52:08 +00001483 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001484 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001485 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001486
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001487 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001488 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001489 }
1490
Paul Duffin4b8b7932020-05-06 12:35:38 +01001491 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001492
1493 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001494 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001495}
1496
1497// Add the properties for an os to a property set.
1498//
1499// Maps the properties related to the os variants through to an appropriate
1500// module structure that will produce equivalent set of variants when it is
1501// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001502func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001503
1504 var osPropertySet android.BpPropertySet
1505 var archPropertySet android.BpPropertySet
1506 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001507 if osInfo.Properties.Base().Os_count == 1 &&
1508 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1509 // There is only one OS type present in the variants and it shouldn't have a
1510 // variant-specific target. The latter is the case if it's either for device
1511 // where there is only one OS (android), or for host and the member type
1512 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001513
1514 // Create a structure that looks like:
1515 // module_type {
1516 // name: "...",
1517 // ...
1518 // <common properties>
1519 // ...
1520 // <single os type specific properties>
1521 //
1522 // arch: {
1523 // <arch specific sections>
1524 // }
1525 //
1526 osPropertySet = bpModule
1527 archPropertySet = osPropertySet.AddPropertySet("arch")
1528
1529 // Arch specific properties need to be added to an arch specific section
1530 // within arch.
1531 archOsPrefix = ""
1532 } else {
1533 // Create a structure that looks like:
1534 // module_type {
1535 // name: "...",
1536 // ...
1537 // <common properties>
1538 // ...
1539 // target: {
1540 // <arch independent os specific sections, e.g. android>
1541 // ...
1542 // <arch and os specific sections, e.g. android_x86>
1543 // }
1544 //
1545 osType := osInfo.osType
1546 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1547 archPropertySet = targetPropertySet
1548
1549 // Arch specific properties need to be added to an os and arch specific
1550 // section prefixed with <os>_.
1551 archOsPrefix = osType.Name + "_"
1552 }
1553
1554 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001555 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001556
1557 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1558 // os) specific properties.
1559 //
1560 // The archInfos list will be empty if the os contains variants for the common
1561 // architecture.
1562 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001563 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001564 }
1565}
1566
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001567func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1568 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001569 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001570}
1571
1572var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1573
Paul Duffin4b8b7932020-05-06 12:35:38 +01001574func (osInfo *osTypeSpecificInfo) String() string {
1575 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1576}
1577
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001578// archId encapsulates the information needed to identify a combination of arch type and native
1579// bridge support.
1580//
1581// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1582// essentially using one android.Arch to implement another. However, in terms of the handling of
1583// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1584// on android.Target.
1585//
1586// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1587type archId struct {
1588 // The arch type of the variant's target.
1589 archType android.ArchType
1590
1591 // True if the variants is for the native bridge, false otherwise.
1592 nativeBridge bool
1593}
1594
1595// propertyName returns the name of the property corresponding to use for this arch id.
1596func (i *archId) propertyName() string {
1597 name := i.archType.Name
1598 if i.nativeBridge {
1599 // Note: This does not result in a valid property because there is no architecture specific
1600 // native bridge property, only a generic "native_bridge" property. However, this will be used
1601 // in error messages if there is an attempt to use this in a generated bp file.
1602 name += "_native_bridge"
1603 }
1604 return name
1605}
1606
1607func (i *archId) String() string {
1608 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1609}
1610
1611// archIdFromTarget returns an archId initialized from information in the supplied target.
1612func archIdFromTarget(target android.Target) archId {
1613 return archId{
1614 archType: target.Arch.ArchType,
1615 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1616 }
1617}
1618
1619// commonArchId is the archId for the common architecture.
1620var commonArchId = archId{archType: android.Common}
1621
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001622type archTypeSpecificInfo struct {
1623 baseInfo
1624
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001625 archId archId
1626 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001627
Paul Duffinb42fa672021-09-09 16:37:49 +01001628 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001629}
1630
Paul Duffin4b8b7932020-05-06 12:35:38 +01001631var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1632
Paul Duffinfc8dd232020-03-17 12:51:37 +00001633// Create a new archTypeSpecificInfo for the specified arch type and its properties
1634// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001635func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001636
Paul Duffinfc8dd232020-03-17 12:51:37 +00001637 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001638 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001639
1640 // Create the properties into which the arch type specific properties will be
1641 // added.
1642 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001643
1644 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001645 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001646 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001647 // Group the variants by image type.
1648 variantsByImage := make(map[string][]android.Module)
1649 for _, variant := range archVariants {
1650 image := variant.ImageVariation().Variation
1651 variantsByImage[image] = append(variantsByImage[image], variant)
1652 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001653
Paul Duffinb42fa672021-09-09 16:37:49 +01001654 // Create the image variant info in a fixed order.
1655 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1656 variants := variantsByImage[imageVariantName]
1657 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001658 }
1659 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001660
1661 return archInfo
1662}
1663
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001664// Get the link type of the variant
1665//
1666// If the variant is not differentiated by link type then it returns "",
1667// otherwise it returns one of "static" or "shared".
1668func getLinkType(variant android.Module) string {
1669 linkType := ""
1670 if linkable, ok := variant.(cc.LinkableInterface); ok {
1671 if linkable.Shared() && linkable.Static() {
1672 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1673 } else if linkable.Shared() {
1674 linkType = "shared"
1675 } else if linkable.Static() {
1676 linkType = "static"
1677 } else {
1678 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1679 }
1680 }
1681 return linkType
1682}
1683
Paul Duffin39abf8f2021-09-24 14:58:27 +01001684func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1685 if len(archInfo.imageVariantInfos) == 0 {
1686 pruner.pruneProperties(archInfo.Properties)
1687 } else {
1688 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1689 imageVariantInfo.pruneUnsupportedProperties(pruner)
1690 }
1691 }
1692}
1693
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001694// Optimize the properties by extracting common properties from link type specific
1695// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001696func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001697 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001698 return
1699 }
1700
Paul Duffinb42fa672021-09-09 16:37:49 +01001701 // Optimize the image variant properties first.
1702 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1703 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1704 }
1705
1706 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001707}
1708
Paul Duffinfc8dd232020-03-17 12:51:37 +00001709// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001710func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001711 archPropertySuffix := archInfo.archId.propertyName()
1712 propertySetName := archOsPrefix + archPropertySuffix
1713 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001714 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1715 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1716 archTypePropertySet.AddProperty("enabled", true)
1717 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001718 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001719
Paul Duffinb42fa672021-09-09 16:37:49 +01001720 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1721 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001722 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001723
1724 // If this is for a native bridge architecture then make sure that the property set does not
1725 // contain any properties as providing native bridge specific properties is not currently
1726 // supported.
1727 if archInfo.archId.nativeBridge {
1728 propertySetContents := getPropertySetContents(archTypePropertySet)
1729 if propertySetContents != "" {
1730 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",
1731 propertySetName, ctx.name, propertySetContents)
1732 }
1733 }
1734}
1735
1736// getPropertySetContents returns the string representation of the contents of a property set, after
1737// recursively pruning any empty nested property sets.
1738func getPropertySetContents(propertySet android.BpPropertySet) string {
1739 set := propertySet.(*bpPropertySet)
1740 set.transformContents(pruneEmptySetTransformer{})
1741 if len(set.properties) != 0 {
1742 contents := &generatedContents{}
1743 contents.Indent()
1744 outputPropertySet(contents, set)
1745 setAsString := contents.content.String()
1746 return setAsString
1747 }
1748 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001749}
1750
Paul Duffin4b8b7932020-05-06 12:35:38 +01001751func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001752 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001753}
1754
Paul Duffinb42fa672021-09-09 16:37:49 +01001755type imageVariantSpecificInfo struct {
1756 baseInfo
1757
1758 imageVariant string
1759
1760 linkInfos []*linkTypeSpecificInfo
1761}
1762
1763func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1764
1765 // Create an image variant specific info into which the variant properties can be copied.
1766 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1767
1768 // Create the properties into which the image variant specific properties will be added.
1769 imageInfo.Properties = variantPropertiesFactory()
1770
1771 if len(imageVariants) == 1 {
1772 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1773 } else {
1774 // There is more than one variant for this image variant which must be differentiated by link
1775 // type.
1776 for _, linkVariant := range imageVariants {
1777 linkType := getLinkType(linkVariant)
1778 if linkType == "" {
1779 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1780 } else {
1781 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1782
1783 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1784 }
1785 }
1786 }
1787
1788 return imageInfo
1789}
1790
Paul Duffin39abf8f2021-09-24 14:58:27 +01001791func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1792 if len(imageInfo.linkInfos) == 0 {
1793 pruner.pruneProperties(imageInfo.Properties)
1794 } else {
1795 for _, linkInfo := range imageInfo.linkInfos {
1796 linkInfo.pruneUnsupportedProperties(pruner)
1797 }
1798 }
1799}
1800
Paul Duffinb42fa672021-09-09 16:37:49 +01001801// Optimize the properties by extracting common properties from link type specific
1802// properties into arch type specific properties.
1803func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1804 if len(imageInfo.linkInfos) == 0 {
1805 return
1806 }
1807
1808 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1809}
1810
1811// Add the properties for an arch type to a property set.
1812func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1813 if imageInfo.imageVariant != android.CoreVariation {
1814 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1815 }
1816
1817 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1818
1819 for _, linkInfo := range imageInfo.linkInfos {
1820 linkInfo.addToPropertySet(ctx, propertySet)
1821 }
1822
1823 // If this is for a non-core image variant then make sure that the property set does not contain
1824 // any properties as providing non-core image variant specific properties for prebuilts is not
1825 // currently supported.
1826 if imageInfo.imageVariant != android.CoreVariation {
1827 propertySetContents := getPropertySetContents(propertySet)
1828 if propertySetContents != "" {
1829 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",
1830 imageInfo.imageVariant, ctx.name, propertySetContents)
1831 }
1832 }
1833}
1834
1835func (imageInfo *imageVariantSpecificInfo) String() string {
1836 return imageInfo.imageVariant
1837}
1838
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001839type linkTypeSpecificInfo struct {
1840 baseInfo
1841
1842 linkType string
1843}
1844
Paul Duffin4b8b7932020-05-06 12:35:38 +01001845var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1846
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001847// Create a new linkTypeSpecificInfo for the specified link type and its properties
1848// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001849func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001850 linkInfo := &linkTypeSpecificInfo{
1851 baseInfo: baseInfo{
1852 // Create the properties into which the link type specific properties will be
1853 // added.
1854 Properties: variantPropertiesFactory(),
1855 },
1856 linkType: linkType,
1857 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001858 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001859 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001860}
1861
Paul Duffinf68f85a2021-09-09 16:11:42 +01001862func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1863 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1864 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1865}
1866
Paul Duffin39abf8f2021-09-24 14:58:27 +01001867func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1868 pruner.pruneProperties(l.Properties)
1869}
1870
Paul Duffin4b8b7932020-05-06 12:35:38 +01001871func (l *linkTypeSpecificInfo) String() string {
1872 return fmt.Sprintf("LinkType{%s}", l.linkType)
1873}
1874
Paul Duffin3a4eb502020-03-19 16:11:18 +00001875type memberContext struct {
1876 sdkMemberContext android.ModuleContext
1877 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001878 memberType android.SdkMemberType
1879 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001880
1881 // The set of traits required of this member.
1882 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001883}
1884
1885func (m *memberContext) SdkModuleContext() android.ModuleContext {
1886 return m.sdkMemberContext
1887}
1888
1889func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1890 return m.builder
1891}
1892
Paul Duffina551a1c2020-03-17 21:04:24 +00001893func (m *memberContext) MemberType() android.SdkMemberType {
1894 return m.memberType
1895}
1896
1897func (m *memberContext) Name() string {
1898 return m.name
1899}
1900
Paul Duffind19f8942021-07-14 12:08:37 +01001901func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1902 return m.requiredTraits.Contains(trait)
1903}
1904
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001905func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001906
1907 memberType := member.memberType
1908
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001909 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01001910 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001911 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001912 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1913 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001914 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1915 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001916 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001917
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001918 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1919 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1920 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1921 // behavior is for the module.
1922 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001923
1924 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1925 if configVar != "" {
1926 parts := strings.Split(configVar, ":")
1927 cfp := android.ConfigVarProperties{
1928 Config_namespace: proptools.StringPtr(parts[0]),
1929 Var_name: proptools.StringPtr(parts[1]),
1930 }
1931 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1932 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001933 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001934
Paul Duffina04c1072020-03-02 10:16:35 +00001935 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001936 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001937 variants := member.Variants()
1938 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001939 osType := variant.Target().Os
1940 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001941 }
1942
Paul Duffina04c1072020-03-02 10:16:35 +00001943 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001944 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001945 properties := memberType.CreateVariantPropertiesStruct()
1946 base := properties.Base()
1947 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001948 return properties
1949 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001950
Paul Duffina04c1072020-03-02 10:16:35 +00001951 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001952
Paul Duffina04c1072020-03-02 10:16:35 +00001953 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001954 commonProperties := variantPropertiesFactory()
1955 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001956
Paul Duffin39abf8f2021-09-24 14:58:27 +01001957 // Create a property pruner that will prune any properties unsupported by the target build
1958 // release.
1959 targetBuildRelease := ctx.builder.targetBuildRelease
1960 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1961
Paul Duffinc097e362020-03-10 22:50:03 +00001962 // Create common value extractor that can be used to optimize the properties.
1963 commonValueExtractor := newCommonValueExtractor(commonProperties)
1964
Paul Duffina04c1072020-03-02 10:16:35 +00001965 // The list of property structures which are os type specific but common across
1966 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001967 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001968
1969 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001970 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001971 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001972 // Add the os specific properties to a list of os type specific yet architecture
1973 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001974 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001975
Paul Duffin39abf8f2021-09-24 14:58:27 +01001976 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
1977
Paul Duffin00e46802020-03-12 20:40:35 +00001978 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001979 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001980 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001981
Paul Duffina04c1072020-03-02 10:16:35 +00001982 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001983 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001984
Paul Duffina04c1072020-03-02 10:16:35 +00001985 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001986 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001987
Paul Duffina04c1072020-03-02 10:16:35 +00001988 // Create a target property set into which target specific properties can be
1989 // added.
1990 targetPropertySet := bpModule.AddPropertySet("target")
1991
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001992 // If the member is host OS dependent and has host_supported then disable by
1993 // default and enable each host OS variant explicitly. This avoids problems
1994 // with implicitly enabled OS variants when the snapshot is used, which might
1995 // be different from this run (e.g. different build OS).
1996 if ctx.memberType.IsHostOsDependent() {
1997 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1998 if hostSupported {
1999 hostPropertySet := targetPropertySet.AddPropertySet("host")
2000 hostPropertySet.AddProperty("enabled", false)
2001 }
2002 }
2003
Paul Duffina04c1072020-03-02 10:16:35 +00002004 // Iterate over the os types in a fixed order.
2005 for _, osType := range s.getPossibleOsTypes() {
2006 osInfo := osTypeToInfo[osType]
2007 if osInfo == nil {
2008 continue
2009 }
2010
Paul Duffin3a4eb502020-03-19 16:11:18 +00002011 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002012 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002013}
2014
Paul Duffina04c1072020-03-02 10:16:35 +00002015// Compute the list of possible os types that this sdk could support.
2016func (s *sdk) getPossibleOsTypes() []android.OsType {
2017 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002018 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002019 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002020 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002021 osTypes = append(osTypes, osType)
2022 }
2023 }
2024 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002025 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002026 osTypes = append(osTypes, osType)
2027 }
2028 }
2029 }
2030 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2031 return osTypes
2032}
2033
Paul Duffinb28369a2020-05-04 15:39:59 +01002034// Given a set of properties (struct value), return the value of the field within that
2035// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002036type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2037
Paul Duffinc459f892020-04-30 18:08:29 +01002038// Checks the metadata to determine whether the property should be ignored for the
2039// purposes of common value extraction or not.
2040type extractorMetadataPredicate func(metadata propertiesContainer) bool
2041
2042// Indicates whether optimizable properties are provided by a host variant or
2043// not.
2044type isHostVariant interface {
2045 isHostVariant() bool
2046}
2047
Paul Duffinb28369a2020-05-04 15:39:59 +01002048// A property that can be optimized by the commonValueExtractor.
2049type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002050 // The name of the field for this property. It is a "."-separated path for
2051 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002052 name string
2053
Paul Duffinc459f892020-04-30 18:08:29 +01002054 // Filter that can use metadata associated with the properties being optimized
2055 // to determine whether the field should be ignored during common value
2056 // optimization.
2057 filter extractorMetadataPredicate
2058
Paul Duffinb28369a2020-05-04 15:39:59 +01002059 // Retrieves the value on which common value optimization will be performed.
2060 getter fieldAccessorFunc
2061
2062 // The empty value for the field.
2063 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002064
2065 // True if the property can support arch variants false otherwise.
2066 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002067}
2068
Paul Duffin4b8b7932020-05-06 12:35:38 +01002069func (p extractorProperty) String() string {
2070 return p.name
2071}
2072
Paul Duffinc097e362020-03-10 22:50:03 +00002073// Supports extracting common values from a number of instances of a properties
2074// structure into a separate common set of properties.
2075type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002076 // The properties that the extractor can optimize.
2077 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002078}
2079
2080// Create a new common value extractor for the structure type for the supplied
2081// properties struct.
2082//
2083// The returned extractor can be used on any properties structure of the same type
2084// as the supplied set of properties.
2085func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2086 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2087 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002088 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002089 return extractor
2090}
2091
2092// Gather the fields from the supplied structure type from which common values will
2093// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002094//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002095// This is recursive function. If it encounters a struct then it will recurse
2096// into it, passing in the accessor for the field and the struct name as prefix
2097// for the nested fields. That will then be used in the accessors for the fields
2098// in the embedded struct.
2099func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002100 for f := 0; f < structType.NumField(); f++ {
2101 field := structType.Field(f)
2102 if field.PkgPath != "" {
2103 // Ignore unexported fields.
2104 continue
2105 }
2106
Paul Duffinb07fa512020-03-10 22:17:04 +00002107 // Ignore fields whose value should be kept.
2108 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002109 continue
2110 }
2111
Paul Duffinc459f892020-04-30 18:08:29 +01002112 var filter extractorMetadataPredicate
2113
2114 // Add a filter
2115 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2116 filter = func(metadata propertiesContainer) bool {
2117 if m, ok := metadata.(isHostVariant); ok {
2118 if m.isHostVariant() {
2119 return false
2120 }
2121 }
2122 return true
2123 }
2124 }
2125
Paul Duffinc097e362020-03-10 22:50:03 +00002126 // Save a copy of the field index for use in the function.
2127 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002128
Martin Stjernholmb0249572020-09-15 02:32:35 +01002129 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002130
Paul Duffinc097e362020-03-10 22:50:03 +00002131 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002132 if containingStructAccessor != nil {
2133 // This is an embedded structure so first access the field for the embedded
2134 // structure.
2135 value = containingStructAccessor(value)
2136 }
2137
Paul Duffinc097e362020-03-10 22:50:03 +00002138 // Skip through interface and pointer values to find the structure.
2139 value = getStructValue(value)
2140
Paul Duffin4b8b7932020-05-06 12:35:38 +01002141 defer func() {
2142 if r := recover(); r != nil {
2143 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2144 }
2145 }()
2146
Paul Duffinc097e362020-03-10 22:50:03 +00002147 // Return the field.
2148 return value.Field(fieldIndex)
2149 }
2150
Martin Stjernholmb0249572020-09-15 02:32:35 +01002151 if field.Type.Kind() == reflect.Struct {
2152 // Gather fields from the nested or embedded structure.
2153 var subNamePrefix string
2154 if field.Anonymous {
2155 subNamePrefix = namePrefix
2156 } else {
2157 subNamePrefix = name + "."
2158 }
2159 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002160 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002161 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002162 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002163 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002164 fieldGetter,
2165 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002166 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002167 }
2168 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002169 }
Paul Duffinc097e362020-03-10 22:50:03 +00002170 }
2171}
2172
2173func getStructValue(value reflect.Value) reflect.Value {
2174foundStruct:
2175 for {
2176 kind := value.Kind()
2177 switch kind {
2178 case reflect.Interface, reflect.Ptr:
2179 value = value.Elem()
2180 case reflect.Struct:
2181 break foundStruct
2182 default:
2183 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2184 }
2185 }
2186 return value
2187}
2188
Paul Duffinf34f6d82020-04-30 15:48:31 +01002189// A container of properties to be optimized.
2190//
2191// Allows additional information to be associated with the properties, e.g. for
2192// filtering.
2193type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002194 fmt.Stringer
2195
Paul Duffinf34f6d82020-04-30 15:48:31 +01002196 // Get the properties that need optimizing.
2197 optimizableProperties() interface{}
2198}
2199
Paul Duffin2d1bb892021-04-24 11:32:59 +01002200// A wrapper for sdk variant related properties to allow them to be optimized.
2201type sdkVariantPropertiesContainer struct {
2202 sdkVariant *sdk
2203 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002204}
2205
Paul Duffin2d1bb892021-04-24 11:32:59 +01002206func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2207 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002208}
2209
Paul Duffin2d1bb892021-04-24 11:32:59 +01002210func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002211 return c.sdkVariant.String()
2212}
2213
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002214// Extract common properties from a slice of property structures of the same type.
2215//
2216// All the property structures must be of the same type.
2217// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002218// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002219//
2220// Iterates over each exported field (capitalized name) and checks to see whether they
2221// have the same value (using DeepEquals) across all the input properties. If it does not then no
2222// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002223// and the field in each of the input properties structure is set to its default value. Nested
2224// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002225func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002226 commonPropertiesValue := reflect.ValueOf(commonProperties)
2227 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002228
Paul Duffinf34f6d82020-04-30 15:48:31 +01002229 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2230
Paul Duffinb28369a2020-05-04 15:39:59 +01002231 for _, property := range e.properties {
2232 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002233 filter := property.filter
2234 if filter == nil {
2235 filter = func(metadata propertiesContainer) bool {
2236 return true
2237 }
2238 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002239
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002240 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002241 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2242 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002243 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002244
Paul Duffin864e1b42020-05-06 10:23:19 +01002245 // Assume that all the values will be the same.
2246 //
2247 // While similar to this is not quite the same as commonValue == nil. If all the values
2248 // have been filtered out then this will be false but commonValue == nil will be true.
2249 valuesDiffer := false
2250
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002251 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002252 container := sliceValue.Index(i).Interface().(propertiesContainer)
2253 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002254 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002255
Paul Duffinc459f892020-04-30 18:08:29 +01002256 if !filter(container) {
2257 expectedValue := property.emptyValue.Interface()
2258 actualValue := fieldValue.Interface()
2259 if !reflect.DeepEqual(expectedValue, actualValue) {
2260 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2261 }
2262 continue
2263 }
2264
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002265 if commonValue == nil {
2266 // Use the first value as the commonProperties value.
2267 commonValue = &fieldValue
2268 } else {
2269 // If the value does not match the current common value then there is
2270 // no value in common so break out.
2271 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2272 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002273 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002274 break
2275 }
2276 }
2277 }
2278
Paul Duffin864e1b42020-05-06 10:23:19 +01002279 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002280 // and set the input struct's field to the empty value.
2281 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002282 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002283 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002284 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002285 container := sliceValue.Index(i).Interface().(propertiesContainer)
2286 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002287 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002288 fieldValue.Set(emptyValue)
2289 }
2290 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002291
2292 if valuesDiffer && !property.archVariant {
2293 // The values differ but the property does not support arch variants so it
2294 // is an error.
2295 var details strings.Builder
2296 for i := 0; i < sliceValue.Len(); i++ {
2297 container := sliceValue.Index(i).Interface().(propertiesContainer)
2298 itemValue := reflect.ValueOf(container.optimizableProperties())
2299 fieldValue := fieldGetter(itemValue)
2300
2301 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2302 }
2303
2304 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2305 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002306 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002307
2308 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002309}