blob: 7d6780a182a213aee4dced8ca5a7f6c5476920cb [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 Cross440e0d02020-06-11 11:32:11 -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
36// 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.
38//
Paul Duffin43f7bf02021-05-05 22:00:51 +010039// SOONG_SDK_SNAPSHOT_VERSION
40// This provides control over the version of the generated snapshot.
41//
42// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
43// versioned snapshot module. This is the default behavior. The zip file containing the
44// generated snapshot will be <sdk-name>-current.zip.
45//
46// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
47// file containing the generated snapshot will be <sdk-name>.zip.
48//
49// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
50// snapshot module only. The zip file containing the generated snapshot will be
51// <sdk-name>-<number>.zip.
52//
Paul Duffin64fb5262021-05-05 21:36:04 +010053
Jiyong Park9b409bc2019-10-11 14:59:13 +090054var pctx = android.NewPackageContext("android/soong/sdk")
55
Paul Duffin375058f2019-11-29 20:17:53 +000056var (
57 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
58 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000059 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000060 CommandDeps: []string{
61 "${config.Zip2ZipCmd}",
62 },
63 },
64 "destdir")
65
66 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
67 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070068 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000069 CommandDeps: []string{
70 "${config.SoongZipCmd}",
71 },
72 Rspfile: "$out.rsp",
73 RspfileContent: "$in",
74 },
75 "basedir")
76
77 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
78 blueprint.RuleParams{
79 Command: `${config.MergeZipsCmd} $out $in`,
80 CommandDeps: []string{
81 "${config.MergeZipsCmd}",
82 },
83 })
84)
85
Paul Duffin43f7bf02021-05-05 22:00:51 +010086const (
87 soongSdkSnapshotVersionUnversioned = "unversioned"
88 soongSdkSnapshotVersionCurrent = "current"
89)
90
Paul Duffinb645ec82019-11-27 17:43:54 +000091type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090092 content strings.Builder
93 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090094}
95
Paul Duffinb645ec82019-11-27 17:43:54 +000096// generatedFile abstracts operations for writing contents into a file and emit a build rule
97// for the file.
98type generatedFile struct {
99 generatedContents
100 path android.OutputPath
101}
102
Jiyong Park232e7852019-11-04 12:23:40 +0900103func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000105 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900106 }
107}
108
Paul Duffinb645ec82019-11-27 17:43:54 +0000109func (gc *generatedContents) Indent() {
110 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900111}
112
Paul Duffinb645ec82019-11-27 17:43:54 +0000113func (gc *generatedContents) Dedent() {
114 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900115}
116
Paul Duffina08e4dc2021-06-22 18:19:19 +0100117// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
118// arguments.
119func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
120 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
121}
122
123// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
124// the arguments.
125func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
126 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900127}
128
129func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800130 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100131
132 content := gf.content.String()
133
134 // ninja consumes newline characters in rspfile_content. Prevent it by
135 // escaping the backslash in the newline character. The extra backslash
136 // is removed when the rspfile is written to the actual script file
137 content = strings.ReplaceAll(content, "\n", "\\n")
138
Jiyong Park9b409bc2019-10-11 14:59:13 +0900139 rb.Command().
140 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100141 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100142 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900143 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
144 rb.Command().
145 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800146 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900147}
148
Paul Duffin13879572019-11-28 14:31:38 +0000149// Collect all the members.
150//
Paul Duffincc3132e2021-04-24 01:10:30 +0100151// Updates the sdk module with a list of sdkMemberVariantDeps and details as to which multilibs
152// (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000153func (s *sdk) collectMembers(ctx android.ModuleContext) {
154 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000155 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
156 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000157 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100158 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900159
Paul Duffin13879572019-11-28 14:31:38 +0000160 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000161 if !memberType.IsInstance(child) {
162 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900163 }
Paul Duffin13879572019-11-28 14:31:38 +0000164
Paul Duffin6a7e9532020-03-20 17:50:07 +0000165 // Keep track of which multilib variants are used by the sdk.
166 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
167
Paul Duffina7208112021-04-23 21:20:20 +0100168 export := memberTag.ExportMember()
Paul Duffincd064672021-04-24 00:47:29 +0100169 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{s, memberType, child.(android.SdkAware), export})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000170
Paul Duffin2d3da312021-05-06 12:02:27 +0100171 // Recurse down into the member's dependencies as it may have dependencies that need to be
172 // automatically added to the sdk.
173 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900174 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000175
176 return false
Paul Duffin13879572019-11-28 14:31:38 +0000177 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000178}
179
Paul Duffincc3132e2021-04-24 01:10:30 +0100180// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
181// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000182//
Paul Duffincc3132e2021-04-24 01:10:30 +0100183// The sdkMember instances are then grouped into slices by member type. Within each such slice the
184// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000185//
Paul Duffincc3132e2021-04-24 01:10:30 +0100186// Finally, the member type slices are concatenated together to form a single slice. The order in
187// which they are concatenated is the order in which the member types were registered in the
188// android.SdkMemberTypesRegistry.
189func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000190 byType := make(map[android.SdkMemberType][]*sdkMember)
191 byName := make(map[string]*sdkMember)
192
Paul Duffin21827262021-04-24 12:16:36 +0100193 for _, memberVariantDep := range memberVariantDeps {
194 memberType := memberVariantDep.memberType
195 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000196
197 name := ctx.OtherModuleName(variant)
198 member := byName[name]
199 if member == nil {
200 member = &sdkMember{memberType: memberType, name: name}
201 byName[name] = member
202 byType[memberType] = append(byType[memberType], member)
203 }
204
Paul Duffin1356d8c2020-02-25 19:26:33 +0000205 // Only append new variants to the list. This is needed because a member can be both
206 // exported by the sdk and also be a transitive sdk member.
207 member.variants = appendUniqueVariants(member.variants, variant)
208 }
209
Paul Duffin13879572019-11-28 14:31:38 +0000210 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000211 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000212 membersOfType := byType[memberListProperty.memberType]
213 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900214 }
215
Paul Duffin6a7e9532020-03-20 17:50:07 +0000216 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900217}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900218
Paul Duffin72910952020-01-20 18:16:30 +0000219func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
220 for _, v := range variants {
221 if v == newVariant {
222 return variants
223 }
224 }
225 return append(variants, newVariant)
226}
227
Jiyong Park73c54ee2019-10-22 20:31:18 +0900228// SDK directory structure
229// <sdk_root>/
230// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
231// <api_ver>/ : below this directory are all auto-generated
232// Android.bp : definition of 'sdk_snapshot' module is here
233// aidl/
234// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
235// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900236// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900237// include/
238// bionic/libc/include/stdlib.h : an exported header file
239// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900240// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900241// <arch>/include/ : arch-specific exported headers
242// <arch>/include_gen/ : arch-specific generated headers
243// <arch>/lib/
244// libFoo.so : a stub library
245
Jiyong Park232e7852019-11-04 12:23:40 +0900246// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900247// This isn't visible to users, so could be changed in future.
248func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
249 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
250}
251
Jiyong Park232e7852019-11-04 12:23:40 +0900252// buildSnapshot is the main function in this source file. It creates rules to copy
253// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000254func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
255
Paul Duffin13f02712020-03-06 12:30:43 +0000256 allMembersByName := make(map[string]struct{})
257 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100258 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100259 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000260 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100261 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffin865171e2020-03-02 18:38:15 +0000262
Paul Duffin13f02712020-03-06 12:30:43 +0000263 // Record the names of all the members, both explicitly specified and implicitly
264 // included.
Paul Duffin21827262021-04-24 12:16:36 +0100265 for _, memberVariantDep := range sdkVariant.memberVariantDeps {
Paul Duffina7208112021-04-23 21:20:20 +0100266 name := memberVariantDep.variant.Name()
267 allMembersByName[name] = struct{}{}
Paul Duffin13f02712020-03-06 12:30:43 +0000268
Paul Duffina7208112021-04-23 21:20:20 +0100269 if memberVariantDep.export {
270 exportedMembersByName[name] = struct{}{}
271 }
Paul Duffin62131702021-05-07 01:10:01 +0100272
273 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
274 hasLicenses = true
275 }
Paul Duffin865171e2020-03-02 18:38:15 +0000276 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000277 }
278
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000279 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900280
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000281 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000282
283 bpFile := &bpFile{
284 modules: make(map[string]*bpModule),
285 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000286
Paul Duffin43f7bf02021-05-05 22:00:51 +0100287 config := ctx.Config()
288 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
289
290 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
291 generateVersioned := version != soongSdkSnapshotVersionUnversioned
292
293 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
294 //
295 // Unversioned modules are not required in that case because the numbered version will be a
296 // finalized version of the snapshot that is intended to be kept separate from the
297 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
298 snapshotZipFileSuffix := ""
299 if generateVersioned {
300 snapshotZipFileSuffix = "-" + version
301 }
302
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000303 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000304 ctx: ctx,
305 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100306 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000307 snapshotDir: snapshotDir.OutputPath,
308 copies: make(map[string]string),
309 filesToZip: []android.Path{bp.path},
310 bpFile: bpFile,
311 prebuiltModules: make(map[string]*bpModule),
312 allMembersByName: allMembersByName,
313 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900314 }
Paul Duffinac37c502019-11-26 18:02:20 +0000315 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900316
Paul Duffin62131702021-05-07 01:10:01 +0100317 // If the sdk snapshot includes any license modules then add a package module which has a
318 // default_applicable_licenses property. That will prevent the LSC license process from updating
319 // the generated Android.bp file to add a package module that includes all licenses used by all
320 // the modules in that package. That would be unnecessary as every module in the sdk should have
321 // their own licenses property specified.
322 if hasLicenses {
323 pkg := bpFile.newModule("package")
324 property := "default_applicable_licenses"
325 pkg.AddCommentForProperty(property, `
326A default list here prevents the license LSC from adding its own list which would
327be unnecessary as every module in the sdk already has its own licenses property.
328`)
329 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
330 bpFile.AddModule(pkg)
331 }
332
Paul Duffin0df49682021-05-07 01:10:01 +0100333 // Group the variants for each member module together and then group the members of each member
334 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100335 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100336
337 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000338 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000339 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000340
Paul Duffina551a1c2020-03-17 21:04:24 +0000341 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000342
343 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100344 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900345 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900346
Paul Duffine6c0d842020-01-15 14:08:51 +0000347 // Create a transformer that will transform an unversioned module into a versioned module.
348 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
349
Paul Duffin72910952020-01-20 18:16:30 +0000350 // Create a transformer that will transform an unversioned module by replacing any references
351 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100352 unversionedTransformer := unversionedTransformation{
353 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100354 }
Paul Duffin72910952020-01-20 18:16:30 +0000355
Paul Duffinb645ec82019-11-27 17:43:54 +0000356 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000357 // Prune any empty property sets.
358 unversioned = unversioned.transform(pruneEmptySetTransformer{})
359
Paul Duffin43f7bf02021-05-05 22:00:51 +0100360 if generateVersioned {
361 // Copy the unversioned module so it can be modified to make it versioned.
362 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000363
Paul Duffin43f7bf02021-05-05 22:00:51 +0100364 // Transform the unversioned module into a versioned one.
365 versioned.transform(unversionedToVersionedTransformer)
366 bpFile.AddModule(versioned)
367 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000368
Paul Duffin43f7bf02021-05-05 22:00:51 +0100369 if generateUnversioned {
370 // Transform the unversioned module to make it suitable for use in the snapshot.
371 unversioned.transform(unversionedTransformer)
372 bpFile.AddModule(unversioned)
373 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000374 }
375
Paul Duffin43f7bf02021-05-05 22:00:51 +0100376 if generateVersioned {
377 // Add the sdk/module_exports_snapshot module to the bp file.
378 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
379 }
Paul Duffin26197a62021-04-24 00:34:10 +0100380
381 // generate Android.bp
382 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
383 generateBpContents(&bp.generatedContents, bpFile)
384
385 contents := bp.content.String()
386 syntaxCheckSnapshotBpFile(ctx, contents)
387
388 bp.build(pctx, ctx, nil)
389
390 filesToZip := builder.filesToZip
391
392 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100393 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
394 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100395 outputDesc := "Building snapshot for " + ctx.ModuleName()
396
397 // If there are no zips to merge then generate the output zip directly.
398 // Otherwise, generate an intermediate zip file into which other zips can be
399 // merged.
400 var zipFile android.OutputPath
401 var desc string
402 if len(builder.zipsToMerge) == 0 {
403 zipFile = outputZipFile
404 desc = outputDesc
405 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100406 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
407 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100408 desc = "Building intermediate snapshot for " + ctx.ModuleName()
409 }
410
411 ctx.Build(pctx, android.BuildParams{
412 Description: desc,
413 Rule: zipFiles,
414 Inputs: filesToZip,
415 Output: zipFile,
416 Args: map[string]string{
417 "basedir": builder.snapshotDir.String(),
418 },
419 })
420
421 if len(builder.zipsToMerge) != 0 {
422 ctx.Build(pctx, android.BuildParams{
423 Description: outputDesc,
424 Rule: mergeZips,
425 Input: zipFile,
426 Inputs: builder.zipsToMerge,
427 Output: outputZipFile,
428 })
429 }
430
431 return outputZipFile
432}
433
434// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100435func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100436 bpFile := builder.bpFile
437
Paul Duffinb645ec82019-11-27 17:43:54 +0000438 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000439 var snapshotModuleType string
440 if s.properties.Module_exports {
441 snapshotModuleType = "module_exports_snapshot"
442 } else {
443 snapshotModuleType = "sdk_snapshot"
444 }
445 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000446 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000447
448 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100449 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000450 if len(visibility) != 0 {
451 snapshotModule.AddProperty("visibility", visibility)
452 }
453
Paul Duffin865171e2020-03-02 18:38:15 +0000454 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000455
Paul Duffincd064672021-04-24 00:47:29 +0100456 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100457 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000458
Paul Duffin2d1bb892021-04-24 11:32:59 +0100459 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100460
Paul Duffin6a7e9532020-03-20 17:50:07 +0000461 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100462
Paul Duffin2d1bb892021-04-24 11:32:59 +0100463 // Create a mapping from osType to combined properties.
464 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
465 for _, combined := range combinedPropertiesList {
466 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
467 }
468
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100469 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000470 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100471 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100472 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000473
Paul Duffin2d1bb892021-04-24 11:32:59 +0100474 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000475 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000476 }
Paul Duffin865171e2020-03-02 18:38:15 +0000477
Jiyong Park8fe14e62020-10-19 22:47:34 +0900478 // If host is supported and any member is host OS dependent then disable host
479 // by default, so that we can enable each host OS variant explicitly. This
480 // avoids problems with implicitly enabled OS variants when the snapshot is
481 // used, which might be different from this run (e.g. different build OS).
482 if s.HostSupported() {
483 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100484 for _, memberVariantDep := range memberVariantDeps {
485 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
486 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900487 if !android.InList(targetString, supportedHostTargets) {
488 supportedHostTargets = append(supportedHostTargets, targetString)
489 }
490 }
491 }
492 if len(supportedHostTargets) > 0 {
493 hostPropertySet := targetPropertySet.AddPropertySet("host")
494 hostPropertySet.AddProperty("enabled", false)
495 }
496 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
497 for _, hostTarget := range supportedHostTargets {
498 propertySet := targetPropertySet.AddPropertySet(hostTarget)
499 propertySet.AddProperty("enabled", true)
500 }
501 }
502
Paul Duffin865171e2020-03-02 18:38:15 +0000503 // Prune any empty property sets.
504 snapshotModule.transform(pruneEmptySetTransformer{})
505
Paul Duffinb645ec82019-11-27 17:43:54 +0000506 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900507}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000508
Paul Duffinf88d8e02020-05-07 20:21:34 +0100509// Check the syntax of the generated Android.bp file contents and if they are
510// invalid then log an error with the contents (tagged with line numbers) and the
511// errors that were found so that it is easy to see where the problem lies.
512func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
513 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
514 if len(errs) != 0 {
515 message := &strings.Builder{}
516 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
517
518Generated Android.bp contents
519========================================================================
520`)
521 for i, line := range strings.Split(contents, "\n") {
522 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
523 }
524
525 _, _ = fmt.Fprint(message, `
526========================================================================
527
528Errors found:
529`)
530
531 for _, err := range errs {
532 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
533 }
534
535 ctx.ModuleErrorf("%s", message.String())
536 }
537}
538
Paul Duffin4b8b7932020-05-06 12:35:38 +0100539func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
540 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
541 if err != nil {
542 ctx.ModuleErrorf("error extracting common properties: %s", err)
543 }
544}
545
Paul Duffinfbe470e2021-04-24 12:37:13 +0100546// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
547type snapshotModuleStaticProperties struct {
548 Compile_multilib string `android:"arch_variant"`
549}
550
Paul Duffin2d1bb892021-04-24 11:32:59 +0100551// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
552type combinedSnapshotModuleProperties struct {
553 // The sdk variant from which this information was collected.
554 sdkVariant *sdk
555
556 // Static snapshot module properties.
557 staticProperties *snapshotModuleStaticProperties
558
559 // The dynamically generated member list properties.
560 dynamicProperties interface{}
561}
562
563// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100564func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
565 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100566 var list []*combinedSnapshotModuleProperties
567 for _, sdkVariant := range sdkVariants {
568 staticProperties := &snapshotModuleStaticProperties{
569 Compile_multilib: sdkVariant.multilibUsages.String(),
570 }
Paul Duffincd064672021-04-24 00:47:29 +0100571 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100572
Paul Duffincd064672021-04-24 00:47:29 +0100573 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100574 sdkVariant: sdkVariant,
575 staticProperties: staticProperties,
576 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100577 }
578 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
579
580 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100581 }
Paul Duffincd064672021-04-24 00:47:29 +0100582
583 for _, memberVariantDep := range memberVariantDeps {
584 // If the member dependency is internal then do not add the dependency to the snapshot member
585 // list properties.
586 if !memberVariantDep.export {
587 continue
588 }
589
590 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100591 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100592 memberName := ctx.OtherModuleName(memberVariantDep.variant)
593
Paul Duffin13082052021-05-11 00:31:38 +0100594 if memberListProperty.getter == nil {
595 continue
596 }
597
Paul Duffincd064672021-04-24 00:47:29 +0100598 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100599 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100600 if !android.InList(memberName, memberList) {
601 memberList = append(memberList, memberName)
602 }
Paul Duffin13082052021-05-11 00:31:38 +0100603 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100604 }
605
Paul Duffin2d1bb892021-04-24 11:32:59 +0100606 return list
607}
608
609func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
610
611 // Extract the dynamic properties and add them to a list of propertiesContainer.
612 propertyContainers := []propertiesContainer{}
613 for _, i := range list {
614 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
615 sdkVariant: i.sdkVariant,
616 properties: i.dynamicProperties,
617 })
618 }
619
620 // Extract the common members, removing them from the original properties.
621 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
622 extractor := newCommonValueExtractor(commonDynamicProperties)
623 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
624
625 // Extract the static properties and add them to a list of propertiesContainer.
626 propertyContainers = []propertiesContainer{}
627 for _, i := range list {
628 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
629 sdkVariant: i.sdkVariant,
630 properties: i.staticProperties,
631 })
632 }
633
634 commonStaticProperties := &snapshotModuleStaticProperties{}
635 extractor = newCommonValueExtractor(commonStaticProperties)
636 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
637
638 return &combinedSnapshotModuleProperties{
639 sdkVariant: nil,
640 staticProperties: commonStaticProperties,
641 dynamicProperties: commonDynamicProperties,
642 }
643}
644
645func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
646 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100647 multilib := staticProperties.Compile_multilib
648 if multilib != "" && multilib != "both" {
649 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
650 propertySet.AddProperty("compile_multilib", multilib)
651 }
652
Paul Duffin2d1bb892021-04-24 11:32:59 +0100653 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000654 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100655 if memberListProperty.getter == nil {
656 continue
657 }
Paul Duffin865171e2020-03-02 18:38:15 +0000658 names := memberListProperty.getter(dynamicMemberTypeListProperties)
659 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000660 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000661 }
662 }
663}
664
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000665type propertyTag struct {
666 name string
667}
668
Paul Duffin0cb37b92020-03-04 14:52:46 +0000669// A BpPropertyTag to add to a property that contains references to other sdk members.
670//
671// This will cause the references to be rewritten to a versioned reference in the version
672// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000673var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000674var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000675
Paul Duffin0cb37b92020-03-04 14:52:46 +0000676// A BpPropertyTag that indicates the property should only be present in the versioned
677// module.
678//
679// This will cause the property to be removed from the unversioned instance of a
680// snapshot module.
681var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
682
Paul Duffine6c0d842020-01-15 14:08:51 +0000683type unversionedToVersionedTransformation struct {
684 identityTransformation
685 builder *snapshotBuilder
686}
687
Paul Duffine6c0d842020-01-15 14:08:51 +0000688func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
689 // Use a versioned name for the module but remember the original name for the
690 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100691 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000692 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000693 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100694 // Remove the prefer property if present as versioned modules never need marking with prefer.
695 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000696 return module
697}
698
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000699func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000700 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
701 required := tag == requiredSdkMemberReferencePropertyTag
702 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000703 } else {
704 return value, tag
705 }
706}
707
Paul Duffin72910952020-01-20 18:16:30 +0000708type unversionedTransformation struct {
709 identityTransformation
710 builder *snapshotBuilder
711}
712
713func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
714 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100715 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000716 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000717 return module
718}
719
720func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000721 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
722 required := tag == requiredSdkMemberReferencePropertyTag
723 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000724 } else if tag == sdkVersionedOnlyPropertyTag {
725 // The property is not allowed in the unversioned module so remove it.
726 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000727 } else {
728 return value, tag
729 }
730}
731
Paul Duffina78f3a72020-02-21 16:29:35 +0000732type pruneEmptySetTransformer struct {
733 identityTransformation
734}
735
736var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
737
738func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
739 if len(propertySet.properties) == 0 {
740 return nil, nil
741 } else {
742 return propertySet, tag
743 }
744}
745
Paul Duffinb645ec82019-11-27 17:43:54 +0000746func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000747 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
748 return true
749 })
750}
751
752func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100753 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000754 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000755 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100756 contents.IndentedPrintf("\n")
757 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000758 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100759 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000760 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000761 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000762}
763
764func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
765 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000766
Paul Duffin0df49682021-05-07 01:10:01 +0100767 addComment := func(name string) {
768 if text, ok := set.comments[name]; ok {
769 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100770 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100771 }
772 }
773 }
774
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000775 // Output the properties first, followed by the nested sets. This ensures a
776 // consistent output irrespective of whether property sets are created before
777 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000778 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000779 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000780
Paul Duffin0df49682021-05-07 01:10:01 +0100781 // Do not write property sets in the properties phase.
782 if _, ok := value.(*bpPropertySet); ok {
783 continue
784 }
785
786 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100787 reflectValue := reflect.ValueOf(value)
788 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000789 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000790
791 for _, name := range set.order {
792 value := set.getValue(name)
793
794 // Only write property sets in the sets phase.
795 switch v := value.(type) {
796 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100797 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100798 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000799 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100800 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000801 }
802 }
803
Paul Duffinb645ec82019-11-27 17:43:54 +0000804 contents.Dedent()
805}
806
Paul Duffina08e4dc2021-06-22 18:19:19 +0100807// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
808// by the value and then followed by a , and a newline.
809func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
810 contents.IndentedPrintf("%s: ", name)
811 outputUnnamedValue(contents, value)
812 contents.UnindentedPrintf(",\n")
813}
814
815// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
816// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
817// indented and all but the last line will end with a newline.
818func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
819 valueType := value.Type()
820 switch valueType.Kind() {
821 case reflect.Bool:
822 contents.UnindentedPrintf("%t", value.Bool())
823
824 case reflect.String:
825 contents.UnindentedPrintf("%q", value)
826
827 case reflect.Slice:
828 length := value.Len()
829 if length == 0 {
830 contents.UnindentedPrintf("[]")
831 } else if length == 1 {
832 contents.UnindentedPrintf("[")
833 outputUnnamedValue(contents, value.Index(0))
834 contents.UnindentedPrintf("]")
835 } else {
836 contents.UnindentedPrintf("[\n")
837 contents.Indent()
838 for i := 0; i < length; i++ {
839 itemValue := value.Index(i)
840 contents.IndentedPrintf("")
841 outputUnnamedValue(contents, itemValue)
842 contents.UnindentedPrintf(",\n")
843 }
844 contents.Dedent()
845 contents.IndentedPrintf("]")
846 }
847
848 default:
849 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
850 }
851}
852
Paul Duffinac37c502019-11-26 18:02:20 +0000853func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000854 contents := &generatedContents{}
855 generateBpContents(contents, s.builderForTests.bpFile)
856 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000857}
858
Paul Duffind0759072021-02-17 11:23:00 +0000859func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
860 contents := &generatedContents{}
861 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100862 name := module.Name()
863 // Include modules that are either unversioned or have no name.
864 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000865 })
866 return contents.content.String()
867}
868
869func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
870 contents := &generatedContents{}
871 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100872 name := module.Name()
873 // Include modules that are either versioned or have no name.
874 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000875 })
876 return contents.content.String()
877}
878
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000879type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100880 ctx android.ModuleContext
881 sdk *sdk
882
883 // The version of the generated snapshot.
884 //
885 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
886 // this field.
887 version string
888
Paul Duffinb645ec82019-11-27 17:43:54 +0000889 snapshotDir android.OutputPath
890 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000891
892 // Map from destination to source of each copy - used to eliminate duplicates and
893 // detect conflicts.
894 copies map[string]string
895
Paul Duffinb645ec82019-11-27 17:43:54 +0000896 filesToZip android.Paths
897 zipsToMerge android.Paths
898
899 prebuiltModules map[string]*bpModule
900 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000901
902 // The set of all members by name.
903 allMembersByName map[string]struct{}
904
905 // The set of exported members by name.
906 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000907}
908
909func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000910 if existing, ok := s.copies[dest]; ok {
911 if existing != src.String() {
912 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
913 return
914 }
915 } else {
916 path := s.snapshotDir.Join(s.ctx, dest)
917 s.ctx.Build(pctx, android.BuildParams{
918 Rule: android.Cp,
919 Input: src,
920 Output: path,
921 })
922 s.filesToZip = append(s.filesToZip, path)
923
924 s.copies[dest] = src.String()
925 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000926}
927
Paul Duffin91547182019-11-12 19:39:36 +0000928func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
929 ctx := s.ctx
930
931 // Repackage the zip file so that the entries are in the destDir directory.
932 // This will allow the zip file to be merged into the snapshot.
933 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000934
935 ctx.Build(pctx, android.BuildParams{
936 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
937 Rule: repackageZip,
938 Input: zipPath,
939 Output: tmpZipPath,
940 Args: map[string]string{
941 "destdir": destDir,
942 },
943 })
Paul Duffin91547182019-11-12 19:39:36 +0000944
945 // Add the repackaged zip file to the files to merge.
946 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
947}
948
Paul Duffin9d8d6092019-12-05 18:19:29 +0000949func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
950 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000951 if s.prebuiltModules[name] != nil {
952 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
953 }
954
955 m := s.bpFile.newModule(moduleType)
956 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000957
Paul Duffinbefa4b92020-03-04 14:22:45 +0000958 variant := member.Variants()[0]
959
Paul Duffin13f02712020-03-06 12:30:43 +0000960 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000961 // An internal member is only referenced from the sdk snapshot which is in the
962 // same package so can be marked as private.
963 m.AddProperty("visibility", []string{"//visibility:private"})
964 } else {
965 // Extract visibility information from a member variant. All variants have the same
966 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100967 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
968
969 // Add any additional visibility rules needed for the prebuilts to reference each other.
970 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
971 if err != nil {
972 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
973 }
974
975 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000976 if len(visibility) != 0 {
977 m.AddProperty("visibility", visibility)
978 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000979 }
980
Martin Stjernholm1e041092020-11-03 00:11:09 +0000981 // Where available copy apex_available properties from the member.
982 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
983 apexAvailable := apexAware.ApexAvailable()
984 if len(apexAvailable) == 0 {
985 // //apex_available:platform is the default.
986 apexAvailable = []string{android.AvailableToPlatform}
987 }
988
989 // Add in any baseline apex available settings.
990 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
991
992 // Remove duplicates and sort.
993 apexAvailable = android.FirstUniqueStrings(apexAvailable)
994 sort.Strings(apexAvailable)
995
996 m.AddProperty("apex_available", apexAvailable)
997 }
998
Paul Duffinb0bb3762021-05-06 16:48:05 +0100999 // The licenses are the same for all variants.
1000 mctx := s.ctx
1001 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1002 if len(licenseInfo.Licenses) > 0 {
1003 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1004 }
1005
Paul Duffin865171e2020-03-02 18:38:15 +00001006 deviceSupported := false
1007 hostSupported := false
1008
1009 for _, variant := range member.Variants() {
1010 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001011 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001012 hostSupported = true
1013 } else if osClass == android.Device {
1014 deviceSupported = true
1015 }
1016 }
1017
1018 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001019
Paul Duffin0cb37b92020-03-04 14:52:46 +00001020 // Disable installation in the versioned module of those modules that are ever installable.
1021 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1022 if installable.EverInstallable() {
1023 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1024 }
1025 }
1026
Paul Duffinb645ec82019-11-27 17:43:54 +00001027 s.prebuiltModules[name] = m
1028 s.prebuiltOrder = append(s.prebuiltOrder, m)
1029 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001030}
1031
Paul Duffin865171e2020-03-02 18:38:15 +00001032func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001033 // If neither device or host is supported then this module does not support either so will not
1034 // recognize the properties.
1035 if !deviceSupported && !hostSupported {
1036 return
1037 }
1038
Paul Duffin865171e2020-03-02 18:38:15 +00001039 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001040 bpModule.AddProperty("device_supported", false)
1041 }
Paul Duffin865171e2020-03-02 18:38:15 +00001042 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001043 bpModule.AddProperty("host_supported", true)
1044 }
1045}
1046
Paul Duffin13f02712020-03-06 12:30:43 +00001047func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1048 if required {
1049 return requiredSdkMemberReferencePropertyTag
1050 } else {
1051 return optionalSdkMemberReferencePropertyTag
1052 }
1053}
1054
1055func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1056 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001057}
1058
Paul Duffinb645ec82019-11-27 17:43:54 +00001059// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001060func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1061 if _, ok := s.allMembersByName[unversionedName]; !ok {
1062 if required {
1063 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1064 }
1065 return unversionedName
1066 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001067 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1068}
Paul Duffinb645ec82019-11-27 17:43:54 +00001069
Paul Duffin13f02712020-03-06 12:30:43 +00001070func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001071 var references []string = nil
1072 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001073 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001074 }
1075 return references
1076}
Paul Duffin13879572019-11-28 14:31:38 +00001077
Paul Duffin72910952020-01-20 18:16:30 +00001078// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001079func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1080 if _, ok := s.allMembersByName[unversionedName]; !ok {
1081 if required {
1082 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1083 }
1084 return unversionedName
1085 }
1086
1087 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001088 return s.ctx.ModuleName() + "_" + unversionedName
1089 } else {
1090 return unversionedName
1091 }
1092}
1093
Paul Duffin13f02712020-03-06 12:30:43 +00001094func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001095 var references []string = nil
1096 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001097 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001098 }
1099 return references
1100}
1101
Paul Duffin13f02712020-03-06 12:30:43 +00001102func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1103 _, ok := s.exportedMembersByName[memberName]
1104 return !ok
1105}
1106
Martin Stjernholm89238f42020-07-10 00:14:03 +01001107// Add the properties from the given SdkMemberProperties to the blueprint
1108// property set. This handles common properties in SdkMemberPropertiesBase and
1109// calls the member-specific AddToPropertySet for the rest.
1110func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1111 if memberProperties.Base().Compile_multilib != "" {
1112 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1113 }
1114
1115 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1116}
1117
Paul Duffin21827262021-04-24 12:16:36 +01001118// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1119type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001120 // The sdk variant that depends (possibly indirectly) on the member variant.
1121 sdkVariant *sdk
Paul Duffin1356d8c2020-02-25 19:26:33 +00001122 memberType android.SdkMemberType
1123 variant android.SdkAware
Paul Duffina7208112021-04-23 21:20:20 +01001124 export bool
Paul Duffin1356d8c2020-02-25 19:26:33 +00001125}
1126
Paul Duffin13879572019-11-28 14:31:38 +00001127var _ android.SdkMember = (*sdkMember)(nil)
1128
Paul Duffin21827262021-04-24 12:16:36 +01001129// sdkMember groups all the variants of a specific member module together along with the name of the
1130// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001131type sdkMember struct {
1132 memberType android.SdkMemberType
1133 name string
1134 variants []android.SdkAware
1135}
1136
1137func (m *sdkMember) Name() string {
1138 return m.name
1139}
1140
1141func (m *sdkMember) Variants() []android.SdkAware {
1142 return m.variants
1143}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001144
Paul Duffin9c3760e2020-03-16 19:52:08 +00001145// Track usages of multilib variants.
1146type multilibUsage int
1147
1148const (
1149 multilibNone multilibUsage = 0
1150 multilib32 multilibUsage = 1
1151 multilib64 multilibUsage = 2
1152 multilibBoth = multilib32 | multilib64
1153)
1154
1155// Add the multilib that is used in the arch type.
1156func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1157 multilib := archType.Multilib
1158 switch multilib {
1159 case "":
1160 return m
1161 case "lib32":
1162 return m | multilib32
1163 case "lib64":
1164 return m | multilib64
1165 default:
1166 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1167 }
1168}
1169
1170func (m multilibUsage) String() string {
1171 switch m {
1172 case multilibNone:
1173 return ""
1174 case multilib32:
1175 return "32"
1176 case multilib64:
1177 return "64"
1178 case multilibBoth:
1179 return "both"
1180 default:
1181 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1182 m, multilibNone, multilib32, multilib64, multilibBoth))
1183 }
1184}
1185
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001186type baseInfo struct {
1187 Properties android.SdkMemberProperties
1188}
1189
Paul Duffinf34f6d82020-04-30 15:48:31 +01001190func (b *baseInfo) optimizableProperties() interface{} {
1191 return b.Properties
1192}
1193
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001194type osTypeSpecificInfo struct {
1195 baseInfo
1196
Paul Duffin00e46802020-03-12 20:40:35 +00001197 osType android.OsType
1198
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001199 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001200 //
1201 // Nil if there is one variant whose arch type is common
1202 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001203}
1204
Paul Duffin4b8b7932020-05-06 12:35:38 +01001205var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1206
Paul Duffinfc8dd232020-03-17 12:51:37 +00001207type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1208
Paul Duffin00e46802020-03-12 20:40:35 +00001209// Create a new osTypeSpecificInfo for the specified os type and its properties
1210// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001211func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001212 osInfo := &osTypeSpecificInfo{
1213 osType: osType,
1214 }
1215
1216 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1217 properties := variantPropertiesFactory()
1218 properties.Base().Os = osType
1219 return properties
1220 }
1221
1222 // Create a structure into which properties common across the architectures in
1223 // this os type will be stored.
1224 osInfo.Properties = osSpecificVariantPropertiesFactory()
1225
1226 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001227 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001228 var archTypes []android.ArchType
1229 for _, variant := range osTypeVariants {
1230 archType := variant.Target().Arch.ArchType
1231 archTypeName := archType.Name
1232 if _, ok := variantsByArchName[archTypeName]; !ok {
1233 archTypes = append(archTypes, archType)
1234 }
1235
1236 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1237 }
1238
1239 if commonVariants, ok := variantsByArchName["common"]; ok {
1240 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001241 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 +00001242 }
1243
1244 // A common arch type only has one variant and its properties should be treated
1245 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001246 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001247 } else {
1248 // Create an arch specific info for each supported architecture type.
1249 for _, archType := range archTypes {
1250 archTypeName := archType.Name
1251
1252 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001253 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001254
1255 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1256 }
1257 }
1258
1259 return osInfo
1260}
1261
1262// Optimize the properties by extracting common properties from arch type specific
1263// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001264func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001265 // Nothing to do if there is only a single common architecture.
1266 if len(osInfo.archInfos) == 0 {
1267 return
1268 }
1269
Paul Duffin9c3760e2020-03-16 19:52:08 +00001270 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001271 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001272 multilib = multilib.addArchType(archInfo.archType)
1273
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001274 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001275 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001276 }
1277
Paul Duffin4b8b7932020-05-06 12:35:38 +01001278 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001279
1280 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001281 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001282}
1283
1284// Add the properties for an os to a property set.
1285//
1286// Maps the properties related to the os variants through to an appropriate
1287// module structure that will produce equivalent set of variants when it is
1288// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001289func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001290
1291 var osPropertySet android.BpPropertySet
1292 var archPropertySet android.BpPropertySet
1293 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001294 if osInfo.Properties.Base().Os_count == 1 &&
1295 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1296 // There is only one OS type present in the variants and it shouldn't have a
1297 // variant-specific target. The latter is the case if it's either for device
1298 // where there is only one OS (android), or for host and the member type
1299 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001300
1301 // Create a structure that looks like:
1302 // module_type {
1303 // name: "...",
1304 // ...
1305 // <common properties>
1306 // ...
1307 // <single os type specific properties>
1308 //
1309 // arch: {
1310 // <arch specific sections>
1311 // }
1312 //
1313 osPropertySet = bpModule
1314 archPropertySet = osPropertySet.AddPropertySet("arch")
1315
1316 // Arch specific properties need to be added to an arch specific section
1317 // within arch.
1318 archOsPrefix = ""
1319 } else {
1320 // Create a structure that looks like:
1321 // module_type {
1322 // name: "...",
1323 // ...
1324 // <common properties>
1325 // ...
1326 // target: {
1327 // <arch independent os specific sections, e.g. android>
1328 // ...
1329 // <arch and os specific sections, e.g. android_x86>
1330 // }
1331 //
1332 osType := osInfo.osType
1333 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1334 archPropertySet = targetPropertySet
1335
1336 // Arch specific properties need to be added to an os and arch specific
1337 // section prefixed with <os>_.
1338 archOsPrefix = osType.Name + "_"
1339 }
1340
1341 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001342 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001343
1344 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1345 // os) specific properties.
1346 //
1347 // The archInfos list will be empty if the os contains variants for the common
1348 // architecture.
1349 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001350 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001351 }
1352}
1353
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001354func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1355 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001356 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001357}
1358
1359var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1360
Paul Duffin4b8b7932020-05-06 12:35:38 +01001361func (osInfo *osTypeSpecificInfo) String() string {
1362 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1363}
1364
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001365type archTypeSpecificInfo struct {
1366 baseInfo
1367
1368 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001369 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001370
1371 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001372}
1373
Paul Duffin4b8b7932020-05-06 12:35:38 +01001374var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1375
Paul Duffinfc8dd232020-03-17 12:51:37 +00001376// Create a new archTypeSpecificInfo for the specified arch type and its properties
1377// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001378func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001379
Paul Duffinfc8dd232020-03-17 12:51:37 +00001380 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001381 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001382
1383 // Create the properties into which the arch type specific properties will be
1384 // added.
1385 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001386
1387 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001388 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001389 } else {
1390 // There is more than one variant for this arch type which must be differentiated
1391 // by link type.
1392 for _, linkVariant := range archVariants {
1393 linkType := getLinkType(linkVariant)
1394 if linkType == "" {
1395 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1396 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001397 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001398
1399 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1400 }
1401 }
1402 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001403
1404 return archInfo
1405}
1406
Paul Duffinf34f6d82020-04-30 15:48:31 +01001407func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1408 return archInfo.Properties
1409}
1410
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001411// Get the link type of the variant
1412//
1413// If the variant is not differentiated by link type then it returns "",
1414// otherwise it returns one of "static" or "shared".
1415func getLinkType(variant android.Module) string {
1416 linkType := ""
1417 if linkable, ok := variant.(cc.LinkableInterface); ok {
1418 if linkable.Shared() && linkable.Static() {
1419 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1420 } else if linkable.Shared() {
1421 linkType = "shared"
1422 } else if linkable.Static() {
1423 linkType = "static"
1424 } else {
1425 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1426 }
1427 }
1428 return linkType
1429}
1430
1431// Optimize the properties by extracting common properties from link type specific
1432// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001433func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001434 if len(archInfo.linkInfos) == 0 {
1435 return
1436 }
1437
Paul Duffin4b8b7932020-05-06 12:35:38 +01001438 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001439}
1440
Paul Duffinfc8dd232020-03-17 12:51:37 +00001441// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001442func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001443 archTypeName := archInfo.archType.Name
1444 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001445 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1446 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1447 archTypePropertySet.AddProperty("enabled", true)
1448 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001449 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001450
1451 for _, linkInfo := range archInfo.linkInfos {
1452 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001453 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001454 }
1455}
1456
Paul Duffin4b8b7932020-05-06 12:35:38 +01001457func (archInfo *archTypeSpecificInfo) String() string {
1458 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1459}
1460
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001461type linkTypeSpecificInfo struct {
1462 baseInfo
1463
1464 linkType string
1465}
1466
Paul Duffin4b8b7932020-05-06 12:35:38 +01001467var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1468
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001469// Create a new linkTypeSpecificInfo for the specified link type and its properties
1470// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001471func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001472 linkInfo := &linkTypeSpecificInfo{
1473 baseInfo: baseInfo{
1474 // Create the properties into which the link type specific properties will be
1475 // added.
1476 Properties: variantPropertiesFactory(),
1477 },
1478 linkType: linkType,
1479 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001480 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001481 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001482}
1483
Paul Duffin4b8b7932020-05-06 12:35:38 +01001484func (l *linkTypeSpecificInfo) String() string {
1485 return fmt.Sprintf("LinkType{%s}", l.linkType)
1486}
1487
Paul Duffin3a4eb502020-03-19 16:11:18 +00001488type memberContext struct {
1489 sdkMemberContext android.ModuleContext
1490 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001491 memberType android.SdkMemberType
1492 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001493}
1494
1495func (m *memberContext) SdkModuleContext() android.ModuleContext {
1496 return m.sdkMemberContext
1497}
1498
1499func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1500 return m.builder
1501}
1502
Paul Duffina551a1c2020-03-17 21:04:24 +00001503func (m *memberContext) MemberType() android.SdkMemberType {
1504 return m.memberType
1505}
1506
1507func (m *memberContext) Name() string {
1508 return m.name
1509}
1510
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001511func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001512
1513 memberType := member.memberType
1514
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001515 // Do not add the prefer property if the member snapshot module is a source module type.
1516 if !memberType.UsesSourceModuleTypeInSnapshot() {
1517 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1518 // snapshot to be created that sets prefer: true.
1519 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1520 // dynamically at build time not at snapshot generation time.
1521 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001522
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001523 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1524 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1525 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1526 // behavior is for the module.
1527 bpModule.insertAfter("name", "prefer", prefer)
1528 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001529
Paul Duffina04c1072020-03-02 10:16:35 +00001530 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001531 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001532 variants := member.Variants()
1533 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001534 osType := variant.Target().Os
1535 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001536 }
1537
Paul Duffina04c1072020-03-02 10:16:35 +00001538 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001539 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001540 properties := memberType.CreateVariantPropertiesStruct()
1541 base := properties.Base()
1542 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001543 return properties
1544 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001545
Paul Duffina04c1072020-03-02 10:16:35 +00001546 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001547
Paul Duffina04c1072020-03-02 10:16:35 +00001548 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001549 commonProperties := variantPropertiesFactory()
1550 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001551
Paul Duffinc097e362020-03-10 22:50:03 +00001552 // Create common value extractor that can be used to optimize the properties.
1553 commonValueExtractor := newCommonValueExtractor(commonProperties)
1554
Paul Duffina04c1072020-03-02 10:16:35 +00001555 // The list of property structures which are os type specific but common across
1556 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001557 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001558
1559 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001560 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001561 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001562 // Add the os specific properties to a list of os type specific yet architecture
1563 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001564 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001565
Paul Duffin00e46802020-03-12 20:40:35 +00001566 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001567 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001568 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001569
Paul Duffina04c1072020-03-02 10:16:35 +00001570 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001571 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001572
Paul Duffina04c1072020-03-02 10:16:35 +00001573 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001574 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001575
Paul Duffina04c1072020-03-02 10:16:35 +00001576 // Create a target property set into which target specific properties can be
1577 // added.
1578 targetPropertySet := bpModule.AddPropertySet("target")
1579
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001580 // If the member is host OS dependent and has host_supported then disable by
1581 // default and enable each host OS variant explicitly. This avoids problems
1582 // with implicitly enabled OS variants when the snapshot is used, which might
1583 // be different from this run (e.g. different build OS).
1584 if ctx.memberType.IsHostOsDependent() {
1585 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1586 if hostSupported {
1587 hostPropertySet := targetPropertySet.AddPropertySet("host")
1588 hostPropertySet.AddProperty("enabled", false)
1589 }
1590 }
1591
Paul Duffina04c1072020-03-02 10:16:35 +00001592 // Iterate over the os types in a fixed order.
1593 for _, osType := range s.getPossibleOsTypes() {
1594 osInfo := osTypeToInfo[osType]
1595 if osInfo == nil {
1596 continue
1597 }
1598
Paul Duffin3a4eb502020-03-19 16:11:18 +00001599 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001600 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001601}
1602
Paul Duffina04c1072020-03-02 10:16:35 +00001603// Compute the list of possible os types that this sdk could support.
1604func (s *sdk) getPossibleOsTypes() []android.OsType {
1605 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001606 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001607 if s.DeviceSupported() {
1608 if osType.Class == android.Device && osType != android.Fuchsia {
1609 osTypes = append(osTypes, osType)
1610 }
1611 }
1612 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001613 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001614 osTypes = append(osTypes, osType)
1615 }
1616 }
1617 }
1618 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1619 return osTypes
1620}
1621
Paul Duffinb28369a2020-05-04 15:39:59 +01001622// Given a set of properties (struct value), return the value of the field within that
1623// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001624type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1625
Paul Duffinc459f892020-04-30 18:08:29 +01001626// Checks the metadata to determine whether the property should be ignored for the
1627// purposes of common value extraction or not.
1628type extractorMetadataPredicate func(metadata propertiesContainer) bool
1629
1630// Indicates whether optimizable properties are provided by a host variant or
1631// not.
1632type isHostVariant interface {
1633 isHostVariant() bool
1634}
1635
Paul Duffinb28369a2020-05-04 15:39:59 +01001636// A property that can be optimized by the commonValueExtractor.
1637type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001638 // The name of the field for this property. It is a "."-separated path for
1639 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001640 name string
1641
Paul Duffinc459f892020-04-30 18:08:29 +01001642 // Filter that can use metadata associated with the properties being optimized
1643 // to determine whether the field should be ignored during common value
1644 // optimization.
1645 filter extractorMetadataPredicate
1646
Paul Duffinb28369a2020-05-04 15:39:59 +01001647 // Retrieves the value on which common value optimization will be performed.
1648 getter fieldAccessorFunc
1649
1650 // The empty value for the field.
1651 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001652
1653 // True if the property can support arch variants false otherwise.
1654 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001655}
1656
Paul Duffin4b8b7932020-05-06 12:35:38 +01001657func (p extractorProperty) String() string {
1658 return p.name
1659}
1660
Paul Duffinc097e362020-03-10 22:50:03 +00001661// Supports extracting common values from a number of instances of a properties
1662// structure into a separate common set of properties.
1663type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001664 // The properties that the extractor can optimize.
1665 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001666}
1667
1668// Create a new common value extractor for the structure type for the supplied
1669// properties struct.
1670//
1671// The returned extractor can be used on any properties structure of the same type
1672// as the supplied set of properties.
1673func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1674 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1675 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001676 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001677 return extractor
1678}
1679
1680// Gather the fields from the supplied structure type from which common values will
1681// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001682//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001683// This is recursive function. If it encounters a struct then it will recurse
1684// into it, passing in the accessor for the field and the struct name as prefix
1685// for the nested fields. That will then be used in the accessors for the fields
1686// in the embedded struct.
1687func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001688 for f := 0; f < structType.NumField(); f++ {
1689 field := structType.Field(f)
1690 if field.PkgPath != "" {
1691 // Ignore unexported fields.
1692 continue
1693 }
1694
Paul Duffinb07fa512020-03-10 22:17:04 +00001695 // Ignore fields whose value should be kept.
1696 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001697 continue
1698 }
1699
Paul Duffinc459f892020-04-30 18:08:29 +01001700 var filter extractorMetadataPredicate
1701
1702 // Add a filter
1703 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1704 filter = func(metadata propertiesContainer) bool {
1705 if m, ok := metadata.(isHostVariant); ok {
1706 if m.isHostVariant() {
1707 return false
1708 }
1709 }
1710 return true
1711 }
1712 }
1713
Paul Duffinc097e362020-03-10 22:50:03 +00001714 // Save a copy of the field index for use in the function.
1715 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001716
Martin Stjernholmb0249572020-09-15 02:32:35 +01001717 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001718
Paul Duffinc097e362020-03-10 22:50:03 +00001719 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001720 if containingStructAccessor != nil {
1721 // This is an embedded structure so first access the field for the embedded
1722 // structure.
1723 value = containingStructAccessor(value)
1724 }
1725
Paul Duffinc097e362020-03-10 22:50:03 +00001726 // Skip through interface and pointer values to find the structure.
1727 value = getStructValue(value)
1728
Paul Duffin4b8b7932020-05-06 12:35:38 +01001729 defer func() {
1730 if r := recover(); r != nil {
1731 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1732 }
1733 }()
1734
Paul Duffinc097e362020-03-10 22:50:03 +00001735 // Return the field.
1736 return value.Field(fieldIndex)
1737 }
1738
Martin Stjernholmb0249572020-09-15 02:32:35 +01001739 if field.Type.Kind() == reflect.Struct {
1740 // Gather fields from the nested or embedded structure.
1741 var subNamePrefix string
1742 if field.Anonymous {
1743 subNamePrefix = namePrefix
1744 } else {
1745 subNamePrefix = name + "."
1746 }
1747 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001748 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001749 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001750 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001751 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001752 fieldGetter,
1753 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001754 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001755 }
1756 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001757 }
Paul Duffinc097e362020-03-10 22:50:03 +00001758 }
1759}
1760
1761func getStructValue(value reflect.Value) reflect.Value {
1762foundStruct:
1763 for {
1764 kind := value.Kind()
1765 switch kind {
1766 case reflect.Interface, reflect.Ptr:
1767 value = value.Elem()
1768 case reflect.Struct:
1769 break foundStruct
1770 default:
1771 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1772 }
1773 }
1774 return value
1775}
1776
Paul Duffinf34f6d82020-04-30 15:48:31 +01001777// A container of properties to be optimized.
1778//
1779// Allows additional information to be associated with the properties, e.g. for
1780// filtering.
1781type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001782 fmt.Stringer
1783
Paul Duffinf34f6d82020-04-30 15:48:31 +01001784 // Get the properties that need optimizing.
1785 optimizableProperties() interface{}
1786}
1787
Paul Duffin2d1bb892021-04-24 11:32:59 +01001788// A wrapper for sdk variant related properties to allow them to be optimized.
1789type sdkVariantPropertiesContainer struct {
1790 sdkVariant *sdk
1791 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001792}
1793
Paul Duffin2d1bb892021-04-24 11:32:59 +01001794func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1795 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001796}
1797
Paul Duffin2d1bb892021-04-24 11:32:59 +01001798func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001799 return c.sdkVariant.String()
1800}
1801
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001802// Extract common properties from a slice of property structures of the same type.
1803//
1804// All the property structures must be of the same type.
1805// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001806// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001807//
1808// Iterates over each exported field (capitalized name) and checks to see whether they
1809// have the same value (using DeepEquals) across all the input properties. If it does not then no
1810// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001811// and the field in each of the input properties structure is set to its default value. Nested
1812// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001813func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001814 commonPropertiesValue := reflect.ValueOf(commonProperties)
1815 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001816
Paul Duffinf34f6d82020-04-30 15:48:31 +01001817 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1818
Paul Duffinb28369a2020-05-04 15:39:59 +01001819 for _, property := range e.properties {
1820 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001821 filter := property.filter
1822 if filter == nil {
1823 filter = func(metadata propertiesContainer) bool {
1824 return true
1825 }
1826 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001827
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001828 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001829 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1830 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001831 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001832
Paul Duffin864e1b42020-05-06 10:23:19 +01001833 // Assume that all the values will be the same.
1834 //
1835 // While similar to this is not quite the same as commonValue == nil. If all the values
1836 // have been filtered out then this will be false but commonValue == nil will be true.
1837 valuesDiffer := false
1838
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001839 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001840 container := sliceValue.Index(i).Interface().(propertiesContainer)
1841 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001842 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001843
Paul Duffinc459f892020-04-30 18:08:29 +01001844 if !filter(container) {
1845 expectedValue := property.emptyValue.Interface()
1846 actualValue := fieldValue.Interface()
1847 if !reflect.DeepEqual(expectedValue, actualValue) {
1848 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1849 }
1850 continue
1851 }
1852
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001853 if commonValue == nil {
1854 // Use the first value as the commonProperties value.
1855 commonValue = &fieldValue
1856 } else {
1857 // If the value does not match the current common value then there is
1858 // no value in common so break out.
1859 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1860 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001861 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001862 break
1863 }
1864 }
1865 }
1866
Paul Duffin864e1b42020-05-06 10:23:19 +01001867 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001868 // and set the input struct's field to the empty value.
1869 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001870 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001871 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001872 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001873 container := sliceValue.Index(i).Interface().(propertiesContainer)
1874 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001875 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001876 fieldValue.Set(emptyValue)
1877 }
1878 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001879
1880 if valuesDiffer && !property.archVariant {
1881 // The values differ but the property does not support arch variants so it
1882 // is an error.
1883 var details strings.Builder
1884 for i := 0; i < sliceValue.Len(); i++ {
1885 container := sliceValue.Index(i).Interface().(propertiesContainer)
1886 itemValue := reflect.ValueOf(container.optimizableProperties())
1887 fieldValue := fieldGetter(itemValue)
1888
1889 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1890 }
1891
1892 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1893 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001894 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001895
1896 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001897}