blob: e2e59979e15d7c29c83e89446b2a20dc557ac079 [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
Paul Duffin51227d82021-05-18 12:54:27 +0100827 case reflect.Ptr:
828 outputUnnamedValue(contents, value.Elem())
829
Paul Duffina08e4dc2021-06-22 18:19:19 +0100830 case reflect.Slice:
831 length := value.Len()
832 if length == 0 {
833 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100834 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100835 firstValue := value.Index(0)
836 if length == 1 && !multiLineValue(firstValue) {
837 contents.UnindentedPrintf("[")
838 outputUnnamedValue(contents, firstValue)
839 contents.UnindentedPrintf("]")
840 } else {
841 contents.UnindentedPrintf("[\n")
842 contents.Indent()
843 for i := 0; i < length; i++ {
844 itemValue := value.Index(i)
845 contents.IndentedPrintf("")
846 outputUnnamedValue(contents, itemValue)
847 contents.UnindentedPrintf(",\n")
848 }
849 contents.Dedent()
850 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100851 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100852 }
853
Paul Duffin51227d82021-05-18 12:54:27 +0100854 case reflect.Struct:
855 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
856 v := value.Interface()
857 if _, ok := v.(android.BpPrintable); !ok {
858 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
859 }
860 contents.UnindentedPrintf("{\n")
861 contents.Indent()
862 for f := 0; f < valueType.NumField(); f++ {
863 fieldType := valueType.Field(f)
864 if fieldType.Anonymous {
865 continue
866 }
867 fieldValue := value.Field(f)
868 fieldName := fieldType.Name
869 propertyName := proptools.PropertyNameForField(fieldName)
870 outputNamedValue(contents, propertyName, fieldValue)
871 }
872 contents.Dedent()
873 contents.IndentedPrintf("}")
874
Paul Duffina08e4dc2021-06-22 18:19:19 +0100875 default:
876 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
877 }
878}
879
Paul Duffin51227d82021-05-18 12:54:27 +0100880// multiLineValue returns true if the supplied value may require multiple lines in the output.
881func multiLineValue(value reflect.Value) bool {
882 kind := value.Kind()
883 return kind == reflect.Slice || kind == reflect.Struct
884}
885
Paul Duffinac37c502019-11-26 18:02:20 +0000886func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000887 contents := &generatedContents{}
888 generateBpContents(contents, s.builderForTests.bpFile)
889 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000890}
891
Paul Duffind0759072021-02-17 11:23:00 +0000892func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
893 contents := &generatedContents{}
894 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100895 name := module.Name()
896 // Include modules that are either unversioned or have no name.
897 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000898 })
899 return contents.content.String()
900}
901
902func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
903 contents := &generatedContents{}
904 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100905 name := module.Name()
906 // Include modules that are either versioned or have no name.
907 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000908 })
909 return contents.content.String()
910}
911
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000912type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100913 ctx android.ModuleContext
914 sdk *sdk
915
916 // The version of the generated snapshot.
917 //
918 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
919 // this field.
920 version string
921
Paul Duffinb645ec82019-11-27 17:43:54 +0000922 snapshotDir android.OutputPath
923 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000924
925 // Map from destination to source of each copy - used to eliminate duplicates and
926 // detect conflicts.
927 copies map[string]string
928
Paul Duffinb645ec82019-11-27 17:43:54 +0000929 filesToZip android.Paths
930 zipsToMerge android.Paths
931
932 prebuiltModules map[string]*bpModule
933 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000934
935 // The set of all members by name.
936 allMembersByName map[string]struct{}
937
938 // The set of exported members by name.
939 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000940}
941
942func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000943 if existing, ok := s.copies[dest]; ok {
944 if existing != src.String() {
945 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
946 return
947 }
948 } else {
949 path := s.snapshotDir.Join(s.ctx, dest)
950 s.ctx.Build(pctx, android.BuildParams{
951 Rule: android.Cp,
952 Input: src,
953 Output: path,
954 })
955 s.filesToZip = append(s.filesToZip, path)
956
957 s.copies[dest] = src.String()
958 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000959}
960
Paul Duffin91547182019-11-12 19:39:36 +0000961func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
962 ctx := s.ctx
963
964 // Repackage the zip file so that the entries are in the destDir directory.
965 // This will allow the zip file to be merged into the snapshot.
966 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000967
968 ctx.Build(pctx, android.BuildParams{
969 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
970 Rule: repackageZip,
971 Input: zipPath,
972 Output: tmpZipPath,
973 Args: map[string]string{
974 "destdir": destDir,
975 },
976 })
Paul Duffin91547182019-11-12 19:39:36 +0000977
978 // Add the repackaged zip file to the files to merge.
979 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
980}
981
Paul Duffin9d8d6092019-12-05 18:19:29 +0000982func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
983 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000984 if s.prebuiltModules[name] != nil {
985 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
986 }
987
988 m := s.bpFile.newModule(moduleType)
989 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000990
Paul Duffinbefa4b92020-03-04 14:22:45 +0000991 variant := member.Variants()[0]
992
Paul Duffin13f02712020-03-06 12:30:43 +0000993 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000994 // An internal member is only referenced from the sdk snapshot which is in the
995 // same package so can be marked as private.
996 m.AddProperty("visibility", []string{"//visibility:private"})
997 } else {
998 // Extract visibility information from a member variant. All variants have the same
999 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001000 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1001
1002 // Add any additional visibility rules needed for the prebuilts to reference each other.
1003 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1004 if err != nil {
1005 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1006 }
1007
1008 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001009 if len(visibility) != 0 {
1010 m.AddProperty("visibility", visibility)
1011 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001012 }
1013
Martin Stjernholm1e041092020-11-03 00:11:09 +00001014 // Where available copy apex_available properties from the member.
1015 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1016 apexAvailable := apexAware.ApexAvailable()
1017 if len(apexAvailable) == 0 {
1018 // //apex_available:platform is the default.
1019 apexAvailable = []string{android.AvailableToPlatform}
1020 }
1021
1022 // Add in any baseline apex available settings.
1023 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1024
1025 // Remove duplicates and sort.
1026 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1027 sort.Strings(apexAvailable)
1028
1029 m.AddProperty("apex_available", apexAvailable)
1030 }
1031
Paul Duffinb0bb3762021-05-06 16:48:05 +01001032 // The licenses are the same for all variants.
1033 mctx := s.ctx
1034 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1035 if len(licenseInfo.Licenses) > 0 {
1036 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1037 }
1038
Paul Duffin865171e2020-03-02 18:38:15 +00001039 deviceSupported := false
1040 hostSupported := false
1041
1042 for _, variant := range member.Variants() {
1043 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001044 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001045 hostSupported = true
1046 } else if osClass == android.Device {
1047 deviceSupported = true
1048 }
1049 }
1050
1051 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001052
Paul Duffin0cb37b92020-03-04 14:52:46 +00001053 // Disable installation in the versioned module of those modules that are ever installable.
1054 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1055 if installable.EverInstallable() {
1056 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1057 }
1058 }
1059
Paul Duffinb645ec82019-11-27 17:43:54 +00001060 s.prebuiltModules[name] = m
1061 s.prebuiltOrder = append(s.prebuiltOrder, m)
1062 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001063}
1064
Paul Duffin865171e2020-03-02 18:38:15 +00001065func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001066 // If neither device or host is supported then this module does not support either so will not
1067 // recognize the properties.
1068 if !deviceSupported && !hostSupported {
1069 return
1070 }
1071
Paul Duffin865171e2020-03-02 18:38:15 +00001072 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001073 bpModule.AddProperty("device_supported", false)
1074 }
Paul Duffin865171e2020-03-02 18:38:15 +00001075 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001076 bpModule.AddProperty("host_supported", true)
1077 }
1078}
1079
Paul Duffin13f02712020-03-06 12:30:43 +00001080func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1081 if required {
1082 return requiredSdkMemberReferencePropertyTag
1083 } else {
1084 return optionalSdkMemberReferencePropertyTag
1085 }
1086}
1087
1088func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1089 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001090}
1091
Paul Duffinb645ec82019-11-27 17:43:54 +00001092// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001093func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1094 if _, ok := s.allMembersByName[unversionedName]; !ok {
1095 if required {
1096 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1097 }
1098 return unversionedName
1099 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001100 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1101}
Paul Duffinb645ec82019-11-27 17:43:54 +00001102
Paul Duffin13f02712020-03-06 12:30:43 +00001103func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001104 var references []string = nil
1105 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001106 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001107 }
1108 return references
1109}
Paul Duffin13879572019-11-28 14:31:38 +00001110
Paul Duffin72910952020-01-20 18:16:30 +00001111// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001112func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1113 if _, ok := s.allMembersByName[unversionedName]; !ok {
1114 if required {
1115 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1116 }
1117 return unversionedName
1118 }
1119
1120 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001121 return s.ctx.ModuleName() + "_" + unversionedName
1122 } else {
1123 return unversionedName
1124 }
1125}
1126
Paul Duffin13f02712020-03-06 12:30:43 +00001127func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001128 var references []string = nil
1129 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001130 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001131 }
1132 return references
1133}
1134
Paul Duffin13f02712020-03-06 12:30:43 +00001135func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1136 _, ok := s.exportedMembersByName[memberName]
1137 return !ok
1138}
1139
Martin Stjernholm89238f42020-07-10 00:14:03 +01001140// Add the properties from the given SdkMemberProperties to the blueprint
1141// property set. This handles common properties in SdkMemberPropertiesBase and
1142// calls the member-specific AddToPropertySet for the rest.
1143func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1144 if memberProperties.Base().Compile_multilib != "" {
1145 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1146 }
1147
1148 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1149}
1150
Paul Duffin21827262021-04-24 12:16:36 +01001151// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1152type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001153 // The sdk variant that depends (possibly indirectly) on the member variant.
1154 sdkVariant *sdk
Paul Duffin1356d8c2020-02-25 19:26:33 +00001155 memberType android.SdkMemberType
1156 variant android.SdkAware
Paul Duffina7208112021-04-23 21:20:20 +01001157 export bool
Paul Duffin1356d8c2020-02-25 19:26:33 +00001158}
1159
Paul Duffin13879572019-11-28 14:31:38 +00001160var _ android.SdkMember = (*sdkMember)(nil)
1161
Paul Duffin21827262021-04-24 12:16:36 +01001162// sdkMember groups all the variants of a specific member module together along with the name of the
1163// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001164type sdkMember struct {
1165 memberType android.SdkMemberType
1166 name string
1167 variants []android.SdkAware
1168}
1169
1170func (m *sdkMember) Name() string {
1171 return m.name
1172}
1173
1174func (m *sdkMember) Variants() []android.SdkAware {
1175 return m.variants
1176}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001177
Paul Duffin9c3760e2020-03-16 19:52:08 +00001178// Track usages of multilib variants.
1179type multilibUsage int
1180
1181const (
1182 multilibNone multilibUsage = 0
1183 multilib32 multilibUsage = 1
1184 multilib64 multilibUsage = 2
1185 multilibBoth = multilib32 | multilib64
1186)
1187
1188// Add the multilib that is used in the arch type.
1189func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1190 multilib := archType.Multilib
1191 switch multilib {
1192 case "":
1193 return m
1194 case "lib32":
1195 return m | multilib32
1196 case "lib64":
1197 return m | multilib64
1198 default:
1199 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1200 }
1201}
1202
1203func (m multilibUsage) String() string {
1204 switch m {
1205 case multilibNone:
1206 return ""
1207 case multilib32:
1208 return "32"
1209 case multilib64:
1210 return "64"
1211 case multilibBoth:
1212 return "both"
1213 default:
1214 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1215 m, multilibNone, multilib32, multilib64, multilibBoth))
1216 }
1217}
1218
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001219type baseInfo struct {
1220 Properties android.SdkMemberProperties
1221}
1222
Paul Duffinf34f6d82020-04-30 15:48:31 +01001223func (b *baseInfo) optimizableProperties() interface{} {
1224 return b.Properties
1225}
1226
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001227type osTypeSpecificInfo struct {
1228 baseInfo
1229
Paul Duffin00e46802020-03-12 20:40:35 +00001230 osType android.OsType
1231
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001232 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001233 //
1234 // Nil if there is one variant whose arch type is common
1235 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001236}
1237
Paul Duffin4b8b7932020-05-06 12:35:38 +01001238var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1239
Paul Duffinfc8dd232020-03-17 12:51:37 +00001240type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1241
Paul Duffin00e46802020-03-12 20:40:35 +00001242// Create a new osTypeSpecificInfo for the specified os type and its properties
1243// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001244func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001245 osInfo := &osTypeSpecificInfo{
1246 osType: osType,
1247 }
1248
1249 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1250 properties := variantPropertiesFactory()
1251 properties.Base().Os = osType
1252 return properties
1253 }
1254
1255 // Create a structure into which properties common across the architectures in
1256 // this os type will be stored.
1257 osInfo.Properties = osSpecificVariantPropertiesFactory()
1258
1259 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001260 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001261 var archTypes []android.ArchType
1262 for _, variant := range osTypeVariants {
1263 archType := variant.Target().Arch.ArchType
1264 archTypeName := archType.Name
1265 if _, ok := variantsByArchName[archTypeName]; !ok {
1266 archTypes = append(archTypes, archType)
1267 }
1268
1269 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1270 }
1271
1272 if commonVariants, ok := variantsByArchName["common"]; ok {
1273 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001274 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 +00001275 }
1276
1277 // A common arch type only has one variant and its properties should be treated
1278 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001279 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001280 } else {
1281 // Create an arch specific info for each supported architecture type.
1282 for _, archType := range archTypes {
1283 archTypeName := archType.Name
1284
1285 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001286 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001287
1288 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1289 }
1290 }
1291
1292 return osInfo
1293}
1294
1295// Optimize the properties by extracting common properties from arch type specific
1296// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001297func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001298 // Nothing to do if there is only a single common architecture.
1299 if len(osInfo.archInfos) == 0 {
1300 return
1301 }
1302
Paul Duffin9c3760e2020-03-16 19:52:08 +00001303 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001304 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001305 multilib = multilib.addArchType(archInfo.archType)
1306
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001307 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001308 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001309 }
1310
Paul Duffin4b8b7932020-05-06 12:35:38 +01001311 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001312
1313 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001314 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001315}
1316
1317// Add the properties for an os to a property set.
1318//
1319// Maps the properties related to the os variants through to an appropriate
1320// module structure that will produce equivalent set of variants when it is
1321// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001322func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001323
1324 var osPropertySet android.BpPropertySet
1325 var archPropertySet android.BpPropertySet
1326 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001327 if osInfo.Properties.Base().Os_count == 1 &&
1328 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1329 // There is only one OS type present in the variants and it shouldn't have a
1330 // variant-specific target. The latter is the case if it's either for device
1331 // where there is only one OS (android), or for host and the member type
1332 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001333
1334 // Create a structure that looks like:
1335 // module_type {
1336 // name: "...",
1337 // ...
1338 // <common properties>
1339 // ...
1340 // <single os type specific properties>
1341 //
1342 // arch: {
1343 // <arch specific sections>
1344 // }
1345 //
1346 osPropertySet = bpModule
1347 archPropertySet = osPropertySet.AddPropertySet("arch")
1348
1349 // Arch specific properties need to be added to an arch specific section
1350 // within arch.
1351 archOsPrefix = ""
1352 } else {
1353 // Create a structure that looks like:
1354 // module_type {
1355 // name: "...",
1356 // ...
1357 // <common properties>
1358 // ...
1359 // target: {
1360 // <arch independent os specific sections, e.g. android>
1361 // ...
1362 // <arch and os specific sections, e.g. android_x86>
1363 // }
1364 //
1365 osType := osInfo.osType
1366 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1367 archPropertySet = targetPropertySet
1368
1369 // Arch specific properties need to be added to an os and arch specific
1370 // section prefixed with <os>_.
1371 archOsPrefix = osType.Name + "_"
1372 }
1373
1374 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001375 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001376
1377 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1378 // os) specific properties.
1379 //
1380 // The archInfos list will be empty if the os contains variants for the common
1381 // architecture.
1382 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001383 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001384 }
1385}
1386
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001387func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1388 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001389 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001390}
1391
1392var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1393
Paul Duffin4b8b7932020-05-06 12:35:38 +01001394func (osInfo *osTypeSpecificInfo) String() string {
1395 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1396}
1397
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001398type archTypeSpecificInfo struct {
1399 baseInfo
1400
1401 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001402 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001403
1404 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001405}
1406
Paul Duffin4b8b7932020-05-06 12:35:38 +01001407var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1408
Paul Duffinfc8dd232020-03-17 12:51:37 +00001409// Create a new archTypeSpecificInfo for the specified arch type and its properties
1410// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001411func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001412
Paul Duffinfc8dd232020-03-17 12:51:37 +00001413 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001414 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001415
1416 // Create the properties into which the arch type specific properties will be
1417 // added.
1418 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001419
1420 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001421 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001422 } else {
1423 // There is more than one variant for this arch type which must be differentiated
1424 // by link type.
1425 for _, linkVariant := range archVariants {
1426 linkType := getLinkType(linkVariant)
1427 if linkType == "" {
1428 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1429 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001430 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001431
1432 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1433 }
1434 }
1435 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001436
1437 return archInfo
1438}
1439
Paul Duffinf34f6d82020-04-30 15:48:31 +01001440func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1441 return archInfo.Properties
1442}
1443
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001444// Get the link type of the variant
1445//
1446// If the variant is not differentiated by link type then it returns "",
1447// otherwise it returns one of "static" or "shared".
1448func getLinkType(variant android.Module) string {
1449 linkType := ""
1450 if linkable, ok := variant.(cc.LinkableInterface); ok {
1451 if linkable.Shared() && linkable.Static() {
1452 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1453 } else if linkable.Shared() {
1454 linkType = "shared"
1455 } else if linkable.Static() {
1456 linkType = "static"
1457 } else {
1458 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1459 }
1460 }
1461 return linkType
1462}
1463
1464// Optimize the properties by extracting common properties from link type specific
1465// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001466func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001467 if len(archInfo.linkInfos) == 0 {
1468 return
1469 }
1470
Paul Duffin4b8b7932020-05-06 12:35:38 +01001471 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001472}
1473
Paul Duffinfc8dd232020-03-17 12:51:37 +00001474// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001475func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001476 archTypeName := archInfo.archType.Name
1477 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001478 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1479 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1480 archTypePropertySet.AddProperty("enabled", true)
1481 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001482 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001483
1484 for _, linkInfo := range archInfo.linkInfos {
1485 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001486 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001487 }
1488}
1489
Paul Duffin4b8b7932020-05-06 12:35:38 +01001490func (archInfo *archTypeSpecificInfo) String() string {
1491 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1492}
1493
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001494type linkTypeSpecificInfo struct {
1495 baseInfo
1496
1497 linkType string
1498}
1499
Paul Duffin4b8b7932020-05-06 12:35:38 +01001500var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1501
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001502// Create a new linkTypeSpecificInfo for the specified link type and its properties
1503// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001504func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001505 linkInfo := &linkTypeSpecificInfo{
1506 baseInfo: baseInfo{
1507 // Create the properties into which the link type specific properties will be
1508 // added.
1509 Properties: variantPropertiesFactory(),
1510 },
1511 linkType: linkType,
1512 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001513 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001514 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001515}
1516
Paul Duffin4b8b7932020-05-06 12:35:38 +01001517func (l *linkTypeSpecificInfo) String() string {
1518 return fmt.Sprintf("LinkType{%s}", l.linkType)
1519}
1520
Paul Duffin3a4eb502020-03-19 16:11:18 +00001521type memberContext struct {
1522 sdkMemberContext android.ModuleContext
1523 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001524 memberType android.SdkMemberType
1525 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001526}
1527
1528func (m *memberContext) SdkModuleContext() android.ModuleContext {
1529 return m.sdkMemberContext
1530}
1531
1532func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1533 return m.builder
1534}
1535
Paul Duffina551a1c2020-03-17 21:04:24 +00001536func (m *memberContext) MemberType() android.SdkMemberType {
1537 return m.memberType
1538}
1539
1540func (m *memberContext) Name() string {
1541 return m.name
1542}
1543
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001544func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001545
1546 memberType := member.memberType
1547
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001548 // Do not add the prefer property if the member snapshot module is a source module type.
1549 if !memberType.UsesSourceModuleTypeInSnapshot() {
1550 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1551 // snapshot to be created that sets prefer: true.
1552 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1553 // dynamically at build time not at snapshot generation time.
1554 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001555
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001556 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1557 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1558 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1559 // behavior is for the module.
1560 bpModule.insertAfter("name", "prefer", prefer)
1561 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001562
Paul Duffina04c1072020-03-02 10:16:35 +00001563 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001564 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001565 variants := member.Variants()
1566 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001567 osType := variant.Target().Os
1568 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001569 }
1570
Paul Duffina04c1072020-03-02 10:16:35 +00001571 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001572 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001573 properties := memberType.CreateVariantPropertiesStruct()
1574 base := properties.Base()
1575 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001576 return properties
1577 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001578
Paul Duffina04c1072020-03-02 10:16:35 +00001579 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001580
Paul Duffina04c1072020-03-02 10:16:35 +00001581 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001582 commonProperties := variantPropertiesFactory()
1583 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001584
Paul Duffinc097e362020-03-10 22:50:03 +00001585 // Create common value extractor that can be used to optimize the properties.
1586 commonValueExtractor := newCommonValueExtractor(commonProperties)
1587
Paul Duffina04c1072020-03-02 10:16:35 +00001588 // The list of property structures which are os type specific but common across
1589 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001590 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001591
1592 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001593 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001594 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001595 // Add the os specific properties to a list of os type specific yet architecture
1596 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001597 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001598
Paul Duffin00e46802020-03-12 20:40:35 +00001599 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001600 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001601 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001602
Paul Duffina04c1072020-03-02 10:16:35 +00001603 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001604 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001605
Paul Duffina04c1072020-03-02 10:16:35 +00001606 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001607 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001608
Paul Duffina04c1072020-03-02 10:16:35 +00001609 // Create a target property set into which target specific properties can be
1610 // added.
1611 targetPropertySet := bpModule.AddPropertySet("target")
1612
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001613 // If the member is host OS dependent and has host_supported then disable by
1614 // default and enable each host OS variant explicitly. This avoids problems
1615 // with implicitly enabled OS variants when the snapshot is used, which might
1616 // be different from this run (e.g. different build OS).
1617 if ctx.memberType.IsHostOsDependent() {
1618 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1619 if hostSupported {
1620 hostPropertySet := targetPropertySet.AddPropertySet("host")
1621 hostPropertySet.AddProperty("enabled", false)
1622 }
1623 }
1624
Paul Duffina04c1072020-03-02 10:16:35 +00001625 // Iterate over the os types in a fixed order.
1626 for _, osType := range s.getPossibleOsTypes() {
1627 osInfo := osTypeToInfo[osType]
1628 if osInfo == nil {
1629 continue
1630 }
1631
Paul Duffin3a4eb502020-03-19 16:11:18 +00001632 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001633 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001634}
1635
Paul Duffina04c1072020-03-02 10:16:35 +00001636// Compute the list of possible os types that this sdk could support.
1637func (s *sdk) getPossibleOsTypes() []android.OsType {
1638 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001639 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001640 if s.DeviceSupported() {
1641 if osType.Class == android.Device && osType != android.Fuchsia {
1642 osTypes = append(osTypes, osType)
1643 }
1644 }
1645 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001646 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001647 osTypes = append(osTypes, osType)
1648 }
1649 }
1650 }
1651 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1652 return osTypes
1653}
1654
Paul Duffinb28369a2020-05-04 15:39:59 +01001655// Given a set of properties (struct value), return the value of the field within that
1656// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001657type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1658
Paul Duffinc459f892020-04-30 18:08:29 +01001659// Checks the metadata to determine whether the property should be ignored for the
1660// purposes of common value extraction or not.
1661type extractorMetadataPredicate func(metadata propertiesContainer) bool
1662
1663// Indicates whether optimizable properties are provided by a host variant or
1664// not.
1665type isHostVariant interface {
1666 isHostVariant() bool
1667}
1668
Paul Duffinb28369a2020-05-04 15:39:59 +01001669// A property that can be optimized by the commonValueExtractor.
1670type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001671 // The name of the field for this property. It is a "."-separated path for
1672 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001673 name string
1674
Paul Duffinc459f892020-04-30 18:08:29 +01001675 // Filter that can use metadata associated with the properties being optimized
1676 // to determine whether the field should be ignored during common value
1677 // optimization.
1678 filter extractorMetadataPredicate
1679
Paul Duffinb28369a2020-05-04 15:39:59 +01001680 // Retrieves the value on which common value optimization will be performed.
1681 getter fieldAccessorFunc
1682
1683 // The empty value for the field.
1684 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001685
1686 // True if the property can support arch variants false otherwise.
1687 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001688}
1689
Paul Duffin4b8b7932020-05-06 12:35:38 +01001690func (p extractorProperty) String() string {
1691 return p.name
1692}
1693
Paul Duffinc097e362020-03-10 22:50:03 +00001694// Supports extracting common values from a number of instances of a properties
1695// structure into a separate common set of properties.
1696type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001697 // The properties that the extractor can optimize.
1698 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001699}
1700
1701// Create a new common value extractor for the structure type for the supplied
1702// properties struct.
1703//
1704// The returned extractor can be used on any properties structure of the same type
1705// as the supplied set of properties.
1706func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1707 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1708 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001709 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001710 return extractor
1711}
1712
1713// Gather the fields from the supplied structure type from which common values will
1714// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001715//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001716// This is recursive function. If it encounters a struct then it will recurse
1717// into it, passing in the accessor for the field and the struct name as prefix
1718// for the nested fields. That will then be used in the accessors for the fields
1719// in the embedded struct.
1720func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001721 for f := 0; f < structType.NumField(); f++ {
1722 field := structType.Field(f)
1723 if field.PkgPath != "" {
1724 // Ignore unexported fields.
1725 continue
1726 }
1727
Paul Duffinb07fa512020-03-10 22:17:04 +00001728 // Ignore fields whose value should be kept.
1729 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001730 continue
1731 }
1732
Paul Duffinc459f892020-04-30 18:08:29 +01001733 var filter extractorMetadataPredicate
1734
1735 // Add a filter
1736 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1737 filter = func(metadata propertiesContainer) bool {
1738 if m, ok := metadata.(isHostVariant); ok {
1739 if m.isHostVariant() {
1740 return false
1741 }
1742 }
1743 return true
1744 }
1745 }
1746
Paul Duffinc097e362020-03-10 22:50:03 +00001747 // Save a copy of the field index for use in the function.
1748 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001749
Martin Stjernholmb0249572020-09-15 02:32:35 +01001750 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001751
Paul Duffinc097e362020-03-10 22:50:03 +00001752 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001753 if containingStructAccessor != nil {
1754 // This is an embedded structure so first access the field for the embedded
1755 // structure.
1756 value = containingStructAccessor(value)
1757 }
1758
Paul Duffinc097e362020-03-10 22:50:03 +00001759 // Skip through interface and pointer values to find the structure.
1760 value = getStructValue(value)
1761
Paul Duffin4b8b7932020-05-06 12:35:38 +01001762 defer func() {
1763 if r := recover(); r != nil {
1764 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1765 }
1766 }()
1767
Paul Duffinc097e362020-03-10 22:50:03 +00001768 // Return the field.
1769 return value.Field(fieldIndex)
1770 }
1771
Martin Stjernholmb0249572020-09-15 02:32:35 +01001772 if field.Type.Kind() == reflect.Struct {
1773 // Gather fields from the nested or embedded structure.
1774 var subNamePrefix string
1775 if field.Anonymous {
1776 subNamePrefix = namePrefix
1777 } else {
1778 subNamePrefix = name + "."
1779 }
1780 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001781 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001782 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001783 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001784 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001785 fieldGetter,
1786 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001787 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001788 }
1789 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001790 }
Paul Duffinc097e362020-03-10 22:50:03 +00001791 }
1792}
1793
1794func getStructValue(value reflect.Value) reflect.Value {
1795foundStruct:
1796 for {
1797 kind := value.Kind()
1798 switch kind {
1799 case reflect.Interface, reflect.Ptr:
1800 value = value.Elem()
1801 case reflect.Struct:
1802 break foundStruct
1803 default:
1804 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1805 }
1806 }
1807 return value
1808}
1809
Paul Duffinf34f6d82020-04-30 15:48:31 +01001810// A container of properties to be optimized.
1811//
1812// Allows additional information to be associated with the properties, e.g. for
1813// filtering.
1814type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001815 fmt.Stringer
1816
Paul Duffinf34f6d82020-04-30 15:48:31 +01001817 // Get the properties that need optimizing.
1818 optimizableProperties() interface{}
1819}
1820
Paul Duffin2d1bb892021-04-24 11:32:59 +01001821// A wrapper for sdk variant related properties to allow them to be optimized.
1822type sdkVariantPropertiesContainer struct {
1823 sdkVariant *sdk
1824 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001825}
1826
Paul Duffin2d1bb892021-04-24 11:32:59 +01001827func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1828 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001829}
1830
Paul Duffin2d1bb892021-04-24 11:32:59 +01001831func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001832 return c.sdkVariant.String()
1833}
1834
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001835// Extract common properties from a slice of property structures of the same type.
1836//
1837// All the property structures must be of the same type.
1838// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001839// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001840//
1841// Iterates over each exported field (capitalized name) and checks to see whether they
1842// have the same value (using DeepEquals) across all the input properties. If it does not then no
1843// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001844// and the field in each of the input properties structure is set to its default value. Nested
1845// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001846func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001847 commonPropertiesValue := reflect.ValueOf(commonProperties)
1848 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001849
Paul Duffinf34f6d82020-04-30 15:48:31 +01001850 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1851
Paul Duffinb28369a2020-05-04 15:39:59 +01001852 for _, property := range e.properties {
1853 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001854 filter := property.filter
1855 if filter == nil {
1856 filter = func(metadata propertiesContainer) bool {
1857 return true
1858 }
1859 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001860
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001861 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001862 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1863 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001864 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001865
Paul Duffin864e1b42020-05-06 10:23:19 +01001866 // Assume that all the values will be the same.
1867 //
1868 // While similar to this is not quite the same as commonValue == nil. If all the values
1869 // have been filtered out then this will be false but commonValue == nil will be true.
1870 valuesDiffer := false
1871
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
Paul Duffinc459f892020-04-30 18:08:29 +01001877 if !filter(container) {
1878 expectedValue := property.emptyValue.Interface()
1879 actualValue := fieldValue.Interface()
1880 if !reflect.DeepEqual(expectedValue, actualValue) {
1881 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1882 }
1883 continue
1884 }
1885
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001886 if commonValue == nil {
1887 // Use the first value as the commonProperties value.
1888 commonValue = &fieldValue
1889 } else {
1890 // If the value does not match the current common value then there is
1891 // no value in common so break out.
1892 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1893 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001894 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001895 break
1896 }
1897 }
1898 }
1899
Paul Duffin864e1b42020-05-06 10:23:19 +01001900 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001901 // and set the input struct's field to the empty value.
1902 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001903 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001904 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001905 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001906 container := sliceValue.Index(i).Interface().(propertiesContainer)
1907 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001908 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001909 fieldValue.Set(emptyValue)
1910 }
1911 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001912
1913 if valuesDiffer && !property.archVariant {
1914 // The values differ but the property does not support arch variants so it
1915 // is an error.
1916 var details strings.Builder
1917 for i := 0; i < sliceValue.Len(); i++ {
1918 container := sliceValue.Index(i).Interface().(propertiesContainer)
1919 itemValue := reflect.ValueOf(container.optimizableProperties())
1920 fieldValue := fieldGetter(itemValue)
1921
1922 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1923 }
1924
1925 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1926 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001927 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001928
1929 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001930}