blob: 3246832d4e26e8ecdc5abf5193765600241c2166 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000036// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010038//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010039// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
40// If set this specifies the Soong config var that can be used to control whether the prebuilt
41// modules from the generated snapshot or the original source modules. Values must be a colon
42// separated pair of strings, the first of which is the Soong config namespace, and the second
43// is the name of the variable within that namespace.
44//
45// The config namespace and var name are used to set the `use_source_config_var` property. That
46// in turn will cause the generated prebuilts to use the soong config variable to select whether
47// source or the prebuilt is used.
48// e.g. If an sdk snapshot is built using:
49// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
50// Then the resulting snapshot will include:
51// use_source_config_var: {
52// config_namespace: "acme",
53// var_name: "build_from_source",
54// }
55//
56// Assuming that the config variable is defined in .mk using something like:
57// $(call add_soong_config_namespace,acme)
58// $(call add_soong_config_var_value,acme,build_from_source,true)
59//
60// Then when the snapshot is unpacked in the repository it will have the following behavior:
61// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
62// sources.
63// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
64// sources, if present. Otherwise, it will use the prebuilts.
65//
66// This is a temporary mechanism to control the prefer flags and will be removed once a more
67// maintainable solution has been implemented.
68// TODO(b/174997203): Remove when no longer necessary.
69//
Paul Duffin43f7bf02021-05-05 22:00:51 +010070// SOONG_SDK_SNAPSHOT_VERSION
71// This provides control over the version of the generated snapshot.
72//
73// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
74// versioned snapshot module. This is the default behavior. The zip file containing the
75// generated snapshot will be <sdk-name>-current.zip.
76//
77// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
78// file containing the generated snapshot will be <sdk-name>.zip.
79//
80// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
81// snapshot module only. The zip file containing the generated snapshot will be
82// <sdk-name>-<number>.zip.
83//
Paul Duffin64fb5262021-05-05 21:36:04 +010084
Jiyong Park9b409bc2019-10-11 14:59:13 +090085var pctx = android.NewPackageContext("android/soong/sdk")
86
Paul Duffin375058f2019-11-29 20:17:53 +000087var (
88 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
89 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000090 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000091 CommandDeps: []string{
92 "${config.Zip2ZipCmd}",
93 },
94 },
95 "destdir")
96
97 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
98 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070099 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000100 CommandDeps: []string{
101 "${config.SoongZipCmd}",
102 },
103 Rspfile: "$out.rsp",
104 RspfileContent: "$in",
105 },
106 "basedir")
107
108 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
109 blueprint.RuleParams{
110 Command: `${config.MergeZipsCmd} $out $in`,
111 CommandDeps: []string{
112 "${config.MergeZipsCmd}",
113 },
114 })
115)
116
Paul Duffin43f7bf02021-05-05 22:00:51 +0100117const (
118 soongSdkSnapshotVersionUnversioned = "unversioned"
119 soongSdkSnapshotVersionCurrent = "current"
120)
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{}) {
151 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
152}
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{}) {
157 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 Duffina7208112021-04-23 21:20:20 +0100209 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100210 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
211 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
212 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000213
Paul Duffin2d3da312021-05-06 12:02:27 +0100214 // Recurse down into the member's dependencies as it may have dependencies that need to be
215 // automatically added to the sdk.
216 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900217 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000218
219 return false
Paul Duffin13879572019-11-28 14:31:38 +0000220 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000221}
222
Paul Duffincc3132e2021-04-24 01:10:30 +0100223// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
224// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000225//
Paul Duffincc3132e2021-04-24 01:10:30 +0100226// The sdkMember instances are then grouped into slices by member type. Within each such slice the
227// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000228//
Paul Duffincc3132e2021-04-24 01:10:30 +0100229// Finally, the member type slices are concatenated together to form a single slice. The order in
230// which they are concatenated is the order in which the member types were registered in the
231// android.SdkMemberTypesRegistry.
232func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000233 byType := make(map[android.SdkMemberType][]*sdkMember)
234 byName := make(map[string]*sdkMember)
235
Paul Duffin21827262021-04-24 12:16:36 +0100236 for _, memberVariantDep := range memberVariantDeps {
237 memberType := memberVariantDep.memberType
238 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000239
240 name := ctx.OtherModuleName(variant)
241 member := byName[name]
242 if member == nil {
243 member = &sdkMember{memberType: memberType, name: name}
244 byName[name] = member
245 byType[memberType] = append(byType[memberType], member)
246 }
247
Paul Duffin1356d8c2020-02-25 19:26:33 +0000248 // Only append new variants to the list. This is needed because a member can be both
249 // exported by the sdk and also be a transitive sdk member.
250 member.variants = appendUniqueVariants(member.variants, variant)
251 }
252
Paul Duffin13879572019-11-28 14:31:38 +0000253 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100254 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000255 membersOfType := byType[memberListProperty.memberType]
256 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900257 }
258
Paul Duffin6a7e9532020-03-20 17:50:07 +0000259 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900260}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900261
Paul Duffin72910952020-01-20 18:16:30 +0000262func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
263 for _, v := range variants {
264 if v == newVariant {
265 return variants
266 }
267 }
268 return append(variants, newVariant)
269}
270
Jiyong Park73c54ee2019-10-22 20:31:18 +0900271// SDK directory structure
272// <sdk_root>/
273// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
274// <api_ver>/ : below this directory are all auto-generated
275// Android.bp : definition of 'sdk_snapshot' module is here
276// aidl/
277// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
278// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900279// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900280// include/
281// bionic/libc/include/stdlib.h : an exported header file
282// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900283// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900284// <arch>/include/ : arch-specific exported headers
285// <arch>/include_gen/ : arch-specific generated headers
286// <arch>/lib/
287// libFoo.so : a stub library
288
Jiyong Park232e7852019-11-04 12:23:40 +0900289// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900290// This isn't visible to users, so could be changed in future.
291func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
292 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
293}
294
Jiyong Park232e7852019-11-04 12:23:40 +0900295// buildSnapshot is the main function in this source file. It creates rules to copy
296// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000297func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
298
Paul Duffinb97b1572021-04-29 21:50:40 +0100299 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100300 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100301 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000302 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100303 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100304 }
Paul Duffin865171e2020-03-02 18:38:15 +0000305
Paul Duffinb97b1572021-04-29 21:50:40 +0100306 // Filter out any sdkMemberVariantDep that is a component of another.
307 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000308
Paul Duffinb97b1572021-04-29 21:50:40 +0100309 // Record the names of all the members, both explicitly specified and implicitly
310 // included.
311 allMembersByName := make(map[string]struct{})
312 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100313
Paul Duffinb97b1572021-04-29 21:50:40 +0100314 addMember := func(name string, export bool) {
315 allMembersByName[name] = struct{}{}
316 if export {
317 exportedMembersByName[name] = struct{}{}
318 }
319 }
320
321 for _, memberVariantDep := range memberVariantDeps {
322 name := memberVariantDep.variant.Name()
323 export := memberVariantDep.export
324
325 addMember(name, export)
326
327 // Add any components provided by the module.
328 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
329 addMember(component, export)
330 }
331
332 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
333 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000334 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000335 }
336
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000337 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900338
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000339 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000340
341 bpFile := &bpFile{
342 modules: make(map[string]*bpModule),
343 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000344
Paul Duffin43f7bf02021-05-05 22:00:51 +0100345 config := ctx.Config()
346 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
347
348 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
349 generateVersioned := version != soongSdkSnapshotVersionUnversioned
350
351 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
352 //
353 // Unversioned modules are not required in that case because the numbered version will be a
354 // finalized version of the snapshot that is intended to be kept separate from the
355 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
356 snapshotZipFileSuffix := ""
357 if generateVersioned {
358 snapshotZipFileSuffix = "-" + version
359 }
360
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000361 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000362 ctx: ctx,
363 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100364 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000365 snapshotDir: snapshotDir.OutputPath,
366 copies: make(map[string]string),
367 filesToZip: []android.Path{bp.path},
368 bpFile: bpFile,
369 prebuiltModules: make(map[string]*bpModule),
370 allMembersByName: allMembersByName,
371 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900372 }
Paul Duffinac37c502019-11-26 18:02:20 +0000373 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900374
Paul Duffin62131702021-05-07 01:10:01 +0100375 // If the sdk snapshot includes any license modules then add a package module which has a
376 // default_applicable_licenses property. That will prevent the LSC license process from updating
377 // the generated Android.bp file to add a package module that includes all licenses used by all
378 // the modules in that package. That would be unnecessary as every module in the sdk should have
379 // their own licenses property specified.
380 if hasLicenses {
381 pkg := bpFile.newModule("package")
382 property := "default_applicable_licenses"
383 pkg.AddCommentForProperty(property, `
384A default list here prevents the license LSC from adding its own list which would
385be unnecessary as every module in the sdk already has its own licenses property.
386`)
387 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
388 bpFile.AddModule(pkg)
389 }
390
Paul Duffin0df49682021-05-07 01:10:01 +0100391 // Group the variants for each member module together and then group the members of each member
392 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100393 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100394
395 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100396 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000397 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000398 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000399
Paul Duffind19f8942021-07-14 12:08:37 +0100400 name := member.name
401 requiredTraits := traits[name]
402 if requiredTraits == nil {
403 requiredTraits = android.EmptySdkMemberTraitSet()
404 }
405
406 // Create the snapshot for the member.
407 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000408
409 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100410 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900411 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900412
Paul Duffine6c0d842020-01-15 14:08:51 +0000413 // Create a transformer that will transform an unversioned module into a versioned module.
414 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
415
Paul Duffin72910952020-01-20 18:16:30 +0000416 // Create a transformer that will transform an unversioned module by replacing any references
417 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100418 unversionedTransformer := unversionedTransformation{
419 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100420 }
Paul Duffin72910952020-01-20 18:16:30 +0000421
Paul Duffinb645ec82019-11-27 17:43:54 +0000422 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000423 // Prune any empty property sets.
424 unversioned = unversioned.transform(pruneEmptySetTransformer{})
425
Paul Duffin43f7bf02021-05-05 22:00:51 +0100426 if generateVersioned {
427 // Copy the unversioned module so it can be modified to make it versioned.
428 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000429
Paul Duffin43f7bf02021-05-05 22:00:51 +0100430 // Transform the unversioned module into a versioned one.
431 versioned.transform(unversionedToVersionedTransformer)
432 bpFile.AddModule(versioned)
433 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000434
Paul Duffin43f7bf02021-05-05 22:00:51 +0100435 if generateUnversioned {
436 // Transform the unversioned module to make it suitable for use in the snapshot.
437 unversioned.transform(unversionedTransformer)
438 bpFile.AddModule(unversioned)
439 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000440 }
441
Paul Duffin43f7bf02021-05-05 22:00:51 +0100442 if generateVersioned {
443 // Add the sdk/module_exports_snapshot module to the bp file.
444 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
445 }
Paul Duffin26197a62021-04-24 00:34:10 +0100446
447 // generate Android.bp
448 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
449 generateBpContents(&bp.generatedContents, bpFile)
450
451 contents := bp.content.String()
452 syntaxCheckSnapshotBpFile(ctx, contents)
453
454 bp.build(pctx, ctx, nil)
455
456 filesToZip := builder.filesToZip
457
458 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100459 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
460 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100461 outputDesc := "Building snapshot for " + ctx.ModuleName()
462
463 // If there are no zips to merge then generate the output zip directly.
464 // Otherwise, generate an intermediate zip file into which other zips can be
465 // merged.
466 var zipFile android.OutputPath
467 var desc string
468 if len(builder.zipsToMerge) == 0 {
469 zipFile = outputZipFile
470 desc = outputDesc
471 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100472 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
473 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100474 desc = "Building intermediate snapshot for " + ctx.ModuleName()
475 }
476
477 ctx.Build(pctx, android.BuildParams{
478 Description: desc,
479 Rule: zipFiles,
480 Inputs: filesToZip,
481 Output: zipFile,
482 Args: map[string]string{
483 "basedir": builder.snapshotDir.String(),
484 },
485 })
486
487 if len(builder.zipsToMerge) != 0 {
488 ctx.Build(pctx, android.BuildParams{
489 Description: outputDesc,
490 Rule: mergeZips,
491 Input: zipFile,
492 Inputs: builder.zipsToMerge,
493 Output: outputZipFile,
494 })
495 }
496
497 return outputZipFile
498}
499
Paul Duffinb97b1572021-04-29 21:50:40 +0100500// filterOutComponents removes any item from the deps list that is a component of another item in
501// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
502// then it will remove "foo.stubs" from the deps.
503func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
504 // Collate the set of components that all the modules added to the sdk provide.
505 components := map[string]*sdkMemberVariantDep{}
506 for i, _ := range deps {
507 dep := &deps[i]
508 for _, c := range dep.exportedComponentsInfo.Components {
509 components[c] = dep
510 }
511 }
512
513 // If no module provides components then return the input deps unfiltered.
514 if len(components) == 0 {
515 return deps
516 }
517
518 filtered := make([]sdkMemberVariantDep, 0, len(deps))
519 for _, dep := range deps {
520 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
521 if owner, ok := components[name]; ok {
522 // This is a component of another module that is a member of the sdk.
523
524 // If the component is exported but the owning module is not then the configuration is not
525 // supported.
526 if dep.export && !owner.export {
527 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
528 continue
529 }
530
531 // This module must not be added to the list of members of the sdk as that would result in a
532 // duplicate module in the sdk snapshot.
533 continue
534 }
535
536 filtered = append(filtered, dep)
537 }
538 return filtered
539}
540
Paul Duffin26197a62021-04-24 00:34:10 +0100541// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100542func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100543 bpFile := builder.bpFile
544
Paul Duffinb645ec82019-11-27 17:43:54 +0000545 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000546 var snapshotModuleType string
547 if s.properties.Module_exports {
548 snapshotModuleType = "module_exports_snapshot"
549 } else {
550 snapshotModuleType = "sdk_snapshot"
551 }
552 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000553 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000554
555 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100556 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000557 if len(visibility) != 0 {
558 snapshotModule.AddProperty("visibility", visibility)
559 }
560
Paul Duffin865171e2020-03-02 18:38:15 +0000561 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000562
Paul Duffincd064672021-04-24 00:47:29 +0100563 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100564 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000565
Paul Duffin2d1bb892021-04-24 11:32:59 +0100566 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100567
Paul Duffin6a7e9532020-03-20 17:50:07 +0000568 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100569
Paul Duffin2d1bb892021-04-24 11:32:59 +0100570 // Create a mapping from osType to combined properties.
571 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
572 for _, combined := range combinedPropertiesList {
573 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
574 }
575
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100576 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000577 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100578 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100579 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000580
Paul Duffin2d1bb892021-04-24 11:32:59 +0100581 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000582 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000583 }
Paul Duffin865171e2020-03-02 18:38:15 +0000584
Jiyong Park8fe14e62020-10-19 22:47:34 +0900585 // If host is supported and any member is host OS dependent then disable host
586 // by default, so that we can enable each host OS variant explicitly. This
587 // avoids problems with implicitly enabled OS variants when the snapshot is
588 // used, which might be different from this run (e.g. different build OS).
589 if s.HostSupported() {
590 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100591 for _, memberVariantDep := range memberVariantDeps {
592 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
593 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900594 if !android.InList(targetString, supportedHostTargets) {
595 supportedHostTargets = append(supportedHostTargets, targetString)
596 }
597 }
598 }
599 if len(supportedHostTargets) > 0 {
600 hostPropertySet := targetPropertySet.AddPropertySet("host")
601 hostPropertySet.AddProperty("enabled", false)
602 }
603 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
604 for _, hostTarget := range supportedHostTargets {
605 propertySet := targetPropertySet.AddPropertySet(hostTarget)
606 propertySet.AddProperty("enabled", true)
607 }
608 }
609
Paul Duffin865171e2020-03-02 18:38:15 +0000610 // Prune any empty property sets.
611 snapshotModule.transform(pruneEmptySetTransformer{})
612
Paul Duffinb645ec82019-11-27 17:43:54 +0000613 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900614}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000615
Paul Duffinf88d8e02020-05-07 20:21:34 +0100616// Check the syntax of the generated Android.bp file contents and if they are
617// invalid then log an error with the contents (tagged with line numbers) and the
618// errors that were found so that it is easy to see where the problem lies.
619func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
620 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
621 if len(errs) != 0 {
622 message := &strings.Builder{}
623 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
624
625Generated Android.bp contents
626========================================================================
627`)
628 for i, line := range strings.Split(contents, "\n") {
629 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
630 }
631
632 _, _ = fmt.Fprint(message, `
633========================================================================
634
635Errors found:
636`)
637
638 for _, err := range errs {
639 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
640 }
641
642 ctx.ModuleErrorf("%s", message.String())
643 }
644}
645
Paul Duffin4b8b7932020-05-06 12:35:38 +0100646func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
647 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
648 if err != nil {
649 ctx.ModuleErrorf("error extracting common properties: %s", err)
650 }
651}
652
Paul Duffinfbe470e2021-04-24 12:37:13 +0100653// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
654type snapshotModuleStaticProperties struct {
655 Compile_multilib string `android:"arch_variant"`
656}
657
Paul Duffin2d1bb892021-04-24 11:32:59 +0100658// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
659type combinedSnapshotModuleProperties struct {
660 // The sdk variant from which this information was collected.
661 sdkVariant *sdk
662
663 // Static snapshot module properties.
664 staticProperties *snapshotModuleStaticProperties
665
666 // The dynamically generated member list properties.
667 dynamicProperties interface{}
668}
669
670// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100671func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
672 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100673 var list []*combinedSnapshotModuleProperties
674 for _, sdkVariant := range sdkVariants {
675 staticProperties := &snapshotModuleStaticProperties{
676 Compile_multilib: sdkVariant.multilibUsages.String(),
677 }
Paul Duffin62782de2021-07-14 12:05:16 +0100678 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100679
Paul Duffincd064672021-04-24 00:47:29 +0100680 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100681 sdkVariant: sdkVariant,
682 staticProperties: staticProperties,
683 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100684 }
685 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
686
687 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100688 }
Paul Duffincd064672021-04-24 00:47:29 +0100689
690 for _, memberVariantDep := range memberVariantDeps {
691 // If the member dependency is internal then do not add the dependency to the snapshot member
692 // list properties.
693 if !memberVariantDep.export {
694 continue
695 }
696
697 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100698 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100699 memberName := ctx.OtherModuleName(memberVariantDep.variant)
700
Paul Duffin13082052021-05-11 00:31:38 +0100701 if memberListProperty.getter == nil {
702 continue
703 }
704
Paul Duffincd064672021-04-24 00:47:29 +0100705 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100706 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100707 if !android.InList(memberName, memberList) {
708 memberList = append(memberList, memberName)
709 }
Paul Duffin13082052021-05-11 00:31:38 +0100710 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100711 }
712
Paul Duffin2d1bb892021-04-24 11:32:59 +0100713 return list
714}
715
716func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
717
718 // Extract the dynamic properties and add them to a list of propertiesContainer.
719 propertyContainers := []propertiesContainer{}
720 for _, i := range list {
721 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
722 sdkVariant: i.sdkVariant,
723 properties: i.dynamicProperties,
724 })
725 }
726
727 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100728 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100729 extractor := newCommonValueExtractor(commonDynamicProperties)
730 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
731
732 // Extract the static properties and add them to a list of propertiesContainer.
733 propertyContainers = []propertiesContainer{}
734 for _, i := range list {
735 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
736 sdkVariant: i.sdkVariant,
737 properties: i.staticProperties,
738 })
739 }
740
741 commonStaticProperties := &snapshotModuleStaticProperties{}
742 extractor = newCommonValueExtractor(commonStaticProperties)
743 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
744
745 return &combinedSnapshotModuleProperties{
746 sdkVariant: nil,
747 staticProperties: commonStaticProperties,
748 dynamicProperties: commonDynamicProperties,
749 }
750}
751
752func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
753 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100754 multilib := staticProperties.Compile_multilib
755 if multilib != "" && multilib != "both" {
756 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
757 propertySet.AddProperty("compile_multilib", multilib)
758 }
759
Paul Duffin2d1bb892021-04-24 11:32:59 +0100760 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100761 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100762 if memberListProperty.getter == nil {
763 continue
764 }
Paul Duffin865171e2020-03-02 18:38:15 +0000765 names := memberListProperty.getter(dynamicMemberTypeListProperties)
766 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000767 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000768 }
769 }
770}
771
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000772type propertyTag struct {
773 name string
774}
775
Paul Duffin94289702021-09-09 15:38:32 +0100776var _ android.BpPropertyTag = propertyTag{}
777
Paul Duffin0cb37b92020-03-04 14:52:46 +0000778// A BpPropertyTag to add to a property that contains references to other sdk members.
779//
780// This will cause the references to be rewritten to a versioned reference in the version
781// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000782var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000783var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000784
Paul Duffin0cb37b92020-03-04 14:52:46 +0000785// A BpPropertyTag that indicates the property should only be present in the versioned
786// module.
787//
788// This will cause the property to be removed from the unversioned instance of a
789// snapshot module.
790var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
791
Paul Duffine6c0d842020-01-15 14:08:51 +0000792type unversionedToVersionedTransformation struct {
793 identityTransformation
794 builder *snapshotBuilder
795}
796
Paul Duffine6c0d842020-01-15 14:08:51 +0000797func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
798 // Use a versioned name for the module but remember the original name for the
799 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100800 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000801 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000802 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100803 // Remove the prefer property if present as versioned modules never need marking with prefer.
804 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100805 // Ditto for use_source_config_var
806 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000807 return module
808}
809
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000810func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000811 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
812 required := tag == requiredSdkMemberReferencePropertyTag
813 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000814 } else {
815 return value, tag
816 }
817}
818
Paul Duffin72910952020-01-20 18:16:30 +0000819type unversionedTransformation struct {
820 identityTransformation
821 builder *snapshotBuilder
822}
823
824func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
825 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100826 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000827 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000828 return module
829}
830
831func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000832 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
833 required := tag == requiredSdkMemberReferencePropertyTag
834 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000835 } else if tag == sdkVersionedOnlyPropertyTag {
836 // The property is not allowed in the unversioned module so remove it.
837 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000838 } else {
839 return value, tag
840 }
841}
842
Paul Duffina78f3a72020-02-21 16:29:35 +0000843type pruneEmptySetTransformer struct {
844 identityTransformation
845}
846
847var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
848
849func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
850 if len(propertySet.properties) == 0 {
851 return nil, nil
852 } else {
853 return propertySet, tag
854 }
855}
856
Paul Duffinb645ec82019-11-27 17:43:54 +0000857func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000858 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
859 return true
860 })
861}
862
863func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100864 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000865 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000866 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100867 contents.IndentedPrintf("\n")
868 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000869 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100870 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000871 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000872 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000873}
874
875func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
876 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000877
Paul Duffin0df49682021-05-07 01:10:01 +0100878 addComment := func(name string) {
879 if text, ok := set.comments[name]; ok {
880 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100881 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100882 }
883 }
884 }
885
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000886 // Output the properties first, followed by the nested sets. This ensures a
887 // consistent output irrespective of whether property sets are created before
888 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000889 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000890 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000891
Paul Duffin0df49682021-05-07 01:10:01 +0100892 // Do not write property sets in the properties phase.
893 if _, ok := value.(*bpPropertySet); ok {
894 continue
895 }
896
897 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100898 reflectValue := reflect.ValueOf(value)
899 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000900 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000901
902 for _, name := range set.order {
903 value := set.getValue(name)
904
905 // Only write property sets in the sets phase.
906 switch v := value.(type) {
907 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100908 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100909 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000910 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100911 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000912 }
913 }
914
Paul Duffinb645ec82019-11-27 17:43:54 +0000915 contents.Dedent()
916}
917
Paul Duffina08e4dc2021-06-22 18:19:19 +0100918// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
919// by the value and then followed by a , and a newline.
920func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
921 contents.IndentedPrintf("%s: ", name)
922 outputUnnamedValue(contents, value)
923 contents.UnindentedPrintf(",\n")
924}
925
926// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
927// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
928// indented and all but the last line will end with a newline.
929func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
930 valueType := value.Type()
931 switch valueType.Kind() {
932 case reflect.Bool:
933 contents.UnindentedPrintf("%t", value.Bool())
934
935 case reflect.String:
936 contents.UnindentedPrintf("%q", value)
937
Paul Duffin51227d82021-05-18 12:54:27 +0100938 case reflect.Ptr:
939 outputUnnamedValue(contents, value.Elem())
940
Paul Duffina08e4dc2021-06-22 18:19:19 +0100941 case reflect.Slice:
942 length := value.Len()
943 if length == 0 {
944 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100945 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100946 firstValue := value.Index(0)
947 if length == 1 && !multiLineValue(firstValue) {
948 contents.UnindentedPrintf("[")
949 outputUnnamedValue(contents, firstValue)
950 contents.UnindentedPrintf("]")
951 } else {
952 contents.UnindentedPrintf("[\n")
953 contents.Indent()
954 for i := 0; i < length; i++ {
955 itemValue := value.Index(i)
956 contents.IndentedPrintf("")
957 outputUnnamedValue(contents, itemValue)
958 contents.UnindentedPrintf(",\n")
959 }
960 contents.Dedent()
961 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100962 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100963 }
964
Paul Duffin51227d82021-05-18 12:54:27 +0100965 case reflect.Struct:
966 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
967 v := value.Interface()
968 if _, ok := v.(android.BpPrintable); !ok {
969 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
970 }
971 contents.UnindentedPrintf("{\n")
972 contents.Indent()
973 for f := 0; f < valueType.NumField(); f++ {
974 fieldType := valueType.Field(f)
975 if fieldType.Anonymous {
976 continue
977 }
978 fieldValue := value.Field(f)
979 fieldName := fieldType.Name
980 propertyName := proptools.PropertyNameForField(fieldName)
981 outputNamedValue(contents, propertyName, fieldValue)
982 }
983 contents.Dedent()
984 contents.IndentedPrintf("}")
985
Paul Duffina08e4dc2021-06-22 18:19:19 +0100986 default:
987 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
988 }
989}
990
Paul Duffin51227d82021-05-18 12:54:27 +0100991// multiLineValue returns true if the supplied value may require multiple lines in the output.
992func multiLineValue(value reflect.Value) bool {
993 kind := value.Kind()
994 return kind == reflect.Slice || kind == reflect.Struct
995}
996
Paul Duffinac37c502019-11-26 18:02:20 +0000997func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000998 contents := &generatedContents{}
999 generateBpContents(contents, s.builderForTests.bpFile)
1000 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001001}
1002
Paul Duffind0759072021-02-17 11:23:00 +00001003func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1004 contents := &generatedContents{}
1005 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001006 name := module.Name()
1007 // Include modules that are either unversioned or have no name.
1008 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001009 })
1010 return contents.content.String()
1011}
1012
1013func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1014 contents := &generatedContents{}
1015 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001016 name := module.Name()
1017 // Include modules that are either versioned or have no name.
1018 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001019 })
1020 return contents.content.String()
1021}
1022
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001023type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001024 ctx android.ModuleContext
1025 sdk *sdk
1026
1027 // The version of the generated snapshot.
1028 //
1029 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1030 // this field.
1031 version string
1032
Paul Duffinb645ec82019-11-27 17:43:54 +00001033 snapshotDir android.OutputPath
1034 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001035
1036 // Map from destination to source of each copy - used to eliminate duplicates and
1037 // detect conflicts.
1038 copies map[string]string
1039
Paul Duffinb645ec82019-11-27 17:43:54 +00001040 filesToZip android.Paths
1041 zipsToMerge android.Paths
1042
Paul Duffin5c211452021-07-15 12:42:44 +01001043 // The path to an empty file.
1044 emptyFile android.WritablePath
1045
Paul Duffinb645ec82019-11-27 17:43:54 +00001046 prebuiltModules map[string]*bpModule
1047 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001048
1049 // The set of all members by name.
1050 allMembersByName map[string]struct{}
1051
1052 // The set of exported members by name.
1053 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001054}
1055
1056func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001057 if existing, ok := s.copies[dest]; ok {
1058 if existing != src.String() {
1059 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1060 return
1061 }
1062 } else {
1063 path := s.snapshotDir.Join(s.ctx, dest)
1064 s.ctx.Build(pctx, android.BuildParams{
1065 Rule: android.Cp,
1066 Input: src,
1067 Output: path,
1068 })
1069 s.filesToZip = append(s.filesToZip, path)
1070
1071 s.copies[dest] = src.String()
1072 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001073}
1074
Paul Duffin91547182019-11-12 19:39:36 +00001075func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1076 ctx := s.ctx
1077
1078 // Repackage the zip file so that the entries are in the destDir directory.
1079 // This will allow the zip file to be merged into the snapshot.
1080 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001081
1082 ctx.Build(pctx, android.BuildParams{
1083 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1084 Rule: repackageZip,
1085 Input: zipPath,
1086 Output: tmpZipPath,
1087 Args: map[string]string{
1088 "destdir": destDir,
1089 },
1090 })
Paul Duffin91547182019-11-12 19:39:36 +00001091
1092 // Add the repackaged zip file to the files to merge.
1093 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1094}
1095
Paul Duffin5c211452021-07-15 12:42:44 +01001096func (s *snapshotBuilder) EmptyFile() android.Path {
1097 if s.emptyFile == nil {
1098 ctx := s.ctx
1099 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1100 s.ctx.Build(pctx, android.BuildParams{
1101 Rule: android.Touch,
1102 Output: s.emptyFile,
1103 })
1104 }
1105
1106 return s.emptyFile
1107}
1108
Paul Duffin9d8d6092019-12-05 18:19:29 +00001109func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1110 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001111 if s.prebuiltModules[name] != nil {
1112 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1113 }
1114
1115 m := s.bpFile.newModule(moduleType)
1116 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001117
Paul Duffinbefa4b92020-03-04 14:22:45 +00001118 variant := member.Variants()[0]
1119
Paul Duffin13f02712020-03-06 12:30:43 +00001120 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001121 // An internal member is only referenced from the sdk snapshot which is in the
1122 // same package so can be marked as private.
1123 m.AddProperty("visibility", []string{"//visibility:private"})
1124 } else {
1125 // Extract visibility information from a member variant. All variants have the same
1126 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001127 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1128
1129 // Add any additional visibility rules needed for the prebuilts to reference each other.
1130 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1131 if err != nil {
1132 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1133 }
1134
1135 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001136 if len(visibility) != 0 {
1137 m.AddProperty("visibility", visibility)
1138 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001139 }
1140
Martin Stjernholm1e041092020-11-03 00:11:09 +00001141 // Where available copy apex_available properties from the member.
1142 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1143 apexAvailable := apexAware.ApexAvailable()
1144 if len(apexAvailable) == 0 {
1145 // //apex_available:platform is the default.
1146 apexAvailable = []string{android.AvailableToPlatform}
1147 }
1148
1149 // Add in any baseline apex available settings.
1150 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1151
1152 // Remove duplicates and sort.
1153 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1154 sort.Strings(apexAvailable)
1155
1156 m.AddProperty("apex_available", apexAvailable)
1157 }
1158
Paul Duffinb0bb3762021-05-06 16:48:05 +01001159 // The licenses are the same for all variants.
1160 mctx := s.ctx
1161 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1162 if len(licenseInfo.Licenses) > 0 {
1163 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1164 }
1165
Paul Duffin865171e2020-03-02 18:38:15 +00001166 deviceSupported := false
1167 hostSupported := false
1168
1169 for _, variant := range member.Variants() {
1170 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001171 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001172 hostSupported = true
1173 } else if osClass == android.Device {
1174 deviceSupported = true
1175 }
1176 }
1177
1178 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001179
Paul Duffin0cb37b92020-03-04 14:52:46 +00001180 // Disable installation in the versioned module of those modules that are ever installable.
1181 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1182 if installable.EverInstallable() {
1183 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1184 }
1185 }
1186
Paul Duffinb645ec82019-11-27 17:43:54 +00001187 s.prebuiltModules[name] = m
1188 s.prebuiltOrder = append(s.prebuiltOrder, m)
1189 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001190}
1191
Paul Duffin865171e2020-03-02 18:38:15 +00001192func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001193 // If neither device or host is supported then this module does not support either so will not
1194 // recognize the properties.
1195 if !deviceSupported && !hostSupported {
1196 return
1197 }
1198
Paul Duffin865171e2020-03-02 18:38:15 +00001199 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001200 bpModule.AddProperty("device_supported", false)
1201 }
Paul Duffin865171e2020-03-02 18:38:15 +00001202 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001203 bpModule.AddProperty("host_supported", true)
1204 }
1205}
1206
Paul Duffin13f02712020-03-06 12:30:43 +00001207func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1208 if required {
1209 return requiredSdkMemberReferencePropertyTag
1210 } else {
1211 return optionalSdkMemberReferencePropertyTag
1212 }
1213}
1214
1215func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1216 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001217}
1218
Paul Duffinb645ec82019-11-27 17:43:54 +00001219// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001220func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1221 if _, ok := s.allMembersByName[unversionedName]; !ok {
1222 if required {
1223 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1224 }
1225 return unversionedName
1226 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001227 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1228}
Paul Duffinb645ec82019-11-27 17:43:54 +00001229
Paul Duffin13f02712020-03-06 12:30:43 +00001230func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001231 var references []string = nil
1232 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001233 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001234 }
1235 return references
1236}
Paul Duffin13879572019-11-28 14:31:38 +00001237
Paul Duffin72910952020-01-20 18:16:30 +00001238// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001239func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1240 if _, ok := s.allMembersByName[unversionedName]; !ok {
1241 if required {
1242 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1243 }
1244 return unversionedName
1245 }
1246
1247 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001248 return s.ctx.ModuleName() + "_" + unversionedName
1249 } else {
1250 return unversionedName
1251 }
1252}
1253
Paul Duffin13f02712020-03-06 12:30:43 +00001254func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001255 var references []string = nil
1256 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001257 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001258 }
1259 return references
1260}
1261
Paul Duffin13f02712020-03-06 12:30:43 +00001262func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1263 _, ok := s.exportedMembersByName[memberName]
1264 return !ok
1265}
1266
Martin Stjernholm89238f42020-07-10 00:14:03 +01001267// Add the properties from the given SdkMemberProperties to the blueprint
1268// property set. This handles common properties in SdkMemberPropertiesBase and
1269// calls the member-specific AddToPropertySet for the rest.
1270func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1271 if memberProperties.Base().Compile_multilib != "" {
1272 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1273 }
1274
1275 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1276}
1277
Paul Duffin21827262021-04-24 12:16:36 +01001278// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1279type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001280 // The sdk variant that depends (possibly indirectly) on the member variant.
1281 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001282
1283 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001284 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001285
1286 // The variant that is added to the sdk.
1287 variant android.SdkAware
1288
1289 // True if the member should be exported, i.e. accessible, from outside the sdk.
1290 export bool
1291
1292 // The names of additional component modules provided by the variant.
1293 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001294}
1295
Paul Duffin13879572019-11-28 14:31:38 +00001296var _ android.SdkMember = (*sdkMember)(nil)
1297
Paul Duffin21827262021-04-24 12:16:36 +01001298// sdkMember groups all the variants of a specific member module together along with the name of the
1299// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001300type sdkMember struct {
1301 memberType android.SdkMemberType
1302 name string
1303 variants []android.SdkAware
1304}
1305
1306func (m *sdkMember) Name() string {
1307 return m.name
1308}
1309
1310func (m *sdkMember) Variants() []android.SdkAware {
1311 return m.variants
1312}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001313
Paul Duffin9c3760e2020-03-16 19:52:08 +00001314// Track usages of multilib variants.
1315type multilibUsage int
1316
1317const (
1318 multilibNone multilibUsage = 0
1319 multilib32 multilibUsage = 1
1320 multilib64 multilibUsage = 2
1321 multilibBoth = multilib32 | multilib64
1322)
1323
1324// Add the multilib that is used in the arch type.
1325func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1326 multilib := archType.Multilib
1327 switch multilib {
1328 case "":
1329 return m
1330 case "lib32":
1331 return m | multilib32
1332 case "lib64":
1333 return m | multilib64
1334 default:
1335 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1336 }
1337}
1338
1339func (m multilibUsage) String() string {
1340 switch m {
1341 case multilibNone:
1342 return ""
1343 case multilib32:
1344 return "32"
1345 case multilib64:
1346 return "64"
1347 case multilibBoth:
1348 return "both"
1349 default:
1350 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1351 m, multilibNone, multilib32, multilib64, multilibBoth))
1352 }
1353}
1354
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001355type baseInfo struct {
1356 Properties android.SdkMemberProperties
1357}
1358
Paul Duffinf34f6d82020-04-30 15:48:31 +01001359func (b *baseInfo) optimizableProperties() interface{} {
1360 return b.Properties
1361}
1362
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001363type osTypeSpecificInfo struct {
1364 baseInfo
1365
Paul Duffin00e46802020-03-12 20:40:35 +00001366 osType android.OsType
1367
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001368 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001369 //
1370 // Nil if there is one variant whose arch type is common
1371 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001372}
1373
Paul Duffin4b8b7932020-05-06 12:35:38 +01001374var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1375
Paul Duffinfc8dd232020-03-17 12:51:37 +00001376type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1377
Paul Duffin00e46802020-03-12 20:40:35 +00001378// Create a new osTypeSpecificInfo for the specified os type and its properties
1379// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001380func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001381 osInfo := &osTypeSpecificInfo{
1382 osType: osType,
1383 }
1384
1385 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1386 properties := variantPropertiesFactory()
1387 properties.Base().Os = osType
1388 return properties
1389 }
1390
1391 // Create a structure into which properties common across the architectures in
1392 // this os type will be stored.
1393 osInfo.Properties = osSpecificVariantPropertiesFactory()
1394
1395 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001396 var variantsByArchId = make(map[archId][]android.Module)
1397 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001398 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001399 target := variant.Target()
1400 id := archIdFromTarget(target)
1401 if _, ok := variantsByArchId[id]; !ok {
1402 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001403 }
1404
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001405 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001406 }
1407
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001408 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001409 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001410 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 +00001411 }
1412
1413 // A common arch type only has one variant and its properties should be treated
1414 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001415 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001416 } else {
1417 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001418 for _, id := range archIds {
1419 archVariants := variantsByArchId[id]
1420 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001421
1422 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1423 }
1424 }
1425
1426 return osInfo
1427}
1428
1429// Optimize the properties by extracting common properties from arch type specific
1430// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001431func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001432 // Nothing to do if there is only a single common architecture.
1433 if len(osInfo.archInfos) == 0 {
1434 return
1435 }
1436
Paul Duffin9c3760e2020-03-16 19:52:08 +00001437 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001438 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001439 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001440
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001441 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001442 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001443 }
1444
Paul Duffin4b8b7932020-05-06 12:35:38 +01001445 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001446
1447 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001448 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001449}
1450
1451// Add the properties for an os to a property set.
1452//
1453// Maps the properties related to the os variants through to an appropriate
1454// module structure that will produce equivalent set of variants when it is
1455// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001456func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001457
1458 var osPropertySet android.BpPropertySet
1459 var archPropertySet android.BpPropertySet
1460 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001461 if osInfo.Properties.Base().Os_count == 1 &&
1462 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1463 // There is only one OS type present in the variants and it shouldn't have a
1464 // variant-specific target. The latter is the case if it's either for device
1465 // where there is only one OS (android), or for host and the member type
1466 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001467
1468 // Create a structure that looks like:
1469 // module_type {
1470 // name: "...",
1471 // ...
1472 // <common properties>
1473 // ...
1474 // <single os type specific properties>
1475 //
1476 // arch: {
1477 // <arch specific sections>
1478 // }
1479 //
1480 osPropertySet = bpModule
1481 archPropertySet = osPropertySet.AddPropertySet("arch")
1482
1483 // Arch specific properties need to be added to an arch specific section
1484 // within arch.
1485 archOsPrefix = ""
1486 } else {
1487 // Create a structure that looks like:
1488 // module_type {
1489 // name: "...",
1490 // ...
1491 // <common properties>
1492 // ...
1493 // target: {
1494 // <arch independent os specific sections, e.g. android>
1495 // ...
1496 // <arch and os specific sections, e.g. android_x86>
1497 // }
1498 //
1499 osType := osInfo.osType
1500 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1501 archPropertySet = targetPropertySet
1502
1503 // Arch specific properties need to be added to an os and arch specific
1504 // section prefixed with <os>_.
1505 archOsPrefix = osType.Name + "_"
1506 }
1507
1508 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001509 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001510
1511 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1512 // os) specific properties.
1513 //
1514 // The archInfos list will be empty if the os contains variants for the common
1515 // architecture.
1516 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001517 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001518 }
1519}
1520
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001521func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1522 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001523 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001524}
1525
1526var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1527
Paul Duffin4b8b7932020-05-06 12:35:38 +01001528func (osInfo *osTypeSpecificInfo) String() string {
1529 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1530}
1531
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001532// archId encapsulates the information needed to identify a combination of arch type and native
1533// bridge support.
1534//
1535// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1536// essentially using one android.Arch to implement another. However, in terms of the handling of
1537// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1538// on android.Target.
1539//
1540// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1541type archId struct {
1542 // The arch type of the variant's target.
1543 archType android.ArchType
1544
1545 // True if the variants is for the native bridge, false otherwise.
1546 nativeBridge bool
1547}
1548
1549// propertyName returns the name of the property corresponding to use for this arch id.
1550func (i *archId) propertyName() string {
1551 name := i.archType.Name
1552 if i.nativeBridge {
1553 // Note: This does not result in a valid property because there is no architecture specific
1554 // native bridge property, only a generic "native_bridge" property. However, this will be used
1555 // in error messages if there is an attempt to use this in a generated bp file.
1556 name += "_native_bridge"
1557 }
1558 return name
1559}
1560
1561func (i *archId) String() string {
1562 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1563}
1564
1565// archIdFromTarget returns an archId initialized from information in the supplied target.
1566func archIdFromTarget(target android.Target) archId {
1567 return archId{
1568 archType: target.Arch.ArchType,
1569 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1570 }
1571}
1572
1573// commonArchId is the archId for the common architecture.
1574var commonArchId = archId{archType: android.Common}
1575
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001576type archTypeSpecificInfo struct {
1577 baseInfo
1578
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001579 archId archId
1580 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001581
Paul Duffinb42fa672021-09-09 16:37:49 +01001582 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001583}
1584
Paul Duffin4b8b7932020-05-06 12:35:38 +01001585var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1586
Paul Duffinfc8dd232020-03-17 12:51:37 +00001587// Create a new archTypeSpecificInfo for the specified arch type and its properties
1588// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001589func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001590
Paul Duffinfc8dd232020-03-17 12:51:37 +00001591 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001592 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001593
1594 // Create the properties into which the arch type specific properties will be
1595 // added.
1596 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001597
1598 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001599 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001600 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001601 // Group the variants by image type.
1602 variantsByImage := make(map[string][]android.Module)
1603 for _, variant := range archVariants {
1604 image := variant.ImageVariation().Variation
1605 variantsByImage[image] = append(variantsByImage[image], variant)
1606 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001607
Paul Duffinb42fa672021-09-09 16:37:49 +01001608 // Create the image variant info in a fixed order.
1609 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1610 variants := variantsByImage[imageVariantName]
1611 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001612 }
1613 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001614
1615 return archInfo
1616}
1617
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001618// Get the link type of the variant
1619//
1620// If the variant is not differentiated by link type then it returns "",
1621// otherwise it returns one of "static" or "shared".
1622func getLinkType(variant android.Module) string {
1623 linkType := ""
1624 if linkable, ok := variant.(cc.LinkableInterface); ok {
1625 if linkable.Shared() && linkable.Static() {
1626 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1627 } else if linkable.Shared() {
1628 linkType = "shared"
1629 } else if linkable.Static() {
1630 linkType = "static"
1631 } else {
1632 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1633 }
1634 }
1635 return linkType
1636}
1637
1638// Optimize the properties by extracting common properties from link type specific
1639// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001640func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001641 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001642 return
1643 }
1644
Paul Duffinb42fa672021-09-09 16:37:49 +01001645 // Optimize the image variant properties first.
1646 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1647 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1648 }
1649
1650 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001651}
1652
Paul Duffinfc8dd232020-03-17 12:51:37 +00001653// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001654func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001655 archPropertySuffix := archInfo.archId.propertyName()
1656 propertySetName := archOsPrefix + archPropertySuffix
1657 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001658 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1659 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1660 archTypePropertySet.AddProperty("enabled", true)
1661 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001662 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001663
Paul Duffinb42fa672021-09-09 16:37:49 +01001664 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1665 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001666 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001667
1668 // If this is for a native bridge architecture then make sure that the property set does not
1669 // contain any properties as providing native bridge specific properties is not currently
1670 // supported.
1671 if archInfo.archId.nativeBridge {
1672 propertySetContents := getPropertySetContents(archTypePropertySet)
1673 if propertySetContents != "" {
1674 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",
1675 propertySetName, ctx.name, propertySetContents)
1676 }
1677 }
1678}
1679
1680// getPropertySetContents returns the string representation of the contents of a property set, after
1681// recursively pruning any empty nested property sets.
1682func getPropertySetContents(propertySet android.BpPropertySet) string {
1683 set := propertySet.(*bpPropertySet)
1684 set.transformContents(pruneEmptySetTransformer{})
1685 if len(set.properties) != 0 {
1686 contents := &generatedContents{}
1687 contents.Indent()
1688 outputPropertySet(contents, set)
1689 setAsString := contents.content.String()
1690 return setAsString
1691 }
1692 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001693}
1694
Paul Duffin4b8b7932020-05-06 12:35:38 +01001695func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001696 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001697}
1698
Paul Duffinb42fa672021-09-09 16:37:49 +01001699type imageVariantSpecificInfo struct {
1700 baseInfo
1701
1702 imageVariant string
1703
1704 linkInfos []*linkTypeSpecificInfo
1705}
1706
1707func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1708
1709 // Create an image variant specific info into which the variant properties can be copied.
1710 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1711
1712 // Create the properties into which the image variant specific properties will be added.
1713 imageInfo.Properties = variantPropertiesFactory()
1714
1715 if len(imageVariants) == 1 {
1716 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1717 } else {
1718 // There is more than one variant for this image variant which must be differentiated by link
1719 // type.
1720 for _, linkVariant := range imageVariants {
1721 linkType := getLinkType(linkVariant)
1722 if linkType == "" {
1723 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1724 } else {
1725 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1726
1727 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1728 }
1729 }
1730 }
1731
1732 return imageInfo
1733}
1734
1735// Optimize the properties by extracting common properties from link type specific
1736// properties into arch type specific properties.
1737func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1738 if len(imageInfo.linkInfos) == 0 {
1739 return
1740 }
1741
1742 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1743}
1744
1745// Add the properties for an arch type to a property set.
1746func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1747 if imageInfo.imageVariant != android.CoreVariation {
1748 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1749 }
1750
1751 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1752
1753 for _, linkInfo := range imageInfo.linkInfos {
1754 linkInfo.addToPropertySet(ctx, propertySet)
1755 }
1756
1757 // If this is for a non-core image variant then make sure that the property set does not contain
1758 // any properties as providing non-core image variant specific properties for prebuilts is not
1759 // currently supported.
1760 if imageInfo.imageVariant != android.CoreVariation {
1761 propertySetContents := getPropertySetContents(propertySet)
1762 if propertySetContents != "" {
1763 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",
1764 imageInfo.imageVariant, ctx.name, propertySetContents)
1765 }
1766 }
1767}
1768
1769func (imageInfo *imageVariantSpecificInfo) String() string {
1770 return imageInfo.imageVariant
1771}
1772
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001773type linkTypeSpecificInfo struct {
1774 baseInfo
1775
1776 linkType string
1777}
1778
Paul Duffin4b8b7932020-05-06 12:35:38 +01001779var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1780
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001781// Create a new linkTypeSpecificInfo for the specified link type and its properties
1782// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001783func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001784 linkInfo := &linkTypeSpecificInfo{
1785 baseInfo: baseInfo{
1786 // Create the properties into which the link type specific properties will be
1787 // added.
1788 Properties: variantPropertiesFactory(),
1789 },
1790 linkType: linkType,
1791 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001792 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001793 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001794}
1795
Paul Duffinf68f85a2021-09-09 16:11:42 +01001796func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1797 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1798 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1799}
1800
Paul Duffin4b8b7932020-05-06 12:35:38 +01001801func (l *linkTypeSpecificInfo) String() string {
1802 return fmt.Sprintf("LinkType{%s}", l.linkType)
1803}
1804
Paul Duffin3a4eb502020-03-19 16:11:18 +00001805type memberContext struct {
1806 sdkMemberContext android.ModuleContext
1807 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001808 memberType android.SdkMemberType
1809 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001810
1811 // The set of traits required of this member.
1812 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001813}
1814
1815func (m *memberContext) SdkModuleContext() android.ModuleContext {
1816 return m.sdkMemberContext
1817}
1818
1819func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1820 return m.builder
1821}
1822
Paul Duffina551a1c2020-03-17 21:04:24 +00001823func (m *memberContext) MemberType() android.SdkMemberType {
1824 return m.memberType
1825}
1826
1827func (m *memberContext) Name() string {
1828 return m.name
1829}
1830
Paul Duffind19f8942021-07-14 12:08:37 +01001831func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1832 return m.requiredTraits.Contains(trait)
1833}
1834
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001835func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001836
1837 memberType := member.memberType
1838
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001839 // Do not add the prefer property if the member snapshot module is a source module type.
1840 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001841 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1842 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001843 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1844 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001845 config := ctx.sdkMemberContext.Config()
1846 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001847
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001848 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1849 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1850 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1851 // behavior is for the module.
1852 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001853
1854 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1855 if configVar != "" {
1856 parts := strings.Split(configVar, ":")
1857 cfp := android.ConfigVarProperties{
1858 Config_namespace: proptools.StringPtr(parts[0]),
1859 Var_name: proptools.StringPtr(parts[1]),
1860 }
1861 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1862 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001863 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001864
Paul Duffina04c1072020-03-02 10:16:35 +00001865 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001866 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001867 variants := member.Variants()
1868 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001869 osType := variant.Target().Os
1870 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001871 }
1872
Paul Duffina04c1072020-03-02 10:16:35 +00001873 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001874 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001875 properties := memberType.CreateVariantPropertiesStruct()
1876 base := properties.Base()
1877 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001878 return properties
1879 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001880
Paul Duffina04c1072020-03-02 10:16:35 +00001881 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001882
Paul Duffina04c1072020-03-02 10:16:35 +00001883 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001884 commonProperties := variantPropertiesFactory()
1885 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001886
Paul Duffinc097e362020-03-10 22:50:03 +00001887 // Create common value extractor that can be used to optimize the properties.
1888 commonValueExtractor := newCommonValueExtractor(commonProperties)
1889
Paul Duffina04c1072020-03-02 10:16:35 +00001890 // The list of property structures which are os type specific but common across
1891 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001892 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001893
1894 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001895 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001896 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001897 // Add the os specific properties to a list of os type specific yet architecture
1898 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001899 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001900
Paul Duffin00e46802020-03-12 20:40:35 +00001901 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001902 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001903 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001904
Paul Duffina04c1072020-03-02 10:16:35 +00001905 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001906 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001907
Paul Duffina04c1072020-03-02 10:16:35 +00001908 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001909 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001910
Paul Duffina04c1072020-03-02 10:16:35 +00001911 // Create a target property set into which target specific properties can be
1912 // added.
1913 targetPropertySet := bpModule.AddPropertySet("target")
1914
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001915 // If the member is host OS dependent and has host_supported then disable by
1916 // default and enable each host OS variant explicitly. This avoids problems
1917 // with implicitly enabled OS variants when the snapshot is used, which might
1918 // be different from this run (e.g. different build OS).
1919 if ctx.memberType.IsHostOsDependent() {
1920 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1921 if hostSupported {
1922 hostPropertySet := targetPropertySet.AddPropertySet("host")
1923 hostPropertySet.AddProperty("enabled", false)
1924 }
1925 }
1926
Paul Duffina04c1072020-03-02 10:16:35 +00001927 // Iterate over the os types in a fixed order.
1928 for _, osType := range s.getPossibleOsTypes() {
1929 osInfo := osTypeToInfo[osType]
1930 if osInfo == nil {
1931 continue
1932 }
1933
Paul Duffin3a4eb502020-03-19 16:11:18 +00001934 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001935 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001936}
1937
Paul Duffina04c1072020-03-02 10:16:35 +00001938// Compute the list of possible os types that this sdk could support.
1939func (s *sdk) getPossibleOsTypes() []android.OsType {
1940 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001941 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001942 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07001943 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00001944 osTypes = append(osTypes, osType)
1945 }
1946 }
1947 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001948 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001949 osTypes = append(osTypes, osType)
1950 }
1951 }
1952 }
1953 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1954 return osTypes
1955}
1956
Paul Duffinb28369a2020-05-04 15:39:59 +01001957// Given a set of properties (struct value), return the value of the field within that
1958// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001959type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1960
Paul Duffinc459f892020-04-30 18:08:29 +01001961// Checks the metadata to determine whether the property should be ignored for the
1962// purposes of common value extraction or not.
1963type extractorMetadataPredicate func(metadata propertiesContainer) bool
1964
1965// Indicates whether optimizable properties are provided by a host variant or
1966// not.
1967type isHostVariant interface {
1968 isHostVariant() bool
1969}
1970
Paul Duffinb28369a2020-05-04 15:39:59 +01001971// A property that can be optimized by the commonValueExtractor.
1972type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001973 // The name of the field for this property. It is a "."-separated path for
1974 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001975 name string
1976
Paul Duffinc459f892020-04-30 18:08:29 +01001977 // Filter that can use metadata associated with the properties being optimized
1978 // to determine whether the field should be ignored during common value
1979 // optimization.
1980 filter extractorMetadataPredicate
1981
Paul Duffinb28369a2020-05-04 15:39:59 +01001982 // Retrieves the value on which common value optimization will be performed.
1983 getter fieldAccessorFunc
1984
1985 // The empty value for the field.
1986 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001987
1988 // True if the property can support arch variants false otherwise.
1989 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001990}
1991
Paul Duffin4b8b7932020-05-06 12:35:38 +01001992func (p extractorProperty) String() string {
1993 return p.name
1994}
1995
Paul Duffinc097e362020-03-10 22:50:03 +00001996// Supports extracting common values from a number of instances of a properties
1997// structure into a separate common set of properties.
1998type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001999 // The properties that the extractor can optimize.
2000 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002001}
2002
2003// Create a new common value extractor for the structure type for the supplied
2004// properties struct.
2005//
2006// The returned extractor can be used on any properties structure of the same type
2007// as the supplied set of properties.
2008func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2009 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2010 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002011 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002012 return extractor
2013}
2014
2015// Gather the fields from the supplied structure type from which common values will
2016// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002017//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002018// This is recursive function. If it encounters a struct then it will recurse
2019// into it, passing in the accessor for the field and the struct name as prefix
2020// for the nested fields. That will then be used in the accessors for the fields
2021// in the embedded struct.
2022func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002023 for f := 0; f < structType.NumField(); f++ {
2024 field := structType.Field(f)
2025 if field.PkgPath != "" {
2026 // Ignore unexported fields.
2027 continue
2028 }
2029
Paul Duffinb07fa512020-03-10 22:17:04 +00002030 // Ignore fields whose value should be kept.
2031 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002032 continue
2033 }
2034
Paul Duffinc459f892020-04-30 18:08:29 +01002035 var filter extractorMetadataPredicate
2036
2037 // Add a filter
2038 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2039 filter = func(metadata propertiesContainer) bool {
2040 if m, ok := metadata.(isHostVariant); ok {
2041 if m.isHostVariant() {
2042 return false
2043 }
2044 }
2045 return true
2046 }
2047 }
2048
Paul Duffinc097e362020-03-10 22:50:03 +00002049 // Save a copy of the field index for use in the function.
2050 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002051
Martin Stjernholmb0249572020-09-15 02:32:35 +01002052 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002053
Paul Duffinc097e362020-03-10 22:50:03 +00002054 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002055 if containingStructAccessor != nil {
2056 // This is an embedded structure so first access the field for the embedded
2057 // structure.
2058 value = containingStructAccessor(value)
2059 }
2060
Paul Duffinc097e362020-03-10 22:50:03 +00002061 // Skip through interface and pointer values to find the structure.
2062 value = getStructValue(value)
2063
Paul Duffin4b8b7932020-05-06 12:35:38 +01002064 defer func() {
2065 if r := recover(); r != nil {
2066 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2067 }
2068 }()
2069
Paul Duffinc097e362020-03-10 22:50:03 +00002070 // Return the field.
2071 return value.Field(fieldIndex)
2072 }
2073
Martin Stjernholmb0249572020-09-15 02:32:35 +01002074 if field.Type.Kind() == reflect.Struct {
2075 // Gather fields from the nested or embedded structure.
2076 var subNamePrefix string
2077 if field.Anonymous {
2078 subNamePrefix = namePrefix
2079 } else {
2080 subNamePrefix = name + "."
2081 }
2082 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002083 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002084 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002085 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002086 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002087 fieldGetter,
2088 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002089 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002090 }
2091 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002092 }
Paul Duffinc097e362020-03-10 22:50:03 +00002093 }
2094}
2095
2096func getStructValue(value reflect.Value) reflect.Value {
2097foundStruct:
2098 for {
2099 kind := value.Kind()
2100 switch kind {
2101 case reflect.Interface, reflect.Ptr:
2102 value = value.Elem()
2103 case reflect.Struct:
2104 break foundStruct
2105 default:
2106 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2107 }
2108 }
2109 return value
2110}
2111
Paul Duffinf34f6d82020-04-30 15:48:31 +01002112// A container of properties to be optimized.
2113//
2114// Allows additional information to be associated with the properties, e.g. for
2115// filtering.
2116type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002117 fmt.Stringer
2118
Paul Duffinf34f6d82020-04-30 15:48:31 +01002119 // Get the properties that need optimizing.
2120 optimizableProperties() interface{}
2121}
2122
Paul Duffin2d1bb892021-04-24 11:32:59 +01002123// A wrapper for sdk variant related properties to allow them to be optimized.
2124type sdkVariantPropertiesContainer struct {
2125 sdkVariant *sdk
2126 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002127}
2128
Paul Duffin2d1bb892021-04-24 11:32:59 +01002129func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2130 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002131}
2132
Paul Duffin2d1bb892021-04-24 11:32:59 +01002133func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002134 return c.sdkVariant.String()
2135}
2136
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002137// Extract common properties from a slice of property structures of the same type.
2138//
2139// All the property structures must be of the same type.
2140// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002141// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002142//
2143// Iterates over each exported field (capitalized name) and checks to see whether they
2144// have the same value (using DeepEquals) across all the input properties. If it does not then no
2145// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002146// and the field in each of the input properties structure is set to its default value. Nested
2147// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002148func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002149 commonPropertiesValue := reflect.ValueOf(commonProperties)
2150 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002151
Paul Duffinf34f6d82020-04-30 15:48:31 +01002152 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2153
Paul Duffinb28369a2020-05-04 15:39:59 +01002154 for _, property := range e.properties {
2155 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002156 filter := property.filter
2157 if filter == nil {
2158 filter = func(metadata propertiesContainer) bool {
2159 return true
2160 }
2161 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002162
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002163 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002164 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2165 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002166 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002167
Paul Duffin864e1b42020-05-06 10:23:19 +01002168 // Assume that all the values will be the same.
2169 //
2170 // While similar to this is not quite the same as commonValue == nil. If all the values
2171 // have been filtered out then this will be false but commonValue == nil will be true.
2172 valuesDiffer := false
2173
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002174 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002175 container := sliceValue.Index(i).Interface().(propertiesContainer)
2176 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002177 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002178
Paul Duffinc459f892020-04-30 18:08:29 +01002179 if !filter(container) {
2180 expectedValue := property.emptyValue.Interface()
2181 actualValue := fieldValue.Interface()
2182 if !reflect.DeepEqual(expectedValue, actualValue) {
2183 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2184 }
2185 continue
2186 }
2187
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002188 if commonValue == nil {
2189 // Use the first value as the commonProperties value.
2190 commonValue = &fieldValue
2191 } else {
2192 // If the value does not match the current common value then there is
2193 // no value in common so break out.
2194 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2195 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002196 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002197 break
2198 }
2199 }
2200 }
2201
Paul Duffin864e1b42020-05-06 10:23:19 +01002202 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002203 // and set the input struct's field to the empty value.
2204 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002205 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002206 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002207 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002208 container := sliceValue.Index(i).Interface().(propertiesContainer)
2209 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002210 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002211 fieldValue.Set(emptyValue)
2212 }
2213 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002214
2215 if valuesDiffer && !property.archVariant {
2216 // The values differ but the property does not support arch variants so it
2217 // is an error.
2218 var details strings.Builder
2219 for i := 0; i < sliceValue.Len(); i++ {
2220 container := sliceValue.Index(i).Interface().(propertiesContainer)
2221 itemValue := reflect.ValueOf(container.optimizableProperties())
2222 fieldValue := fieldGetter(itemValue)
2223
2224 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2225 }
2226
2227 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2228 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002229 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002230
2231 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002232}