blob: 13c24844cc8abe21e54b3105cb3fef5221e37341 [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"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
Paul Duffin64fb5262021-05-05 21:36:04 +010031// Environment variables that affect the generated snapshot
32// ========================================================
33//
34// SOONG_SDK_SNAPSHOT_PREFER
35// By default every unversioned module in the generated snapshot has prefer: false. Building it
36// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
37//
Paul Duffin973bedb2021-05-05 22:00:51 +010038// SOONG_SDK_SNAPSHOT_VERSION
39// This provides control over the version of the generated snapshot.
40//
41// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
42// versioned snapshot module. This is the default behavior. The zip file containing the
43// generated snapshot will be <sdk-name>-current.zip.
44//
45// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
46// file containing the generated snapshot will be <sdk-name>.zip.
47//
48// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
49// snapshot module only. The zip file containing the generated snapshot will be
50// <sdk-name>-<number>.zip.
51//
Paul Duffin64fb5262021-05-05 21:36:04 +010052
Jiyong Park9b409bc2019-10-11 14:59:13 +090053var pctx = android.NewPackageContext("android/soong/sdk")
54
Paul Duffin375058f2019-11-29 20:17:53 +000055var (
56 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
57 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000058 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000059 CommandDeps: []string{
60 "${config.Zip2ZipCmd}",
61 },
62 },
63 "destdir")
64
65 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
66 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070067 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000068 CommandDeps: []string{
69 "${config.SoongZipCmd}",
70 },
71 Rspfile: "$out.rsp",
72 RspfileContent: "$in",
73 },
74 "basedir")
75
76 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
77 blueprint.RuleParams{
78 Command: `${config.MergeZipsCmd} $out $in`,
79 CommandDeps: []string{
80 "${config.MergeZipsCmd}",
81 },
82 })
83)
84
Paul Duffin973bedb2021-05-05 22:00:51 +010085const (
86 soongSdkSnapshotVersionUnversioned = "unversioned"
87 soongSdkSnapshotVersionCurrent = "current"
88)
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090091 content strings.Builder
92 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090093}
94
Paul Duffinb645ec82019-11-27 17:43:54 +000095// generatedFile abstracts operations for writing contents into a file and emit a build rule
96// for the file.
97type generatedFile struct {
98 generatedContents
99 path android.OutputPath
100}
101
Jiyong Park232e7852019-11-04 12:23:40 +0900102func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900103 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000104 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900105 }
106}
107
Paul Duffinb645ec82019-11-27 17:43:54 +0000108func (gc *generatedContents) Indent() {
109 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900110}
111
Paul Duffinb645ec82019-11-27 17:43:54 +0000112func (gc *generatedContents) Dedent() {
113 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900114}
115
Paul Duffinb645ec82019-11-27 17:43:54 +0000116func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +0100117 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900118}
119
120func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800121 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100122
123 content := gf.content.String()
124
125 // ninja consumes newline characters in rspfile_content. Prevent it by
126 // escaping the backslash in the newline character. The extra backslash
127 // is removed when the rspfile is written to the actual script file
128 content = strings.ReplaceAll(content, "\n", "\\n")
129
Jiyong Park9b409bc2019-10-11 14:59:13 +0900130 rb.Command().
131 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100132 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100133 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900134 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
135 rb.Command().
136 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800137 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900138}
139
Paul Duffin13879572019-11-28 14:31:38 +0000140// Collect all the members.
141//
Paul Duffina1aa7382021-04-29 21:50:40 +0100142// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
143// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000144func (s *sdk) collectMembers(ctx android.ModuleContext) {
145 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000146 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
147 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000148 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100149 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900150
Paul Duffin13879572019-11-28 14:31:38 +0000151 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000152 if !memberType.IsInstance(child) {
153 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900154 }
Paul Duffin13879572019-11-28 14:31:38 +0000155
Paul Duffin6a7e9532020-03-20 17:50:07 +0000156 // Keep track of which multilib variants are used by the sdk.
157 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
158
Paul Duffina1aa7382021-04-29 21:50:40 +0100159 var exportedComponentsInfo android.ExportedComponentsInfo
160 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
161 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
162 }
163
Paul Duffina7208112021-04-23 21:20:20 +0100164 export := memberTag.ExportMember()
Paul Duffina1aa7382021-04-29 21:50:40 +0100165 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
166 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
167 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000168
Paul Duffin2d3da312021-05-06 12:02:27 +0100169 // Recurse down into the member's dependencies as it may have dependencies that need to be
170 // automatically added to the sdk.
171 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900172 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000173
174 return false
Paul Duffin13879572019-11-28 14:31:38 +0000175 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000176}
177
Paul Duffincc3132e2021-04-24 01:10:30 +0100178// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
179// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000180//
Paul Duffincc3132e2021-04-24 01:10:30 +0100181// The sdkMember instances are then grouped into slices by member type. Within each such slice the
182// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000183//
Paul Duffincc3132e2021-04-24 01:10:30 +0100184// Finally, the member type slices are concatenated together to form a single slice. The order in
185// which they are concatenated is the order in which the member types were registered in the
186// android.SdkMemberTypesRegistry.
187func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000188 byType := make(map[android.SdkMemberType][]*sdkMember)
189 byName := make(map[string]*sdkMember)
190
Paul Duffin21827262021-04-24 12:16:36 +0100191 for _, memberVariantDep := range memberVariantDeps {
192 memberType := memberVariantDep.memberType
193 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000194
195 name := ctx.OtherModuleName(variant)
196 member := byName[name]
197 if member == nil {
198 member = &sdkMember{memberType: memberType, name: name}
199 byName[name] = member
200 byType[memberType] = append(byType[memberType], member)
201 }
202
Paul Duffin1356d8c2020-02-25 19:26:33 +0000203 // Only append new variants to the list. This is needed because a member can be both
204 // exported by the sdk and also be a transitive sdk member.
205 member.variants = appendUniqueVariants(member.variants, variant)
206 }
207
Paul Duffin13879572019-11-28 14:31:38 +0000208 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000209 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000210 membersOfType := byType[memberListProperty.memberType]
211 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900212 }
213
Paul Duffin6a7e9532020-03-20 17:50:07 +0000214 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900215}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900216
Paul Duffin72910952020-01-20 18:16:30 +0000217func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
218 for _, v := range variants {
219 if v == newVariant {
220 return variants
221 }
222 }
223 return append(variants, newVariant)
224}
225
Jiyong Park73c54ee2019-10-22 20:31:18 +0900226// SDK directory structure
227// <sdk_root>/
228// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
229// <api_ver>/ : below this directory are all auto-generated
230// Android.bp : definition of 'sdk_snapshot' module is here
231// aidl/
232// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
233// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900234// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900235// include/
236// bionic/libc/include/stdlib.h : an exported header file
237// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900238// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900239// <arch>/include/ : arch-specific exported headers
240// <arch>/include_gen/ : arch-specific generated headers
241// <arch>/lib/
242// libFoo.so : a stub library
243
Jiyong Park232e7852019-11-04 12:23:40 +0900244// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900245// This isn't visible to users, so could be changed in future.
246func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
247 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
248}
249
Jiyong Park232e7852019-11-04 12:23:40 +0900250// buildSnapshot is the main function in this source file. It creates rules to copy
251// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000252func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
253
Paul Duffina1aa7382021-04-29 21:50:40 +0100254 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100255 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100256 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000257 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100258 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffina1aa7382021-04-29 21:50:40 +0100259 }
Paul Duffin865171e2020-03-02 18:38:15 +0000260
Paul Duffina1aa7382021-04-29 21:50:40 +0100261 // Filter out any sdkMemberVariantDep that is a component of another.
262 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000263
Paul Duffina1aa7382021-04-29 21:50:40 +0100264 // Record the names of all the members, both explicitly specified and implicitly
265 // included.
266 allMembersByName := make(map[string]struct{})
267 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100268
Paul Duffina1aa7382021-04-29 21:50:40 +0100269 addMember := func(name string, export bool) {
270 allMembersByName[name] = struct{}{}
271 if export {
272 exportedMembersByName[name] = struct{}{}
273 }
274 }
275
276 for _, memberVariantDep := range memberVariantDeps {
277 name := memberVariantDep.variant.Name()
278 export := memberVariantDep.export
279
280 addMember(name, export)
281
282 // Add any components provided by the module.
283 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
284 addMember(component, export)
285 }
286
287 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
288 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000289 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000290 }
291
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000292 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900293
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000294 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000295
296 bpFile := &bpFile{
297 modules: make(map[string]*bpModule),
298 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000299
Paul Duffin973bedb2021-05-05 22:00:51 +0100300 config := ctx.Config()
301 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
302
303 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
304 generateVersioned := version != soongSdkSnapshotVersionUnversioned
305
306 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
307 //
308 // Unversioned modules are not required in that case because the numbered version will be a
309 // finalized version of the snapshot that is intended to be kept separate from the
310 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
311 snapshotZipFileSuffix := ""
312 if generateVersioned {
313 snapshotZipFileSuffix = "-" + version
314 }
315
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000316 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000317 ctx: ctx,
318 sdk: s,
Paul Duffin973bedb2021-05-05 22:00:51 +0100319 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000320 snapshotDir: snapshotDir.OutputPath,
321 copies: make(map[string]string),
322 filesToZip: []android.Path{bp.path},
323 bpFile: bpFile,
324 prebuiltModules: make(map[string]*bpModule),
325 allMembersByName: allMembersByName,
326 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900327 }
Paul Duffinac37c502019-11-26 18:02:20 +0000328 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900329
Paul Duffin62131702021-05-07 01:10:01 +0100330 // If the sdk snapshot includes any license modules then add a package module which has a
331 // default_applicable_licenses property. That will prevent the LSC license process from updating
332 // the generated Android.bp file to add a package module that includes all licenses used by all
333 // the modules in that package. That would be unnecessary as every module in the sdk should have
334 // their own licenses property specified.
335 if hasLicenses {
336 pkg := bpFile.newModule("package")
337 property := "default_applicable_licenses"
338 pkg.AddCommentForProperty(property, `
339A default list here prevents the license LSC from adding its own list which would
340be unnecessary as every module in the sdk already has its own licenses property.
341`)
342 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
343 bpFile.AddModule(pkg)
344 }
345
Paul Duffin0df49682021-05-07 01:10:01 +0100346 // Group the variants for each member module together and then group the members of each member
347 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100348 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100349
350 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000351 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000352 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000353
Paul Duffina551a1c2020-03-17 21:04:24 +0000354 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000355
356 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100357 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900358 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900359
Paul Duffine6c0d842020-01-15 14:08:51 +0000360 // Create a transformer that will transform an unversioned module into a versioned module.
361 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
362
Paul Duffin72910952020-01-20 18:16:30 +0000363 // Create a transformer that will transform an unversioned module by replacing any references
364 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100365 unversionedTransformer := unversionedTransformation{
366 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100367 }
Paul Duffin72910952020-01-20 18:16:30 +0000368
Paul Duffinb645ec82019-11-27 17:43:54 +0000369 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000370 // Prune any empty property sets.
371 unversioned = unversioned.transform(pruneEmptySetTransformer{})
372
Paul Duffin973bedb2021-05-05 22:00:51 +0100373 if generateVersioned {
374 // Copy the unversioned module so it can be modified to make it versioned.
375 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000376
Paul Duffin973bedb2021-05-05 22:00:51 +0100377 // Transform the unversioned module into a versioned one.
378 versioned.transform(unversionedToVersionedTransformer)
379 bpFile.AddModule(versioned)
380 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000381
Paul Duffin973bedb2021-05-05 22:00:51 +0100382 if generateUnversioned {
383 // Transform the unversioned module to make it suitable for use in the snapshot.
384 unversioned.transform(unversionedTransformer)
385 bpFile.AddModule(unversioned)
386 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000387 }
388
Paul Duffin973bedb2021-05-05 22:00:51 +0100389 if generateVersioned {
390 // Add the sdk/module_exports_snapshot module to the bp file.
391 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
392 }
Paul Duffin26197a62021-04-24 00:34:10 +0100393
394 // generate Android.bp
395 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
396 generateBpContents(&bp.generatedContents, bpFile)
397
398 contents := bp.content.String()
399 syntaxCheckSnapshotBpFile(ctx, contents)
400
401 bp.build(pctx, ctx, nil)
402
403 filesToZip := builder.filesToZip
404
405 // zip them all
Paul Duffin973bedb2021-05-05 22:00:51 +0100406 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
407 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100408 outputDesc := "Building snapshot for " + ctx.ModuleName()
409
410 // If there are no zips to merge then generate the output zip directly.
411 // Otherwise, generate an intermediate zip file into which other zips can be
412 // merged.
413 var zipFile android.OutputPath
414 var desc string
415 if len(builder.zipsToMerge) == 0 {
416 zipFile = outputZipFile
417 desc = outputDesc
418 } else {
Paul Duffin973bedb2021-05-05 22:00:51 +0100419 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
420 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100421 desc = "Building intermediate snapshot for " + ctx.ModuleName()
422 }
423
424 ctx.Build(pctx, android.BuildParams{
425 Description: desc,
426 Rule: zipFiles,
427 Inputs: filesToZip,
428 Output: zipFile,
429 Args: map[string]string{
430 "basedir": builder.snapshotDir.String(),
431 },
432 })
433
434 if len(builder.zipsToMerge) != 0 {
435 ctx.Build(pctx, android.BuildParams{
436 Description: outputDesc,
437 Rule: mergeZips,
438 Input: zipFile,
439 Inputs: builder.zipsToMerge,
440 Output: outputZipFile,
441 })
442 }
443
444 return outputZipFile
445}
446
Paul Duffina1aa7382021-04-29 21:50:40 +0100447// filterOutComponents removes any item from the deps list that is a component of another item in
448// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
449// then it will remove "foo.stubs" from the deps.
450func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
451 // Collate the set of components that all the modules added to the sdk provide.
452 components := map[string]*sdkMemberVariantDep{}
453 for i, _ := range deps {
454 dep := &deps[i]
455 for _, c := range dep.exportedComponentsInfo.Components {
456 components[c] = dep
457 }
458 }
459
460 // If no module provides components then return the input deps unfiltered.
461 if len(components) == 0 {
462 return deps
463 }
464
465 filtered := make([]sdkMemberVariantDep, 0, len(deps))
466 for _, dep := range deps {
467 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
468 if owner, ok := components[name]; ok {
469 // This is a component of another module that is a member of the sdk.
470
471 // If the component is exported but the owning module is not then the configuration is not
472 // supported.
473 if dep.export && !owner.export {
474 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
475 continue
476 }
477
478 // This module must not be added to the list of members of the sdk as that would result in a
479 // duplicate module in the sdk snapshot.
480 continue
481 }
482
483 filtered = append(filtered, dep)
484 }
485 return filtered
486}
487
Paul Duffin26197a62021-04-24 00:34:10 +0100488// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100489func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100490 bpFile := builder.bpFile
491
Paul Duffinb645ec82019-11-27 17:43:54 +0000492 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000493 var snapshotModuleType string
494 if s.properties.Module_exports {
495 snapshotModuleType = "module_exports_snapshot"
496 } else {
497 snapshotModuleType = "sdk_snapshot"
498 }
499 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000500 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000501
502 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100503 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000504 if len(visibility) != 0 {
505 snapshotModule.AddProperty("visibility", visibility)
506 }
507
Paul Duffin865171e2020-03-02 18:38:15 +0000508 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000509
Paul Duffincd064672021-04-24 00:47:29 +0100510 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100511 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000512
Paul Duffin2d1bb892021-04-24 11:32:59 +0100513 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100514
Paul Duffin6a7e9532020-03-20 17:50:07 +0000515 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100516
Paul Duffin2d1bb892021-04-24 11:32:59 +0100517 // Create a mapping from osType to combined properties.
518 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
519 for _, combined := range combinedPropertiesList {
520 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
521 }
522
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100523 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000524 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100525 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100526 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000527
Paul Duffin2d1bb892021-04-24 11:32:59 +0100528 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000529 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000530 }
Paul Duffin865171e2020-03-02 18:38:15 +0000531
Jiyong Park8fe14e62020-10-19 22:47:34 +0900532 // If host is supported and any member is host OS dependent then disable host
533 // by default, so that we can enable each host OS variant explicitly. This
534 // avoids problems with implicitly enabled OS variants when the snapshot is
535 // used, which might be different from this run (e.g. different build OS).
536 if s.HostSupported() {
537 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100538 for _, memberVariantDep := range memberVariantDeps {
539 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
540 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900541 if !android.InList(targetString, supportedHostTargets) {
542 supportedHostTargets = append(supportedHostTargets, targetString)
543 }
544 }
545 }
546 if len(supportedHostTargets) > 0 {
547 hostPropertySet := targetPropertySet.AddPropertySet("host")
548 hostPropertySet.AddProperty("enabled", false)
549 }
550 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
551 for _, hostTarget := range supportedHostTargets {
552 propertySet := targetPropertySet.AddPropertySet(hostTarget)
553 propertySet.AddProperty("enabled", true)
554 }
555 }
556
Paul Duffin865171e2020-03-02 18:38:15 +0000557 // Prune any empty property sets.
558 snapshotModule.transform(pruneEmptySetTransformer{})
559
Paul Duffinb645ec82019-11-27 17:43:54 +0000560 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900561}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000562
Paul Duffinf88d8e02020-05-07 20:21:34 +0100563// Check the syntax of the generated Android.bp file contents and if they are
564// invalid then log an error with the contents (tagged with line numbers) and the
565// errors that were found so that it is easy to see where the problem lies.
566func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
567 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
568 if len(errs) != 0 {
569 message := &strings.Builder{}
570 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
571
572Generated Android.bp contents
573========================================================================
574`)
575 for i, line := range strings.Split(contents, "\n") {
576 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
577 }
578
579 _, _ = fmt.Fprint(message, `
580========================================================================
581
582Errors found:
583`)
584
585 for _, err := range errs {
586 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
587 }
588
589 ctx.ModuleErrorf("%s", message.String())
590 }
591}
592
Paul Duffin4b8b7932020-05-06 12:35:38 +0100593func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
594 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
595 if err != nil {
596 ctx.ModuleErrorf("error extracting common properties: %s", err)
597 }
598}
599
Paul Duffinfbe470e2021-04-24 12:37:13 +0100600// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
601type snapshotModuleStaticProperties struct {
602 Compile_multilib string `android:"arch_variant"`
603}
604
Paul Duffin2d1bb892021-04-24 11:32:59 +0100605// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
606type combinedSnapshotModuleProperties struct {
607 // The sdk variant from which this information was collected.
608 sdkVariant *sdk
609
610 // Static snapshot module properties.
611 staticProperties *snapshotModuleStaticProperties
612
613 // The dynamically generated member list properties.
614 dynamicProperties interface{}
615}
616
617// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100618func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
619 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100620 var list []*combinedSnapshotModuleProperties
621 for _, sdkVariant := range sdkVariants {
622 staticProperties := &snapshotModuleStaticProperties{
623 Compile_multilib: sdkVariant.multilibUsages.String(),
624 }
Paul Duffincd064672021-04-24 00:47:29 +0100625 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100626
Paul Duffincd064672021-04-24 00:47:29 +0100627 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100628 sdkVariant: sdkVariant,
629 staticProperties: staticProperties,
630 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100631 }
632 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
633
634 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100635 }
Paul Duffincd064672021-04-24 00:47:29 +0100636
637 for _, memberVariantDep := range memberVariantDeps {
638 // If the member dependency is internal then do not add the dependency to the snapshot member
639 // list properties.
640 if !memberVariantDep.export {
641 continue
642 }
643
644 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100645 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100646 memberName := ctx.OtherModuleName(memberVariantDep.variant)
647
Paul Duffin13082052021-05-11 00:31:38 +0100648 if memberListProperty.getter == nil {
649 continue
650 }
651
Paul Duffincd064672021-04-24 00:47:29 +0100652 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100653 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100654 if !android.InList(memberName, memberList) {
655 memberList = append(memberList, memberName)
656 }
Paul Duffin13082052021-05-11 00:31:38 +0100657 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100658 }
659
Paul Duffin2d1bb892021-04-24 11:32:59 +0100660 return list
661}
662
663func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
664
665 // Extract the dynamic properties and add them to a list of propertiesContainer.
666 propertyContainers := []propertiesContainer{}
667 for _, i := range list {
668 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
669 sdkVariant: i.sdkVariant,
670 properties: i.dynamicProperties,
671 })
672 }
673
674 // Extract the common members, removing them from the original properties.
675 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
676 extractor := newCommonValueExtractor(commonDynamicProperties)
677 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
678
679 // Extract the static properties and add them to a list of propertiesContainer.
680 propertyContainers = []propertiesContainer{}
681 for _, i := range list {
682 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
683 sdkVariant: i.sdkVariant,
684 properties: i.staticProperties,
685 })
686 }
687
688 commonStaticProperties := &snapshotModuleStaticProperties{}
689 extractor = newCommonValueExtractor(commonStaticProperties)
690 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
691
692 return &combinedSnapshotModuleProperties{
693 sdkVariant: nil,
694 staticProperties: commonStaticProperties,
695 dynamicProperties: commonDynamicProperties,
696 }
697}
698
699func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
700 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100701 multilib := staticProperties.Compile_multilib
702 if multilib != "" && multilib != "both" {
703 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
704 propertySet.AddProperty("compile_multilib", multilib)
705 }
706
Paul Duffin2d1bb892021-04-24 11:32:59 +0100707 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000708 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100709 if memberListProperty.getter == nil {
710 continue
711 }
Paul Duffin865171e2020-03-02 18:38:15 +0000712 names := memberListProperty.getter(dynamicMemberTypeListProperties)
713 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000714 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000715 }
716 }
717}
718
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000719type propertyTag struct {
720 name string
721}
722
Paul Duffin0cb37b92020-03-04 14:52:46 +0000723// A BpPropertyTag to add to a property that contains references to other sdk members.
724//
725// This will cause the references to be rewritten to a versioned reference in the version
726// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000727var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000728var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000729
Paul Duffin0cb37b92020-03-04 14:52:46 +0000730// A BpPropertyTag that indicates the property should only be present in the versioned
731// module.
732//
733// This will cause the property to be removed from the unversioned instance of a
734// snapshot module.
735var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
736
Paul Duffine6c0d842020-01-15 14:08:51 +0000737type unversionedToVersionedTransformation struct {
738 identityTransformation
739 builder *snapshotBuilder
740}
741
Paul Duffine6c0d842020-01-15 14:08:51 +0000742func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
743 // Use a versioned name for the module but remember the original name for the
744 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100745 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000746 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000747 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100748 // Remove the prefer property if present as versioned modules never need marking with prefer.
749 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000750 return module
751}
752
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000753func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000754 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
755 required := tag == requiredSdkMemberReferencePropertyTag
756 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000757 } else {
758 return value, tag
759 }
760}
761
Paul Duffin72910952020-01-20 18:16:30 +0000762type unversionedTransformation struct {
763 identityTransformation
764 builder *snapshotBuilder
765}
766
767func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
768 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100769 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000770 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000771 return module
772}
773
774func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000775 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
776 required := tag == requiredSdkMemberReferencePropertyTag
777 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000778 } else if tag == sdkVersionedOnlyPropertyTag {
779 // The property is not allowed in the unversioned module so remove it.
780 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000781 } else {
782 return value, tag
783 }
784}
785
Paul Duffina78f3a72020-02-21 16:29:35 +0000786type pruneEmptySetTransformer struct {
787 identityTransformation
788}
789
790var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
791
792func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
793 if len(propertySet.properties) == 0 {
794 return nil, nil
795 } else {
796 return propertySet, tag
797 }
798}
799
Paul Duffinb645ec82019-11-27 17:43:54 +0000800func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000801 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
802 return true
803 })
804}
805
806func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000807 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
808 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000809 if moduleFilter(bpModule) {
810 contents.Printfln("")
811 contents.Printfln("%s {", bpModule.moduleType)
812 outputPropertySet(contents, bpModule.bpPropertySet)
813 contents.Printfln("}")
814 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000815 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000816}
817
818func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
819 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000820
Paul Duffin0df49682021-05-07 01:10:01 +0100821 addComment := func(name string) {
822 if text, ok := set.comments[name]; ok {
823 for _, line := range strings.Split(text, "\n") {
824 contents.Printfln("// %s", line)
825 }
826 }
827 }
828
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000829 // Output the properties first, followed by the nested sets. This ensures a
830 // consistent output irrespective of whether property sets are created before
831 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000832 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000833 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000834
Paul Duffin0df49682021-05-07 01:10:01 +0100835 // Do not write property sets in the properties phase.
836 if _, ok := value.(*bpPropertySet); ok {
837 continue
838 }
839
840 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000841 switch v := value.(type) {
842 case []string:
843 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000844 if length > 1 {
845 contents.Printfln("%s: [", name)
846 contents.Indent()
847 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000848 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000849 }
850 contents.Dedent()
851 contents.Printfln("],")
852 } else if length == 0 {
853 contents.Printfln("%s: [],", name)
854 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000855 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000856 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000857
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000858 case bool:
859 contents.Printfln("%s: %t,", name, v)
860
Paul Duffinb645ec82019-11-27 17:43:54 +0000861 default:
862 contents.Printfln("%s: %q,", name, value)
863 }
864 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000865
866 for _, name := range set.order {
867 value := set.getValue(name)
868
869 // Only write property sets in the sets phase.
870 switch v := value.(type) {
871 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100872 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000873 contents.Printfln("%s: {", name)
874 outputPropertySet(contents, v)
875 contents.Printfln("},")
876 }
877 }
878
Paul Duffinb645ec82019-11-27 17:43:54 +0000879 contents.Dedent()
880}
881
Paul Duffinac37c502019-11-26 18:02:20 +0000882func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000883 contents := &generatedContents{}
884 generateBpContents(contents, s.builderForTests.bpFile)
885 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000886}
887
Paul Duffind0759072021-02-17 11:23:00 +0000888func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
889 contents := &generatedContents{}
890 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100891 name := module.Name()
892 // Include modules that are either unversioned or have no name.
893 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000894 })
895 return contents.content.String()
896}
897
898func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
899 contents := &generatedContents{}
900 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100901 name := module.Name()
902 // Include modules that are either versioned or have no name.
903 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000904 })
905 return contents.content.String()
906}
907
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000908type snapshotBuilder struct {
Paul Duffin973bedb2021-05-05 22:00:51 +0100909 ctx android.ModuleContext
910 sdk *sdk
911
912 // The version of the generated snapshot.
913 //
914 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
915 // this field.
916 version string
917
Paul Duffinb645ec82019-11-27 17:43:54 +0000918 snapshotDir android.OutputPath
919 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000920
921 // Map from destination to source of each copy - used to eliminate duplicates and
922 // detect conflicts.
923 copies map[string]string
924
Paul Duffinb645ec82019-11-27 17:43:54 +0000925 filesToZip android.Paths
926 zipsToMerge android.Paths
927
928 prebuiltModules map[string]*bpModule
929 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000930
931 // The set of all members by name.
932 allMembersByName map[string]struct{}
933
934 // The set of exported members by name.
935 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000936}
937
938func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000939 if existing, ok := s.copies[dest]; ok {
940 if existing != src.String() {
941 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
942 return
943 }
944 } else {
945 path := s.snapshotDir.Join(s.ctx, dest)
946 s.ctx.Build(pctx, android.BuildParams{
947 Rule: android.Cp,
948 Input: src,
949 Output: path,
950 })
951 s.filesToZip = append(s.filesToZip, path)
952
953 s.copies[dest] = src.String()
954 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000955}
956
Paul Duffin91547182019-11-12 19:39:36 +0000957func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
958 ctx := s.ctx
959
960 // Repackage the zip file so that the entries are in the destDir directory.
961 // This will allow the zip file to be merged into the snapshot.
962 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000963
964 ctx.Build(pctx, android.BuildParams{
965 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
966 Rule: repackageZip,
967 Input: zipPath,
968 Output: tmpZipPath,
969 Args: map[string]string{
970 "destdir": destDir,
971 },
972 })
Paul Duffin91547182019-11-12 19:39:36 +0000973
974 // Add the repackaged zip file to the files to merge.
975 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
976}
977
Paul Duffin9d8d6092019-12-05 18:19:29 +0000978func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
979 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000980 if s.prebuiltModules[name] != nil {
981 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
982 }
983
984 m := s.bpFile.newModule(moduleType)
985 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000986
Paul Duffinbefa4b92020-03-04 14:22:45 +0000987 variant := member.Variants()[0]
988
Paul Duffin13f02712020-03-06 12:30:43 +0000989 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000990 // An internal member is only referenced from the sdk snapshot which is in the
991 // same package so can be marked as private.
992 m.AddProperty("visibility", []string{"//visibility:private"})
993 } else {
994 // Extract visibility information from a member variant. All variants have the same
995 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100996 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
997
998 // Add any additional visibility rules needed for the prebuilts to reference each other.
999 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1000 if err != nil {
1001 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1002 }
1003
1004 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001005 if len(visibility) != 0 {
1006 m.AddProperty("visibility", visibility)
1007 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001008 }
1009
Martin Stjernholm1e041092020-11-03 00:11:09 +00001010 // Where available copy apex_available properties from the member.
1011 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1012 apexAvailable := apexAware.ApexAvailable()
1013 if len(apexAvailable) == 0 {
1014 // //apex_available:platform is the default.
1015 apexAvailable = []string{android.AvailableToPlatform}
1016 }
1017
1018 // Add in any baseline apex available settings.
1019 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1020
1021 // Remove duplicates and sort.
1022 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1023 sort.Strings(apexAvailable)
1024
1025 m.AddProperty("apex_available", apexAvailable)
1026 }
1027
Paul Duffinb0bb3762021-05-06 16:48:05 +01001028 // The licenses are the same for all variants.
1029 mctx := s.ctx
1030 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1031 if len(licenseInfo.Licenses) > 0 {
1032 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1033 }
1034
Paul Duffin865171e2020-03-02 18:38:15 +00001035 deviceSupported := false
1036 hostSupported := false
1037
1038 for _, variant := range member.Variants() {
1039 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001040 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001041 hostSupported = true
1042 } else if osClass == android.Device {
1043 deviceSupported = true
1044 }
1045 }
1046
1047 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001048
Paul Duffin0cb37b92020-03-04 14:52:46 +00001049 // Disable installation in the versioned module of those modules that are ever installable.
1050 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1051 if installable.EverInstallable() {
1052 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1053 }
1054 }
1055
Paul Duffinb645ec82019-11-27 17:43:54 +00001056 s.prebuiltModules[name] = m
1057 s.prebuiltOrder = append(s.prebuiltOrder, m)
1058 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001059}
1060
Paul Duffin865171e2020-03-02 18:38:15 +00001061func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001062 // If neither device or host is supported then this module does not support either so will not
1063 // recognize the properties.
1064 if !deviceSupported && !hostSupported {
1065 return
1066 }
1067
Paul Duffin865171e2020-03-02 18:38:15 +00001068 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001069 bpModule.AddProperty("device_supported", false)
1070 }
Paul Duffin865171e2020-03-02 18:38:15 +00001071 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001072 bpModule.AddProperty("host_supported", true)
1073 }
1074}
1075
Paul Duffin13f02712020-03-06 12:30:43 +00001076func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1077 if required {
1078 return requiredSdkMemberReferencePropertyTag
1079 } else {
1080 return optionalSdkMemberReferencePropertyTag
1081 }
1082}
1083
1084func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1085 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001086}
1087
Paul Duffinb645ec82019-11-27 17:43:54 +00001088// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001089func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1090 if _, ok := s.allMembersByName[unversionedName]; !ok {
1091 if required {
1092 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1093 }
1094 return unversionedName
1095 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001096 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1097}
Paul Duffinb645ec82019-11-27 17:43:54 +00001098
Paul Duffin13f02712020-03-06 12:30:43 +00001099func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001100 var references []string = nil
1101 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001102 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001103 }
1104 return references
1105}
Paul Duffin13879572019-11-28 14:31:38 +00001106
Paul Duffin72910952020-01-20 18:16:30 +00001107// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001108func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1109 if _, ok := s.allMembersByName[unversionedName]; !ok {
1110 if required {
1111 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1112 }
1113 return unversionedName
1114 }
1115
1116 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001117 return s.ctx.ModuleName() + "_" + unversionedName
1118 } else {
1119 return unversionedName
1120 }
1121}
1122
Paul Duffin13f02712020-03-06 12:30:43 +00001123func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001124 var references []string = nil
1125 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001126 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001127 }
1128 return references
1129}
1130
Paul Duffin13f02712020-03-06 12:30:43 +00001131func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1132 _, ok := s.exportedMembersByName[memberName]
1133 return !ok
1134}
1135
Martin Stjernholm89238f42020-07-10 00:14:03 +01001136// Add the properties from the given SdkMemberProperties to the blueprint
1137// property set. This handles common properties in SdkMemberPropertiesBase and
1138// calls the member-specific AddToPropertySet for the rest.
1139func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1140 if memberProperties.Base().Compile_multilib != "" {
1141 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1142 }
1143
1144 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1145}
1146
Paul Duffin21827262021-04-24 12:16:36 +01001147// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1148type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001149 // The sdk variant that depends (possibly indirectly) on the member variant.
1150 sdkVariant *sdk
Paul Duffina1aa7382021-04-29 21:50:40 +01001151
1152 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001153 memberType android.SdkMemberType
Paul Duffina1aa7382021-04-29 21:50:40 +01001154
1155 // The variant that is added to the sdk.
1156 variant android.SdkAware
1157
1158 // True if the member should be exported, i.e. accessible, from outside the sdk.
1159 export bool
1160
1161 // The names of additional component modules provided by the variant.
1162 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001163}
1164
Paul Duffin13879572019-11-28 14:31:38 +00001165var _ android.SdkMember = (*sdkMember)(nil)
1166
Paul Duffin21827262021-04-24 12:16:36 +01001167// sdkMember groups all the variants of a specific member module together along with the name of the
1168// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001169type sdkMember struct {
1170 memberType android.SdkMemberType
1171 name string
1172 variants []android.SdkAware
1173}
1174
1175func (m *sdkMember) Name() string {
1176 return m.name
1177}
1178
1179func (m *sdkMember) Variants() []android.SdkAware {
1180 return m.variants
1181}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001182
Paul Duffin9c3760e2020-03-16 19:52:08 +00001183// Track usages of multilib variants.
1184type multilibUsage int
1185
1186const (
1187 multilibNone multilibUsage = 0
1188 multilib32 multilibUsage = 1
1189 multilib64 multilibUsage = 2
1190 multilibBoth = multilib32 | multilib64
1191)
1192
1193// Add the multilib that is used in the arch type.
1194func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1195 multilib := archType.Multilib
1196 switch multilib {
1197 case "":
1198 return m
1199 case "lib32":
1200 return m | multilib32
1201 case "lib64":
1202 return m | multilib64
1203 default:
1204 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1205 }
1206}
1207
1208func (m multilibUsage) String() string {
1209 switch m {
1210 case multilibNone:
1211 return ""
1212 case multilib32:
1213 return "32"
1214 case multilib64:
1215 return "64"
1216 case multilibBoth:
1217 return "both"
1218 default:
1219 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1220 m, multilibNone, multilib32, multilib64, multilibBoth))
1221 }
1222}
1223
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001224type baseInfo struct {
1225 Properties android.SdkMemberProperties
1226}
1227
Paul Duffinf34f6d82020-04-30 15:48:31 +01001228func (b *baseInfo) optimizableProperties() interface{} {
1229 return b.Properties
1230}
1231
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001232type osTypeSpecificInfo struct {
1233 baseInfo
1234
Paul Duffin00e46802020-03-12 20:40:35 +00001235 osType android.OsType
1236
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001237 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001238 //
1239 // Nil if there is one variant whose arch type is common
1240 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001241}
1242
Paul Duffin4b8b7932020-05-06 12:35:38 +01001243var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1244
Paul Duffinfc8dd232020-03-17 12:51:37 +00001245type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1246
Paul Duffin00e46802020-03-12 20:40:35 +00001247// Create a new osTypeSpecificInfo for the specified os type and its properties
1248// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001249func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001250 osInfo := &osTypeSpecificInfo{
1251 osType: osType,
1252 }
1253
1254 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1255 properties := variantPropertiesFactory()
1256 properties.Base().Os = osType
1257 return properties
1258 }
1259
1260 // Create a structure into which properties common across the architectures in
1261 // this os type will be stored.
1262 osInfo.Properties = osSpecificVariantPropertiesFactory()
1263
1264 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001265 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001266 var archTypes []android.ArchType
1267 for _, variant := range osTypeVariants {
1268 archType := variant.Target().Arch.ArchType
1269 archTypeName := archType.Name
1270 if _, ok := variantsByArchName[archTypeName]; !ok {
1271 archTypes = append(archTypes, archType)
1272 }
1273
1274 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1275 }
1276
1277 if commonVariants, ok := variantsByArchName["common"]; ok {
1278 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001279 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 +00001280 }
1281
1282 // A common arch type only has one variant and its properties should be treated
1283 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001284 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001285 } else {
1286 // Create an arch specific info for each supported architecture type.
1287 for _, archType := range archTypes {
1288 archTypeName := archType.Name
1289
1290 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001291 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001292
1293 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1294 }
1295 }
1296
1297 return osInfo
1298}
1299
1300// Optimize the properties by extracting common properties from arch type specific
1301// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001302func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001303 // Nothing to do if there is only a single common architecture.
1304 if len(osInfo.archInfos) == 0 {
1305 return
1306 }
1307
Paul Duffin9c3760e2020-03-16 19:52:08 +00001308 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001309 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001310 multilib = multilib.addArchType(archInfo.archType)
1311
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001312 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001313 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001314 }
1315
Paul Duffin4b8b7932020-05-06 12:35:38 +01001316 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001317
1318 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001319 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001320}
1321
1322// Add the properties for an os to a property set.
1323//
1324// Maps the properties related to the os variants through to an appropriate
1325// module structure that will produce equivalent set of variants when it is
1326// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001327func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001328
1329 var osPropertySet android.BpPropertySet
1330 var archPropertySet android.BpPropertySet
1331 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001332 if osInfo.Properties.Base().Os_count == 1 &&
1333 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1334 // There is only one OS type present in the variants and it shouldn't have a
1335 // variant-specific target. The latter is the case if it's either for device
1336 // where there is only one OS (android), or for host and the member type
1337 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001338
1339 // Create a structure that looks like:
1340 // module_type {
1341 // name: "...",
1342 // ...
1343 // <common properties>
1344 // ...
1345 // <single os type specific properties>
1346 //
1347 // arch: {
1348 // <arch specific sections>
1349 // }
1350 //
1351 osPropertySet = bpModule
1352 archPropertySet = osPropertySet.AddPropertySet("arch")
1353
1354 // Arch specific properties need to be added to an arch specific section
1355 // within arch.
1356 archOsPrefix = ""
1357 } else {
1358 // Create a structure that looks like:
1359 // module_type {
1360 // name: "...",
1361 // ...
1362 // <common properties>
1363 // ...
1364 // target: {
1365 // <arch independent os specific sections, e.g. android>
1366 // ...
1367 // <arch and os specific sections, e.g. android_x86>
1368 // }
1369 //
1370 osType := osInfo.osType
1371 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1372 archPropertySet = targetPropertySet
1373
1374 // Arch specific properties need to be added to an os and arch specific
1375 // section prefixed with <os>_.
1376 archOsPrefix = osType.Name + "_"
1377 }
1378
1379 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001380 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001381
1382 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1383 // os) specific properties.
1384 //
1385 // The archInfos list will be empty if the os contains variants for the common
1386 // architecture.
1387 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001388 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001389 }
1390}
1391
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001392func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1393 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001394 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001395}
1396
1397var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1398
Paul Duffin4b8b7932020-05-06 12:35:38 +01001399func (osInfo *osTypeSpecificInfo) String() string {
1400 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1401}
1402
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001403type archTypeSpecificInfo struct {
1404 baseInfo
1405
1406 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001407 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001408
1409 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001410}
1411
Paul Duffin4b8b7932020-05-06 12:35:38 +01001412var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1413
Paul Duffinfc8dd232020-03-17 12:51:37 +00001414// Create a new archTypeSpecificInfo for the specified arch type and its properties
1415// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001416func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001417
Paul Duffinfc8dd232020-03-17 12:51:37 +00001418 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001419 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001420
1421 // Create the properties into which the arch type specific properties will be
1422 // added.
1423 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001424
1425 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001426 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001427 } else {
1428 // There is more than one variant for this arch type which must be differentiated
1429 // by link type.
1430 for _, linkVariant := range archVariants {
1431 linkType := getLinkType(linkVariant)
1432 if linkType == "" {
1433 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1434 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001435 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001436
1437 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1438 }
1439 }
1440 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001441
1442 return archInfo
1443}
1444
Paul Duffinf34f6d82020-04-30 15:48:31 +01001445func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1446 return archInfo.Properties
1447}
1448
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001449// Get the link type of the variant
1450//
1451// If the variant is not differentiated by link type then it returns "",
1452// otherwise it returns one of "static" or "shared".
1453func getLinkType(variant android.Module) string {
1454 linkType := ""
1455 if linkable, ok := variant.(cc.LinkableInterface); ok {
1456 if linkable.Shared() && linkable.Static() {
1457 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1458 } else if linkable.Shared() {
1459 linkType = "shared"
1460 } else if linkable.Static() {
1461 linkType = "static"
1462 } else {
1463 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1464 }
1465 }
1466 return linkType
1467}
1468
1469// Optimize the properties by extracting common properties from link type specific
1470// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001471func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001472 if len(archInfo.linkInfos) == 0 {
1473 return
1474 }
1475
Paul Duffin4b8b7932020-05-06 12:35:38 +01001476 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001477}
1478
Paul Duffinfc8dd232020-03-17 12:51:37 +00001479// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001480func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001481 archTypeName := archInfo.archType.Name
1482 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001483 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1484 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1485 archTypePropertySet.AddProperty("enabled", true)
1486 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001487 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001488
1489 for _, linkInfo := range archInfo.linkInfos {
1490 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001491 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001492 }
1493}
1494
Paul Duffin4b8b7932020-05-06 12:35:38 +01001495func (archInfo *archTypeSpecificInfo) String() string {
1496 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1497}
1498
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001499type linkTypeSpecificInfo struct {
1500 baseInfo
1501
1502 linkType string
1503}
1504
Paul Duffin4b8b7932020-05-06 12:35:38 +01001505var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1506
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001507// Create a new linkTypeSpecificInfo for the specified link type and its properties
1508// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001509func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001510 linkInfo := &linkTypeSpecificInfo{
1511 baseInfo: baseInfo{
1512 // Create the properties into which the link type specific properties will be
1513 // added.
1514 Properties: variantPropertiesFactory(),
1515 },
1516 linkType: linkType,
1517 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001518 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001519 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001520}
1521
Paul Duffin4b8b7932020-05-06 12:35:38 +01001522func (l *linkTypeSpecificInfo) String() string {
1523 return fmt.Sprintf("LinkType{%s}", l.linkType)
1524}
1525
Paul Duffin3a4eb502020-03-19 16:11:18 +00001526type memberContext struct {
1527 sdkMemberContext android.ModuleContext
1528 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001529 memberType android.SdkMemberType
1530 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001531}
1532
1533func (m *memberContext) SdkModuleContext() android.ModuleContext {
1534 return m.sdkMemberContext
1535}
1536
1537func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1538 return m.builder
1539}
1540
Paul Duffina551a1c2020-03-17 21:04:24 +00001541func (m *memberContext) MemberType() android.SdkMemberType {
1542 return m.memberType
1543}
1544
1545func (m *memberContext) Name() string {
1546 return m.name
1547}
1548
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001549func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001550
1551 memberType := member.memberType
1552
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001553 // Do not add the prefer property if the member snapshot module is a source module type.
1554 if !memberType.UsesSourceModuleTypeInSnapshot() {
1555 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1556 // snapshot to be created that sets prefer: true.
1557 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1558 // dynamically at build time not at snapshot generation time.
1559 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001560
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001561 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1562 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1563 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1564 // behavior is for the module.
1565 bpModule.insertAfter("name", "prefer", prefer)
1566 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001567
Paul Duffina04c1072020-03-02 10:16:35 +00001568 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001569 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001570 variants := member.Variants()
1571 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001572 osType := variant.Target().Os
1573 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001574 }
1575
Paul Duffina04c1072020-03-02 10:16:35 +00001576 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001577 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001578 properties := memberType.CreateVariantPropertiesStruct()
1579 base := properties.Base()
1580 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001581 return properties
1582 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001583
Paul Duffina04c1072020-03-02 10:16:35 +00001584 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001585
Paul Duffina04c1072020-03-02 10:16:35 +00001586 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001587 commonProperties := variantPropertiesFactory()
1588 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001589
Paul Duffinc097e362020-03-10 22:50:03 +00001590 // Create common value extractor that can be used to optimize the properties.
1591 commonValueExtractor := newCommonValueExtractor(commonProperties)
1592
Paul Duffina04c1072020-03-02 10:16:35 +00001593 // The list of property structures which are os type specific but common across
1594 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001595 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001596
1597 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001598 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001599 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001600 // Add the os specific properties to a list of os type specific yet architecture
1601 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001602 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001603
Paul Duffin00e46802020-03-12 20:40:35 +00001604 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001605 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001606 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001607
Paul Duffina04c1072020-03-02 10:16:35 +00001608 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001609 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001610
Paul Duffina04c1072020-03-02 10:16:35 +00001611 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001612 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001613
Paul Duffina04c1072020-03-02 10:16:35 +00001614 // Create a target property set into which target specific properties can be
1615 // added.
1616 targetPropertySet := bpModule.AddPropertySet("target")
1617
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001618 // If the member is host OS dependent and has host_supported then disable by
1619 // default and enable each host OS variant explicitly. This avoids problems
1620 // with implicitly enabled OS variants when the snapshot is used, which might
1621 // be different from this run (e.g. different build OS).
1622 if ctx.memberType.IsHostOsDependent() {
1623 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1624 if hostSupported {
1625 hostPropertySet := targetPropertySet.AddPropertySet("host")
1626 hostPropertySet.AddProperty("enabled", false)
1627 }
1628 }
1629
Paul Duffina04c1072020-03-02 10:16:35 +00001630 // Iterate over the os types in a fixed order.
1631 for _, osType := range s.getPossibleOsTypes() {
1632 osInfo := osTypeToInfo[osType]
1633 if osInfo == nil {
1634 continue
1635 }
1636
Paul Duffin3a4eb502020-03-19 16:11:18 +00001637 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001638 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001639}
1640
Paul Duffina04c1072020-03-02 10:16:35 +00001641// Compute the list of possible os types that this sdk could support.
1642func (s *sdk) getPossibleOsTypes() []android.OsType {
1643 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001644 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001645 if s.DeviceSupported() {
1646 if osType.Class == android.Device && osType != android.Fuchsia {
1647 osTypes = append(osTypes, osType)
1648 }
1649 }
1650 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001651 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001652 osTypes = append(osTypes, osType)
1653 }
1654 }
1655 }
1656 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1657 return osTypes
1658}
1659
Paul Duffinb28369a2020-05-04 15:39:59 +01001660// Given a set of properties (struct value), return the value of the field within that
1661// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001662type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1663
Paul Duffinc459f892020-04-30 18:08:29 +01001664// Checks the metadata to determine whether the property should be ignored for the
1665// purposes of common value extraction or not.
1666type extractorMetadataPredicate func(metadata propertiesContainer) bool
1667
1668// Indicates whether optimizable properties are provided by a host variant or
1669// not.
1670type isHostVariant interface {
1671 isHostVariant() bool
1672}
1673
Paul Duffinb28369a2020-05-04 15:39:59 +01001674// A property that can be optimized by the commonValueExtractor.
1675type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001676 // The name of the field for this property. It is a "."-separated path for
1677 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001678 name string
1679
Paul Duffinc459f892020-04-30 18:08:29 +01001680 // Filter that can use metadata associated with the properties being optimized
1681 // to determine whether the field should be ignored during common value
1682 // optimization.
1683 filter extractorMetadataPredicate
1684
Paul Duffinb28369a2020-05-04 15:39:59 +01001685 // Retrieves the value on which common value optimization will be performed.
1686 getter fieldAccessorFunc
1687
1688 // The empty value for the field.
1689 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001690
1691 // True if the property can support arch variants false otherwise.
1692 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001693}
1694
Paul Duffin4b8b7932020-05-06 12:35:38 +01001695func (p extractorProperty) String() string {
1696 return p.name
1697}
1698
Paul Duffinc097e362020-03-10 22:50:03 +00001699// Supports extracting common values from a number of instances of a properties
1700// structure into a separate common set of properties.
1701type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001702 // The properties that the extractor can optimize.
1703 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001704}
1705
1706// Create a new common value extractor for the structure type for the supplied
1707// properties struct.
1708//
1709// The returned extractor can be used on any properties structure of the same type
1710// as the supplied set of properties.
1711func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1712 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1713 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001714 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001715 return extractor
1716}
1717
1718// Gather the fields from the supplied structure type from which common values will
1719// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001720//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001721// This is recursive function. If it encounters a struct then it will recurse
1722// into it, passing in the accessor for the field and the struct name as prefix
1723// for the nested fields. That will then be used in the accessors for the fields
1724// in the embedded struct.
1725func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001726 for f := 0; f < structType.NumField(); f++ {
1727 field := structType.Field(f)
1728 if field.PkgPath != "" {
1729 // Ignore unexported fields.
1730 continue
1731 }
1732
Paul Duffinb07fa512020-03-10 22:17:04 +00001733 // Ignore fields whose value should be kept.
1734 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001735 continue
1736 }
1737
Paul Duffinc459f892020-04-30 18:08:29 +01001738 var filter extractorMetadataPredicate
1739
1740 // Add a filter
1741 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1742 filter = func(metadata propertiesContainer) bool {
1743 if m, ok := metadata.(isHostVariant); ok {
1744 if m.isHostVariant() {
1745 return false
1746 }
1747 }
1748 return true
1749 }
1750 }
1751
Paul Duffinc097e362020-03-10 22:50:03 +00001752 // Save a copy of the field index for use in the function.
1753 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001754
Martin Stjernholmb0249572020-09-15 02:32:35 +01001755 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001756
Paul Duffinc097e362020-03-10 22:50:03 +00001757 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001758 if containingStructAccessor != nil {
1759 // This is an embedded structure so first access the field for the embedded
1760 // structure.
1761 value = containingStructAccessor(value)
1762 }
1763
Paul Duffinc097e362020-03-10 22:50:03 +00001764 // Skip through interface and pointer values to find the structure.
1765 value = getStructValue(value)
1766
Paul Duffin4b8b7932020-05-06 12:35:38 +01001767 defer func() {
1768 if r := recover(); r != nil {
1769 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1770 }
1771 }()
1772
Paul Duffinc097e362020-03-10 22:50:03 +00001773 // Return the field.
1774 return value.Field(fieldIndex)
1775 }
1776
Martin Stjernholmb0249572020-09-15 02:32:35 +01001777 if field.Type.Kind() == reflect.Struct {
1778 // Gather fields from the nested or embedded structure.
1779 var subNamePrefix string
1780 if field.Anonymous {
1781 subNamePrefix = namePrefix
1782 } else {
1783 subNamePrefix = name + "."
1784 }
1785 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001786 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001787 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001788 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001789 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001790 fieldGetter,
1791 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001792 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001793 }
1794 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001795 }
Paul Duffinc097e362020-03-10 22:50:03 +00001796 }
1797}
1798
1799func getStructValue(value reflect.Value) reflect.Value {
1800foundStruct:
1801 for {
1802 kind := value.Kind()
1803 switch kind {
1804 case reflect.Interface, reflect.Ptr:
1805 value = value.Elem()
1806 case reflect.Struct:
1807 break foundStruct
1808 default:
1809 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1810 }
1811 }
1812 return value
1813}
1814
Paul Duffinf34f6d82020-04-30 15:48:31 +01001815// A container of properties to be optimized.
1816//
1817// Allows additional information to be associated with the properties, e.g. for
1818// filtering.
1819type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001820 fmt.Stringer
1821
Paul Duffinf34f6d82020-04-30 15:48:31 +01001822 // Get the properties that need optimizing.
1823 optimizableProperties() interface{}
1824}
1825
Paul Duffin2d1bb892021-04-24 11:32:59 +01001826// A wrapper for sdk variant related properties to allow them to be optimized.
1827type sdkVariantPropertiesContainer struct {
1828 sdkVariant *sdk
1829 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001830}
1831
Paul Duffin2d1bb892021-04-24 11:32:59 +01001832func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1833 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001834}
1835
Paul Duffin2d1bb892021-04-24 11:32:59 +01001836func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001837 return c.sdkVariant.String()
1838}
1839
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001840// Extract common properties from a slice of property structures of the same type.
1841//
1842// All the property structures must be of the same type.
1843// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001844// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001845//
1846// Iterates over each exported field (capitalized name) and checks to see whether they
1847// have the same value (using DeepEquals) across all the input properties. If it does not then no
1848// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001849// and the field in each of the input properties structure is set to its default value. Nested
1850// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001851func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001852 commonPropertiesValue := reflect.ValueOf(commonProperties)
1853 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001854
Paul Duffinf34f6d82020-04-30 15:48:31 +01001855 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1856
Paul Duffinb28369a2020-05-04 15:39:59 +01001857 for _, property := range e.properties {
1858 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001859 filter := property.filter
1860 if filter == nil {
1861 filter = func(metadata propertiesContainer) bool {
1862 return true
1863 }
1864 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001865
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001866 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001867 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1868 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001869 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001870
Paul Duffin864e1b42020-05-06 10:23:19 +01001871 // Assume that all the values will be the same.
1872 //
1873 // While similar to this is not quite the same as commonValue == nil. If all the values
1874 // have been filtered out then this will be false but commonValue == nil will be true.
1875 valuesDiffer := false
1876
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001877 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001878 container := sliceValue.Index(i).Interface().(propertiesContainer)
1879 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001880 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001881
Paul Duffinc459f892020-04-30 18:08:29 +01001882 if !filter(container) {
1883 expectedValue := property.emptyValue.Interface()
1884 actualValue := fieldValue.Interface()
1885 if !reflect.DeepEqual(expectedValue, actualValue) {
1886 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1887 }
1888 continue
1889 }
1890
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001891 if commonValue == nil {
1892 // Use the first value as the commonProperties value.
1893 commonValue = &fieldValue
1894 } else {
1895 // If the value does not match the current common value then there is
1896 // no value in common so break out.
1897 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1898 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001899 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001900 break
1901 }
1902 }
1903 }
1904
Paul Duffin864e1b42020-05-06 10:23:19 +01001905 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001906 // and set the input struct's field to the empty value.
1907 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001908 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001909 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001910 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001911 container := sliceValue.Index(i).Interface().(propertiesContainer)
1912 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001913 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001914 fieldValue.Set(emptyValue)
1915 }
1916 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001917
1918 if valuesDiffer && !property.archVariant {
1919 // The values differ but the property does not support arch variants so it
1920 // is an error.
1921 var details strings.Builder
1922 for i := 0; i < sliceValue.Len(); i++ {
1923 container := sliceValue.Index(i).Interface().(propertiesContainer)
1924 itemValue := reflect.ValueOf(container.optimizableProperties())
1925 fieldValue := fieldGetter(itemValue)
1926
1927 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1928 }
1929
1930 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1931 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001932 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001933
1934 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001935}