blob: b146b62c89bc140fff53fb6789834565a26e03a3 [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 Duffin43f7bf02021-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 Duffin43f7bf02021-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 Duffina08e4dc2021-06-22 18:19:19 +0100116// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
117// arguments.
118func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
119 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
120}
121
122// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
123// the arguments.
124func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
125 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900126}
127
128func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800129 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100130
131 content := gf.content.String()
132
133 // ninja consumes newline characters in rspfile_content. Prevent it by
134 // escaping the backslash in the newline character. The extra backslash
135 // is removed when the rspfile is written to the actual script file
136 content = strings.ReplaceAll(content, "\n", "\\n")
137
Jiyong Park9b409bc2019-10-11 14:59:13 +0900138 rb.Command().
139 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100140 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100141 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900142 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
143 rb.Command().
144 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800145 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900146}
147
Paul Duffin13879572019-11-28 14:31:38 +0000148// Collect all the members.
149//
Paul Duffinb97b1572021-04-29 21:50:40 +0100150// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
151// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000152func (s *sdk) collectMembers(ctx android.ModuleContext) {
153 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000154 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
155 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000156 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100157 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900158
Paul Duffin5cca7c42021-05-26 10:16:01 +0100159 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
160 if memberType == nil {
161 return false
162 }
163
Paul Duffin13879572019-11-28 14:31:38 +0000164 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000165 if !memberType.IsInstance(child) {
166 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900167 }
Paul Duffin13879572019-11-28 14:31:38 +0000168
Paul Duffin6a7e9532020-03-20 17:50:07 +0000169 // Keep track of which multilib variants are used by the sdk.
170 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
171
Paul Duffinb97b1572021-04-29 21:50:40 +0100172 var exportedComponentsInfo android.ExportedComponentsInfo
173 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
174 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
175 }
176
Paul Duffina7208112021-04-23 21:20:20 +0100177 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100178 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
179 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
180 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000181
Paul Duffin2d3da312021-05-06 12:02:27 +0100182 // Recurse down into the member's dependencies as it may have dependencies that need to be
183 // automatically added to the sdk.
184 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900185 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000186
187 return false
Paul Duffin13879572019-11-28 14:31:38 +0000188 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000189}
190
Paul Duffincc3132e2021-04-24 01:10:30 +0100191// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
192// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000193//
Paul Duffincc3132e2021-04-24 01:10:30 +0100194// The sdkMember instances are then grouped into slices by member type. Within each such slice the
195// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000196//
Paul Duffincc3132e2021-04-24 01:10:30 +0100197// Finally, the member type slices are concatenated together to form a single slice. The order in
198// which they are concatenated is the order in which the member types were registered in the
199// android.SdkMemberTypesRegistry.
200func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000201 byType := make(map[android.SdkMemberType][]*sdkMember)
202 byName := make(map[string]*sdkMember)
203
Paul Duffin21827262021-04-24 12:16:36 +0100204 for _, memberVariantDep := range memberVariantDeps {
205 memberType := memberVariantDep.memberType
206 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000207
208 name := ctx.OtherModuleName(variant)
209 member := byName[name]
210 if member == nil {
211 member = &sdkMember{memberType: memberType, name: name}
212 byName[name] = member
213 byType[memberType] = append(byType[memberType], member)
214 }
215
Paul Duffin1356d8c2020-02-25 19:26:33 +0000216 // Only append new variants to the list. This is needed because a member can be both
217 // exported by the sdk and also be a transitive sdk member.
218 member.variants = appendUniqueVariants(member.variants, variant)
219 }
220
Paul Duffin13879572019-11-28 14:31:38 +0000221 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000222 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000223 membersOfType := byType[memberListProperty.memberType]
224 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900225 }
226
Paul Duffin6a7e9532020-03-20 17:50:07 +0000227 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900228}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900229
Paul Duffin72910952020-01-20 18:16:30 +0000230func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
231 for _, v := range variants {
232 if v == newVariant {
233 return variants
234 }
235 }
236 return append(variants, newVariant)
237}
238
Jiyong Park73c54ee2019-10-22 20:31:18 +0900239// SDK directory structure
240// <sdk_root>/
241// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
242// <api_ver>/ : below this directory are all auto-generated
243// Android.bp : definition of 'sdk_snapshot' module is here
244// aidl/
245// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
246// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900247// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900248// include/
249// bionic/libc/include/stdlib.h : an exported header file
250// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900251// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900252// <arch>/include/ : arch-specific exported headers
253// <arch>/include_gen/ : arch-specific generated headers
254// <arch>/lib/
255// libFoo.so : a stub library
256
Jiyong Park232e7852019-11-04 12:23:40 +0900257// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900258// This isn't visible to users, so could be changed in future.
259func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
260 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
261}
262
Jiyong Park232e7852019-11-04 12:23:40 +0900263// buildSnapshot is the main function in this source file. It creates rules to copy
264// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000265func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
266
Paul Duffinb97b1572021-04-29 21:50:40 +0100267 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100268 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100269 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000270 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100271 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100272 }
Paul Duffin865171e2020-03-02 18:38:15 +0000273
Paul Duffinb97b1572021-04-29 21:50:40 +0100274 // Filter out any sdkMemberVariantDep that is a component of another.
275 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000276
Paul Duffinb97b1572021-04-29 21:50:40 +0100277 // Record the names of all the members, both explicitly specified and implicitly
278 // included.
279 allMembersByName := make(map[string]struct{})
280 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100281
Paul Duffinb97b1572021-04-29 21:50:40 +0100282 addMember := func(name string, export bool) {
283 allMembersByName[name] = struct{}{}
284 if export {
285 exportedMembersByName[name] = struct{}{}
286 }
287 }
288
289 for _, memberVariantDep := range memberVariantDeps {
290 name := memberVariantDep.variant.Name()
291 export := memberVariantDep.export
292
293 addMember(name, export)
294
295 // Add any components provided by the module.
296 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
297 addMember(component, export)
298 }
299
300 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
301 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000302 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000303 }
304
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000305 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900306
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000307 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000308
309 bpFile := &bpFile{
310 modules: make(map[string]*bpModule),
311 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000312
Paul Duffin43f7bf02021-05-05 22:00:51 +0100313 config := ctx.Config()
314 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
315
316 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
317 generateVersioned := version != soongSdkSnapshotVersionUnversioned
318
319 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
320 //
321 // Unversioned modules are not required in that case because the numbered version will be a
322 // finalized version of the snapshot that is intended to be kept separate from the
323 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
324 snapshotZipFileSuffix := ""
325 if generateVersioned {
326 snapshotZipFileSuffix = "-" + version
327 }
328
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000329 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000330 ctx: ctx,
331 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100332 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000333 snapshotDir: snapshotDir.OutputPath,
334 copies: make(map[string]string),
335 filesToZip: []android.Path{bp.path},
336 bpFile: bpFile,
337 prebuiltModules: make(map[string]*bpModule),
338 allMembersByName: allMembersByName,
339 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900340 }
Paul Duffinac37c502019-11-26 18:02:20 +0000341 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900342
Paul Duffin62131702021-05-07 01:10:01 +0100343 // If the sdk snapshot includes any license modules then add a package module which has a
344 // default_applicable_licenses property. That will prevent the LSC license process from updating
345 // the generated Android.bp file to add a package module that includes all licenses used by all
346 // the modules in that package. That would be unnecessary as every module in the sdk should have
347 // their own licenses property specified.
348 if hasLicenses {
349 pkg := bpFile.newModule("package")
350 property := "default_applicable_licenses"
351 pkg.AddCommentForProperty(property, `
352A default list here prevents the license LSC from adding its own list which would
353be unnecessary as every module in the sdk already has its own licenses property.
354`)
355 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
356 bpFile.AddModule(pkg)
357 }
358
Paul Duffin0df49682021-05-07 01:10:01 +0100359 // Group the variants for each member module together and then group the members of each member
360 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100361 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100362
363 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000364 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000365 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000366
Paul Duffina551a1c2020-03-17 21:04:24 +0000367 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000368
369 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100370 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900371 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900372
Paul Duffine6c0d842020-01-15 14:08:51 +0000373 // Create a transformer that will transform an unversioned module into a versioned module.
374 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
375
Paul Duffin72910952020-01-20 18:16:30 +0000376 // Create a transformer that will transform an unversioned module by replacing any references
377 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100378 unversionedTransformer := unversionedTransformation{
379 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100380 }
Paul Duffin72910952020-01-20 18:16:30 +0000381
Paul Duffinb645ec82019-11-27 17:43:54 +0000382 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000383 // Prune any empty property sets.
384 unversioned = unversioned.transform(pruneEmptySetTransformer{})
385
Paul Duffin43f7bf02021-05-05 22:00:51 +0100386 if generateVersioned {
387 // Copy the unversioned module so it can be modified to make it versioned.
388 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000389
Paul Duffin43f7bf02021-05-05 22:00:51 +0100390 // Transform the unversioned module into a versioned one.
391 versioned.transform(unversionedToVersionedTransformer)
392 bpFile.AddModule(versioned)
393 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000394
Paul Duffin43f7bf02021-05-05 22:00:51 +0100395 if generateUnversioned {
396 // Transform the unversioned module to make it suitable for use in the snapshot.
397 unversioned.transform(unversionedTransformer)
398 bpFile.AddModule(unversioned)
399 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000400 }
401
Paul Duffin43f7bf02021-05-05 22:00:51 +0100402 if generateVersioned {
403 // Add the sdk/module_exports_snapshot module to the bp file.
404 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
405 }
Paul Duffin26197a62021-04-24 00:34:10 +0100406
407 // generate Android.bp
408 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
409 generateBpContents(&bp.generatedContents, bpFile)
410
411 contents := bp.content.String()
412 syntaxCheckSnapshotBpFile(ctx, contents)
413
414 bp.build(pctx, ctx, nil)
415
416 filesToZip := builder.filesToZip
417
418 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100419 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
420 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100421 outputDesc := "Building snapshot for " + ctx.ModuleName()
422
423 // If there are no zips to merge then generate the output zip directly.
424 // Otherwise, generate an intermediate zip file into which other zips can be
425 // merged.
426 var zipFile android.OutputPath
427 var desc string
428 if len(builder.zipsToMerge) == 0 {
429 zipFile = outputZipFile
430 desc = outputDesc
431 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100432 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
433 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100434 desc = "Building intermediate snapshot for " + ctx.ModuleName()
435 }
436
437 ctx.Build(pctx, android.BuildParams{
438 Description: desc,
439 Rule: zipFiles,
440 Inputs: filesToZip,
441 Output: zipFile,
442 Args: map[string]string{
443 "basedir": builder.snapshotDir.String(),
444 },
445 })
446
447 if len(builder.zipsToMerge) != 0 {
448 ctx.Build(pctx, android.BuildParams{
449 Description: outputDesc,
450 Rule: mergeZips,
451 Input: zipFile,
452 Inputs: builder.zipsToMerge,
453 Output: outputZipFile,
454 })
455 }
456
457 return outputZipFile
458}
459
Paul Duffinb97b1572021-04-29 21:50:40 +0100460// filterOutComponents removes any item from the deps list that is a component of another item in
461// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
462// then it will remove "foo.stubs" from the deps.
463func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
464 // Collate the set of components that all the modules added to the sdk provide.
465 components := map[string]*sdkMemberVariantDep{}
466 for i, _ := range deps {
467 dep := &deps[i]
468 for _, c := range dep.exportedComponentsInfo.Components {
469 components[c] = dep
470 }
471 }
472
473 // If no module provides components then return the input deps unfiltered.
474 if len(components) == 0 {
475 return deps
476 }
477
478 filtered := make([]sdkMemberVariantDep, 0, len(deps))
479 for _, dep := range deps {
480 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
481 if owner, ok := components[name]; ok {
482 // This is a component of another module that is a member of the sdk.
483
484 // If the component is exported but the owning module is not then the configuration is not
485 // supported.
486 if dep.export && !owner.export {
487 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
488 continue
489 }
490
491 // This module must not be added to the list of members of the sdk as that would result in a
492 // duplicate module in the sdk snapshot.
493 continue
494 }
495
496 filtered = append(filtered, dep)
497 }
498 return filtered
499}
500
Paul Duffin26197a62021-04-24 00:34:10 +0100501// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100502func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100503 bpFile := builder.bpFile
504
Paul Duffinb645ec82019-11-27 17:43:54 +0000505 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000506 var snapshotModuleType string
507 if s.properties.Module_exports {
508 snapshotModuleType = "module_exports_snapshot"
509 } else {
510 snapshotModuleType = "sdk_snapshot"
511 }
512 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000513 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000514
515 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100516 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000517 if len(visibility) != 0 {
518 snapshotModule.AddProperty("visibility", visibility)
519 }
520
Paul Duffin865171e2020-03-02 18:38:15 +0000521 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000522
Paul Duffincd064672021-04-24 00:47:29 +0100523 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100524 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000525
Paul Duffin2d1bb892021-04-24 11:32:59 +0100526 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100527
Paul Duffin6a7e9532020-03-20 17:50:07 +0000528 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100529
Paul Duffin2d1bb892021-04-24 11:32:59 +0100530 // Create a mapping from osType to combined properties.
531 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
532 for _, combined := range combinedPropertiesList {
533 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
534 }
535
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100536 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000537 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100538 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100539 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000540
Paul Duffin2d1bb892021-04-24 11:32:59 +0100541 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000542 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000543 }
Paul Duffin865171e2020-03-02 18:38:15 +0000544
Jiyong Park8fe14e62020-10-19 22:47:34 +0900545 // If host is supported and any member is host OS dependent then disable host
546 // by default, so that we can enable each host OS variant explicitly. This
547 // avoids problems with implicitly enabled OS variants when the snapshot is
548 // used, which might be different from this run (e.g. different build OS).
549 if s.HostSupported() {
550 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100551 for _, memberVariantDep := range memberVariantDeps {
552 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
553 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900554 if !android.InList(targetString, supportedHostTargets) {
555 supportedHostTargets = append(supportedHostTargets, targetString)
556 }
557 }
558 }
559 if len(supportedHostTargets) > 0 {
560 hostPropertySet := targetPropertySet.AddPropertySet("host")
561 hostPropertySet.AddProperty("enabled", false)
562 }
563 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
564 for _, hostTarget := range supportedHostTargets {
565 propertySet := targetPropertySet.AddPropertySet(hostTarget)
566 propertySet.AddProperty("enabled", true)
567 }
568 }
569
Paul Duffin865171e2020-03-02 18:38:15 +0000570 // Prune any empty property sets.
571 snapshotModule.transform(pruneEmptySetTransformer{})
572
Paul Duffinb645ec82019-11-27 17:43:54 +0000573 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900574}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000575
Paul Duffinf88d8e02020-05-07 20:21:34 +0100576// Check the syntax of the generated Android.bp file contents and if they are
577// invalid then log an error with the contents (tagged with line numbers) and the
578// errors that were found so that it is easy to see where the problem lies.
579func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
580 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
581 if len(errs) != 0 {
582 message := &strings.Builder{}
583 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
584
585Generated Android.bp contents
586========================================================================
587`)
588 for i, line := range strings.Split(contents, "\n") {
589 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
590 }
591
592 _, _ = fmt.Fprint(message, `
593========================================================================
594
595Errors found:
596`)
597
598 for _, err := range errs {
599 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
600 }
601
602 ctx.ModuleErrorf("%s", message.String())
603 }
604}
605
Paul Duffin4b8b7932020-05-06 12:35:38 +0100606func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
607 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
608 if err != nil {
609 ctx.ModuleErrorf("error extracting common properties: %s", err)
610 }
611}
612
Paul Duffinfbe470e2021-04-24 12:37:13 +0100613// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
614type snapshotModuleStaticProperties struct {
615 Compile_multilib string `android:"arch_variant"`
616}
617
Paul Duffin2d1bb892021-04-24 11:32:59 +0100618// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
619type combinedSnapshotModuleProperties struct {
620 // The sdk variant from which this information was collected.
621 sdkVariant *sdk
622
623 // Static snapshot module properties.
624 staticProperties *snapshotModuleStaticProperties
625
626 // The dynamically generated member list properties.
627 dynamicProperties interface{}
628}
629
630// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100631func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
632 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100633 var list []*combinedSnapshotModuleProperties
634 for _, sdkVariant := range sdkVariants {
635 staticProperties := &snapshotModuleStaticProperties{
636 Compile_multilib: sdkVariant.multilibUsages.String(),
637 }
Paul Duffincd064672021-04-24 00:47:29 +0100638 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100639
Paul Duffincd064672021-04-24 00:47:29 +0100640 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100641 sdkVariant: sdkVariant,
642 staticProperties: staticProperties,
643 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100644 }
645 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
646
647 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100648 }
Paul Duffincd064672021-04-24 00:47:29 +0100649
650 for _, memberVariantDep := range memberVariantDeps {
651 // If the member dependency is internal then do not add the dependency to the snapshot member
652 // list properties.
653 if !memberVariantDep.export {
654 continue
655 }
656
657 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100658 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100659 memberName := ctx.OtherModuleName(memberVariantDep.variant)
660
Paul Duffin13082052021-05-11 00:31:38 +0100661 if memberListProperty.getter == nil {
662 continue
663 }
664
Paul Duffincd064672021-04-24 00:47:29 +0100665 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100666 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100667 if !android.InList(memberName, memberList) {
668 memberList = append(memberList, memberName)
669 }
Paul Duffin13082052021-05-11 00:31:38 +0100670 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100671 }
672
Paul Duffin2d1bb892021-04-24 11:32:59 +0100673 return list
674}
675
676func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
677
678 // Extract the dynamic properties and add them to a list of propertiesContainer.
679 propertyContainers := []propertiesContainer{}
680 for _, i := range list {
681 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
682 sdkVariant: i.sdkVariant,
683 properties: i.dynamicProperties,
684 })
685 }
686
687 // Extract the common members, removing them from the original properties.
688 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
689 extractor := newCommonValueExtractor(commonDynamicProperties)
690 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
691
692 // Extract the static properties and add them to a list of propertiesContainer.
693 propertyContainers = []propertiesContainer{}
694 for _, i := range list {
695 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
696 sdkVariant: i.sdkVariant,
697 properties: i.staticProperties,
698 })
699 }
700
701 commonStaticProperties := &snapshotModuleStaticProperties{}
702 extractor = newCommonValueExtractor(commonStaticProperties)
703 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
704
705 return &combinedSnapshotModuleProperties{
706 sdkVariant: nil,
707 staticProperties: commonStaticProperties,
708 dynamicProperties: commonDynamicProperties,
709 }
710}
711
712func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
713 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100714 multilib := staticProperties.Compile_multilib
715 if multilib != "" && multilib != "both" {
716 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
717 propertySet.AddProperty("compile_multilib", multilib)
718 }
719
Paul Duffin2d1bb892021-04-24 11:32:59 +0100720 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000721 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100722 if memberListProperty.getter == nil {
723 continue
724 }
Paul Duffin865171e2020-03-02 18:38:15 +0000725 names := memberListProperty.getter(dynamicMemberTypeListProperties)
726 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000727 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000728 }
729 }
730}
731
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000732type propertyTag struct {
733 name string
734}
735
Paul Duffin0cb37b92020-03-04 14:52:46 +0000736// A BpPropertyTag to add to a property that contains references to other sdk members.
737//
738// This will cause the references to be rewritten to a versioned reference in the version
739// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000740var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000741var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000742
Paul Duffin0cb37b92020-03-04 14:52:46 +0000743// A BpPropertyTag that indicates the property should only be present in the versioned
744// module.
745//
746// This will cause the property to be removed from the unversioned instance of a
747// snapshot module.
748var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
749
Paul Duffine6c0d842020-01-15 14:08:51 +0000750type unversionedToVersionedTransformation struct {
751 identityTransformation
752 builder *snapshotBuilder
753}
754
Paul Duffine6c0d842020-01-15 14:08:51 +0000755func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
756 // Use a versioned name for the module but remember the original name for the
757 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100758 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000759 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000760 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100761 // Remove the prefer property if present as versioned modules never need marking with prefer.
762 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000763 return module
764}
765
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000766func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000767 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
768 required := tag == requiredSdkMemberReferencePropertyTag
769 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000770 } else {
771 return value, tag
772 }
773}
774
Paul Duffin72910952020-01-20 18:16:30 +0000775type unversionedTransformation struct {
776 identityTransformation
777 builder *snapshotBuilder
778}
779
780func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
781 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100782 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000783 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000784 return module
785}
786
787func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000788 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
789 required := tag == requiredSdkMemberReferencePropertyTag
790 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000791 } else if tag == sdkVersionedOnlyPropertyTag {
792 // The property is not allowed in the unversioned module so remove it.
793 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000794 } else {
795 return value, tag
796 }
797}
798
Paul Duffina78f3a72020-02-21 16:29:35 +0000799type pruneEmptySetTransformer struct {
800 identityTransformation
801}
802
803var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
804
805func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
806 if len(propertySet.properties) == 0 {
807 return nil, nil
808 } else {
809 return propertySet, tag
810 }
811}
812
Paul Duffinb645ec82019-11-27 17:43:54 +0000813func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000814 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
815 return true
816 })
817}
818
819func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100820 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000821 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000822 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100823 contents.IndentedPrintf("\n")
824 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000825 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100826 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000827 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000828 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000829}
830
831func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
832 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000833
Paul Duffin0df49682021-05-07 01:10:01 +0100834 addComment := func(name string) {
835 if text, ok := set.comments[name]; ok {
836 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100837 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100838 }
839 }
840 }
841
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000842 // Output the properties first, followed by the nested sets. This ensures a
843 // consistent output irrespective of whether property sets are created before
844 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000845 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000846 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000847
Paul Duffin0df49682021-05-07 01:10:01 +0100848 // Do not write property sets in the properties phase.
849 if _, ok := value.(*bpPropertySet); ok {
850 continue
851 }
852
853 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100854 reflectValue := reflect.ValueOf(value)
855 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000856 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000857
858 for _, name := range set.order {
859 value := set.getValue(name)
860
861 // Only write property sets in the sets phase.
862 switch v := value.(type) {
863 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100864 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100865 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000866 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100867 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000868 }
869 }
870
Paul Duffinb645ec82019-11-27 17:43:54 +0000871 contents.Dedent()
872}
873
Paul Duffina08e4dc2021-06-22 18:19:19 +0100874// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
875// by the value and then followed by a , and a newline.
876func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
877 contents.IndentedPrintf("%s: ", name)
878 outputUnnamedValue(contents, value)
879 contents.UnindentedPrintf(",\n")
880}
881
882// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
883// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
884// indented and all but the last line will end with a newline.
885func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
886 valueType := value.Type()
887 switch valueType.Kind() {
888 case reflect.Bool:
889 contents.UnindentedPrintf("%t", value.Bool())
890
891 case reflect.String:
892 contents.UnindentedPrintf("%q", value)
893
Paul Duffin51227d82021-05-18 12:54:27 +0100894 case reflect.Ptr:
895 outputUnnamedValue(contents, value.Elem())
896
Paul Duffina08e4dc2021-06-22 18:19:19 +0100897 case reflect.Slice:
898 length := value.Len()
899 if length == 0 {
900 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100901 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100902 firstValue := value.Index(0)
903 if length == 1 && !multiLineValue(firstValue) {
904 contents.UnindentedPrintf("[")
905 outputUnnamedValue(contents, firstValue)
906 contents.UnindentedPrintf("]")
907 } else {
908 contents.UnindentedPrintf("[\n")
909 contents.Indent()
910 for i := 0; i < length; i++ {
911 itemValue := value.Index(i)
912 contents.IndentedPrintf("")
913 outputUnnamedValue(contents, itemValue)
914 contents.UnindentedPrintf(",\n")
915 }
916 contents.Dedent()
917 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100918 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100919 }
920
Paul Duffin51227d82021-05-18 12:54:27 +0100921 case reflect.Struct:
922 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
923 v := value.Interface()
924 if _, ok := v.(android.BpPrintable); !ok {
925 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
926 }
927 contents.UnindentedPrintf("{\n")
928 contents.Indent()
929 for f := 0; f < valueType.NumField(); f++ {
930 fieldType := valueType.Field(f)
931 if fieldType.Anonymous {
932 continue
933 }
934 fieldValue := value.Field(f)
935 fieldName := fieldType.Name
936 propertyName := proptools.PropertyNameForField(fieldName)
937 outputNamedValue(contents, propertyName, fieldValue)
938 }
939 contents.Dedent()
940 contents.IndentedPrintf("}")
941
Paul Duffina08e4dc2021-06-22 18:19:19 +0100942 default:
943 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
944 }
945}
946
Paul Duffin51227d82021-05-18 12:54:27 +0100947// multiLineValue returns true if the supplied value may require multiple lines in the output.
948func multiLineValue(value reflect.Value) bool {
949 kind := value.Kind()
950 return kind == reflect.Slice || kind == reflect.Struct
951}
952
Paul Duffinac37c502019-11-26 18:02:20 +0000953func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000954 contents := &generatedContents{}
955 generateBpContents(contents, s.builderForTests.bpFile)
956 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000957}
958
Paul Duffind0759072021-02-17 11:23:00 +0000959func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
960 contents := &generatedContents{}
961 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100962 name := module.Name()
963 // Include modules that are either unversioned or have no name.
964 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000965 })
966 return contents.content.String()
967}
968
969func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
970 contents := &generatedContents{}
971 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100972 name := module.Name()
973 // Include modules that are either versioned or have no name.
974 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000975 })
976 return contents.content.String()
977}
978
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000979type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100980 ctx android.ModuleContext
981 sdk *sdk
982
983 // The version of the generated snapshot.
984 //
985 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
986 // this field.
987 version string
988
Paul Duffinb645ec82019-11-27 17:43:54 +0000989 snapshotDir android.OutputPath
990 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000991
992 // Map from destination to source of each copy - used to eliminate duplicates and
993 // detect conflicts.
994 copies map[string]string
995
Paul Duffinb645ec82019-11-27 17:43:54 +0000996 filesToZip android.Paths
997 zipsToMerge android.Paths
998
999 prebuiltModules map[string]*bpModule
1000 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001001
1002 // The set of all members by name.
1003 allMembersByName map[string]struct{}
1004
1005 // The set of exported members by name.
1006 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001007}
1008
1009func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001010 if existing, ok := s.copies[dest]; ok {
1011 if existing != src.String() {
1012 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1013 return
1014 }
1015 } else {
1016 path := s.snapshotDir.Join(s.ctx, dest)
1017 s.ctx.Build(pctx, android.BuildParams{
1018 Rule: android.Cp,
1019 Input: src,
1020 Output: path,
1021 })
1022 s.filesToZip = append(s.filesToZip, path)
1023
1024 s.copies[dest] = src.String()
1025 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001026}
1027
Paul Duffin91547182019-11-12 19:39:36 +00001028func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1029 ctx := s.ctx
1030
1031 // Repackage the zip file so that the entries are in the destDir directory.
1032 // This will allow the zip file to be merged into the snapshot.
1033 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001034
1035 ctx.Build(pctx, android.BuildParams{
1036 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1037 Rule: repackageZip,
1038 Input: zipPath,
1039 Output: tmpZipPath,
1040 Args: map[string]string{
1041 "destdir": destDir,
1042 },
1043 })
Paul Duffin91547182019-11-12 19:39:36 +00001044
1045 // Add the repackaged zip file to the files to merge.
1046 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1047}
1048
Paul Duffin9d8d6092019-12-05 18:19:29 +00001049func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1050 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001051 if s.prebuiltModules[name] != nil {
1052 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1053 }
1054
1055 m := s.bpFile.newModule(moduleType)
1056 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001057
Paul Duffinbefa4b92020-03-04 14:22:45 +00001058 variant := member.Variants()[0]
1059
Paul Duffin13f02712020-03-06 12:30:43 +00001060 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001061 // An internal member is only referenced from the sdk snapshot which is in the
1062 // same package so can be marked as private.
1063 m.AddProperty("visibility", []string{"//visibility:private"})
1064 } else {
1065 // Extract visibility information from a member variant. All variants have the same
1066 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001067 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1068
1069 // Add any additional visibility rules needed for the prebuilts to reference each other.
1070 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1071 if err != nil {
1072 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1073 }
1074
1075 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001076 if len(visibility) != 0 {
1077 m.AddProperty("visibility", visibility)
1078 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001079 }
1080
Martin Stjernholm1e041092020-11-03 00:11:09 +00001081 // Where available copy apex_available properties from the member.
1082 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1083 apexAvailable := apexAware.ApexAvailable()
1084 if len(apexAvailable) == 0 {
1085 // //apex_available:platform is the default.
1086 apexAvailable = []string{android.AvailableToPlatform}
1087 }
1088
1089 // Add in any baseline apex available settings.
1090 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1091
1092 // Remove duplicates and sort.
1093 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1094 sort.Strings(apexAvailable)
1095
1096 m.AddProperty("apex_available", apexAvailable)
1097 }
1098
Paul Duffinb0bb3762021-05-06 16:48:05 +01001099 // The licenses are the same for all variants.
1100 mctx := s.ctx
1101 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1102 if len(licenseInfo.Licenses) > 0 {
1103 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1104 }
1105
Paul Duffin865171e2020-03-02 18:38:15 +00001106 deviceSupported := false
1107 hostSupported := false
1108
1109 for _, variant := range member.Variants() {
1110 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001111 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001112 hostSupported = true
1113 } else if osClass == android.Device {
1114 deviceSupported = true
1115 }
1116 }
1117
1118 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001119
Paul Duffin0cb37b92020-03-04 14:52:46 +00001120 // Disable installation in the versioned module of those modules that are ever installable.
1121 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1122 if installable.EverInstallable() {
1123 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1124 }
1125 }
1126
Paul Duffinb645ec82019-11-27 17:43:54 +00001127 s.prebuiltModules[name] = m
1128 s.prebuiltOrder = append(s.prebuiltOrder, m)
1129 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001130}
1131
Paul Duffin865171e2020-03-02 18:38:15 +00001132func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001133 // If neither device or host is supported then this module does not support either so will not
1134 // recognize the properties.
1135 if !deviceSupported && !hostSupported {
1136 return
1137 }
1138
Paul Duffin865171e2020-03-02 18:38:15 +00001139 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001140 bpModule.AddProperty("device_supported", false)
1141 }
Paul Duffin865171e2020-03-02 18:38:15 +00001142 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001143 bpModule.AddProperty("host_supported", true)
1144 }
1145}
1146
Paul Duffin13f02712020-03-06 12:30:43 +00001147func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1148 if required {
1149 return requiredSdkMemberReferencePropertyTag
1150 } else {
1151 return optionalSdkMemberReferencePropertyTag
1152 }
1153}
1154
1155func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1156 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001157}
1158
Paul Duffinb645ec82019-11-27 17:43:54 +00001159// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001160func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1161 if _, ok := s.allMembersByName[unversionedName]; !ok {
1162 if required {
1163 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1164 }
1165 return unversionedName
1166 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001167 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1168}
Paul Duffinb645ec82019-11-27 17:43:54 +00001169
Paul Duffin13f02712020-03-06 12:30:43 +00001170func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001171 var references []string = nil
1172 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001173 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001174 }
1175 return references
1176}
Paul Duffin13879572019-11-28 14:31:38 +00001177
Paul Duffin72910952020-01-20 18:16:30 +00001178// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001179func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1180 if _, ok := s.allMembersByName[unversionedName]; !ok {
1181 if required {
1182 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1183 }
1184 return unversionedName
1185 }
1186
1187 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001188 return s.ctx.ModuleName() + "_" + unversionedName
1189 } else {
1190 return unversionedName
1191 }
1192}
1193
Paul Duffin13f02712020-03-06 12:30:43 +00001194func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001195 var references []string = nil
1196 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001197 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001198 }
1199 return references
1200}
1201
Paul Duffin13f02712020-03-06 12:30:43 +00001202func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1203 _, ok := s.exportedMembersByName[memberName]
1204 return !ok
1205}
1206
Martin Stjernholm89238f42020-07-10 00:14:03 +01001207// Add the properties from the given SdkMemberProperties to the blueprint
1208// property set. This handles common properties in SdkMemberPropertiesBase and
1209// calls the member-specific AddToPropertySet for the rest.
1210func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1211 if memberProperties.Base().Compile_multilib != "" {
1212 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1213 }
1214
1215 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1216}
1217
Paul Duffin21827262021-04-24 12:16:36 +01001218// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1219type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001220 // The sdk variant that depends (possibly indirectly) on the member variant.
1221 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001222
1223 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001224 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001225
1226 // The variant that is added to the sdk.
1227 variant android.SdkAware
1228
1229 // True if the member should be exported, i.e. accessible, from outside the sdk.
1230 export bool
1231
1232 // The names of additional component modules provided by the variant.
1233 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001234}
1235
Paul Duffin13879572019-11-28 14:31:38 +00001236var _ android.SdkMember = (*sdkMember)(nil)
1237
Paul Duffin21827262021-04-24 12:16:36 +01001238// sdkMember groups all the variants of a specific member module together along with the name of the
1239// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001240type sdkMember struct {
1241 memberType android.SdkMemberType
1242 name string
1243 variants []android.SdkAware
1244}
1245
1246func (m *sdkMember) Name() string {
1247 return m.name
1248}
1249
1250func (m *sdkMember) Variants() []android.SdkAware {
1251 return m.variants
1252}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001253
Paul Duffin9c3760e2020-03-16 19:52:08 +00001254// Track usages of multilib variants.
1255type multilibUsage int
1256
1257const (
1258 multilibNone multilibUsage = 0
1259 multilib32 multilibUsage = 1
1260 multilib64 multilibUsage = 2
1261 multilibBoth = multilib32 | multilib64
1262)
1263
1264// Add the multilib that is used in the arch type.
1265func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1266 multilib := archType.Multilib
1267 switch multilib {
1268 case "":
1269 return m
1270 case "lib32":
1271 return m | multilib32
1272 case "lib64":
1273 return m | multilib64
1274 default:
1275 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1276 }
1277}
1278
1279func (m multilibUsage) String() string {
1280 switch m {
1281 case multilibNone:
1282 return ""
1283 case multilib32:
1284 return "32"
1285 case multilib64:
1286 return "64"
1287 case multilibBoth:
1288 return "both"
1289 default:
1290 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1291 m, multilibNone, multilib32, multilib64, multilibBoth))
1292 }
1293}
1294
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001295type baseInfo struct {
1296 Properties android.SdkMemberProperties
1297}
1298
Paul Duffinf34f6d82020-04-30 15:48:31 +01001299func (b *baseInfo) optimizableProperties() interface{} {
1300 return b.Properties
1301}
1302
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001303type osTypeSpecificInfo struct {
1304 baseInfo
1305
Paul Duffin00e46802020-03-12 20:40:35 +00001306 osType android.OsType
1307
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001308 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001309 //
1310 // Nil if there is one variant whose arch type is common
1311 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001312}
1313
Paul Duffin4b8b7932020-05-06 12:35:38 +01001314var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1315
Paul Duffinfc8dd232020-03-17 12:51:37 +00001316type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1317
Paul Duffin00e46802020-03-12 20:40:35 +00001318// Create a new osTypeSpecificInfo for the specified os type and its properties
1319// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001320func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001321 osInfo := &osTypeSpecificInfo{
1322 osType: osType,
1323 }
1324
1325 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1326 properties := variantPropertiesFactory()
1327 properties.Base().Os = osType
1328 return properties
1329 }
1330
1331 // Create a structure into which properties common across the architectures in
1332 // this os type will be stored.
1333 osInfo.Properties = osSpecificVariantPropertiesFactory()
1334
1335 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001336 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001337 var archTypes []android.ArchType
1338 for _, variant := range osTypeVariants {
1339 archType := variant.Target().Arch.ArchType
1340 archTypeName := archType.Name
1341 if _, ok := variantsByArchName[archTypeName]; !ok {
1342 archTypes = append(archTypes, archType)
1343 }
1344
1345 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1346 }
1347
1348 if commonVariants, ok := variantsByArchName["common"]; ok {
1349 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001350 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 +00001351 }
1352
1353 // A common arch type only has one variant and its properties should be treated
1354 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001355 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001356 } else {
1357 // Create an arch specific info for each supported architecture type.
1358 for _, archType := range archTypes {
1359 archTypeName := archType.Name
1360
1361 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001362 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001363
1364 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1365 }
1366 }
1367
1368 return osInfo
1369}
1370
1371// Optimize the properties by extracting common properties from arch type specific
1372// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001373func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001374 // Nothing to do if there is only a single common architecture.
1375 if len(osInfo.archInfos) == 0 {
1376 return
1377 }
1378
Paul Duffin9c3760e2020-03-16 19:52:08 +00001379 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001380 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001381 multilib = multilib.addArchType(archInfo.archType)
1382
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001383 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001384 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001385 }
1386
Paul Duffin4b8b7932020-05-06 12:35:38 +01001387 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001388
1389 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001390 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001391}
1392
1393// Add the properties for an os to a property set.
1394//
1395// Maps the properties related to the os variants through to an appropriate
1396// module structure that will produce equivalent set of variants when it is
1397// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001398func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001399
1400 var osPropertySet android.BpPropertySet
1401 var archPropertySet android.BpPropertySet
1402 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001403 if osInfo.Properties.Base().Os_count == 1 &&
1404 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1405 // There is only one OS type present in the variants and it shouldn't have a
1406 // variant-specific target. The latter is the case if it's either for device
1407 // where there is only one OS (android), or for host and the member type
1408 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001409
1410 // Create a structure that looks like:
1411 // module_type {
1412 // name: "...",
1413 // ...
1414 // <common properties>
1415 // ...
1416 // <single os type specific properties>
1417 //
1418 // arch: {
1419 // <arch specific sections>
1420 // }
1421 //
1422 osPropertySet = bpModule
1423 archPropertySet = osPropertySet.AddPropertySet("arch")
1424
1425 // Arch specific properties need to be added to an arch specific section
1426 // within arch.
1427 archOsPrefix = ""
1428 } else {
1429 // Create a structure that looks like:
1430 // module_type {
1431 // name: "...",
1432 // ...
1433 // <common properties>
1434 // ...
1435 // target: {
1436 // <arch independent os specific sections, e.g. android>
1437 // ...
1438 // <arch and os specific sections, e.g. android_x86>
1439 // }
1440 //
1441 osType := osInfo.osType
1442 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1443 archPropertySet = targetPropertySet
1444
1445 // Arch specific properties need to be added to an os and arch specific
1446 // section prefixed with <os>_.
1447 archOsPrefix = osType.Name + "_"
1448 }
1449
1450 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001451 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001452
1453 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1454 // os) specific properties.
1455 //
1456 // The archInfos list will be empty if the os contains variants for the common
1457 // architecture.
1458 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001459 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001460 }
1461}
1462
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001463func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1464 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001465 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001466}
1467
1468var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1469
Paul Duffin4b8b7932020-05-06 12:35:38 +01001470func (osInfo *osTypeSpecificInfo) String() string {
1471 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1472}
1473
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001474type archTypeSpecificInfo struct {
1475 baseInfo
1476
1477 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001478 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001479
1480 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001481}
1482
Paul Duffin4b8b7932020-05-06 12:35:38 +01001483var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1484
Paul Duffinfc8dd232020-03-17 12:51:37 +00001485// Create a new archTypeSpecificInfo for the specified arch type and its properties
1486// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001487func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001488
Paul Duffinfc8dd232020-03-17 12:51:37 +00001489 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001490 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001491
1492 // Create the properties into which the arch type specific properties will be
1493 // added.
1494 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001495
1496 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001497 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001498 } else {
1499 // There is more than one variant for this arch type which must be differentiated
1500 // by link type.
1501 for _, linkVariant := range archVariants {
1502 linkType := getLinkType(linkVariant)
1503 if linkType == "" {
1504 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1505 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001506 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001507
1508 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1509 }
1510 }
1511 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001512
1513 return archInfo
1514}
1515
Paul Duffinf34f6d82020-04-30 15:48:31 +01001516func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1517 return archInfo.Properties
1518}
1519
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001520// Get the link type of the variant
1521//
1522// If the variant is not differentiated by link type then it returns "",
1523// otherwise it returns one of "static" or "shared".
1524func getLinkType(variant android.Module) string {
1525 linkType := ""
1526 if linkable, ok := variant.(cc.LinkableInterface); ok {
1527 if linkable.Shared() && linkable.Static() {
1528 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1529 } else if linkable.Shared() {
1530 linkType = "shared"
1531 } else if linkable.Static() {
1532 linkType = "static"
1533 } else {
1534 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1535 }
1536 }
1537 return linkType
1538}
1539
1540// Optimize the properties by extracting common properties from link type specific
1541// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001542func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001543 if len(archInfo.linkInfos) == 0 {
1544 return
1545 }
1546
Paul Duffin4b8b7932020-05-06 12:35:38 +01001547 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001548}
1549
Paul Duffinfc8dd232020-03-17 12:51:37 +00001550// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001551func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001552 archTypeName := archInfo.archType.Name
1553 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001554 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1555 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1556 archTypePropertySet.AddProperty("enabled", true)
1557 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001558 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001559
1560 for _, linkInfo := range archInfo.linkInfos {
1561 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001562 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001563 }
1564}
1565
Paul Duffin4b8b7932020-05-06 12:35:38 +01001566func (archInfo *archTypeSpecificInfo) String() string {
1567 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1568}
1569
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001570type linkTypeSpecificInfo struct {
1571 baseInfo
1572
1573 linkType string
1574}
1575
Paul Duffin4b8b7932020-05-06 12:35:38 +01001576var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1577
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001578// Create a new linkTypeSpecificInfo for the specified link type and its properties
1579// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001580func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001581 linkInfo := &linkTypeSpecificInfo{
1582 baseInfo: baseInfo{
1583 // Create the properties into which the link type specific properties will be
1584 // added.
1585 Properties: variantPropertiesFactory(),
1586 },
1587 linkType: linkType,
1588 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001589 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001590 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001591}
1592
Paul Duffin4b8b7932020-05-06 12:35:38 +01001593func (l *linkTypeSpecificInfo) String() string {
1594 return fmt.Sprintf("LinkType{%s}", l.linkType)
1595}
1596
Paul Duffin3a4eb502020-03-19 16:11:18 +00001597type memberContext struct {
1598 sdkMemberContext android.ModuleContext
1599 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001600 memberType android.SdkMemberType
1601 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001602}
1603
1604func (m *memberContext) SdkModuleContext() android.ModuleContext {
1605 return m.sdkMemberContext
1606}
1607
1608func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1609 return m.builder
1610}
1611
Paul Duffina551a1c2020-03-17 21:04:24 +00001612func (m *memberContext) MemberType() android.SdkMemberType {
1613 return m.memberType
1614}
1615
1616func (m *memberContext) Name() string {
1617 return m.name
1618}
1619
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001620func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001621
1622 memberType := member.memberType
1623
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001624 // Do not add the prefer property if the member snapshot module is a source module type.
1625 if !memberType.UsesSourceModuleTypeInSnapshot() {
1626 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1627 // snapshot to be created that sets prefer: true.
1628 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1629 // dynamically at build time not at snapshot generation time.
1630 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001631
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001632 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1633 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1634 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1635 // behavior is for the module.
1636 bpModule.insertAfter("name", "prefer", prefer)
1637 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001638
Paul Duffina04c1072020-03-02 10:16:35 +00001639 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001640 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001641 variants := member.Variants()
1642 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001643 osType := variant.Target().Os
1644 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001645 }
1646
Paul Duffina04c1072020-03-02 10:16:35 +00001647 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001648 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001649 properties := memberType.CreateVariantPropertiesStruct()
1650 base := properties.Base()
1651 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001652 return properties
1653 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001654
Paul Duffina04c1072020-03-02 10:16:35 +00001655 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001656
Paul Duffina04c1072020-03-02 10:16:35 +00001657 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001658 commonProperties := variantPropertiesFactory()
1659 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001660
Paul Duffinc097e362020-03-10 22:50:03 +00001661 // Create common value extractor that can be used to optimize the properties.
1662 commonValueExtractor := newCommonValueExtractor(commonProperties)
1663
Paul Duffina04c1072020-03-02 10:16:35 +00001664 // The list of property structures which are os type specific but common across
1665 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001666 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001667
1668 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001669 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001670 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001671 // Add the os specific properties to a list of os type specific yet architecture
1672 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001673 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001674
Paul Duffin00e46802020-03-12 20:40:35 +00001675 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001676 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001677 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001678
Paul Duffina04c1072020-03-02 10:16:35 +00001679 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001680 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001681
Paul Duffina04c1072020-03-02 10:16:35 +00001682 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001683 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001684
Paul Duffina04c1072020-03-02 10:16:35 +00001685 // Create a target property set into which target specific properties can be
1686 // added.
1687 targetPropertySet := bpModule.AddPropertySet("target")
1688
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001689 // If the member is host OS dependent and has host_supported then disable by
1690 // default and enable each host OS variant explicitly. This avoids problems
1691 // with implicitly enabled OS variants when the snapshot is used, which might
1692 // be different from this run (e.g. different build OS).
1693 if ctx.memberType.IsHostOsDependent() {
1694 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1695 if hostSupported {
1696 hostPropertySet := targetPropertySet.AddPropertySet("host")
1697 hostPropertySet.AddProperty("enabled", false)
1698 }
1699 }
1700
Paul Duffina04c1072020-03-02 10:16:35 +00001701 // Iterate over the os types in a fixed order.
1702 for _, osType := range s.getPossibleOsTypes() {
1703 osInfo := osTypeToInfo[osType]
1704 if osInfo == nil {
1705 continue
1706 }
1707
Paul Duffin3a4eb502020-03-19 16:11:18 +00001708 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001709 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001710}
1711
Paul Duffina04c1072020-03-02 10:16:35 +00001712// Compute the list of possible os types that this sdk could support.
1713func (s *sdk) getPossibleOsTypes() []android.OsType {
1714 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001715 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001716 if s.DeviceSupported() {
1717 if osType.Class == android.Device && osType != android.Fuchsia {
1718 osTypes = append(osTypes, osType)
1719 }
1720 }
1721 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001722 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001723 osTypes = append(osTypes, osType)
1724 }
1725 }
1726 }
1727 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1728 return osTypes
1729}
1730
Paul Duffinb28369a2020-05-04 15:39:59 +01001731// Given a set of properties (struct value), return the value of the field within that
1732// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001733type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1734
Paul Duffinc459f892020-04-30 18:08:29 +01001735// Checks the metadata to determine whether the property should be ignored for the
1736// purposes of common value extraction or not.
1737type extractorMetadataPredicate func(metadata propertiesContainer) bool
1738
1739// Indicates whether optimizable properties are provided by a host variant or
1740// not.
1741type isHostVariant interface {
1742 isHostVariant() bool
1743}
1744
Paul Duffinb28369a2020-05-04 15:39:59 +01001745// A property that can be optimized by the commonValueExtractor.
1746type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001747 // The name of the field for this property. It is a "."-separated path for
1748 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001749 name string
1750
Paul Duffinc459f892020-04-30 18:08:29 +01001751 // Filter that can use metadata associated with the properties being optimized
1752 // to determine whether the field should be ignored during common value
1753 // optimization.
1754 filter extractorMetadataPredicate
1755
Paul Duffinb28369a2020-05-04 15:39:59 +01001756 // Retrieves the value on which common value optimization will be performed.
1757 getter fieldAccessorFunc
1758
1759 // The empty value for the field.
1760 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001761
1762 // True if the property can support arch variants false otherwise.
1763 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001764}
1765
Paul Duffin4b8b7932020-05-06 12:35:38 +01001766func (p extractorProperty) String() string {
1767 return p.name
1768}
1769
Paul Duffinc097e362020-03-10 22:50:03 +00001770// Supports extracting common values from a number of instances of a properties
1771// structure into a separate common set of properties.
1772type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001773 // The properties that the extractor can optimize.
1774 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001775}
1776
1777// Create a new common value extractor for the structure type for the supplied
1778// properties struct.
1779//
1780// The returned extractor can be used on any properties structure of the same type
1781// as the supplied set of properties.
1782func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1783 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1784 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001785 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001786 return extractor
1787}
1788
1789// Gather the fields from the supplied structure type from which common values will
1790// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001791//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001792// This is recursive function. If it encounters a struct then it will recurse
1793// into it, passing in the accessor for the field and the struct name as prefix
1794// for the nested fields. That will then be used in the accessors for the fields
1795// in the embedded struct.
1796func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001797 for f := 0; f < structType.NumField(); f++ {
1798 field := structType.Field(f)
1799 if field.PkgPath != "" {
1800 // Ignore unexported fields.
1801 continue
1802 }
1803
Paul Duffinb07fa512020-03-10 22:17:04 +00001804 // Ignore fields whose value should be kept.
1805 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001806 continue
1807 }
1808
Paul Duffinc459f892020-04-30 18:08:29 +01001809 var filter extractorMetadataPredicate
1810
1811 // Add a filter
1812 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1813 filter = func(metadata propertiesContainer) bool {
1814 if m, ok := metadata.(isHostVariant); ok {
1815 if m.isHostVariant() {
1816 return false
1817 }
1818 }
1819 return true
1820 }
1821 }
1822
Paul Duffinc097e362020-03-10 22:50:03 +00001823 // Save a copy of the field index for use in the function.
1824 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001825
Martin Stjernholmb0249572020-09-15 02:32:35 +01001826 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001827
Paul Duffinc097e362020-03-10 22:50:03 +00001828 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001829 if containingStructAccessor != nil {
1830 // This is an embedded structure so first access the field for the embedded
1831 // structure.
1832 value = containingStructAccessor(value)
1833 }
1834
Paul Duffinc097e362020-03-10 22:50:03 +00001835 // Skip through interface and pointer values to find the structure.
1836 value = getStructValue(value)
1837
Paul Duffin4b8b7932020-05-06 12:35:38 +01001838 defer func() {
1839 if r := recover(); r != nil {
1840 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1841 }
1842 }()
1843
Paul Duffinc097e362020-03-10 22:50:03 +00001844 // Return the field.
1845 return value.Field(fieldIndex)
1846 }
1847
Martin Stjernholmb0249572020-09-15 02:32:35 +01001848 if field.Type.Kind() == reflect.Struct {
1849 // Gather fields from the nested or embedded structure.
1850 var subNamePrefix string
1851 if field.Anonymous {
1852 subNamePrefix = namePrefix
1853 } else {
1854 subNamePrefix = name + "."
1855 }
1856 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001857 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001858 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001859 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001860 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001861 fieldGetter,
1862 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001863 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001864 }
1865 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001866 }
Paul Duffinc097e362020-03-10 22:50:03 +00001867 }
1868}
1869
1870func getStructValue(value reflect.Value) reflect.Value {
1871foundStruct:
1872 for {
1873 kind := value.Kind()
1874 switch kind {
1875 case reflect.Interface, reflect.Ptr:
1876 value = value.Elem()
1877 case reflect.Struct:
1878 break foundStruct
1879 default:
1880 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1881 }
1882 }
1883 return value
1884}
1885
Paul Duffinf34f6d82020-04-30 15:48:31 +01001886// A container of properties to be optimized.
1887//
1888// Allows additional information to be associated with the properties, e.g. for
1889// filtering.
1890type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001891 fmt.Stringer
1892
Paul Duffinf34f6d82020-04-30 15:48:31 +01001893 // Get the properties that need optimizing.
1894 optimizableProperties() interface{}
1895}
1896
Paul Duffin2d1bb892021-04-24 11:32:59 +01001897// A wrapper for sdk variant related properties to allow them to be optimized.
1898type sdkVariantPropertiesContainer struct {
1899 sdkVariant *sdk
1900 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001901}
1902
Paul Duffin2d1bb892021-04-24 11:32:59 +01001903func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1904 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001905}
1906
Paul Duffin2d1bb892021-04-24 11:32:59 +01001907func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001908 return c.sdkVariant.String()
1909}
1910
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001911// Extract common properties from a slice of property structures of the same type.
1912//
1913// All the property structures must be of the same type.
1914// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001915// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001916//
1917// Iterates over each exported field (capitalized name) and checks to see whether they
1918// have the same value (using DeepEquals) across all the input properties. If it does not then no
1919// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001920// and the field in each of the input properties structure is set to its default value. Nested
1921// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001922func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001923 commonPropertiesValue := reflect.ValueOf(commonProperties)
1924 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001925
Paul Duffinf34f6d82020-04-30 15:48:31 +01001926 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1927
Paul Duffinb28369a2020-05-04 15:39:59 +01001928 for _, property := range e.properties {
1929 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001930 filter := property.filter
1931 if filter == nil {
1932 filter = func(metadata propertiesContainer) bool {
1933 return true
1934 }
1935 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001936
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001937 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001938 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1939 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001940 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001941
Paul Duffin864e1b42020-05-06 10:23:19 +01001942 // Assume that all the values will be the same.
1943 //
1944 // While similar to this is not quite the same as commonValue == nil. If all the values
1945 // have been filtered out then this will be false but commonValue == nil will be true.
1946 valuesDiffer := false
1947
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001948 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001949 container := sliceValue.Index(i).Interface().(propertiesContainer)
1950 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001951 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001952
Paul Duffinc459f892020-04-30 18:08:29 +01001953 if !filter(container) {
1954 expectedValue := property.emptyValue.Interface()
1955 actualValue := fieldValue.Interface()
1956 if !reflect.DeepEqual(expectedValue, actualValue) {
1957 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1958 }
1959 continue
1960 }
1961
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001962 if commonValue == nil {
1963 // Use the first value as the commonProperties value.
1964 commonValue = &fieldValue
1965 } else {
1966 // If the value does not match the current common value then there is
1967 // no value in common so break out.
1968 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1969 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001970 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001971 break
1972 }
1973 }
1974 }
1975
Paul Duffin864e1b42020-05-06 10:23:19 +01001976 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001977 // and set the input struct's field to the empty value.
1978 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001979 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001980 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001981 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001982 container := sliceValue.Index(i).Interface().(propertiesContainer)
1983 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001984 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001985 fieldValue.Set(emptyValue)
1986 }
1987 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001988
1989 if valuesDiffer && !property.archVariant {
1990 // The values differ but the property does not support arch variants so it
1991 // is an error.
1992 var details strings.Builder
1993 for i := 0; i < sliceValue.Len(); i++ {
1994 container := sliceValue.Index(i).Interface().(propertiesContainer)
1995 itemValue := reflect.ValueOf(container.optimizableProperties())
1996 fieldValue := fieldGetter(itemValue)
1997
1998 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1999 }
2000
2001 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2002 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002003 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002004
2005 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002006}