blob: 457828bdd585ff06836f0e32932805950a9ae4dd [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
Paul Duffinc6ba1822022-05-06 09:38:02 +000018 "bytes"
19 "encoding/json"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000021 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000022 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "strings"
24
Paul Duffin7d74e7b2020-03-06 12:30:13 +000025 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000026 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070027
Paul Duffin375058f2019-11-29 20:17:53 +000028 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029 "github.com/google/blueprint/proptools"
30
31 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090032)
33
Paul Duffin64fb5262021-05-05 21:36:04 +010034// Environment variables that affect the generated snapshot
35// ========================================================
36//
37// SOONG_SDK_SNAPSHOT_PREFER
Paul Duffinb01ac4b2022-05-24 20:10:05 +000038// By default every module in the generated snapshot has prefer: false. Building it
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000039// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010040//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010041// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
42// If set this specifies the Soong config var that can be used to control whether the prebuilt
43// modules from the generated snapshot or the original source modules. Values must be a colon
44// separated pair of strings, the first of which is the Soong config namespace, and the second
45// is the name of the variable within that namespace.
46//
47// The config namespace and var name are used to set the `use_source_config_var` property. That
48// in turn will cause the generated prebuilts to use the soong config variable to select whether
49// source or the prebuilt is used.
50// e.g. If an sdk snapshot is built using:
51// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
52// Then the resulting snapshot will include:
53// use_source_config_var: {
54// config_namespace: "acme",
55// var_name: "build_from_source",
56// }
57//
58// Assuming that the config variable is defined in .mk using something like:
59// $(call add_soong_config_namespace,acme)
60// $(call add_soong_config_var_value,acme,build_from_source,true)
61//
62// Then when the snapshot is unpacked in the repository it will have the following behavior:
63// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
64// sources.
65// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
66// sources, if present. Otherwise, it will use the prebuilts.
67//
68// This is a temporary mechanism to control the prefer flags and will be removed once a more
69// maintainable solution has been implemented.
70// TODO(b/174997203): Remove when no longer necessary.
71//
Paul Duffin39abf8f2021-09-24 14:58:27 +010072// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
73// This allows the target build release (i.e. the release version of the build within which
74// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
75// to the current build release version. Otherwise, it must be the name of one of the build
76// releases defined in nameToBuildRelease, e.g. S, T, etc..
77//
78// The generated snapshot must only be used in the specified target release. If the target
79// build release is not the current build release then the generated Android.bp file not be
80// checked for compatibility.
81//
82// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
83// to be compatible with S.
84//
Paul Duffin64fb5262021-05-05 21:36:04 +010085
Jiyong Park9b409bc2019-10-11 14:59:13 +090086var pctx = android.NewPackageContext("android/soong/sdk")
87
Paul Duffin375058f2019-11-29 20:17:53 +000088var (
89 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
90 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000091 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000092 CommandDeps: []string{
93 "${config.Zip2ZipCmd}",
94 },
95 },
96 "destdir")
97
98 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
99 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -0700100 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000101 CommandDeps: []string{
102 "${config.SoongZipCmd}",
103 },
104 Rspfile: "$out.rsp",
105 RspfileContent: "$in",
106 },
107 "basedir")
108
109 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
110 blueprint.RuleParams{
111 Command: `${config.MergeZipsCmd} $out $in`,
112 CommandDeps: []string{
113 "${config.MergeZipsCmd}",
114 },
115 })
116)
117
Paul Duffin43f7bf02021-05-05 22:00:51 +0100118const (
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000119 soongSdkSnapshotVersionCurrent = "current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100120)
121
Paul Duffinb645ec82019-11-27 17:43:54 +0000122type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900123 content strings.Builder
124 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900125}
126
Paul Duffinb645ec82019-11-27 17:43:54 +0000127// generatedFile abstracts operations for writing contents into a file and emit a build rule
128// for the file.
129type generatedFile struct {
130 generatedContents
131 path android.OutputPath
132}
133
Jiyong Park232e7852019-11-04 12:23:40 +0900134func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000136 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900137 }
138}
139
Paul Duffinb645ec82019-11-27 17:43:54 +0000140func (gc *generatedContents) Indent() {
141 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900142}
143
Paul Duffinb645ec82019-11-27 17:43:54 +0000144func (gc *generatedContents) Dedent() {
145 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900146}
147
Paul Duffina08e4dc2021-06-22 18:19:19 +0100148// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
149// arguments.
150func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000151 _, _ = fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100152}
153
154// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
155// the arguments.
156func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000157 _, _ = fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900158}
159
160func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800161 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100162
163 content := gf.content.String()
164
165 // ninja consumes newline characters in rspfile_content. Prevent it by
166 // escaping the backslash in the newline character. The extra backslash
167 // is removed when the rspfile is written to the actual script file
168 content = strings.ReplaceAll(content, "\n", "\\n")
169
Jiyong Park9b409bc2019-10-11 14:59:13 +0900170 rb.Command().
171 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100172 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100173 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900174 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
175 rb.Command().
176 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800177 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900178}
179
Paul Duffin13879572019-11-28 14:31:38 +0000180// Collect all the members.
181//
Paul Duffinb97b1572021-04-29 21:50:40 +0100182// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
183// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000184func (s *sdk) collectMembers(ctx android.ModuleContext) {
185 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000186 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
187 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100188 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100189 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900190
Paul Duffin5cca7c42021-05-26 10:16:01 +0100191 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
192 if memberType == nil {
193 return false
194 }
195
Paul Duffin13879572019-11-28 14:31:38 +0000196 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000197 if !memberType.IsInstance(child) {
198 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199 }
Paul Duffin13879572019-11-28 14:31:38 +0000200
Paul Duffin6a7e9532020-03-20 17:50:07 +0000201 // Keep track of which multilib variants are used by the sdk.
202 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
203
Paul Duffinb97b1572021-04-29 21:50:40 +0100204 var exportedComponentsInfo android.ExportedComponentsInfo
205 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
206 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
207 }
208
Paul Duffinc6ba1822022-05-06 09:38:02 +0000209 var container android.SdkAware
210 if parent != ctx.Module() {
211 container = parent.(android.SdkAware)
212 }
213
Paul Duffina7208112021-04-23 21:20:20 +0100214 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100215 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000216 sdkVariant: s,
217 memberType: memberType,
218 variant: child.(android.SdkAware),
219 container: container,
220 export: export,
221 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100222 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000223
Paul Duffin2d3da312021-05-06 12:02:27 +0100224 // Recurse down into the member's dependencies as it may have dependencies that need to be
225 // automatically added to the sdk.
226 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900227 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000228
229 return false
Paul Duffin13879572019-11-28 14:31:38 +0000230 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000231}
232
Paul Duffincc3132e2021-04-24 01:10:30 +0100233// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
234// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000235//
Paul Duffincc3132e2021-04-24 01:10:30 +0100236// The sdkMember instances are then grouped into slices by member type. Within each such slice the
237// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000238//
Paul Duffincc3132e2021-04-24 01:10:30 +0100239// Finally, the member type slices are concatenated together to form a single slice. The order in
240// which they are concatenated is the order in which the member types were registered in the
241// android.SdkMemberTypesRegistry.
242func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000243 byType := make(map[android.SdkMemberType][]*sdkMember)
244 byName := make(map[string]*sdkMember)
245
Paul Duffin21827262021-04-24 12:16:36 +0100246 for _, memberVariantDep := range memberVariantDeps {
247 memberType := memberVariantDep.memberType
248 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000249
250 name := ctx.OtherModuleName(variant)
251 member := byName[name]
252 if member == nil {
253 member = &sdkMember{memberType: memberType, name: name}
254 byName[name] = member
255 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400256 } else if member.memberType != memberType {
257 // validate whether this is the same member type or and overriding member type
258 if memberType.Overrides(member.memberType) {
259 member.memberType = memberType
260 } else if !member.memberType.Overrides(memberType) {
261 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
262 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000263 }
264
Paul Duffin1356d8c2020-02-25 19:26:33 +0000265 // Only append new variants to the list. This is needed because a member can be both
266 // exported by the sdk and also be a transitive sdk member.
267 member.variants = appendUniqueVariants(member.variants, variant)
268 }
Paul Duffin13879572019-11-28 14:31:38 +0000269 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100270 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000271 membersOfType := byType[memberListProperty.memberType]
272 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900273 }
274
Paul Duffin6a7e9532020-03-20 17:50:07 +0000275 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900276}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900277
Paul Duffin72910952020-01-20 18:16:30 +0000278func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
279 for _, v := range variants {
280 if v == newVariant {
281 return variants
282 }
283 }
284 return append(variants, newVariant)
285}
286
Paul Duffin51509a12022-04-06 12:48:09 +0000287// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
288// the build from which the snapshot was produced.
289const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
290
Jiyong Park73c54ee2019-10-22 20:31:18 +0900291// SDK directory structure
292// <sdk_root>/
293// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
294// <api_ver>/ : below this directory are all auto-generated
295// Android.bp : definition of 'sdk_snapshot' module is here
296// aidl/
297// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
298// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900299// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900300// include/
301// bionic/libc/include/stdlib.h : an exported header file
302// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900303// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900304// <arch>/include/ : arch-specific exported headers
305// <arch>/include_gen/ : arch-specific generated headers
306// <arch>/lib/
307// libFoo.so : a stub library
308
Jiyong Park232e7852019-11-04 12:23:40 +0900309// buildSnapshot is the main function in this source file. It creates rules to copy
310// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000311func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000312
Paul Duffinb97b1572021-04-29 21:50:40 +0100313 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100314 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100315 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000316 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100317 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100318 }
Paul Duffin865171e2020-03-02 18:38:15 +0000319
Paul Duffinb97b1572021-04-29 21:50:40 +0100320 // Filter out any sdkMemberVariantDep that is a component of another.
321 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000322
Paul Duffinb97b1572021-04-29 21:50:40 +0100323 // Record the names of all the members, both explicitly specified and implicitly
324 // included.
325 allMembersByName := make(map[string]struct{})
326 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100327
Paul Duffinb97b1572021-04-29 21:50:40 +0100328 addMember := func(name string, export bool) {
329 allMembersByName[name] = struct{}{}
330 if export {
331 exportedMembersByName[name] = struct{}{}
332 }
333 }
334
335 for _, memberVariantDep := range memberVariantDeps {
336 name := memberVariantDep.variant.Name()
337 export := memberVariantDep.export
338
339 addMember(name, export)
340
341 // Add any components provided by the module.
342 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
343 addMember(component, export)
344 }
345
346 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
347 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000348 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000349 }
350
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000351 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900352
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000353 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000354
355 bpFile := &bpFile{
356 modules: make(map[string]*bpModule),
357 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000358
Paul Duffin43f7bf02021-05-05 22:00:51 +0100359 config := ctx.Config()
Paul Duffin43f7bf02021-05-05 22:00:51 +0100360
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000361 // Always add -current to the end
362 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100363
Paul Duffin39abf8f2021-09-24 14:58:27 +0100364 currentBuildRelease := latestBuildRelease()
365 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
366 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
367 if err != nil {
368 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
369 targetBuildRelease = currentBuildRelease
370 }
371
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000372 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000373 ctx: ctx,
374 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000375 snapshotDir: snapshotDir.OutputPath,
376 copies: make(map[string]string),
377 filesToZip: []android.Path{bp.path},
378 bpFile: bpFile,
379 prebuiltModules: make(map[string]*bpModule),
380 allMembersByName: allMembersByName,
381 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100382 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900383 }
Paul Duffinac37c502019-11-26 18:02:20 +0000384 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900385
Paul Duffin62131702021-05-07 01:10:01 +0100386 // If the sdk snapshot includes any license modules then add a package module which has a
387 // default_applicable_licenses property. That will prevent the LSC license process from updating
388 // the generated Android.bp file to add a package module that includes all licenses used by all
389 // the modules in that package. That would be unnecessary as every module in the sdk should have
390 // their own licenses property specified.
391 if hasLicenses {
392 pkg := bpFile.newModule("package")
393 property := "default_applicable_licenses"
394 pkg.AddCommentForProperty(property, `
395A default list here prevents the license LSC from adding its own list which would
396be unnecessary as every module in the sdk already has its own licenses property.
397`)
398 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
399 bpFile.AddModule(pkg)
400 }
401
Paul Duffin0df49682021-05-07 01:10:01 +0100402 // Group the variants for each member module together and then group the members of each member
403 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100404 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100405
406 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100407 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000408 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000409 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000410
Paul Duffind19f8942021-07-14 12:08:37 +0100411 name := member.name
412 requiredTraits := traits[name]
413 if requiredTraits == nil {
414 requiredTraits = android.EmptySdkMemberTraitSet()
415 }
416
417 // Create the snapshot for the member.
418 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000419
420 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100421 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900422 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900423
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000424 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000425 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000426 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100427 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100428 }
Paul Duffin72910952020-01-20 18:16:30 +0000429
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000430 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000431 // Prune any empty property sets.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000432 module = module.transform(pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000433
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000434 // Transform the module module to make it suitable for use in the snapshot.
435 module.transform(snapshotTransformer)
436 bpFile.AddModule(module)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100437 }
Paul Duffin26197a62021-04-24 00:34:10 +0100438
439 // generate Android.bp
440 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
441 generateBpContents(&bp.generatedContents, bpFile)
442
443 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100444 // If the snapshot is being generated for the current build release then check the syntax to make
445 // sure that it is compatible.
446 if targetBuildRelease == currentBuildRelease {
447 syntaxCheckSnapshotBpFile(ctx, contents)
448 }
Paul Duffin26197a62021-04-24 00:34:10 +0100449
450 bp.build(pctx, ctx, nil)
451
Paul Duffin51509a12022-04-06 12:48:09 +0000452 // Copy the build number file into the snapshot.
453 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
454
Paul Duffin26197a62021-04-24 00:34:10 +0100455 filesToZip := builder.filesToZip
456
457 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000458 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100459 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100460 outputDesc := "Building snapshot for " + ctx.ModuleName()
461
462 // If there are no zips to merge then generate the output zip directly.
463 // Otherwise, generate an intermediate zip file into which other zips can be
464 // merged.
465 var zipFile android.OutputPath
466 var desc string
467 if len(builder.zipsToMerge) == 0 {
468 zipFile = outputZipFile
469 desc = outputDesc
470 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000471 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100472 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100473 desc = "Building intermediate snapshot for " + ctx.ModuleName()
474 }
475
476 ctx.Build(pctx, android.BuildParams{
477 Description: desc,
478 Rule: zipFiles,
479 Inputs: filesToZip,
480 Output: zipFile,
481 Args: map[string]string{
482 "basedir": builder.snapshotDir.String(),
483 },
484 })
485
486 if len(builder.zipsToMerge) != 0 {
487 ctx.Build(pctx, android.BuildParams{
488 Description: outputDesc,
489 Rule: mergeZips,
490 Input: zipFile,
491 Inputs: builder.zipsToMerge,
492 Output: outputZipFile,
493 })
494 }
495
Paul Duffinc6ba1822022-05-06 09:38:02 +0000496 modules := s.generateInfoData(ctx, memberVariantDeps)
497
498 // Output the modules information as pretty printed JSON.
499 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
500 output, err := json.MarshalIndent(modules, "", " ")
501 if err != nil {
502 ctx.ModuleErrorf("error generating %q: %s", info, err)
503 }
504 builder.infoContents = string(output)
505 info.generatedContents.UnindentedPrintf("%s", output)
506 info.build(pctx, ctx, nil)
507 infoPath := info.path
508 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
509 s.infoFile = android.OptionalPathForPath(installedInfo)
510
511 // Install the zip, making sure that the info file has been installed as well.
512 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
513 s.snapshotFile = android.OptionalPathForPath(installedZip)
514}
515
516type moduleInfo struct {
517 // The type of the module, e.g. java_sdk_library
518 moduleType string
519 // The name of the module.
520 name string
521 // A list of additional dependencies of the module.
522 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000523 // Additional member specific properties.
524 // These will be added into the generated JSON alongside the above properties.
525 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000526}
527
528func (m *moduleInfo) MarshalJSON() ([]byte, error) {
529 buffer := bytes.Buffer{}
530
531 separator := ""
532 writeObjectPair := func(key string, value interface{}) {
533 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
534 b, err := json.Marshal(value)
535 if err != nil {
536 panic(err)
537 }
538 buffer.Write(b)
539 separator = ","
540 }
541
542 buffer.WriteString("{")
543 writeObjectPair("@type", m.moduleType)
544 writeObjectPair("@name", m.name)
545 if m.deps != nil {
546 writeObjectPair("@deps", m.deps)
547 }
Paul Duffin958806b2022-05-16 13:10:47 +0000548 for _, k := range android.SortedStringKeys(m.memberSpecific) {
549 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000550 writeObjectPair(k, v)
551 }
552 buffer.WriteString("}")
553 return buffer.Bytes(), nil
554}
555
556var _ json.Marshaler = (*moduleInfo)(nil)
557
558// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
559func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
560 modules := []*moduleInfo{}
561 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000562 moduleType: "sdk",
563 name: ctx.ModuleName(),
564 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000565 }
566 modules = append(modules, &sdkInfo)
567
568 name2Info := map[string]*moduleInfo{}
569 getModuleInfo := func(module android.Module) *moduleInfo {
570 name := module.Name()
571 info := name2Info[name]
572 if info == nil {
573 moduleType := ctx.OtherModuleType(module)
574 // Remove any suffix added when creating modules dynamically.
575 moduleType = strings.Split(moduleType, "__")[0]
576 info = &moduleInfo{
577 moduleType: moduleType,
578 name: name,
579 }
Paul Duffin958806b2022-05-16 13:10:47 +0000580
581 additionalSdkInfo := ctx.OtherModuleProvider(module, android.AdditionalSdkInfoProvider).(android.AdditionalSdkInfo)
582 info.memberSpecific = additionalSdkInfo.Properties
583
Paul Duffinc6ba1822022-05-06 09:38:02 +0000584 name2Info[name] = info
585 }
586 return info
587 }
588
589 for _, memberVariantDep := range memberVariantDeps {
590 propertyName := memberVariantDep.memberType.SdkPropertyName()
591 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000592 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000593 list = v.([]string)
594 }
595
596 memberName := memberVariantDep.variant.Name()
597 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000598 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000599
600 if memberVariantDep.container != nil {
601 containerInfo := getModuleInfo(memberVariantDep.container)
602 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
603 }
604
605 // Make sure that the module info is created for each module.
606 getModuleInfo(memberVariantDep.variant)
607 }
608
609 for _, memberName := range android.SortedStringKeys(name2Info) {
610 info := name2Info[memberName]
611 modules = append(modules, info)
612 }
613
614 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100615}
616
Paul Duffinb97b1572021-04-29 21:50:40 +0100617// filterOutComponents removes any item from the deps list that is a component of another item in
618// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
619// then it will remove "foo.stubs" from the deps.
620func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
621 // Collate the set of components that all the modules added to the sdk provide.
622 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000623 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100624 dep := &deps[i]
625 for _, c := range dep.exportedComponentsInfo.Components {
626 components[c] = dep
627 }
628 }
629
630 // If no module provides components then return the input deps unfiltered.
631 if len(components) == 0 {
632 return deps
633 }
634
635 filtered := make([]sdkMemberVariantDep, 0, len(deps))
636 for _, dep := range deps {
637 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
638 if owner, ok := components[name]; ok {
639 // This is a component of another module that is a member of the sdk.
640
641 // If the component is exported but the owning module is not then the configuration is not
642 // supported.
643 if dep.export && !owner.export {
644 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
645 continue
646 }
647
648 // This module must not be added to the list of members of the sdk as that would result in a
649 // duplicate module in the sdk snapshot.
650 continue
651 }
652
653 filtered = append(filtered, dep)
654 }
655 return filtered
656}
657
Paul Duffinf88d8e02020-05-07 20:21:34 +0100658// Check the syntax of the generated Android.bp file contents and if they are
659// invalid then log an error with the contents (tagged with line numbers) and the
660// errors that were found so that it is easy to see where the problem lies.
661func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
662 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
663 if len(errs) != 0 {
664 message := &strings.Builder{}
665 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
666
667Generated Android.bp contents
668========================================================================
669`)
670 for i, line := range strings.Split(contents, "\n") {
671 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
672 }
673
674 _, _ = fmt.Fprint(message, `
675========================================================================
676
677Errors found:
678`)
679
680 for _, err := range errs {
681 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
682 }
683
684 ctx.ModuleErrorf("%s", message.String())
685 }
686}
687
Paul Duffin4b8b7932020-05-06 12:35:38 +0100688func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
689 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
690 if err != nil {
691 ctx.ModuleErrorf("error extracting common properties: %s", err)
692 }
693}
694
Paul Duffinfbe470e2021-04-24 12:37:13 +0100695// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
696type snapshotModuleStaticProperties struct {
697 Compile_multilib string `android:"arch_variant"`
698}
699
Paul Duffin2d1bb892021-04-24 11:32:59 +0100700// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
701type combinedSnapshotModuleProperties struct {
702 // The sdk variant from which this information was collected.
703 sdkVariant *sdk
704
705 // Static snapshot module properties.
706 staticProperties *snapshotModuleStaticProperties
707
708 // The dynamically generated member list properties.
709 dynamicProperties interface{}
710}
711
712// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100713func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
714 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100715 var list []*combinedSnapshotModuleProperties
716 for _, sdkVariant := range sdkVariants {
717 staticProperties := &snapshotModuleStaticProperties{
718 Compile_multilib: sdkVariant.multilibUsages.String(),
719 }
Paul Duffin62782de2021-07-14 12:05:16 +0100720 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100721
Paul Duffincd064672021-04-24 00:47:29 +0100722 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100723 sdkVariant: sdkVariant,
724 staticProperties: staticProperties,
725 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100726 }
727 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
728
729 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100730 }
Paul Duffincd064672021-04-24 00:47:29 +0100731
732 for _, memberVariantDep := range memberVariantDeps {
733 // If the member dependency is internal then do not add the dependency to the snapshot member
734 // list properties.
735 if !memberVariantDep.export {
736 continue
737 }
738
739 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100740 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100741 memberName := ctx.OtherModuleName(memberVariantDep.variant)
742
Paul Duffin13082052021-05-11 00:31:38 +0100743 if memberListProperty.getter == nil {
744 continue
745 }
746
Paul Duffincd064672021-04-24 00:47:29 +0100747 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100748 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100749 if !android.InList(memberName, memberList) {
750 memberList = append(memberList, memberName)
751 }
Paul Duffin13082052021-05-11 00:31:38 +0100752 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100753 }
754
Paul Duffin2d1bb892021-04-24 11:32:59 +0100755 return list
756}
757
758func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
759
760 // Extract the dynamic properties and add them to a list of propertiesContainer.
761 propertyContainers := []propertiesContainer{}
762 for _, i := range list {
763 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
764 sdkVariant: i.sdkVariant,
765 properties: i.dynamicProperties,
766 })
767 }
768
769 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100770 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100771 extractor := newCommonValueExtractor(commonDynamicProperties)
772 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
773
774 // Extract the static properties and add them to a list of propertiesContainer.
775 propertyContainers = []propertiesContainer{}
776 for _, i := range list {
777 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
778 sdkVariant: i.sdkVariant,
779 properties: i.staticProperties,
780 })
781 }
782
783 commonStaticProperties := &snapshotModuleStaticProperties{}
784 extractor = newCommonValueExtractor(commonStaticProperties)
785 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
786
787 return &combinedSnapshotModuleProperties{
788 sdkVariant: nil,
789 staticProperties: commonStaticProperties,
790 dynamicProperties: commonDynamicProperties,
791 }
792}
793
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000794type propertyTag struct {
795 name string
796}
797
Paul Duffin94289702021-09-09 15:38:32 +0100798var _ android.BpPropertyTag = propertyTag{}
799
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000800// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000801//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000802// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000803var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000804var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000805
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000806type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000807 identityTransformation
808 builder *snapshotBuilder
809}
810
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000811func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Paul Duffin72910952020-01-20 18:16:30 +0000812 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100813 name := module.Name()
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000814 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000815 return module
816}
817
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000818func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000819 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
820 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000821 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000822 } else {
823 return value, tag
824 }
825}
826
Paul Duffina78f3a72020-02-21 16:29:35 +0000827type pruneEmptySetTransformer struct {
828 identityTransformation
829}
830
831var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
832
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000833func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000834 if len(propertySet.properties) == 0 {
835 return nil, nil
836 } else {
837 return propertySet, tag
838 }
839}
840
Paul Duffinb645ec82019-11-27 17:43:54 +0000841func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100842 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000843 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000844 contents.IndentedPrintf("\n")
845 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
846 outputPropertySet(contents, bpModule.bpPropertySet)
847 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000848 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000849}
850
851func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
852 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000853
Paul Duffin0df49682021-05-07 01:10:01 +0100854 addComment := func(name string) {
855 if text, ok := set.comments[name]; ok {
856 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100857 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100858 }
859 }
860 }
861
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000862 // Output the properties first, followed by the nested sets. This ensures a
863 // consistent output irrespective of whether property sets are created before
864 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000865 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000866 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000867
Paul Duffin0df49682021-05-07 01:10:01 +0100868 // Do not write property sets in the properties phase.
869 if _, ok := value.(*bpPropertySet); ok {
870 continue
871 }
872
873 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100874 reflectValue := reflect.ValueOf(value)
875 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000876 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000877
878 for _, name := range set.order {
879 value := set.getValue(name)
880
881 // Only write property sets in the sets phase.
882 switch v := value.(type) {
883 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100884 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100885 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000886 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100887 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000888 }
889 }
890
Paul Duffinb645ec82019-11-27 17:43:54 +0000891 contents.Dedent()
892}
893
Paul Duffina08e4dc2021-06-22 18:19:19 +0100894// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
895// by the value and then followed by a , and a newline.
896func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
897 contents.IndentedPrintf("%s: ", name)
898 outputUnnamedValue(contents, value)
899 contents.UnindentedPrintf(",\n")
900}
901
902// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
903// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
904// indented and all but the last line will end with a newline.
905func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
906 valueType := value.Type()
907 switch valueType.Kind() {
908 case reflect.Bool:
909 contents.UnindentedPrintf("%t", value.Bool())
910
911 case reflect.String:
912 contents.UnindentedPrintf("%q", value)
913
Paul Duffin51227d82021-05-18 12:54:27 +0100914 case reflect.Ptr:
915 outputUnnamedValue(contents, value.Elem())
916
Paul Duffina08e4dc2021-06-22 18:19:19 +0100917 case reflect.Slice:
918 length := value.Len()
919 if length == 0 {
920 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100921 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100922 firstValue := value.Index(0)
923 if length == 1 && !multiLineValue(firstValue) {
924 contents.UnindentedPrintf("[")
925 outputUnnamedValue(contents, firstValue)
926 contents.UnindentedPrintf("]")
927 } else {
928 contents.UnindentedPrintf("[\n")
929 contents.Indent()
930 for i := 0; i < length; i++ {
931 itemValue := value.Index(i)
932 contents.IndentedPrintf("")
933 outputUnnamedValue(contents, itemValue)
934 contents.UnindentedPrintf(",\n")
935 }
936 contents.Dedent()
937 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100938 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100939 }
940
Paul Duffin51227d82021-05-18 12:54:27 +0100941 case reflect.Struct:
942 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
943 v := value.Interface()
944 if _, ok := v.(android.BpPrintable); !ok {
945 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
946 }
947 contents.UnindentedPrintf("{\n")
948 contents.Indent()
949 for f := 0; f < valueType.NumField(); f++ {
950 fieldType := valueType.Field(f)
951 if fieldType.Anonymous {
952 continue
953 }
954 fieldValue := value.Field(f)
955 fieldName := fieldType.Name
956 propertyName := proptools.PropertyNameForField(fieldName)
957 outputNamedValue(contents, propertyName, fieldValue)
958 }
959 contents.Dedent()
960 contents.IndentedPrintf("}")
961
Paul Duffina08e4dc2021-06-22 18:19:19 +0100962 default:
963 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
964 }
965}
966
Paul Duffin51227d82021-05-18 12:54:27 +0100967// multiLineValue returns true if the supplied value may require multiple lines in the output.
968func multiLineValue(value reflect.Value) bool {
969 kind := value.Kind()
970 return kind == reflect.Slice || kind == reflect.Struct
971}
972
Paul Duffinac37c502019-11-26 18:02:20 +0000973func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000974 contents := &generatedContents{}
975 generateBpContents(contents, s.builderForTests.bpFile)
976 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000977}
978
Paul Duffinc6ba1822022-05-06 09:38:02 +0000979func (s *sdk) GetInfoContentsForTests() string {
980 return s.builderForTests.infoContents
981}
982
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000983type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100984 ctx android.ModuleContext
985 sdk *sdk
986
Paul Duffinb645ec82019-11-27 17:43:54 +0000987 snapshotDir android.OutputPath
988 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000989
990 // Map from destination to source of each copy - used to eliminate duplicates and
991 // detect conflicts.
992 copies map[string]string
993
Paul Duffinb645ec82019-11-27 17:43:54 +0000994 filesToZip android.Paths
995 zipsToMerge android.Paths
996
Paul Duffin5c211452021-07-15 12:42:44 +0100997 // The path to an empty file.
998 emptyFile android.WritablePath
999
Paul Duffinb645ec82019-11-27 17:43:54 +00001000 prebuiltModules map[string]*bpModule
1001 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001002
1003 // The set of all members by name.
1004 allMembersByName map[string]struct{}
1005
1006 // The set of exported members by name.
1007 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001008
1009 // The target build release for which the snapshot is to be generated.
1010 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001011
Paul Duffin958806b2022-05-16 13:10:47 +00001012 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +00001013 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001014}
1015
1016func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001017 if existing, ok := s.copies[dest]; ok {
1018 if existing != src.String() {
1019 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1020 return
1021 }
1022 } else {
1023 path := s.snapshotDir.Join(s.ctx, dest)
1024 s.ctx.Build(pctx, android.BuildParams{
1025 Rule: android.Cp,
1026 Input: src,
1027 Output: path,
1028 })
1029 s.filesToZip = append(s.filesToZip, path)
1030
1031 s.copies[dest] = src.String()
1032 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001033}
1034
Paul Duffin91547182019-11-12 19:39:36 +00001035func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1036 ctx := s.ctx
1037
1038 // Repackage the zip file so that the entries are in the destDir directory.
1039 // This will allow the zip file to be merged into the snapshot.
1040 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001041
1042 ctx.Build(pctx, android.BuildParams{
1043 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1044 Rule: repackageZip,
1045 Input: zipPath,
1046 Output: tmpZipPath,
1047 Args: map[string]string{
1048 "destdir": destDir,
1049 },
1050 })
Paul Duffin91547182019-11-12 19:39:36 +00001051
1052 // Add the repackaged zip file to the files to merge.
1053 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1054}
1055
Paul Duffin5c211452021-07-15 12:42:44 +01001056func (s *snapshotBuilder) EmptyFile() android.Path {
1057 if s.emptyFile == nil {
1058 ctx := s.ctx
1059 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1060 s.ctx.Build(pctx, android.BuildParams{
1061 Rule: android.Touch,
1062 Output: s.emptyFile,
1063 })
1064 }
1065
1066 return s.emptyFile
1067}
1068
Paul Duffin9d8d6092019-12-05 18:19:29 +00001069func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1070 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001071 if s.prebuiltModules[name] != nil {
1072 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1073 }
1074
1075 m := s.bpFile.newModule(moduleType)
1076 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001077
Paul Duffinbefa4b92020-03-04 14:22:45 +00001078 variant := member.Variants()[0]
1079
Paul Duffin13f02712020-03-06 12:30:43 +00001080 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001081 // An internal member is only referenced from the sdk snapshot which is in the
1082 // same package so can be marked as private.
1083 m.AddProperty("visibility", []string{"//visibility:private"})
1084 } else {
1085 // Extract visibility information from a member variant. All variants have the same
1086 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001087 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1088
1089 // Add any additional visibility rules needed for the prebuilts to reference each other.
1090 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1091 if err != nil {
1092 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1093 }
1094
1095 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001096 if len(visibility) != 0 {
1097 m.AddProperty("visibility", visibility)
1098 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001099 }
1100
Martin Stjernholm1e041092020-11-03 00:11:09 +00001101 // Where available copy apex_available properties from the member.
1102 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1103 apexAvailable := apexAware.ApexAvailable()
1104 if len(apexAvailable) == 0 {
1105 // //apex_available:platform is the default.
1106 apexAvailable = []string{android.AvailableToPlatform}
1107 }
1108
1109 // Add in any baseline apex available settings.
1110 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1111
1112 // Remove duplicates and sort.
1113 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1114 sort.Strings(apexAvailable)
1115
1116 m.AddProperty("apex_available", apexAvailable)
1117 }
1118
Paul Duffinb0bb3762021-05-06 16:48:05 +01001119 // The licenses are the same for all variants.
1120 mctx := s.ctx
1121 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1122 if len(licenseInfo.Licenses) > 0 {
1123 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1124 }
1125
Paul Duffin865171e2020-03-02 18:38:15 +00001126 deviceSupported := false
1127 hostSupported := false
1128
1129 for _, variant := range member.Variants() {
1130 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001131 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001132 hostSupported = true
1133 } else if osClass == android.Device {
1134 deviceSupported = true
1135 }
1136 }
1137
1138 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001139
1140 s.prebuiltModules[name] = m
1141 s.prebuiltOrder = append(s.prebuiltOrder, m)
1142 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001143}
1144
Paul Duffin865171e2020-03-02 18:38:15 +00001145func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001146 // If neither device or host is supported then this module does not support either so will not
1147 // recognize the properties.
1148 if !deviceSupported && !hostSupported {
1149 return
1150 }
1151
Paul Duffin865171e2020-03-02 18:38:15 +00001152 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001153 bpModule.AddProperty("device_supported", false)
1154 }
Paul Duffin865171e2020-03-02 18:38:15 +00001155 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001156 bpModule.AddProperty("host_supported", true)
1157 }
1158}
1159
Paul Duffin13f02712020-03-06 12:30:43 +00001160func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1161 if required {
1162 return requiredSdkMemberReferencePropertyTag
1163 } else {
1164 return optionalSdkMemberReferencePropertyTag
1165 }
1166}
1167
1168func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1169 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001170}
1171
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001172// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1173// name. As part of the processing this checks to make sure that any required members are part of
1174// the snapshot.
1175func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
1176 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001177 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001178 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001179 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001180 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001181 }
1182
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001183 if s.isInternalMember(name) {
1184 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001185 } else {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001186 return name
Paul Duffin72910952020-01-20 18:16:30 +00001187 }
1188}
1189
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001190func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001191 var references []string = nil
1192 for _, m := range members {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001193 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001194 }
1195 return references
1196}
1197
Paul Duffin13f02712020-03-06 12:30:43 +00001198func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1199 _, ok := s.exportedMembersByName[memberName]
1200 return !ok
1201}
1202
Martin Stjernholm89238f42020-07-10 00:14:03 +01001203// Add the properties from the given SdkMemberProperties to the blueprint
1204// property set. This handles common properties in SdkMemberPropertiesBase and
1205// calls the member-specific AddToPropertySet for the rest.
1206func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1207 if memberProperties.Base().Compile_multilib != "" {
1208 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1209 }
1210
1211 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1212}
1213
Paul Duffin21827262021-04-24 12:16:36 +01001214// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1215type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001216 // The sdk variant that depends (possibly indirectly) on the member variant.
1217 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001218
1219 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001220 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001221
1222 // The variant that is added to the sdk.
1223 variant android.SdkAware
1224
Paul Duffinc6ba1822022-05-06 09:38:02 +00001225 // The optional container of this member, i.e. the module that is depended upon by the sdk
1226 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1227 // Is nil if this a direct dependency of the sdk.
1228 container android.SdkAware
1229
Paul Duffinb97b1572021-04-29 21:50:40 +01001230 // True if the member should be exported, i.e. accessible, from outside the sdk.
1231 export bool
1232
1233 // The names of additional component modules provided by the variant.
1234 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001235}
1236
Paul Duffin13879572019-11-28 14:31:38 +00001237var _ android.SdkMember = (*sdkMember)(nil)
1238
Paul Duffin21827262021-04-24 12:16:36 +01001239// sdkMember groups all the variants of a specific member module together along with the name of the
1240// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001241type sdkMember struct {
1242 memberType android.SdkMemberType
1243 name string
1244 variants []android.SdkAware
1245}
1246
1247func (m *sdkMember) Name() string {
1248 return m.name
1249}
1250
1251func (m *sdkMember) Variants() []android.SdkAware {
1252 return m.variants
1253}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001254
Paul Duffin9c3760e2020-03-16 19:52:08 +00001255// Track usages of multilib variants.
1256type multilibUsage int
1257
1258const (
1259 multilibNone multilibUsage = 0
1260 multilib32 multilibUsage = 1
1261 multilib64 multilibUsage = 2
1262 multilibBoth = multilib32 | multilib64
1263)
1264
1265// Add the multilib that is used in the arch type.
1266func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1267 multilib := archType.Multilib
1268 switch multilib {
1269 case "":
1270 return m
1271 case "lib32":
1272 return m | multilib32
1273 case "lib64":
1274 return m | multilib64
1275 default:
1276 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1277 }
1278}
1279
1280func (m multilibUsage) String() string {
1281 switch m {
1282 case multilibNone:
1283 return ""
1284 case multilib32:
1285 return "32"
1286 case multilib64:
1287 return "64"
1288 case multilibBoth:
1289 return "both"
1290 default:
1291 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1292 m, multilibNone, multilib32, multilib64, multilibBoth))
1293 }
1294}
1295
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001296type baseInfo struct {
1297 Properties android.SdkMemberProperties
1298}
1299
Paul Duffinf34f6d82020-04-30 15:48:31 +01001300func (b *baseInfo) optimizableProperties() interface{} {
1301 return b.Properties
1302}
1303
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001304type osTypeSpecificInfo struct {
1305 baseInfo
1306
Paul Duffin00e46802020-03-12 20:40:35 +00001307 osType android.OsType
1308
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001309 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001310 //
1311 // Nil if there is one variant whose arch type is common
1312 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001313}
1314
Paul Duffin4b8b7932020-05-06 12:35:38 +01001315var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1316
Paul Duffinfc8dd232020-03-17 12:51:37 +00001317type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1318
Paul Duffin00e46802020-03-12 20:40:35 +00001319// Create a new osTypeSpecificInfo for the specified os type and its properties
1320// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001321func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001322 osInfo := &osTypeSpecificInfo{
1323 osType: osType,
1324 }
1325
1326 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1327 properties := variantPropertiesFactory()
1328 properties.Base().Os = osType
1329 return properties
1330 }
1331
1332 // Create a structure into which properties common across the architectures in
1333 // this os type will be stored.
1334 osInfo.Properties = osSpecificVariantPropertiesFactory()
1335
1336 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001337 var variantsByArchId = make(map[archId][]android.Module)
1338 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001339 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001340 target := variant.Target()
1341 id := archIdFromTarget(target)
1342 if _, ok := variantsByArchId[id]; !ok {
1343 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001344 }
1345
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001346 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001347 }
1348
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001349 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001350 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001351 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 +00001352 }
1353
1354 // A common arch type only has one variant and its properties should be treated
1355 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001356 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001357 } else {
1358 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001359 for _, id := range archIds {
1360 archVariants := variantsByArchId[id]
1361 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001362
1363 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1364 }
1365 }
1366
1367 return osInfo
1368}
1369
Paul Duffin39abf8f2021-09-24 14:58:27 +01001370func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1371 if len(osInfo.archInfos) == 0 {
1372 pruner.pruneProperties(osInfo.Properties)
1373 } else {
1374 for _, archInfo := range osInfo.archInfos {
1375 archInfo.pruneUnsupportedProperties(pruner)
1376 }
1377 }
1378}
1379
Paul Duffin00e46802020-03-12 20:40:35 +00001380// Optimize the properties by extracting common properties from arch type specific
1381// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001382func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001383 // Nothing to do if there is only a single common architecture.
1384 if len(osInfo.archInfos) == 0 {
1385 return
1386 }
1387
Paul Duffin9c3760e2020-03-16 19:52:08 +00001388 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001389 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001390 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001391
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001392 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001393 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001394 }
1395
Paul Duffin4b8b7932020-05-06 12:35:38 +01001396 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001397
1398 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001399 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001400}
1401
1402// Add the properties for an os to a property set.
1403//
1404// Maps the properties related to the os variants through to an appropriate
1405// module structure that will produce equivalent set of variants when it is
1406// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001407func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001408
1409 var osPropertySet android.BpPropertySet
1410 var archPropertySet android.BpPropertySet
1411 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001412 if osInfo.Properties.Base().Os_count == 1 &&
1413 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1414 // There is only one OS type present in the variants and it shouldn't have a
1415 // variant-specific target. The latter is the case if it's either for device
1416 // where there is only one OS (android), or for host and the member type
1417 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001418
1419 // Create a structure that looks like:
1420 // module_type {
1421 // name: "...",
1422 // ...
1423 // <common properties>
1424 // ...
1425 // <single os type specific properties>
1426 //
1427 // arch: {
1428 // <arch specific sections>
1429 // }
1430 //
1431 osPropertySet = bpModule
1432 archPropertySet = osPropertySet.AddPropertySet("arch")
1433
1434 // Arch specific properties need to be added to an arch specific section
1435 // within arch.
1436 archOsPrefix = ""
1437 } else {
1438 // Create a structure that looks like:
1439 // module_type {
1440 // name: "...",
1441 // ...
1442 // <common properties>
1443 // ...
1444 // target: {
1445 // <arch independent os specific sections, e.g. android>
1446 // ...
1447 // <arch and os specific sections, e.g. android_x86>
1448 // }
1449 //
1450 osType := osInfo.osType
1451 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1452 archPropertySet = targetPropertySet
1453
1454 // Arch specific properties need to be added to an os and arch specific
1455 // section prefixed with <os>_.
1456 archOsPrefix = osType.Name + "_"
1457 }
1458
1459 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001460 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001461
1462 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1463 // os) specific properties.
1464 //
1465 // The archInfos list will be empty if the os contains variants for the common
1466 // architecture.
1467 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001468 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001469 }
1470}
1471
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001472func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1473 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001474 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001475}
1476
1477var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1478
Paul Duffin4b8b7932020-05-06 12:35:38 +01001479func (osInfo *osTypeSpecificInfo) String() string {
1480 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1481}
1482
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001483// archId encapsulates the information needed to identify a combination of arch type and native
1484// bridge support.
1485//
1486// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1487// essentially using one android.Arch to implement another. However, in terms of the handling of
1488// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1489// on android.Target.
1490//
1491// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1492type archId struct {
1493 // The arch type of the variant's target.
1494 archType android.ArchType
1495
1496 // True if the variants is for the native bridge, false otherwise.
1497 nativeBridge bool
1498}
1499
1500// propertyName returns the name of the property corresponding to use for this arch id.
1501func (i *archId) propertyName() string {
1502 name := i.archType.Name
1503 if i.nativeBridge {
1504 // Note: This does not result in a valid property because there is no architecture specific
1505 // native bridge property, only a generic "native_bridge" property. However, this will be used
1506 // in error messages if there is an attempt to use this in a generated bp file.
1507 name += "_native_bridge"
1508 }
1509 return name
1510}
1511
1512func (i *archId) String() string {
1513 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1514}
1515
1516// archIdFromTarget returns an archId initialized from information in the supplied target.
1517func archIdFromTarget(target android.Target) archId {
1518 return archId{
1519 archType: target.Arch.ArchType,
1520 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1521 }
1522}
1523
1524// commonArchId is the archId for the common architecture.
1525var commonArchId = archId{archType: android.Common}
1526
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001527type archTypeSpecificInfo struct {
1528 baseInfo
1529
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001530 archId archId
1531 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001532
Paul Duffinb42fa672021-09-09 16:37:49 +01001533 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001534}
1535
Paul Duffin4b8b7932020-05-06 12:35:38 +01001536var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1537
Paul Duffinfc8dd232020-03-17 12:51:37 +00001538// Create a new archTypeSpecificInfo for the specified arch type and its properties
1539// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001540func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001541
Paul Duffinfc8dd232020-03-17 12:51:37 +00001542 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001543 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001544
1545 // Create the properties into which the arch type specific properties will be
1546 // added.
1547 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001548
Liz Kammer96320df2022-05-12 20:40:00 -04001549 // if there are multiple supported link variants, we want to nest based on linkage even if there
1550 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1551 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001552 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001553 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001554 // Group the variants by image type.
1555 variantsByImage := make(map[string][]android.Module)
1556 for _, variant := range archVariants {
1557 image := variant.ImageVariation().Variation
1558 variantsByImage[image] = append(variantsByImage[image], variant)
1559 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001560
Paul Duffinb42fa672021-09-09 16:37:49 +01001561 // Create the image variant info in a fixed order.
1562 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1563 variants := variantsByImage[imageVariantName]
1564 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001565 }
1566 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001567
1568 return archInfo
1569}
1570
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001571// Get the link type of the variant
1572//
1573// If the variant is not differentiated by link type then it returns "",
1574// otherwise it returns one of "static" or "shared".
1575func getLinkType(variant android.Module) string {
1576 linkType := ""
1577 if linkable, ok := variant.(cc.LinkableInterface); ok {
1578 if linkable.Shared() && linkable.Static() {
1579 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1580 } else if linkable.Shared() {
1581 linkType = "shared"
1582 } else if linkable.Static() {
1583 linkType = "static"
1584 } else {
1585 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1586 }
1587 }
1588 return linkType
1589}
1590
Paul Duffin39abf8f2021-09-24 14:58:27 +01001591func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1592 if len(archInfo.imageVariantInfos) == 0 {
1593 pruner.pruneProperties(archInfo.Properties)
1594 } else {
1595 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1596 imageVariantInfo.pruneUnsupportedProperties(pruner)
1597 }
1598 }
1599}
1600
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001601// Optimize the properties by extracting common properties from link type specific
1602// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001603func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001604 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001605 return
1606 }
1607
Paul Duffinb42fa672021-09-09 16:37:49 +01001608 // Optimize the image variant properties first.
1609 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1610 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1611 }
1612
1613 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001614}
1615
Paul Duffinfc8dd232020-03-17 12:51:37 +00001616// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001617func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001618 archPropertySuffix := archInfo.archId.propertyName()
1619 propertySetName := archOsPrefix + archPropertySuffix
1620 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001621 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1622 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1623 archTypePropertySet.AddProperty("enabled", true)
1624 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001625 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001626
Paul Duffinb42fa672021-09-09 16:37:49 +01001627 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1628 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001629 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001630
1631 // If this is for a native bridge architecture then make sure that the property set does not
1632 // contain any properties as providing native bridge specific properties is not currently
1633 // supported.
1634 if archInfo.archId.nativeBridge {
1635 propertySetContents := getPropertySetContents(archTypePropertySet)
1636 if propertySetContents != "" {
1637 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",
1638 propertySetName, ctx.name, propertySetContents)
1639 }
1640 }
1641}
1642
1643// getPropertySetContents returns the string representation of the contents of a property set, after
1644// recursively pruning any empty nested property sets.
1645func getPropertySetContents(propertySet android.BpPropertySet) string {
1646 set := propertySet.(*bpPropertySet)
1647 set.transformContents(pruneEmptySetTransformer{})
1648 if len(set.properties) != 0 {
1649 contents := &generatedContents{}
1650 contents.Indent()
1651 outputPropertySet(contents, set)
1652 setAsString := contents.content.String()
1653 return setAsString
1654 }
1655 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001656}
1657
Paul Duffin4b8b7932020-05-06 12:35:38 +01001658func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001659 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001660}
1661
Paul Duffinb42fa672021-09-09 16:37:49 +01001662type imageVariantSpecificInfo struct {
1663 baseInfo
1664
1665 imageVariant string
1666
1667 linkInfos []*linkTypeSpecificInfo
1668}
1669
1670func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1671
1672 // Create an image variant specific info into which the variant properties can be copied.
1673 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1674
1675 // Create the properties into which the image variant specific properties will be added.
1676 imageInfo.Properties = variantPropertiesFactory()
1677
Liz Kammer96320df2022-05-12 20:40:00 -04001678 // if there are multiple supported link variants, we want to nest even if there is only one
1679 // variant, otherwise, if there is only one variant we can populate based on the image
1680 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001681 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1682 } else {
1683 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001684 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001685 for _, linkVariant := range imageVariants {
1686 linkType := getLinkType(linkVariant)
1687 if linkType == "" {
1688 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1689 } else {
1690 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1691
1692 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1693 }
1694 }
1695 }
1696
1697 return imageInfo
1698}
1699
Paul Duffin39abf8f2021-09-24 14:58:27 +01001700func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1701 if len(imageInfo.linkInfos) == 0 {
1702 pruner.pruneProperties(imageInfo.Properties)
1703 } else {
1704 for _, linkInfo := range imageInfo.linkInfos {
1705 linkInfo.pruneUnsupportedProperties(pruner)
1706 }
1707 }
1708}
1709
Paul Duffinb42fa672021-09-09 16:37:49 +01001710// Optimize the properties by extracting common properties from link type specific
1711// properties into arch type specific properties.
1712func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1713 if len(imageInfo.linkInfos) == 0 {
1714 return
1715 }
1716
1717 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1718}
1719
1720// Add the properties for an arch type to a property set.
1721func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1722 if imageInfo.imageVariant != android.CoreVariation {
1723 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1724 }
1725
1726 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1727
Liz Kammer96320df2022-05-12 20:40:00 -04001728 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001729 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001730 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001731 linkInfo.addToPropertySet(ctx, propertySet)
1732 }
1733
Liz Kammer96320df2022-05-12 20:40:00 -04001734 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1735 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1736 for _, l := range ctx.MemberType().SupportedLinkages() {
1737 if _, ok := usedLinkages[l]; !ok {
1738 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1739 otherLinkagePropertySet.AddProperty("enabled", false)
1740 }
1741 }
1742 }
1743
Paul Duffinb42fa672021-09-09 16:37:49 +01001744 // If this is for a non-core image variant then make sure that the property set does not contain
1745 // any properties as providing non-core image variant specific properties for prebuilts is not
1746 // currently supported.
1747 if imageInfo.imageVariant != android.CoreVariation {
1748 propertySetContents := getPropertySetContents(propertySet)
1749 if propertySetContents != "" {
1750 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",
1751 imageInfo.imageVariant, ctx.name, propertySetContents)
1752 }
1753 }
1754}
1755
1756func (imageInfo *imageVariantSpecificInfo) String() string {
1757 return imageInfo.imageVariant
1758}
1759
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001760type linkTypeSpecificInfo struct {
1761 baseInfo
1762
1763 linkType string
1764}
1765
Paul Duffin4b8b7932020-05-06 12:35:38 +01001766var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1767
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001768// Create a new linkTypeSpecificInfo for the specified link type and its properties
1769// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001770func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001771 linkInfo := &linkTypeSpecificInfo{
1772 baseInfo: baseInfo{
1773 // Create the properties into which the link type specific properties will be
1774 // added.
1775 Properties: variantPropertiesFactory(),
1776 },
1777 linkType: linkType,
1778 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001779 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001780 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001781}
1782
Paul Duffinf68f85a2021-09-09 16:11:42 +01001783func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1784 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1785 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1786}
1787
Paul Duffin39abf8f2021-09-24 14:58:27 +01001788func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1789 pruner.pruneProperties(l.Properties)
1790}
1791
Paul Duffin4b8b7932020-05-06 12:35:38 +01001792func (l *linkTypeSpecificInfo) String() string {
1793 return fmt.Sprintf("LinkType{%s}", l.linkType)
1794}
1795
Paul Duffin3a4eb502020-03-19 16:11:18 +00001796type memberContext struct {
1797 sdkMemberContext android.ModuleContext
1798 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001799 memberType android.SdkMemberType
1800 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001801
1802 // The set of traits required of this member.
1803 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001804}
1805
1806func (m *memberContext) SdkModuleContext() android.ModuleContext {
1807 return m.sdkMemberContext
1808}
1809
1810func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1811 return m.builder
1812}
1813
Paul Duffina551a1c2020-03-17 21:04:24 +00001814func (m *memberContext) MemberType() android.SdkMemberType {
1815 return m.memberType
1816}
1817
1818func (m *memberContext) Name() string {
1819 return m.name
1820}
1821
Paul Duffind19f8942021-07-14 12:08:37 +01001822func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1823 return m.requiredTraits.Contains(trait)
1824}
1825
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001826func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001827
1828 memberType := member.memberType
1829
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001830 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01001831 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001832 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001833 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1834 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001835 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1836 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001837 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001838
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001839 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1840 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1841 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1842 // behavior is for the module.
1843 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001844
1845 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1846 if configVar != "" {
1847 parts := strings.Split(configVar, ":")
1848 cfp := android.ConfigVarProperties{
1849 Config_namespace: proptools.StringPtr(parts[0]),
1850 Var_name: proptools.StringPtr(parts[1]),
1851 }
1852 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1853 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001854 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001855
Paul Duffina04c1072020-03-02 10:16:35 +00001856 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001857 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001858 variants := member.Variants()
1859 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001860 osType := variant.Target().Os
1861 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001862 }
1863
Paul Duffina04c1072020-03-02 10:16:35 +00001864 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001865 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001866 properties := memberType.CreateVariantPropertiesStruct()
1867 base := properties.Base()
1868 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001869 return properties
1870 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001871
Paul Duffina04c1072020-03-02 10:16:35 +00001872 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001873
Paul Duffina04c1072020-03-02 10:16:35 +00001874 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001875 commonProperties := variantPropertiesFactory()
1876 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001877
Paul Duffin39abf8f2021-09-24 14:58:27 +01001878 // Create a property pruner that will prune any properties unsupported by the target build
1879 // release.
1880 targetBuildRelease := ctx.builder.targetBuildRelease
1881 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1882
Paul Duffinc097e362020-03-10 22:50:03 +00001883 // Create common value extractor that can be used to optimize the properties.
1884 commonValueExtractor := newCommonValueExtractor(commonProperties)
1885
Paul Duffina04c1072020-03-02 10:16:35 +00001886 // The list of property structures which are os type specific but common across
1887 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001888 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001889
1890 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001891 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001892 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001893 // Add the os specific properties to a list of os type specific yet architecture
1894 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001895 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001896
Paul Duffin39abf8f2021-09-24 14:58:27 +01001897 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
1898
Paul Duffin00e46802020-03-12 20:40:35 +00001899 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001900 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001901 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001902
Paul Duffina04c1072020-03-02 10:16:35 +00001903 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001904 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001905
Paul Duffina04c1072020-03-02 10:16:35 +00001906 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001907 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001908
Paul Duffina04c1072020-03-02 10:16:35 +00001909 // Create a target property set into which target specific properties can be
1910 // added.
1911 targetPropertySet := bpModule.AddPropertySet("target")
1912
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001913 // If the member is host OS dependent and has host_supported then disable by
1914 // default and enable each host OS variant explicitly. This avoids problems
1915 // with implicitly enabled OS variants when the snapshot is used, which might
1916 // be different from this run (e.g. different build OS).
1917 if ctx.memberType.IsHostOsDependent() {
1918 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1919 if hostSupported {
1920 hostPropertySet := targetPropertySet.AddPropertySet("host")
1921 hostPropertySet.AddProperty("enabled", false)
1922 }
1923 }
1924
Paul Duffina04c1072020-03-02 10:16:35 +00001925 // Iterate over the os types in a fixed order.
1926 for _, osType := range s.getPossibleOsTypes() {
1927 osInfo := osTypeToInfo[osType]
1928 if osInfo == nil {
1929 continue
1930 }
1931
Paul Duffin3a4eb502020-03-19 16:11:18 +00001932 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001933 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001934}
1935
Paul Duffina04c1072020-03-02 10:16:35 +00001936// Compute the list of possible os types that this sdk could support.
1937func (s *sdk) getPossibleOsTypes() []android.OsType {
1938 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001939 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001940 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07001941 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00001942 osTypes = append(osTypes, osType)
1943 }
1944 }
1945 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001946 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001947 osTypes = append(osTypes, osType)
1948 }
1949 }
1950 }
1951 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1952 return osTypes
1953}
1954
Paul Duffinb28369a2020-05-04 15:39:59 +01001955// Given a set of properties (struct value), return the value of the field within that
1956// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001957type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1958
Paul Duffinc459f892020-04-30 18:08:29 +01001959// Checks the metadata to determine whether the property should be ignored for the
1960// purposes of common value extraction or not.
1961type extractorMetadataPredicate func(metadata propertiesContainer) bool
1962
1963// Indicates whether optimizable properties are provided by a host variant or
1964// not.
1965type isHostVariant interface {
1966 isHostVariant() bool
1967}
1968
Paul Duffinb28369a2020-05-04 15:39:59 +01001969// A property that can be optimized by the commonValueExtractor.
1970type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001971 // The name of the field for this property. It is a "."-separated path for
1972 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001973 name string
1974
Paul Duffinc459f892020-04-30 18:08:29 +01001975 // Filter that can use metadata associated with the properties being optimized
1976 // to determine whether the field should be ignored during common value
1977 // optimization.
1978 filter extractorMetadataPredicate
1979
Paul Duffinb28369a2020-05-04 15:39:59 +01001980 // Retrieves the value on which common value optimization will be performed.
1981 getter fieldAccessorFunc
1982
1983 // The empty value for the field.
1984 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001985
1986 // True if the property can support arch variants false otherwise.
1987 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001988}
1989
Paul Duffin4b8b7932020-05-06 12:35:38 +01001990func (p extractorProperty) String() string {
1991 return p.name
1992}
1993
Paul Duffinc097e362020-03-10 22:50:03 +00001994// Supports extracting common values from a number of instances of a properties
1995// structure into a separate common set of properties.
1996type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001997 // The properties that the extractor can optimize.
1998 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001999}
2000
2001// Create a new common value extractor for the structure type for the supplied
2002// properties struct.
2003//
2004// The returned extractor can be used on any properties structure of the same type
2005// as the supplied set of properties.
2006func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2007 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2008 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002009 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002010 return extractor
2011}
2012
2013// Gather the fields from the supplied structure type from which common values will
2014// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002015//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002016// This is recursive function. If it encounters a struct then it will recurse
2017// into it, passing in the accessor for the field and the struct name as prefix
2018// for the nested fields. That will then be used in the accessors for the fields
2019// in the embedded struct.
2020func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002021 for f := 0; f < structType.NumField(); f++ {
2022 field := structType.Field(f)
2023 if field.PkgPath != "" {
2024 // Ignore unexported fields.
2025 continue
2026 }
2027
Paul Duffinb07fa512020-03-10 22:17:04 +00002028 // Ignore fields whose value should be kept.
2029 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002030 continue
2031 }
2032
Paul Duffinc459f892020-04-30 18:08:29 +01002033 var filter extractorMetadataPredicate
2034
2035 // Add a filter
2036 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2037 filter = func(metadata propertiesContainer) bool {
2038 if m, ok := metadata.(isHostVariant); ok {
2039 if m.isHostVariant() {
2040 return false
2041 }
2042 }
2043 return true
2044 }
2045 }
2046
Paul Duffinc097e362020-03-10 22:50:03 +00002047 // Save a copy of the field index for use in the function.
2048 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002049
Martin Stjernholmb0249572020-09-15 02:32:35 +01002050 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002051
Paul Duffinc097e362020-03-10 22:50:03 +00002052 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002053 if containingStructAccessor != nil {
2054 // This is an embedded structure so first access the field for the embedded
2055 // structure.
2056 value = containingStructAccessor(value)
2057 }
2058
Paul Duffinc097e362020-03-10 22:50:03 +00002059 // Skip through interface and pointer values to find the structure.
2060 value = getStructValue(value)
2061
Paul Duffin4b8b7932020-05-06 12:35:38 +01002062 defer func() {
2063 if r := recover(); r != nil {
2064 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2065 }
2066 }()
2067
Paul Duffinc097e362020-03-10 22:50:03 +00002068 // Return the field.
2069 return value.Field(fieldIndex)
2070 }
2071
Martin Stjernholmb0249572020-09-15 02:32:35 +01002072 if field.Type.Kind() == reflect.Struct {
2073 // Gather fields from the nested or embedded structure.
2074 var subNamePrefix string
2075 if field.Anonymous {
2076 subNamePrefix = namePrefix
2077 } else {
2078 subNamePrefix = name + "."
2079 }
2080 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002081 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002082 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002083 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002084 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002085 fieldGetter,
2086 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002087 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002088 }
2089 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002090 }
Paul Duffinc097e362020-03-10 22:50:03 +00002091 }
2092}
2093
2094func getStructValue(value reflect.Value) reflect.Value {
2095foundStruct:
2096 for {
2097 kind := value.Kind()
2098 switch kind {
2099 case reflect.Interface, reflect.Ptr:
2100 value = value.Elem()
2101 case reflect.Struct:
2102 break foundStruct
2103 default:
2104 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2105 }
2106 }
2107 return value
2108}
2109
Paul Duffinf34f6d82020-04-30 15:48:31 +01002110// A container of properties to be optimized.
2111//
2112// Allows additional information to be associated with the properties, e.g. for
2113// filtering.
2114type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002115 fmt.Stringer
2116
Paul Duffinf34f6d82020-04-30 15:48:31 +01002117 // Get the properties that need optimizing.
2118 optimizableProperties() interface{}
2119}
2120
Paul Duffin2d1bb892021-04-24 11:32:59 +01002121// A wrapper for sdk variant related properties to allow them to be optimized.
2122type sdkVariantPropertiesContainer struct {
2123 sdkVariant *sdk
2124 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002125}
2126
Paul Duffin2d1bb892021-04-24 11:32:59 +01002127func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2128 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002129}
2130
Paul Duffin2d1bb892021-04-24 11:32:59 +01002131func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002132 return c.sdkVariant.String()
2133}
2134
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002135// Extract common properties from a slice of property structures of the same type.
2136//
2137// All the property structures must be of the same type.
2138// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002139// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002140//
2141// Iterates over each exported field (capitalized name) and checks to see whether they
2142// have the same value (using DeepEquals) across all the input properties. If it does not then no
2143// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002144// and the field in each of the input properties structure is set to its default value. Nested
2145// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002146func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002147 commonPropertiesValue := reflect.ValueOf(commonProperties)
2148 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002149
Paul Duffinf34f6d82020-04-30 15:48:31 +01002150 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2151
Paul Duffinb28369a2020-05-04 15:39:59 +01002152 for _, property := range e.properties {
2153 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002154 filter := property.filter
2155 if filter == nil {
2156 filter = func(metadata propertiesContainer) bool {
2157 return true
2158 }
2159 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002160
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002161 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002162 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2163 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002164 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002165
Paul Duffin864e1b42020-05-06 10:23:19 +01002166 // Assume that all the values will be the same.
2167 //
2168 // While similar to this is not quite the same as commonValue == nil. If all the values
2169 // have been filtered out then this will be false but commonValue == nil will be true.
2170 valuesDiffer := false
2171
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002172 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002173 container := sliceValue.Index(i).Interface().(propertiesContainer)
2174 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002175 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002176
Paul Duffinc459f892020-04-30 18:08:29 +01002177 if !filter(container) {
2178 expectedValue := property.emptyValue.Interface()
2179 actualValue := fieldValue.Interface()
2180 if !reflect.DeepEqual(expectedValue, actualValue) {
2181 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2182 }
2183 continue
2184 }
2185
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002186 if commonValue == nil {
2187 // Use the first value as the commonProperties value.
2188 commonValue = &fieldValue
2189 } else {
2190 // If the value does not match the current common value then there is
2191 // no value in common so break out.
2192 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2193 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002194 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002195 break
2196 }
2197 }
2198 }
2199
Paul Duffin864e1b42020-05-06 10:23:19 +01002200 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002201 // and set the input struct's field to the empty value.
2202 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002203 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002204 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002205 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002206 container := sliceValue.Index(i).Interface().(propertiesContainer)
2207 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002208 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002209 fieldValue.Set(emptyValue)
2210 }
2211 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002212
2213 if valuesDiffer && !property.archVariant {
2214 // The values differ but the property does not support arch variants so it
2215 // is an error.
2216 var details strings.Builder
2217 for i := 0; i < sliceValue.Len(); i++ {
2218 container := sliceValue.Index(i).Interface().(propertiesContainer)
2219 itemValue := reflect.ValueOf(container.optimizableProperties())
2220 fieldValue := fieldGetter(itemValue)
2221
2222 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2223 }
2224
2225 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2226 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002227 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002228
2229 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002230}