blob: 36b564fe68509f3bd883174deaa97b73640756d8 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Colin Cross440e0d02020-06-11 11:32:11 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
36// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
38//
Paul Duffin43f7bf02021-05-05 22:00:51 +010039// SOONG_SDK_SNAPSHOT_VERSION
40// This provides control over the version of the generated snapshot.
41//
42// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
43// versioned snapshot module. This is the default behavior. The zip file containing the
44// generated snapshot will be <sdk-name>-current.zip.
45//
46// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
47// file containing the generated snapshot will be <sdk-name>.zip.
48//
49// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
50// snapshot module only. The zip file containing the generated snapshot will be
51// <sdk-name>-<number>.zip.
52//
Paul Duffin64fb5262021-05-05 21:36:04 +010053
Jiyong Park9b409bc2019-10-11 14:59:13 +090054var pctx = android.NewPackageContext("android/soong/sdk")
55
Paul Duffin375058f2019-11-29 20:17:53 +000056var (
57 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
58 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000059 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000060 CommandDeps: []string{
61 "${config.Zip2ZipCmd}",
62 },
63 },
64 "destdir")
65
66 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
67 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070068 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000069 CommandDeps: []string{
70 "${config.SoongZipCmd}",
71 },
72 Rspfile: "$out.rsp",
73 RspfileContent: "$in",
74 },
75 "basedir")
76
77 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
78 blueprint.RuleParams{
79 Command: `${config.MergeZipsCmd} $out $in`,
80 CommandDeps: []string{
81 "${config.MergeZipsCmd}",
82 },
83 })
84)
85
Paul Duffin43f7bf02021-05-05 22:00:51 +010086const (
87 soongSdkSnapshotVersionUnversioned = "unversioned"
88 soongSdkSnapshotVersionCurrent = "current"
89)
90
Paul Duffinb645ec82019-11-27 17:43:54 +000091type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090092 content strings.Builder
93 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090094}
95
Paul Duffinb645ec82019-11-27 17:43:54 +000096// generatedFile abstracts operations for writing contents into a file and emit a build rule
97// for the file.
98type generatedFile struct {
99 generatedContents
100 path android.OutputPath
101}
102
Jiyong Park232e7852019-11-04 12:23:40 +0900103func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000105 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900106 }
107}
108
Paul Duffinb645ec82019-11-27 17:43:54 +0000109func (gc *generatedContents) Indent() {
110 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900111}
112
Paul Duffinb645ec82019-11-27 17:43:54 +0000113func (gc *generatedContents) Dedent() {
114 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900115}
116
Paul Duffinb645ec82019-11-27 17:43:54 +0000117func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +0100118 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900119}
120
121func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800122 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100123
124 content := gf.content.String()
125
126 // ninja consumes newline characters in rspfile_content. Prevent it by
127 // escaping the backslash in the newline character. The extra backslash
128 // is removed when the rspfile is written to the actual script file
129 content = strings.ReplaceAll(content, "\n", "\\n")
130
Jiyong Park9b409bc2019-10-11 14:59:13 +0900131 rb.Command().
132 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100133 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100134 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
136 rb.Command().
137 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800138 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900139}
140
Paul Duffin13879572019-11-28 14:31:38 +0000141// Collect all the members.
142//
Paul Duffincc3132e2021-04-24 01:10:30 +0100143// Updates the sdk module with a list of sdkMemberVariantDeps and details as to which multilibs
144// (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000145func (s *sdk) collectMembers(ctx android.ModuleContext) {
146 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000147 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
148 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000149 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100150 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900151
Paul Duffin13879572019-11-28 14:31:38 +0000152 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000153 if !memberType.IsInstance(child) {
154 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900155 }
Paul Duffin13879572019-11-28 14:31:38 +0000156
Paul Duffin6a7e9532020-03-20 17:50:07 +0000157 // Keep track of which multilib variants are used by the sdk.
158 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
159
Paul Duffina7208112021-04-23 21:20:20 +0100160 export := memberTag.ExportMember()
Paul Duffincd064672021-04-24 00:47:29 +0100161 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{s, memberType, child.(android.SdkAware), export})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000162
Paul Duffin2d3da312021-05-06 12:02:27 +0100163 // Recurse down into the member's dependencies as it may have dependencies that need to be
164 // automatically added to the sdk.
165 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900166 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000167
168 return false
Paul Duffin13879572019-11-28 14:31:38 +0000169 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000170}
171
Paul Duffincc3132e2021-04-24 01:10:30 +0100172// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
173// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000174//
Paul Duffincc3132e2021-04-24 01:10:30 +0100175// The sdkMember instances are then grouped into slices by member type. Within each such slice the
176// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000177//
Paul Duffincc3132e2021-04-24 01:10:30 +0100178// Finally, the member type slices are concatenated together to form a single slice. The order in
179// which they are concatenated is the order in which the member types were registered in the
180// android.SdkMemberTypesRegistry.
181func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000182 byType := make(map[android.SdkMemberType][]*sdkMember)
183 byName := make(map[string]*sdkMember)
184
Paul Duffin21827262021-04-24 12:16:36 +0100185 for _, memberVariantDep := range memberVariantDeps {
186 memberType := memberVariantDep.memberType
187 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000188
189 name := ctx.OtherModuleName(variant)
190 member := byName[name]
191 if member == nil {
192 member = &sdkMember{memberType: memberType, name: name}
193 byName[name] = member
194 byType[memberType] = append(byType[memberType], member)
195 }
196
Paul Duffin1356d8c2020-02-25 19:26:33 +0000197 // Only append new variants to the list. This is needed because a member can be both
198 // exported by the sdk and also be a transitive sdk member.
199 member.variants = appendUniqueVariants(member.variants, variant)
200 }
201
Paul Duffin13879572019-11-28 14:31:38 +0000202 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000203 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000204 membersOfType := byType[memberListProperty.memberType]
205 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900206 }
207
Paul Duffin6a7e9532020-03-20 17:50:07 +0000208 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900209}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900210
Paul Duffin72910952020-01-20 18:16:30 +0000211func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
212 for _, v := range variants {
213 if v == newVariant {
214 return variants
215 }
216 }
217 return append(variants, newVariant)
218}
219
Jiyong Park73c54ee2019-10-22 20:31:18 +0900220// SDK directory structure
221// <sdk_root>/
222// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
223// <api_ver>/ : below this directory are all auto-generated
224// Android.bp : definition of 'sdk_snapshot' module is here
225// aidl/
226// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
227// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900228// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900229// include/
230// bionic/libc/include/stdlib.h : an exported header file
231// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900232// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900233// <arch>/include/ : arch-specific exported headers
234// <arch>/include_gen/ : arch-specific generated headers
235// <arch>/lib/
236// libFoo.so : a stub library
237
Jiyong Park232e7852019-11-04 12:23:40 +0900238// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900239// This isn't visible to users, so could be changed in future.
240func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
241 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
242}
243
Jiyong Park232e7852019-11-04 12:23:40 +0900244// buildSnapshot is the main function in this source file. It creates rules to copy
245// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000246func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
247
Paul Duffin13f02712020-03-06 12:30:43 +0000248 allMembersByName := make(map[string]struct{})
249 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100250 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100251 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000252 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100253 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffin865171e2020-03-02 18:38:15 +0000254
Paul Duffin13f02712020-03-06 12:30:43 +0000255 // Record the names of all the members, both explicitly specified and implicitly
256 // included.
Paul Duffin21827262021-04-24 12:16:36 +0100257 for _, memberVariantDep := range sdkVariant.memberVariantDeps {
Paul Duffina7208112021-04-23 21:20:20 +0100258 name := memberVariantDep.variant.Name()
259 allMembersByName[name] = struct{}{}
Paul Duffin13f02712020-03-06 12:30:43 +0000260
Paul Duffina7208112021-04-23 21:20:20 +0100261 if memberVariantDep.export {
262 exportedMembersByName[name] = struct{}{}
263 }
Paul Duffin62131702021-05-07 01:10:01 +0100264
265 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
266 hasLicenses = true
267 }
Paul Duffin865171e2020-03-02 18:38:15 +0000268 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000269 }
270
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000271 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900272
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000273 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000274
275 bpFile := &bpFile{
276 modules: make(map[string]*bpModule),
277 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000278
Paul Duffin43f7bf02021-05-05 22:00:51 +0100279 config := ctx.Config()
280 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
281
282 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
283 generateVersioned := version != soongSdkSnapshotVersionUnversioned
284
285 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
286 //
287 // Unversioned modules are not required in that case because the numbered version will be a
288 // finalized version of the snapshot that is intended to be kept separate from the
289 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
290 snapshotZipFileSuffix := ""
291 if generateVersioned {
292 snapshotZipFileSuffix = "-" + version
293 }
294
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000295 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000296 ctx: ctx,
297 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100298 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000299 snapshotDir: snapshotDir.OutputPath,
300 copies: make(map[string]string),
301 filesToZip: []android.Path{bp.path},
302 bpFile: bpFile,
303 prebuiltModules: make(map[string]*bpModule),
304 allMembersByName: allMembersByName,
305 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900306 }
Paul Duffinac37c502019-11-26 18:02:20 +0000307 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900308
Paul Duffin62131702021-05-07 01:10:01 +0100309 // If the sdk snapshot includes any license modules then add a package module which has a
310 // default_applicable_licenses property. That will prevent the LSC license process from updating
311 // the generated Android.bp file to add a package module that includes all licenses used by all
312 // the modules in that package. That would be unnecessary as every module in the sdk should have
313 // their own licenses property specified.
314 if hasLicenses {
315 pkg := bpFile.newModule("package")
316 property := "default_applicable_licenses"
317 pkg.AddCommentForProperty(property, `
318A default list here prevents the license LSC from adding its own list which would
319be unnecessary as every module in the sdk already has its own licenses property.
320`)
321 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
322 bpFile.AddModule(pkg)
323 }
324
Paul Duffin0df49682021-05-07 01:10:01 +0100325 // Group the variants for each member module together and then group the members of each member
326 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100327 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100328
329 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000330 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000331 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000332
Paul Duffina551a1c2020-03-17 21:04:24 +0000333 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000334
335 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100336 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900337 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900338
Paul Duffine6c0d842020-01-15 14:08:51 +0000339 // Create a transformer that will transform an unversioned module into a versioned module.
340 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
341
Paul Duffin72910952020-01-20 18:16:30 +0000342 // Create a transformer that will transform an unversioned module by replacing any references
343 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100344 unversionedTransformer := unversionedTransformation{
345 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100346 }
Paul Duffin72910952020-01-20 18:16:30 +0000347
Paul Duffinb645ec82019-11-27 17:43:54 +0000348 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000349 // Prune any empty property sets.
350 unversioned = unversioned.transform(pruneEmptySetTransformer{})
351
Paul Duffin43f7bf02021-05-05 22:00:51 +0100352 if generateVersioned {
353 // Copy the unversioned module so it can be modified to make it versioned.
354 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000355
Paul Duffin43f7bf02021-05-05 22:00:51 +0100356 // Transform the unversioned module into a versioned one.
357 versioned.transform(unversionedToVersionedTransformer)
358 bpFile.AddModule(versioned)
359 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000360
Paul Duffin43f7bf02021-05-05 22:00:51 +0100361 if generateUnversioned {
362 // Transform the unversioned module to make it suitable for use in the snapshot.
363 unversioned.transform(unversionedTransformer)
364 bpFile.AddModule(unversioned)
365 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000366 }
367
Paul Duffin43f7bf02021-05-05 22:00:51 +0100368 if generateVersioned {
369 // Add the sdk/module_exports_snapshot module to the bp file.
370 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
371 }
Paul Duffin26197a62021-04-24 00:34:10 +0100372
373 // generate Android.bp
374 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
375 generateBpContents(&bp.generatedContents, bpFile)
376
377 contents := bp.content.String()
378 syntaxCheckSnapshotBpFile(ctx, contents)
379
380 bp.build(pctx, ctx, nil)
381
382 filesToZip := builder.filesToZip
383
384 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100385 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
386 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100387 outputDesc := "Building snapshot for " + ctx.ModuleName()
388
389 // If there are no zips to merge then generate the output zip directly.
390 // Otherwise, generate an intermediate zip file into which other zips can be
391 // merged.
392 var zipFile android.OutputPath
393 var desc string
394 if len(builder.zipsToMerge) == 0 {
395 zipFile = outputZipFile
396 desc = outputDesc
397 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100398 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
399 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100400 desc = "Building intermediate snapshot for " + ctx.ModuleName()
401 }
402
403 ctx.Build(pctx, android.BuildParams{
404 Description: desc,
405 Rule: zipFiles,
406 Inputs: filesToZip,
407 Output: zipFile,
408 Args: map[string]string{
409 "basedir": builder.snapshotDir.String(),
410 },
411 })
412
413 if len(builder.zipsToMerge) != 0 {
414 ctx.Build(pctx, android.BuildParams{
415 Description: outputDesc,
416 Rule: mergeZips,
417 Input: zipFile,
418 Inputs: builder.zipsToMerge,
419 Output: outputZipFile,
420 })
421 }
422
423 return outputZipFile
424}
425
426// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100427func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100428 bpFile := builder.bpFile
429
Paul Duffinb645ec82019-11-27 17:43:54 +0000430 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000431 var snapshotModuleType string
432 if s.properties.Module_exports {
433 snapshotModuleType = "module_exports_snapshot"
434 } else {
435 snapshotModuleType = "sdk_snapshot"
436 }
437 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000438 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000439
440 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100441 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000442 if len(visibility) != 0 {
443 snapshotModule.AddProperty("visibility", visibility)
444 }
445
Paul Duffin865171e2020-03-02 18:38:15 +0000446 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000447
Paul Duffincd064672021-04-24 00:47:29 +0100448 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100449 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000450
Paul Duffin2d1bb892021-04-24 11:32:59 +0100451 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100452
Paul Duffin6a7e9532020-03-20 17:50:07 +0000453 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100454
Paul Duffin2d1bb892021-04-24 11:32:59 +0100455 // Create a mapping from osType to combined properties.
456 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
457 for _, combined := range combinedPropertiesList {
458 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
459 }
460
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100461 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000462 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100463 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100464 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000465
Paul Duffin2d1bb892021-04-24 11:32:59 +0100466 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000467 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000468 }
Paul Duffin865171e2020-03-02 18:38:15 +0000469
Jiyong Park8fe14e62020-10-19 22:47:34 +0900470 // If host is supported and any member is host OS dependent then disable host
471 // by default, so that we can enable each host OS variant explicitly. This
472 // avoids problems with implicitly enabled OS variants when the snapshot is
473 // used, which might be different from this run (e.g. different build OS).
474 if s.HostSupported() {
475 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100476 for _, memberVariantDep := range memberVariantDeps {
477 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
478 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900479 if !android.InList(targetString, supportedHostTargets) {
480 supportedHostTargets = append(supportedHostTargets, targetString)
481 }
482 }
483 }
484 if len(supportedHostTargets) > 0 {
485 hostPropertySet := targetPropertySet.AddPropertySet("host")
486 hostPropertySet.AddProperty("enabled", false)
487 }
488 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
489 for _, hostTarget := range supportedHostTargets {
490 propertySet := targetPropertySet.AddPropertySet(hostTarget)
491 propertySet.AddProperty("enabled", true)
492 }
493 }
494
Paul Duffin865171e2020-03-02 18:38:15 +0000495 // Prune any empty property sets.
496 snapshotModule.transform(pruneEmptySetTransformer{})
497
Paul Duffinb645ec82019-11-27 17:43:54 +0000498 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900499}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000500
Paul Duffinf88d8e02020-05-07 20:21:34 +0100501// Check the syntax of the generated Android.bp file contents and if they are
502// invalid then log an error with the contents (tagged with line numbers) and the
503// errors that were found so that it is easy to see where the problem lies.
504func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
505 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
506 if len(errs) != 0 {
507 message := &strings.Builder{}
508 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
509
510Generated Android.bp contents
511========================================================================
512`)
513 for i, line := range strings.Split(contents, "\n") {
514 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
515 }
516
517 _, _ = fmt.Fprint(message, `
518========================================================================
519
520Errors found:
521`)
522
523 for _, err := range errs {
524 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
525 }
526
527 ctx.ModuleErrorf("%s", message.String())
528 }
529}
530
Paul Duffin4b8b7932020-05-06 12:35:38 +0100531func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
532 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
533 if err != nil {
534 ctx.ModuleErrorf("error extracting common properties: %s", err)
535 }
536}
537
Paul Duffinfbe470e2021-04-24 12:37:13 +0100538// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
539type snapshotModuleStaticProperties struct {
540 Compile_multilib string `android:"arch_variant"`
541}
542
Paul Duffin2d1bb892021-04-24 11:32:59 +0100543// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
544type combinedSnapshotModuleProperties struct {
545 // The sdk variant from which this information was collected.
546 sdkVariant *sdk
547
548 // Static snapshot module properties.
549 staticProperties *snapshotModuleStaticProperties
550
551 // The dynamically generated member list properties.
552 dynamicProperties interface{}
553}
554
555// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100556func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
557 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100558 var list []*combinedSnapshotModuleProperties
559 for _, sdkVariant := range sdkVariants {
560 staticProperties := &snapshotModuleStaticProperties{
561 Compile_multilib: sdkVariant.multilibUsages.String(),
562 }
Paul Duffincd064672021-04-24 00:47:29 +0100563 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100564
Paul Duffincd064672021-04-24 00:47:29 +0100565 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100566 sdkVariant: sdkVariant,
567 staticProperties: staticProperties,
568 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100569 }
570 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
571
572 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100573 }
Paul Duffincd064672021-04-24 00:47:29 +0100574
575 for _, memberVariantDep := range memberVariantDeps {
576 // If the member dependency is internal then do not add the dependency to the snapshot member
577 // list properties.
578 if !memberVariantDep.export {
579 continue
580 }
581
582 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100583 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100584 memberName := ctx.OtherModuleName(memberVariantDep.variant)
585
Paul Duffin13082052021-05-11 00:31:38 +0100586 if memberListProperty.getter == nil {
587 continue
588 }
589
Paul Duffincd064672021-04-24 00:47:29 +0100590 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100591 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100592 if !android.InList(memberName, memberList) {
593 memberList = append(memberList, memberName)
594 }
Paul Duffin13082052021-05-11 00:31:38 +0100595 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100596 }
597
Paul Duffin2d1bb892021-04-24 11:32:59 +0100598 return list
599}
600
601func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
602
603 // Extract the dynamic properties and add them to a list of propertiesContainer.
604 propertyContainers := []propertiesContainer{}
605 for _, i := range list {
606 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
607 sdkVariant: i.sdkVariant,
608 properties: i.dynamicProperties,
609 })
610 }
611
612 // Extract the common members, removing them from the original properties.
613 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
614 extractor := newCommonValueExtractor(commonDynamicProperties)
615 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
616
617 // Extract the static properties and add them to a list of propertiesContainer.
618 propertyContainers = []propertiesContainer{}
619 for _, i := range list {
620 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
621 sdkVariant: i.sdkVariant,
622 properties: i.staticProperties,
623 })
624 }
625
626 commonStaticProperties := &snapshotModuleStaticProperties{}
627 extractor = newCommonValueExtractor(commonStaticProperties)
628 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
629
630 return &combinedSnapshotModuleProperties{
631 sdkVariant: nil,
632 staticProperties: commonStaticProperties,
633 dynamicProperties: commonDynamicProperties,
634 }
635}
636
637func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
638 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100639 multilib := staticProperties.Compile_multilib
640 if multilib != "" && multilib != "both" {
641 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
642 propertySet.AddProperty("compile_multilib", multilib)
643 }
644
Paul Duffin2d1bb892021-04-24 11:32:59 +0100645 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000646 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100647 if memberListProperty.getter == nil {
648 continue
649 }
Paul Duffin865171e2020-03-02 18:38:15 +0000650 names := memberListProperty.getter(dynamicMemberTypeListProperties)
651 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000652 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000653 }
654 }
655}
656
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000657type propertyTag struct {
658 name string
659}
660
Paul Duffin0cb37b92020-03-04 14:52:46 +0000661// A BpPropertyTag to add to a property that contains references to other sdk members.
662//
663// This will cause the references to be rewritten to a versioned reference in the version
664// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000665var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000666var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000667
Paul Duffin0cb37b92020-03-04 14:52:46 +0000668// A BpPropertyTag that indicates the property should only be present in the versioned
669// module.
670//
671// This will cause the property to be removed from the unversioned instance of a
672// snapshot module.
673var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
674
Paul Duffine6c0d842020-01-15 14:08:51 +0000675type unversionedToVersionedTransformation struct {
676 identityTransformation
677 builder *snapshotBuilder
678}
679
Paul Duffine6c0d842020-01-15 14:08:51 +0000680func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
681 // Use a versioned name for the module but remember the original name for the
682 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100683 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000684 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000685 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100686 // Remove the prefer property if present as versioned modules never need marking with prefer.
687 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000688 return module
689}
690
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000691func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000692 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
693 required := tag == requiredSdkMemberReferencePropertyTag
694 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000695 } else {
696 return value, tag
697 }
698}
699
Paul Duffin72910952020-01-20 18:16:30 +0000700type unversionedTransformation struct {
701 identityTransformation
702 builder *snapshotBuilder
703}
704
705func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
706 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100707 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000708 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000709 return module
710}
711
712func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000713 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
714 required := tag == requiredSdkMemberReferencePropertyTag
715 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000716 } else if tag == sdkVersionedOnlyPropertyTag {
717 // The property is not allowed in the unversioned module so remove it.
718 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000719 } else {
720 return value, tag
721 }
722}
723
Paul Duffina78f3a72020-02-21 16:29:35 +0000724type pruneEmptySetTransformer struct {
725 identityTransformation
726}
727
728var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
729
730func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
731 if len(propertySet.properties) == 0 {
732 return nil, nil
733 } else {
734 return propertySet, tag
735 }
736}
737
Paul Duffinb645ec82019-11-27 17:43:54 +0000738func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000739 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
740 return true
741 })
742}
743
744func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000745 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
746 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000747 if moduleFilter(bpModule) {
748 contents.Printfln("")
749 contents.Printfln("%s {", bpModule.moduleType)
750 outputPropertySet(contents, bpModule.bpPropertySet)
751 contents.Printfln("}")
752 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000753 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000754}
755
756func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
757 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000758
Paul Duffin0df49682021-05-07 01:10:01 +0100759 addComment := func(name string) {
760 if text, ok := set.comments[name]; ok {
761 for _, line := range strings.Split(text, "\n") {
762 contents.Printfln("// %s", line)
763 }
764 }
765 }
766
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000767 // Output the properties first, followed by the nested sets. This ensures a
768 // consistent output irrespective of whether property sets are created before
769 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000770 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000771 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000772
Paul Duffin0df49682021-05-07 01:10:01 +0100773 // Do not write property sets in the properties phase.
774 if _, ok := value.(*bpPropertySet); ok {
775 continue
776 }
777
778 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000779 switch v := value.(type) {
780 case []string:
781 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000782 if length > 1 {
783 contents.Printfln("%s: [", name)
784 contents.Indent()
785 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000786 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000787 }
788 contents.Dedent()
789 contents.Printfln("],")
790 } else if length == 0 {
791 contents.Printfln("%s: [],", name)
792 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000793 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000794 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000795
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000796 case bool:
797 contents.Printfln("%s: %t,", name, v)
798
Paul Duffinb645ec82019-11-27 17:43:54 +0000799 default:
800 contents.Printfln("%s: %q,", name, value)
801 }
802 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000803
804 for _, name := range set.order {
805 value := set.getValue(name)
806
807 // Only write property sets in the sets phase.
808 switch v := value.(type) {
809 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100810 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000811 contents.Printfln("%s: {", name)
812 outputPropertySet(contents, v)
813 contents.Printfln("},")
814 }
815 }
816
Paul Duffinb645ec82019-11-27 17:43:54 +0000817 contents.Dedent()
818}
819
Paul Duffinac37c502019-11-26 18:02:20 +0000820func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000821 contents := &generatedContents{}
822 generateBpContents(contents, s.builderForTests.bpFile)
823 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000824}
825
Paul Duffind0759072021-02-17 11:23:00 +0000826func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
827 contents := &generatedContents{}
828 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100829 name := module.Name()
830 // Include modules that are either unversioned or have no name.
831 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000832 })
833 return contents.content.String()
834}
835
836func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
837 contents := &generatedContents{}
838 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100839 name := module.Name()
840 // Include modules that are either versioned or have no name.
841 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000842 })
843 return contents.content.String()
844}
845
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000846type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100847 ctx android.ModuleContext
848 sdk *sdk
849
850 // The version of the generated snapshot.
851 //
852 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
853 // this field.
854 version string
855
Paul Duffinb645ec82019-11-27 17:43:54 +0000856 snapshotDir android.OutputPath
857 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000858
859 // Map from destination to source of each copy - used to eliminate duplicates and
860 // detect conflicts.
861 copies map[string]string
862
Paul Duffinb645ec82019-11-27 17:43:54 +0000863 filesToZip android.Paths
864 zipsToMerge android.Paths
865
866 prebuiltModules map[string]*bpModule
867 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000868
869 // The set of all members by name.
870 allMembersByName map[string]struct{}
871
872 // The set of exported members by name.
873 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000874}
875
876func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000877 if existing, ok := s.copies[dest]; ok {
878 if existing != src.String() {
879 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
880 return
881 }
882 } else {
883 path := s.snapshotDir.Join(s.ctx, dest)
884 s.ctx.Build(pctx, android.BuildParams{
885 Rule: android.Cp,
886 Input: src,
887 Output: path,
888 })
889 s.filesToZip = append(s.filesToZip, path)
890
891 s.copies[dest] = src.String()
892 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000893}
894
Paul Duffin91547182019-11-12 19:39:36 +0000895func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
896 ctx := s.ctx
897
898 // Repackage the zip file so that the entries are in the destDir directory.
899 // This will allow the zip file to be merged into the snapshot.
900 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000901
902 ctx.Build(pctx, android.BuildParams{
903 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
904 Rule: repackageZip,
905 Input: zipPath,
906 Output: tmpZipPath,
907 Args: map[string]string{
908 "destdir": destDir,
909 },
910 })
Paul Duffin91547182019-11-12 19:39:36 +0000911
912 // Add the repackaged zip file to the files to merge.
913 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
914}
915
Paul Duffin9d8d6092019-12-05 18:19:29 +0000916func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
917 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000918 if s.prebuiltModules[name] != nil {
919 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
920 }
921
922 m := s.bpFile.newModule(moduleType)
923 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000924
Paul Duffinbefa4b92020-03-04 14:22:45 +0000925 variant := member.Variants()[0]
926
Paul Duffin13f02712020-03-06 12:30:43 +0000927 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000928 // An internal member is only referenced from the sdk snapshot which is in the
929 // same package so can be marked as private.
930 m.AddProperty("visibility", []string{"//visibility:private"})
931 } else {
932 // Extract visibility information from a member variant. All variants have the same
933 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100934 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
935
936 // Add any additional visibility rules needed for the prebuilts to reference each other.
937 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
938 if err != nil {
939 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
940 }
941
942 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000943 if len(visibility) != 0 {
944 m.AddProperty("visibility", visibility)
945 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000946 }
947
Martin Stjernholm1e041092020-11-03 00:11:09 +0000948 // Where available copy apex_available properties from the member.
949 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
950 apexAvailable := apexAware.ApexAvailable()
951 if len(apexAvailable) == 0 {
952 // //apex_available:platform is the default.
953 apexAvailable = []string{android.AvailableToPlatform}
954 }
955
956 // Add in any baseline apex available settings.
957 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
958
959 // Remove duplicates and sort.
960 apexAvailable = android.FirstUniqueStrings(apexAvailable)
961 sort.Strings(apexAvailable)
962
963 m.AddProperty("apex_available", apexAvailable)
964 }
965
Paul Duffinb0bb3762021-05-06 16:48:05 +0100966 // The licenses are the same for all variants.
967 mctx := s.ctx
968 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
969 if len(licenseInfo.Licenses) > 0 {
970 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
971 }
972
Paul Duffin865171e2020-03-02 18:38:15 +0000973 deviceSupported := false
974 hostSupported := false
975
976 for _, variant := range member.Variants() {
977 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900978 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000979 hostSupported = true
980 } else if osClass == android.Device {
981 deviceSupported = true
982 }
983 }
984
985 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000986
Paul Duffin0cb37b92020-03-04 14:52:46 +0000987 // Disable installation in the versioned module of those modules that are ever installable.
988 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
989 if installable.EverInstallable() {
990 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
991 }
992 }
993
Paul Duffinb645ec82019-11-27 17:43:54 +0000994 s.prebuiltModules[name] = m
995 s.prebuiltOrder = append(s.prebuiltOrder, m)
996 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000997}
998
Paul Duffin865171e2020-03-02 18:38:15 +0000999func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001000 // If neither device or host is supported then this module does not support either so will not
1001 // recognize the properties.
1002 if !deviceSupported && !hostSupported {
1003 return
1004 }
1005
Paul Duffin865171e2020-03-02 18:38:15 +00001006 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001007 bpModule.AddProperty("device_supported", false)
1008 }
Paul Duffin865171e2020-03-02 18:38:15 +00001009 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001010 bpModule.AddProperty("host_supported", true)
1011 }
1012}
1013
Paul Duffin13f02712020-03-06 12:30:43 +00001014func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1015 if required {
1016 return requiredSdkMemberReferencePropertyTag
1017 } else {
1018 return optionalSdkMemberReferencePropertyTag
1019 }
1020}
1021
1022func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1023 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001024}
1025
Paul Duffinb645ec82019-11-27 17:43:54 +00001026// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001027func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1028 if _, ok := s.allMembersByName[unversionedName]; !ok {
1029 if required {
1030 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1031 }
1032 return unversionedName
1033 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001034 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1035}
Paul Duffinb645ec82019-11-27 17:43:54 +00001036
Paul Duffin13f02712020-03-06 12:30:43 +00001037func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001038 var references []string = nil
1039 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001040 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001041 }
1042 return references
1043}
Paul Duffin13879572019-11-28 14:31:38 +00001044
Paul Duffin72910952020-01-20 18:16:30 +00001045// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001046func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1047 if _, ok := s.allMembersByName[unversionedName]; !ok {
1048 if required {
1049 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1050 }
1051 return unversionedName
1052 }
1053
1054 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001055 return s.ctx.ModuleName() + "_" + unversionedName
1056 } else {
1057 return unversionedName
1058 }
1059}
1060
Paul Duffin13f02712020-03-06 12:30:43 +00001061func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001062 var references []string = nil
1063 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001064 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001065 }
1066 return references
1067}
1068
Paul Duffin13f02712020-03-06 12:30:43 +00001069func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1070 _, ok := s.exportedMembersByName[memberName]
1071 return !ok
1072}
1073
Martin Stjernholm89238f42020-07-10 00:14:03 +01001074// Add the properties from the given SdkMemberProperties to the blueprint
1075// property set. This handles common properties in SdkMemberPropertiesBase and
1076// calls the member-specific AddToPropertySet for the rest.
1077func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1078 if memberProperties.Base().Compile_multilib != "" {
1079 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1080 }
1081
1082 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1083}
1084
Paul Duffin21827262021-04-24 12:16:36 +01001085// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1086type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001087 // The sdk variant that depends (possibly indirectly) on the member variant.
1088 sdkVariant *sdk
Paul Duffin1356d8c2020-02-25 19:26:33 +00001089 memberType android.SdkMemberType
1090 variant android.SdkAware
Paul Duffina7208112021-04-23 21:20:20 +01001091 export bool
Paul Duffin1356d8c2020-02-25 19:26:33 +00001092}
1093
Paul Duffin13879572019-11-28 14:31:38 +00001094var _ android.SdkMember = (*sdkMember)(nil)
1095
Paul Duffin21827262021-04-24 12:16:36 +01001096// sdkMember groups all the variants of a specific member module together along with the name of the
1097// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001098type sdkMember struct {
1099 memberType android.SdkMemberType
1100 name string
1101 variants []android.SdkAware
1102}
1103
1104func (m *sdkMember) Name() string {
1105 return m.name
1106}
1107
1108func (m *sdkMember) Variants() []android.SdkAware {
1109 return m.variants
1110}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001111
Paul Duffin9c3760e2020-03-16 19:52:08 +00001112// Track usages of multilib variants.
1113type multilibUsage int
1114
1115const (
1116 multilibNone multilibUsage = 0
1117 multilib32 multilibUsage = 1
1118 multilib64 multilibUsage = 2
1119 multilibBoth = multilib32 | multilib64
1120)
1121
1122// Add the multilib that is used in the arch type.
1123func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1124 multilib := archType.Multilib
1125 switch multilib {
1126 case "":
1127 return m
1128 case "lib32":
1129 return m | multilib32
1130 case "lib64":
1131 return m | multilib64
1132 default:
1133 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1134 }
1135}
1136
1137func (m multilibUsage) String() string {
1138 switch m {
1139 case multilibNone:
1140 return ""
1141 case multilib32:
1142 return "32"
1143 case multilib64:
1144 return "64"
1145 case multilibBoth:
1146 return "both"
1147 default:
1148 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1149 m, multilibNone, multilib32, multilib64, multilibBoth))
1150 }
1151}
1152
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001153type baseInfo struct {
1154 Properties android.SdkMemberProperties
1155}
1156
Paul Duffinf34f6d82020-04-30 15:48:31 +01001157func (b *baseInfo) optimizableProperties() interface{} {
1158 return b.Properties
1159}
1160
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001161type osTypeSpecificInfo struct {
1162 baseInfo
1163
Paul Duffin00e46802020-03-12 20:40:35 +00001164 osType android.OsType
1165
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001166 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001167 //
1168 // Nil if there is one variant whose arch type is common
1169 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001170}
1171
Paul Duffin4b8b7932020-05-06 12:35:38 +01001172var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1173
Paul Duffinfc8dd232020-03-17 12:51:37 +00001174type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1175
Paul Duffin00e46802020-03-12 20:40:35 +00001176// Create a new osTypeSpecificInfo for the specified os type and its properties
1177// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001178func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001179 osInfo := &osTypeSpecificInfo{
1180 osType: osType,
1181 }
1182
1183 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1184 properties := variantPropertiesFactory()
1185 properties.Base().Os = osType
1186 return properties
1187 }
1188
1189 // Create a structure into which properties common across the architectures in
1190 // this os type will be stored.
1191 osInfo.Properties = osSpecificVariantPropertiesFactory()
1192
1193 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001194 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001195 var archTypes []android.ArchType
1196 for _, variant := range osTypeVariants {
1197 archType := variant.Target().Arch.ArchType
1198 archTypeName := archType.Name
1199 if _, ok := variantsByArchName[archTypeName]; !ok {
1200 archTypes = append(archTypes, archType)
1201 }
1202
1203 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1204 }
1205
1206 if commonVariants, ok := variantsByArchName["common"]; ok {
1207 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001208 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 +00001209 }
1210
1211 // A common arch type only has one variant and its properties should be treated
1212 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001213 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001214 } else {
1215 // Create an arch specific info for each supported architecture type.
1216 for _, archType := range archTypes {
1217 archTypeName := archType.Name
1218
1219 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001220 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001221
1222 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1223 }
1224 }
1225
1226 return osInfo
1227}
1228
1229// Optimize the properties by extracting common properties from arch type specific
1230// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001231func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001232 // Nothing to do if there is only a single common architecture.
1233 if len(osInfo.archInfos) == 0 {
1234 return
1235 }
1236
Paul Duffin9c3760e2020-03-16 19:52:08 +00001237 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001238 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001239 multilib = multilib.addArchType(archInfo.archType)
1240
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001241 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001242 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001243 }
1244
Paul Duffin4b8b7932020-05-06 12:35:38 +01001245 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001246
1247 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001248 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001249}
1250
1251// Add the properties for an os to a property set.
1252//
1253// Maps the properties related to the os variants through to an appropriate
1254// module structure that will produce equivalent set of variants when it is
1255// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001256func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001257
1258 var osPropertySet android.BpPropertySet
1259 var archPropertySet android.BpPropertySet
1260 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001261 if osInfo.Properties.Base().Os_count == 1 &&
1262 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1263 // There is only one OS type present in the variants and it shouldn't have a
1264 // variant-specific target. The latter is the case if it's either for device
1265 // where there is only one OS (android), or for host and the member type
1266 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001267
1268 // Create a structure that looks like:
1269 // module_type {
1270 // name: "...",
1271 // ...
1272 // <common properties>
1273 // ...
1274 // <single os type specific properties>
1275 //
1276 // arch: {
1277 // <arch specific sections>
1278 // }
1279 //
1280 osPropertySet = bpModule
1281 archPropertySet = osPropertySet.AddPropertySet("arch")
1282
1283 // Arch specific properties need to be added to an arch specific section
1284 // within arch.
1285 archOsPrefix = ""
1286 } else {
1287 // Create a structure that looks like:
1288 // module_type {
1289 // name: "...",
1290 // ...
1291 // <common properties>
1292 // ...
1293 // target: {
1294 // <arch independent os specific sections, e.g. android>
1295 // ...
1296 // <arch and os specific sections, e.g. android_x86>
1297 // }
1298 //
1299 osType := osInfo.osType
1300 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1301 archPropertySet = targetPropertySet
1302
1303 // Arch specific properties need to be added to an os and arch specific
1304 // section prefixed with <os>_.
1305 archOsPrefix = osType.Name + "_"
1306 }
1307
1308 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001309 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001310
1311 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1312 // os) specific properties.
1313 //
1314 // The archInfos list will be empty if the os contains variants for the common
1315 // architecture.
1316 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001317 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001318 }
1319}
1320
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001321func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1322 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001323 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001324}
1325
1326var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1327
Paul Duffin4b8b7932020-05-06 12:35:38 +01001328func (osInfo *osTypeSpecificInfo) String() string {
1329 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1330}
1331
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001332type archTypeSpecificInfo struct {
1333 baseInfo
1334
1335 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001336 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001337
1338 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001339}
1340
Paul Duffin4b8b7932020-05-06 12:35:38 +01001341var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1342
Paul Duffinfc8dd232020-03-17 12:51:37 +00001343// Create a new archTypeSpecificInfo for the specified arch type and its properties
1344// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001345func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001346
Paul Duffinfc8dd232020-03-17 12:51:37 +00001347 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001348 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001349
1350 // Create the properties into which the arch type specific properties will be
1351 // added.
1352 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001353
1354 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001355 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001356 } else {
1357 // There is more than one variant for this arch type which must be differentiated
1358 // by link type.
1359 for _, linkVariant := range archVariants {
1360 linkType := getLinkType(linkVariant)
1361 if linkType == "" {
1362 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1363 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001364 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001365
1366 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1367 }
1368 }
1369 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001370
1371 return archInfo
1372}
1373
Paul Duffinf34f6d82020-04-30 15:48:31 +01001374func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1375 return archInfo.Properties
1376}
1377
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001378// Get the link type of the variant
1379//
1380// If the variant is not differentiated by link type then it returns "",
1381// otherwise it returns one of "static" or "shared".
1382func getLinkType(variant android.Module) string {
1383 linkType := ""
1384 if linkable, ok := variant.(cc.LinkableInterface); ok {
1385 if linkable.Shared() && linkable.Static() {
1386 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1387 } else if linkable.Shared() {
1388 linkType = "shared"
1389 } else if linkable.Static() {
1390 linkType = "static"
1391 } else {
1392 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1393 }
1394 }
1395 return linkType
1396}
1397
1398// Optimize the properties by extracting common properties from link type specific
1399// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001400func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001401 if len(archInfo.linkInfos) == 0 {
1402 return
1403 }
1404
Paul Duffin4b8b7932020-05-06 12:35:38 +01001405 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001406}
1407
Paul Duffinfc8dd232020-03-17 12:51:37 +00001408// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001409func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001410 archTypeName := archInfo.archType.Name
1411 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001412 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1413 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1414 archTypePropertySet.AddProperty("enabled", true)
1415 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001416 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001417
1418 for _, linkInfo := range archInfo.linkInfos {
1419 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001420 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001421 }
1422}
1423
Paul Duffin4b8b7932020-05-06 12:35:38 +01001424func (archInfo *archTypeSpecificInfo) String() string {
1425 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1426}
1427
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001428type linkTypeSpecificInfo struct {
1429 baseInfo
1430
1431 linkType string
1432}
1433
Paul Duffin4b8b7932020-05-06 12:35:38 +01001434var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1435
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001436// Create a new linkTypeSpecificInfo for the specified link type and its properties
1437// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001438func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001439 linkInfo := &linkTypeSpecificInfo{
1440 baseInfo: baseInfo{
1441 // Create the properties into which the link type specific properties will be
1442 // added.
1443 Properties: variantPropertiesFactory(),
1444 },
1445 linkType: linkType,
1446 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001447 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001448 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001449}
1450
Paul Duffin4b8b7932020-05-06 12:35:38 +01001451func (l *linkTypeSpecificInfo) String() string {
1452 return fmt.Sprintf("LinkType{%s}", l.linkType)
1453}
1454
Paul Duffin3a4eb502020-03-19 16:11:18 +00001455type memberContext struct {
1456 sdkMemberContext android.ModuleContext
1457 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001458 memberType android.SdkMemberType
1459 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001460}
1461
1462func (m *memberContext) SdkModuleContext() android.ModuleContext {
1463 return m.sdkMemberContext
1464}
1465
1466func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1467 return m.builder
1468}
1469
Paul Duffina551a1c2020-03-17 21:04:24 +00001470func (m *memberContext) MemberType() android.SdkMemberType {
1471 return m.memberType
1472}
1473
1474func (m *memberContext) Name() string {
1475 return m.name
1476}
1477
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001478func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001479
1480 memberType := member.memberType
1481
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001482 // Do not add the prefer property if the member snapshot module is a source module type.
1483 if !memberType.UsesSourceModuleTypeInSnapshot() {
1484 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1485 // snapshot to be created that sets prefer: true.
1486 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1487 // dynamically at build time not at snapshot generation time.
1488 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001489
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001490 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1491 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1492 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1493 // behavior is for the module.
1494 bpModule.insertAfter("name", "prefer", prefer)
1495 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001496
Paul Duffina04c1072020-03-02 10:16:35 +00001497 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001498 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001499 variants := member.Variants()
1500 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001501 osType := variant.Target().Os
1502 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001503 }
1504
Paul Duffina04c1072020-03-02 10:16:35 +00001505 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001506 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001507 properties := memberType.CreateVariantPropertiesStruct()
1508 base := properties.Base()
1509 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001510 return properties
1511 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001512
Paul Duffina04c1072020-03-02 10:16:35 +00001513 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001514
Paul Duffina04c1072020-03-02 10:16:35 +00001515 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001516 commonProperties := variantPropertiesFactory()
1517 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001518
Paul Duffinc097e362020-03-10 22:50:03 +00001519 // Create common value extractor that can be used to optimize the properties.
1520 commonValueExtractor := newCommonValueExtractor(commonProperties)
1521
Paul Duffina04c1072020-03-02 10:16:35 +00001522 // The list of property structures which are os type specific but common across
1523 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001524 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001525
1526 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001527 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001528 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001529 // Add the os specific properties to a list of os type specific yet architecture
1530 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001531 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001532
Paul Duffin00e46802020-03-12 20:40:35 +00001533 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001534 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001535 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001536
Paul Duffina04c1072020-03-02 10:16:35 +00001537 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001538 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001539
Paul Duffina04c1072020-03-02 10:16:35 +00001540 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001541 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001542
Paul Duffina04c1072020-03-02 10:16:35 +00001543 // Create a target property set into which target specific properties can be
1544 // added.
1545 targetPropertySet := bpModule.AddPropertySet("target")
1546
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001547 // If the member is host OS dependent and has host_supported then disable by
1548 // default and enable each host OS variant explicitly. This avoids problems
1549 // with implicitly enabled OS variants when the snapshot is used, which might
1550 // be different from this run (e.g. different build OS).
1551 if ctx.memberType.IsHostOsDependent() {
1552 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1553 if hostSupported {
1554 hostPropertySet := targetPropertySet.AddPropertySet("host")
1555 hostPropertySet.AddProperty("enabled", false)
1556 }
1557 }
1558
Paul Duffina04c1072020-03-02 10:16:35 +00001559 // Iterate over the os types in a fixed order.
1560 for _, osType := range s.getPossibleOsTypes() {
1561 osInfo := osTypeToInfo[osType]
1562 if osInfo == nil {
1563 continue
1564 }
1565
Paul Duffin3a4eb502020-03-19 16:11:18 +00001566 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001567 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001568}
1569
Paul Duffina04c1072020-03-02 10:16:35 +00001570// Compute the list of possible os types that this sdk could support.
1571func (s *sdk) getPossibleOsTypes() []android.OsType {
1572 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001573 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001574 if s.DeviceSupported() {
1575 if osType.Class == android.Device && osType != android.Fuchsia {
1576 osTypes = append(osTypes, osType)
1577 }
1578 }
1579 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001580 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001581 osTypes = append(osTypes, osType)
1582 }
1583 }
1584 }
1585 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1586 return osTypes
1587}
1588
Paul Duffinb28369a2020-05-04 15:39:59 +01001589// Given a set of properties (struct value), return the value of the field within that
1590// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001591type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1592
Paul Duffinc459f892020-04-30 18:08:29 +01001593// Checks the metadata to determine whether the property should be ignored for the
1594// purposes of common value extraction or not.
1595type extractorMetadataPredicate func(metadata propertiesContainer) bool
1596
1597// Indicates whether optimizable properties are provided by a host variant or
1598// not.
1599type isHostVariant interface {
1600 isHostVariant() bool
1601}
1602
Paul Duffinb28369a2020-05-04 15:39:59 +01001603// A property that can be optimized by the commonValueExtractor.
1604type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001605 // The name of the field for this property. It is a "."-separated path for
1606 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001607 name string
1608
Paul Duffinc459f892020-04-30 18:08:29 +01001609 // Filter that can use metadata associated with the properties being optimized
1610 // to determine whether the field should be ignored during common value
1611 // optimization.
1612 filter extractorMetadataPredicate
1613
Paul Duffinb28369a2020-05-04 15:39:59 +01001614 // Retrieves the value on which common value optimization will be performed.
1615 getter fieldAccessorFunc
1616
1617 // The empty value for the field.
1618 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001619
1620 // True if the property can support arch variants false otherwise.
1621 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001622}
1623
Paul Duffin4b8b7932020-05-06 12:35:38 +01001624func (p extractorProperty) String() string {
1625 return p.name
1626}
1627
Paul Duffinc097e362020-03-10 22:50:03 +00001628// Supports extracting common values from a number of instances of a properties
1629// structure into a separate common set of properties.
1630type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001631 // The properties that the extractor can optimize.
1632 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001633}
1634
1635// Create a new common value extractor for the structure type for the supplied
1636// properties struct.
1637//
1638// The returned extractor can be used on any properties structure of the same type
1639// as the supplied set of properties.
1640func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1641 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1642 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001643 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001644 return extractor
1645}
1646
1647// Gather the fields from the supplied structure type from which common values will
1648// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001649//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001650// This is recursive function. If it encounters a struct then it will recurse
1651// into it, passing in the accessor for the field and the struct name as prefix
1652// for the nested fields. That will then be used in the accessors for the fields
1653// in the embedded struct.
1654func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001655 for f := 0; f < structType.NumField(); f++ {
1656 field := structType.Field(f)
1657 if field.PkgPath != "" {
1658 // Ignore unexported fields.
1659 continue
1660 }
1661
Paul Duffinb07fa512020-03-10 22:17:04 +00001662 // Ignore fields whose value should be kept.
1663 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001664 continue
1665 }
1666
Paul Duffinc459f892020-04-30 18:08:29 +01001667 var filter extractorMetadataPredicate
1668
1669 // Add a filter
1670 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1671 filter = func(metadata propertiesContainer) bool {
1672 if m, ok := metadata.(isHostVariant); ok {
1673 if m.isHostVariant() {
1674 return false
1675 }
1676 }
1677 return true
1678 }
1679 }
1680
Paul Duffinc097e362020-03-10 22:50:03 +00001681 // Save a copy of the field index for use in the function.
1682 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001683
Martin Stjernholmb0249572020-09-15 02:32:35 +01001684 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001685
Paul Duffinc097e362020-03-10 22:50:03 +00001686 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001687 if containingStructAccessor != nil {
1688 // This is an embedded structure so first access the field for the embedded
1689 // structure.
1690 value = containingStructAccessor(value)
1691 }
1692
Paul Duffinc097e362020-03-10 22:50:03 +00001693 // Skip through interface and pointer values to find the structure.
1694 value = getStructValue(value)
1695
Paul Duffin4b8b7932020-05-06 12:35:38 +01001696 defer func() {
1697 if r := recover(); r != nil {
1698 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1699 }
1700 }()
1701
Paul Duffinc097e362020-03-10 22:50:03 +00001702 // Return the field.
1703 return value.Field(fieldIndex)
1704 }
1705
Martin Stjernholmb0249572020-09-15 02:32:35 +01001706 if field.Type.Kind() == reflect.Struct {
1707 // Gather fields from the nested or embedded structure.
1708 var subNamePrefix string
1709 if field.Anonymous {
1710 subNamePrefix = namePrefix
1711 } else {
1712 subNamePrefix = name + "."
1713 }
1714 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001715 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001716 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001717 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001718 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001719 fieldGetter,
1720 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001721 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001722 }
1723 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001724 }
Paul Duffinc097e362020-03-10 22:50:03 +00001725 }
1726}
1727
1728func getStructValue(value reflect.Value) reflect.Value {
1729foundStruct:
1730 for {
1731 kind := value.Kind()
1732 switch kind {
1733 case reflect.Interface, reflect.Ptr:
1734 value = value.Elem()
1735 case reflect.Struct:
1736 break foundStruct
1737 default:
1738 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1739 }
1740 }
1741 return value
1742}
1743
Paul Duffinf34f6d82020-04-30 15:48:31 +01001744// A container of properties to be optimized.
1745//
1746// Allows additional information to be associated with the properties, e.g. for
1747// filtering.
1748type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001749 fmt.Stringer
1750
Paul Duffinf34f6d82020-04-30 15:48:31 +01001751 // Get the properties that need optimizing.
1752 optimizableProperties() interface{}
1753}
1754
Paul Duffin2d1bb892021-04-24 11:32:59 +01001755// A wrapper for sdk variant related properties to allow them to be optimized.
1756type sdkVariantPropertiesContainer struct {
1757 sdkVariant *sdk
1758 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001759}
1760
Paul Duffin2d1bb892021-04-24 11:32:59 +01001761func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1762 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001763}
1764
Paul Duffin2d1bb892021-04-24 11:32:59 +01001765func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001766 return c.sdkVariant.String()
1767}
1768
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001769// Extract common properties from a slice of property structures of the same type.
1770//
1771// All the property structures must be of the same type.
1772// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001773// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001774//
1775// Iterates over each exported field (capitalized name) and checks to see whether they
1776// have the same value (using DeepEquals) across all the input properties. If it does not then no
1777// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001778// and the field in each of the input properties structure is set to its default value. Nested
1779// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001780func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001781 commonPropertiesValue := reflect.ValueOf(commonProperties)
1782 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001783
Paul Duffinf34f6d82020-04-30 15:48:31 +01001784 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1785
Paul Duffinb28369a2020-05-04 15:39:59 +01001786 for _, property := range e.properties {
1787 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001788 filter := property.filter
1789 if filter == nil {
1790 filter = func(metadata propertiesContainer) bool {
1791 return true
1792 }
1793 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001794
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001795 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001796 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1797 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001798 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001799
Paul Duffin864e1b42020-05-06 10:23:19 +01001800 // Assume that all the values will be the same.
1801 //
1802 // While similar to this is not quite the same as commonValue == nil. If all the values
1803 // have been filtered out then this will be false but commonValue == nil will be true.
1804 valuesDiffer := false
1805
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001806 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001807 container := sliceValue.Index(i).Interface().(propertiesContainer)
1808 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001809 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001810
Paul Duffinc459f892020-04-30 18:08:29 +01001811 if !filter(container) {
1812 expectedValue := property.emptyValue.Interface()
1813 actualValue := fieldValue.Interface()
1814 if !reflect.DeepEqual(expectedValue, actualValue) {
1815 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1816 }
1817 continue
1818 }
1819
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001820 if commonValue == nil {
1821 // Use the first value as the commonProperties value.
1822 commonValue = &fieldValue
1823 } else {
1824 // If the value does not match the current common value then there is
1825 // no value in common so break out.
1826 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1827 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001828 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001829 break
1830 }
1831 }
1832 }
1833
Paul Duffin864e1b42020-05-06 10:23:19 +01001834 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001835 // and set the input struct's field to the empty value.
1836 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001837 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001838 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001839 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001840 container := sliceValue.Index(i).Interface().(propertiesContainer)
1841 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001842 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001843 fieldValue.Set(emptyValue)
1844 }
1845 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001846
1847 if valuesDiffer && !property.archVariant {
1848 // The values differ but the property does not support arch variants so it
1849 // is an error.
1850 var details strings.Builder
1851 for i := 0; i < sliceValue.Len(); i++ {
1852 container := sliceValue.Index(i).Interface().(propertiesContainer)
1853 itemValue := reflect.ValueOf(container.optimizableProperties())
1854 fieldValue := fieldGetter(itemValue)
1855
1856 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1857 }
1858
1859 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1860 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001861 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001862
1863 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001864}