blob: 85dfc4acfba087c5a07a946e70b3ac371712ed28 [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//
39
Jiyong Park9b409bc2019-10-11 14:59:13 +090040var pctx = android.NewPackageContext("android/soong/sdk")
41
Paul Duffin375058f2019-11-29 20:17:53 +000042var (
43 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
44 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000045 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000046 CommandDeps: []string{
47 "${config.Zip2ZipCmd}",
48 },
49 },
50 "destdir")
51
52 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
53 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070054 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000055 CommandDeps: []string{
56 "${config.SoongZipCmd}",
57 },
58 Rspfile: "$out.rsp",
59 RspfileContent: "$in",
60 },
61 "basedir")
62
63 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
64 blueprint.RuleParams{
65 Command: `${config.MergeZipsCmd} $out $in`,
66 CommandDeps: []string{
67 "${config.MergeZipsCmd}",
68 },
69 })
70)
71
Paul Duffinb645ec82019-11-27 17:43:54 +000072type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090073 content strings.Builder
74 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090075}
76
Paul Duffinb645ec82019-11-27 17:43:54 +000077// generatedFile abstracts operations for writing contents into a file and emit a build rule
78// for the file.
79type generatedFile struct {
80 generatedContents
81 path android.OutputPath
82}
83
Jiyong Park232e7852019-11-04 12:23:40 +090084func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090085 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000086 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090087 }
88}
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090func (gc *generatedContents) Indent() {
91 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090092}
93
Paul Duffinb645ec82019-11-27 17:43:54 +000094func (gc *generatedContents) Dedent() {
95 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090096}
97
Paul Duffinb645ec82019-11-27 17:43:54 +000098func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +010099 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900100}
101
102func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800103 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100104
105 content := gf.content.String()
106
107 // ninja consumes newline characters in rspfile_content. Prevent it by
108 // escaping the backslash in the newline character. The extra backslash
109 // is removed when the rspfile is written to the actual script file
110 content = strings.ReplaceAll(content, "\n", "\\n")
111
Jiyong Park9b409bc2019-10-11 14:59:13 +0900112 rb.Command().
113 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100114 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100115 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900116 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
117 rb.Command().
118 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800119 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900120}
121
Paul Duffin13879572019-11-28 14:31:38 +0000122// Collect all the members.
123//
Paul Duffincc3132e2021-04-24 01:10:30 +0100124// Updates the sdk module with a list of sdkMemberVariantDeps and details as to which multilibs
125// (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000126func (s *sdk) collectMembers(ctx android.ModuleContext) {
127 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000128 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
129 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000130 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100131 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900132
Paul Duffin13879572019-11-28 14:31:38 +0000133 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000134 if !memberType.IsInstance(child) {
135 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900136 }
Paul Duffin13879572019-11-28 14:31:38 +0000137
Paul Duffin6a7e9532020-03-20 17:50:07 +0000138 // Keep track of which multilib variants are used by the sdk.
139 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
140
Paul Duffina7208112021-04-23 21:20:20 +0100141 export := memberTag.ExportMember()
Paul Duffincd064672021-04-24 00:47:29 +0100142 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{s, memberType, child.(android.SdkAware), export})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000143
Paul Duffin2d3da312021-05-06 12:02:27 +0100144 // Recurse down into the member's dependencies as it may have dependencies that need to be
145 // automatically added to the sdk.
146 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900147 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000148
149 return false
Paul Duffin13879572019-11-28 14:31:38 +0000150 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000151}
152
Paul Duffincc3132e2021-04-24 01:10:30 +0100153// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
154// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000155//
Paul Duffincc3132e2021-04-24 01:10:30 +0100156// The sdkMember instances are then grouped into slices by member type. Within each such slice the
157// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000158//
Paul Duffincc3132e2021-04-24 01:10:30 +0100159// Finally, the member type slices are concatenated together to form a single slice. The order in
160// which they are concatenated is the order in which the member types were registered in the
161// android.SdkMemberTypesRegistry.
162func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000163 byType := make(map[android.SdkMemberType][]*sdkMember)
164 byName := make(map[string]*sdkMember)
165
Paul Duffin21827262021-04-24 12:16:36 +0100166 for _, memberVariantDep := range memberVariantDeps {
167 memberType := memberVariantDep.memberType
168 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000169
170 name := ctx.OtherModuleName(variant)
171 member := byName[name]
172 if member == nil {
173 member = &sdkMember{memberType: memberType, name: name}
174 byName[name] = member
175 byType[memberType] = append(byType[memberType], member)
176 }
177
Paul Duffin1356d8c2020-02-25 19:26:33 +0000178 // Only append new variants to the list. This is needed because a member can be both
179 // exported by the sdk and also be a transitive sdk member.
180 member.variants = appendUniqueVariants(member.variants, variant)
181 }
182
Paul Duffin13879572019-11-28 14:31:38 +0000183 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000184 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000185 membersOfType := byType[memberListProperty.memberType]
186 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900187 }
188
Paul Duffin6a7e9532020-03-20 17:50:07 +0000189 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900190}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900191
Paul Duffin72910952020-01-20 18:16:30 +0000192func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
193 for _, v := range variants {
194 if v == newVariant {
195 return variants
196 }
197 }
198 return append(variants, newVariant)
199}
200
Jiyong Park73c54ee2019-10-22 20:31:18 +0900201// SDK directory structure
202// <sdk_root>/
203// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
204// <api_ver>/ : below this directory are all auto-generated
205// Android.bp : definition of 'sdk_snapshot' module is here
206// aidl/
207// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
208// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900209// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900210// include/
211// bionic/libc/include/stdlib.h : an exported header file
212// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900213// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900214// <arch>/include/ : arch-specific exported headers
215// <arch>/include_gen/ : arch-specific generated headers
216// <arch>/lib/
217// libFoo.so : a stub library
218
Jiyong Park232e7852019-11-04 12:23:40 +0900219// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900220// This isn't visible to users, so could be changed in future.
221func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
222 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
223}
224
Jiyong Park232e7852019-11-04 12:23:40 +0900225// buildSnapshot is the main function in this source file. It creates rules to copy
226// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000227func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
228
Paul Duffin13f02712020-03-06 12:30:43 +0000229 allMembersByName := make(map[string]struct{})
230 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100231 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100232 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000233 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100234 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffin865171e2020-03-02 18:38:15 +0000235
Paul Duffin13f02712020-03-06 12:30:43 +0000236 // Record the names of all the members, both explicitly specified and implicitly
237 // included.
Paul Duffin21827262021-04-24 12:16:36 +0100238 for _, memberVariantDep := range sdkVariant.memberVariantDeps {
Paul Duffina7208112021-04-23 21:20:20 +0100239 name := memberVariantDep.variant.Name()
240 allMembersByName[name] = struct{}{}
Paul Duffin13f02712020-03-06 12:30:43 +0000241
Paul Duffina7208112021-04-23 21:20:20 +0100242 if memberVariantDep.export {
243 exportedMembersByName[name] = struct{}{}
244 }
Paul Duffin62131702021-05-07 01:10:01 +0100245
246 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
247 hasLicenses = true
248 }
Paul Duffin865171e2020-03-02 18:38:15 +0000249 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000250 }
251
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000252 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900253
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000254 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000255
256 bpFile := &bpFile{
257 modules: make(map[string]*bpModule),
258 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000259
260 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000261 ctx: ctx,
262 sdk: s,
263 version: "current",
264 snapshotDir: snapshotDir.OutputPath,
265 copies: make(map[string]string),
266 filesToZip: []android.Path{bp.path},
267 bpFile: bpFile,
268 prebuiltModules: make(map[string]*bpModule),
269 allMembersByName: allMembersByName,
270 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900271 }
Paul Duffinac37c502019-11-26 18:02:20 +0000272 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900273
Paul Duffin62131702021-05-07 01:10:01 +0100274 // If the sdk snapshot includes any license modules then add a package module which has a
275 // default_applicable_licenses property. That will prevent the LSC license process from updating
276 // the generated Android.bp file to add a package module that includes all licenses used by all
277 // the modules in that package. That would be unnecessary as every module in the sdk should have
278 // their own licenses property specified.
279 if hasLicenses {
280 pkg := bpFile.newModule("package")
281 property := "default_applicable_licenses"
282 pkg.AddCommentForProperty(property, `
283A default list here prevents the license LSC from adding its own list which would
284be unnecessary as every module in the sdk already has its own licenses property.
285`)
286 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
287 bpFile.AddModule(pkg)
288 }
289
Paul Duffin0df49682021-05-07 01:10:01 +0100290 // Group the variants for each member module together and then group the members of each member
291 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100292 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100293
294 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000295 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000296 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000297
Paul Duffina551a1c2020-03-17 21:04:24 +0000298 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000299
300 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100301 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900302 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900303
Paul Duffine6c0d842020-01-15 14:08:51 +0000304 // Create a transformer that will transform an unversioned module into a versioned module.
305 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
306
Paul Duffin72910952020-01-20 18:16:30 +0000307 // Create a transformer that will transform an unversioned module by replacing any references
308 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100309 unversionedTransformer := unversionedTransformation{
310 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100311 }
Paul Duffin72910952020-01-20 18:16:30 +0000312
Paul Duffinb645ec82019-11-27 17:43:54 +0000313 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000314 // Prune any empty property sets.
315 unversioned = unversioned.transform(pruneEmptySetTransformer{})
316
Paul Duffinb645ec82019-11-27 17:43:54 +0000317 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000318 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000319
320 // Transform the unversioned module into a versioned one.
321 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000322 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000323
Paul Duffin72910952020-01-20 18:16:30 +0000324 // Transform the unversioned module to make it suitable for use in the snapshot.
325 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000326 bpFile.AddModule(unversioned)
327 }
328
Paul Duffin26197a62021-04-24 00:34:10 +0100329 // Add the sdk/module_exports_snapshot module to the bp file.
Paul Duffin21827262021-04-24 12:16:36 +0100330 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
Paul Duffin26197a62021-04-24 00:34:10 +0100331
332 // generate Android.bp
333 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
334 generateBpContents(&bp.generatedContents, bpFile)
335
336 contents := bp.content.String()
337 syntaxCheckSnapshotBpFile(ctx, contents)
338
339 bp.build(pctx, ctx, nil)
340
341 filesToZip := builder.filesToZip
342
343 // zip them all
344 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
345 outputDesc := "Building snapshot for " + ctx.ModuleName()
346
347 // If there are no zips to merge then generate the output zip directly.
348 // Otherwise, generate an intermediate zip file into which other zips can be
349 // merged.
350 var zipFile android.OutputPath
351 var desc string
352 if len(builder.zipsToMerge) == 0 {
353 zipFile = outputZipFile
354 desc = outputDesc
355 } else {
356 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
357 desc = "Building intermediate snapshot for " + ctx.ModuleName()
358 }
359
360 ctx.Build(pctx, android.BuildParams{
361 Description: desc,
362 Rule: zipFiles,
363 Inputs: filesToZip,
364 Output: zipFile,
365 Args: map[string]string{
366 "basedir": builder.snapshotDir.String(),
367 },
368 })
369
370 if len(builder.zipsToMerge) != 0 {
371 ctx.Build(pctx, android.BuildParams{
372 Description: outputDesc,
373 Rule: mergeZips,
374 Input: zipFile,
375 Inputs: builder.zipsToMerge,
376 Output: outputZipFile,
377 })
378 }
379
380 return outputZipFile
381}
382
383// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100384func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100385 bpFile := builder.bpFile
386
Paul Duffinb645ec82019-11-27 17:43:54 +0000387 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000388 var snapshotModuleType string
389 if s.properties.Module_exports {
390 snapshotModuleType = "module_exports_snapshot"
391 } else {
392 snapshotModuleType = "sdk_snapshot"
393 }
394 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000395 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000396
397 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100398 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000399 if len(visibility) != 0 {
400 snapshotModule.AddProperty("visibility", visibility)
401 }
402
Paul Duffin865171e2020-03-02 18:38:15 +0000403 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000404
Paul Duffincd064672021-04-24 00:47:29 +0100405 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100406 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000407
Paul Duffin2d1bb892021-04-24 11:32:59 +0100408 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100409
Paul Duffin6a7e9532020-03-20 17:50:07 +0000410 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100411
Paul Duffin2d1bb892021-04-24 11:32:59 +0100412 // Create a mapping from osType to combined properties.
413 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
414 for _, combined := range combinedPropertiesList {
415 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
416 }
417
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100418 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000419 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100420 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100421 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000422
Paul Duffin2d1bb892021-04-24 11:32:59 +0100423 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000424 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000425 }
Paul Duffin865171e2020-03-02 18:38:15 +0000426
Jiyong Park8fe14e62020-10-19 22:47:34 +0900427 // If host is supported and any member is host OS dependent then disable host
428 // by default, so that we can enable each host OS variant explicitly. This
429 // avoids problems with implicitly enabled OS variants when the snapshot is
430 // used, which might be different from this run (e.g. different build OS).
431 if s.HostSupported() {
432 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100433 for _, memberVariantDep := range memberVariantDeps {
434 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
435 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900436 if !android.InList(targetString, supportedHostTargets) {
437 supportedHostTargets = append(supportedHostTargets, targetString)
438 }
439 }
440 }
441 if len(supportedHostTargets) > 0 {
442 hostPropertySet := targetPropertySet.AddPropertySet("host")
443 hostPropertySet.AddProperty("enabled", false)
444 }
445 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
446 for _, hostTarget := range supportedHostTargets {
447 propertySet := targetPropertySet.AddPropertySet(hostTarget)
448 propertySet.AddProperty("enabled", true)
449 }
450 }
451
Paul Duffin865171e2020-03-02 18:38:15 +0000452 // Prune any empty property sets.
453 snapshotModule.transform(pruneEmptySetTransformer{})
454
Paul Duffinb645ec82019-11-27 17:43:54 +0000455 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900456}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000457
Paul Duffinf88d8e02020-05-07 20:21:34 +0100458// Check the syntax of the generated Android.bp file contents and if they are
459// invalid then log an error with the contents (tagged with line numbers) and the
460// errors that were found so that it is easy to see where the problem lies.
461func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
462 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
463 if len(errs) != 0 {
464 message := &strings.Builder{}
465 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
466
467Generated Android.bp contents
468========================================================================
469`)
470 for i, line := range strings.Split(contents, "\n") {
471 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
472 }
473
474 _, _ = fmt.Fprint(message, `
475========================================================================
476
477Errors found:
478`)
479
480 for _, err := range errs {
481 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
482 }
483
484 ctx.ModuleErrorf("%s", message.String())
485 }
486}
487
Paul Duffin4b8b7932020-05-06 12:35:38 +0100488func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
489 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
490 if err != nil {
491 ctx.ModuleErrorf("error extracting common properties: %s", err)
492 }
493}
494
Paul Duffinfbe470e2021-04-24 12:37:13 +0100495// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
496type snapshotModuleStaticProperties struct {
497 Compile_multilib string `android:"arch_variant"`
498}
499
Paul Duffin2d1bb892021-04-24 11:32:59 +0100500// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
501type combinedSnapshotModuleProperties struct {
502 // The sdk variant from which this information was collected.
503 sdkVariant *sdk
504
505 // Static snapshot module properties.
506 staticProperties *snapshotModuleStaticProperties
507
508 // The dynamically generated member list properties.
509 dynamicProperties interface{}
510}
511
512// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100513func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
514 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100515 var list []*combinedSnapshotModuleProperties
516 for _, sdkVariant := range sdkVariants {
517 staticProperties := &snapshotModuleStaticProperties{
518 Compile_multilib: sdkVariant.multilibUsages.String(),
519 }
Paul Duffincd064672021-04-24 00:47:29 +0100520 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100521
Paul Duffincd064672021-04-24 00:47:29 +0100522 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100523 sdkVariant: sdkVariant,
524 staticProperties: staticProperties,
525 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100526 }
527 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
528
529 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100530 }
Paul Duffincd064672021-04-24 00:47:29 +0100531
532 for _, memberVariantDep := range memberVariantDeps {
533 // If the member dependency is internal then do not add the dependency to the snapshot member
534 // list properties.
535 if !memberVariantDep.export {
536 continue
537 }
538
539 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100540 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100541 memberName := ctx.OtherModuleName(memberVariantDep.variant)
542
Paul Duffin13082052021-05-11 00:31:38 +0100543 if memberListProperty.getter == nil {
544 continue
545 }
546
Paul Duffincd064672021-04-24 00:47:29 +0100547 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100548 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100549 if !android.InList(memberName, memberList) {
550 memberList = append(memberList, memberName)
551 }
Paul Duffin13082052021-05-11 00:31:38 +0100552 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100553 }
554
Paul Duffin2d1bb892021-04-24 11:32:59 +0100555 return list
556}
557
558func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
559
560 // Extract the dynamic properties and add them to a list of propertiesContainer.
561 propertyContainers := []propertiesContainer{}
562 for _, i := range list {
563 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
564 sdkVariant: i.sdkVariant,
565 properties: i.dynamicProperties,
566 })
567 }
568
569 // Extract the common members, removing them from the original properties.
570 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
571 extractor := newCommonValueExtractor(commonDynamicProperties)
572 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
573
574 // Extract the static properties and add them to a list of propertiesContainer.
575 propertyContainers = []propertiesContainer{}
576 for _, i := range list {
577 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
578 sdkVariant: i.sdkVariant,
579 properties: i.staticProperties,
580 })
581 }
582
583 commonStaticProperties := &snapshotModuleStaticProperties{}
584 extractor = newCommonValueExtractor(commonStaticProperties)
585 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
586
587 return &combinedSnapshotModuleProperties{
588 sdkVariant: nil,
589 staticProperties: commonStaticProperties,
590 dynamicProperties: commonDynamicProperties,
591 }
592}
593
594func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
595 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100596 multilib := staticProperties.Compile_multilib
597 if multilib != "" && multilib != "both" {
598 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
599 propertySet.AddProperty("compile_multilib", multilib)
600 }
601
Paul Duffin2d1bb892021-04-24 11:32:59 +0100602 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000603 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100604 if memberListProperty.getter == nil {
605 continue
606 }
Paul Duffin865171e2020-03-02 18:38:15 +0000607 names := memberListProperty.getter(dynamicMemberTypeListProperties)
608 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000609 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000610 }
611 }
612}
613
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000614type propertyTag struct {
615 name string
616}
617
Paul Duffin0cb37b92020-03-04 14:52:46 +0000618// A BpPropertyTag to add to a property that contains references to other sdk members.
619//
620// This will cause the references to be rewritten to a versioned reference in the version
621// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000622var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000623var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000624
Paul Duffin0cb37b92020-03-04 14:52:46 +0000625// A BpPropertyTag that indicates the property should only be present in the versioned
626// module.
627//
628// This will cause the property to be removed from the unversioned instance of a
629// snapshot module.
630var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
631
Paul Duffine6c0d842020-01-15 14:08:51 +0000632type unversionedToVersionedTransformation struct {
633 identityTransformation
634 builder *snapshotBuilder
635}
636
Paul Duffine6c0d842020-01-15 14:08:51 +0000637func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
638 // Use a versioned name for the module but remember the original name for the
639 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100640 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000641 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000642 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100643 // Remove the prefer property if present as versioned modules never need marking with prefer.
644 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000645 return module
646}
647
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000648func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000649 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
650 required := tag == requiredSdkMemberReferencePropertyTag
651 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000652 } else {
653 return value, tag
654 }
655}
656
Paul Duffin72910952020-01-20 18:16:30 +0000657type unversionedTransformation struct {
658 identityTransformation
659 builder *snapshotBuilder
660}
661
662func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
663 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100664 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000665 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000666 return module
667}
668
669func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000670 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
671 required := tag == requiredSdkMemberReferencePropertyTag
672 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000673 } else if tag == sdkVersionedOnlyPropertyTag {
674 // The property is not allowed in the unversioned module so remove it.
675 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000676 } else {
677 return value, tag
678 }
679}
680
Paul Duffina78f3a72020-02-21 16:29:35 +0000681type pruneEmptySetTransformer struct {
682 identityTransformation
683}
684
685var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
686
687func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
688 if len(propertySet.properties) == 0 {
689 return nil, nil
690 } else {
691 return propertySet, tag
692 }
693}
694
Paul Duffinb645ec82019-11-27 17:43:54 +0000695func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000696 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
697 return true
698 })
699}
700
701func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000702 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
703 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000704 if moduleFilter(bpModule) {
705 contents.Printfln("")
706 contents.Printfln("%s {", bpModule.moduleType)
707 outputPropertySet(contents, bpModule.bpPropertySet)
708 contents.Printfln("}")
709 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000710 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000711}
712
713func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
714 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000715
Paul Duffin0df49682021-05-07 01:10:01 +0100716 addComment := func(name string) {
717 if text, ok := set.comments[name]; ok {
718 for _, line := range strings.Split(text, "\n") {
719 contents.Printfln("// %s", line)
720 }
721 }
722 }
723
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000724 // Output the properties first, followed by the nested sets. This ensures a
725 // consistent output irrespective of whether property sets are created before
726 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000727 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000728 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000729
Paul Duffin0df49682021-05-07 01:10:01 +0100730 // Do not write property sets in the properties phase.
731 if _, ok := value.(*bpPropertySet); ok {
732 continue
733 }
734
735 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000736 switch v := value.(type) {
737 case []string:
738 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000739 if length > 1 {
740 contents.Printfln("%s: [", name)
741 contents.Indent()
742 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000743 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000744 }
745 contents.Dedent()
746 contents.Printfln("],")
747 } else if length == 0 {
748 contents.Printfln("%s: [],", name)
749 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000750 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000751 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000752
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000753 case bool:
754 contents.Printfln("%s: %t,", name, v)
755
Paul Duffinb645ec82019-11-27 17:43:54 +0000756 default:
757 contents.Printfln("%s: %q,", name, value)
758 }
759 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000760
761 for _, name := range set.order {
762 value := set.getValue(name)
763
764 // Only write property sets in the sets phase.
765 switch v := value.(type) {
766 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100767 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000768 contents.Printfln("%s: {", name)
769 outputPropertySet(contents, v)
770 contents.Printfln("},")
771 }
772 }
773
Paul Duffinb645ec82019-11-27 17:43:54 +0000774 contents.Dedent()
775}
776
Paul Duffinac37c502019-11-26 18:02:20 +0000777func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000778 contents := &generatedContents{}
779 generateBpContents(contents, s.builderForTests.bpFile)
780 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000781}
782
Paul Duffind0759072021-02-17 11:23:00 +0000783func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
784 contents := &generatedContents{}
785 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100786 name := module.Name()
787 // Include modules that are either unversioned or have no name.
788 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000789 })
790 return contents.content.String()
791}
792
793func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
794 contents := &generatedContents{}
795 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100796 name := module.Name()
797 // Include modules that are either versioned or have no name.
798 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000799 })
800 return contents.content.String()
801}
802
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000803type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000804 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000805 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000806 version string
807 snapshotDir android.OutputPath
808 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000809
810 // Map from destination to source of each copy - used to eliminate duplicates and
811 // detect conflicts.
812 copies map[string]string
813
Paul Duffinb645ec82019-11-27 17:43:54 +0000814 filesToZip android.Paths
815 zipsToMerge android.Paths
816
817 prebuiltModules map[string]*bpModule
818 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000819
820 // The set of all members by name.
821 allMembersByName map[string]struct{}
822
823 // The set of exported members by name.
824 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000825}
826
827func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000828 if existing, ok := s.copies[dest]; ok {
829 if existing != src.String() {
830 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
831 return
832 }
833 } else {
834 path := s.snapshotDir.Join(s.ctx, dest)
835 s.ctx.Build(pctx, android.BuildParams{
836 Rule: android.Cp,
837 Input: src,
838 Output: path,
839 })
840 s.filesToZip = append(s.filesToZip, path)
841
842 s.copies[dest] = src.String()
843 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000844}
845
Paul Duffin91547182019-11-12 19:39:36 +0000846func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
847 ctx := s.ctx
848
849 // Repackage the zip file so that the entries are in the destDir directory.
850 // This will allow the zip file to be merged into the snapshot.
851 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000852
853 ctx.Build(pctx, android.BuildParams{
854 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
855 Rule: repackageZip,
856 Input: zipPath,
857 Output: tmpZipPath,
858 Args: map[string]string{
859 "destdir": destDir,
860 },
861 })
Paul Duffin91547182019-11-12 19:39:36 +0000862
863 // Add the repackaged zip file to the files to merge.
864 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
865}
866
Paul Duffin9d8d6092019-12-05 18:19:29 +0000867func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
868 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000869 if s.prebuiltModules[name] != nil {
870 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
871 }
872
873 m := s.bpFile.newModule(moduleType)
874 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000875
Paul Duffinbefa4b92020-03-04 14:22:45 +0000876 variant := member.Variants()[0]
877
Paul Duffin13f02712020-03-06 12:30:43 +0000878 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000879 // An internal member is only referenced from the sdk snapshot which is in the
880 // same package so can be marked as private.
881 m.AddProperty("visibility", []string{"//visibility:private"})
882 } else {
883 // Extract visibility information from a member variant. All variants have the same
884 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100885 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
886
887 // Add any additional visibility rules needed for the prebuilts to reference each other.
888 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
889 if err != nil {
890 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
891 }
892
893 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000894 if len(visibility) != 0 {
895 m.AddProperty("visibility", visibility)
896 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000897 }
898
Martin Stjernholm1e041092020-11-03 00:11:09 +0000899 // Where available copy apex_available properties from the member.
900 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
901 apexAvailable := apexAware.ApexAvailable()
902 if len(apexAvailable) == 0 {
903 // //apex_available:platform is the default.
904 apexAvailable = []string{android.AvailableToPlatform}
905 }
906
907 // Add in any baseline apex available settings.
908 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
909
910 // Remove duplicates and sort.
911 apexAvailable = android.FirstUniqueStrings(apexAvailable)
912 sort.Strings(apexAvailable)
913
914 m.AddProperty("apex_available", apexAvailable)
915 }
916
Paul Duffinb0bb3762021-05-06 16:48:05 +0100917 // The licenses are the same for all variants.
918 mctx := s.ctx
919 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
920 if len(licenseInfo.Licenses) > 0 {
921 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
922 }
923
Paul Duffin865171e2020-03-02 18:38:15 +0000924 deviceSupported := false
925 hostSupported := false
926
927 for _, variant := range member.Variants() {
928 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900929 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000930 hostSupported = true
931 } else if osClass == android.Device {
932 deviceSupported = true
933 }
934 }
935
936 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000937
Paul Duffin0cb37b92020-03-04 14:52:46 +0000938 // Disable installation in the versioned module of those modules that are ever installable.
939 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
940 if installable.EverInstallable() {
941 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
942 }
943 }
944
Paul Duffinb645ec82019-11-27 17:43:54 +0000945 s.prebuiltModules[name] = m
946 s.prebuiltOrder = append(s.prebuiltOrder, m)
947 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000948}
949
Paul Duffin865171e2020-03-02 18:38:15 +0000950func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +0100951 // If neither device or host is supported then this module does not support either so will not
952 // recognize the properties.
953 if !deviceSupported && !hostSupported {
954 return
955 }
956
Paul Duffin865171e2020-03-02 18:38:15 +0000957 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000958 bpModule.AddProperty("device_supported", false)
959 }
Paul Duffin865171e2020-03-02 18:38:15 +0000960 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000961 bpModule.AddProperty("host_supported", true)
962 }
963}
964
Paul Duffin13f02712020-03-06 12:30:43 +0000965func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
966 if required {
967 return requiredSdkMemberReferencePropertyTag
968 } else {
969 return optionalSdkMemberReferencePropertyTag
970 }
971}
972
973func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
974 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000975}
976
Paul Duffinb645ec82019-11-27 17:43:54 +0000977// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000978func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
979 if _, ok := s.allMembersByName[unversionedName]; !ok {
980 if required {
981 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
982 }
983 return unversionedName
984 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000985 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
986}
Paul Duffinb645ec82019-11-27 17:43:54 +0000987
Paul Duffin13f02712020-03-06 12:30:43 +0000988func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000989 var references []string = nil
990 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000991 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000992 }
993 return references
994}
Paul Duffin13879572019-11-28 14:31:38 +0000995
Paul Duffin72910952020-01-20 18:16:30 +0000996// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000997func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
998 if _, ok := s.allMembersByName[unversionedName]; !ok {
999 if required {
1000 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1001 }
1002 return unversionedName
1003 }
1004
1005 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001006 return s.ctx.ModuleName() + "_" + unversionedName
1007 } else {
1008 return unversionedName
1009 }
1010}
1011
Paul Duffin13f02712020-03-06 12:30:43 +00001012func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001013 var references []string = nil
1014 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001015 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001016 }
1017 return references
1018}
1019
Paul Duffin13f02712020-03-06 12:30:43 +00001020func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1021 _, ok := s.exportedMembersByName[memberName]
1022 return !ok
1023}
1024
Martin Stjernholm89238f42020-07-10 00:14:03 +01001025// Add the properties from the given SdkMemberProperties to the blueprint
1026// property set. This handles common properties in SdkMemberPropertiesBase and
1027// calls the member-specific AddToPropertySet for the rest.
1028func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1029 if memberProperties.Base().Compile_multilib != "" {
1030 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1031 }
1032
1033 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1034}
1035
Paul Duffin21827262021-04-24 12:16:36 +01001036// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1037type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001038 // The sdk variant that depends (possibly indirectly) on the member variant.
1039 sdkVariant *sdk
Paul Duffin1356d8c2020-02-25 19:26:33 +00001040 memberType android.SdkMemberType
1041 variant android.SdkAware
Paul Duffina7208112021-04-23 21:20:20 +01001042 export bool
Paul Duffin1356d8c2020-02-25 19:26:33 +00001043}
1044
Paul Duffin13879572019-11-28 14:31:38 +00001045var _ android.SdkMember = (*sdkMember)(nil)
1046
Paul Duffin21827262021-04-24 12:16:36 +01001047// sdkMember groups all the variants of a specific member module together along with the name of the
1048// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001049type sdkMember struct {
1050 memberType android.SdkMemberType
1051 name string
1052 variants []android.SdkAware
1053}
1054
1055func (m *sdkMember) Name() string {
1056 return m.name
1057}
1058
1059func (m *sdkMember) Variants() []android.SdkAware {
1060 return m.variants
1061}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001062
Paul Duffin9c3760e2020-03-16 19:52:08 +00001063// Track usages of multilib variants.
1064type multilibUsage int
1065
1066const (
1067 multilibNone multilibUsage = 0
1068 multilib32 multilibUsage = 1
1069 multilib64 multilibUsage = 2
1070 multilibBoth = multilib32 | multilib64
1071)
1072
1073// Add the multilib that is used in the arch type.
1074func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1075 multilib := archType.Multilib
1076 switch multilib {
1077 case "":
1078 return m
1079 case "lib32":
1080 return m | multilib32
1081 case "lib64":
1082 return m | multilib64
1083 default:
1084 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1085 }
1086}
1087
1088func (m multilibUsage) String() string {
1089 switch m {
1090 case multilibNone:
1091 return ""
1092 case multilib32:
1093 return "32"
1094 case multilib64:
1095 return "64"
1096 case multilibBoth:
1097 return "both"
1098 default:
1099 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1100 m, multilibNone, multilib32, multilib64, multilibBoth))
1101 }
1102}
1103
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001104type baseInfo struct {
1105 Properties android.SdkMemberProperties
1106}
1107
Paul Duffinf34f6d82020-04-30 15:48:31 +01001108func (b *baseInfo) optimizableProperties() interface{} {
1109 return b.Properties
1110}
1111
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001112type osTypeSpecificInfo struct {
1113 baseInfo
1114
Paul Duffin00e46802020-03-12 20:40:35 +00001115 osType android.OsType
1116
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001117 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001118 //
1119 // Nil if there is one variant whose arch type is common
1120 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001121}
1122
Paul Duffin4b8b7932020-05-06 12:35:38 +01001123var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1124
Paul Duffinfc8dd232020-03-17 12:51:37 +00001125type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1126
Paul Duffin00e46802020-03-12 20:40:35 +00001127// Create a new osTypeSpecificInfo for the specified os type and its properties
1128// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001129func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001130 osInfo := &osTypeSpecificInfo{
1131 osType: osType,
1132 }
1133
1134 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1135 properties := variantPropertiesFactory()
1136 properties.Base().Os = osType
1137 return properties
1138 }
1139
1140 // Create a structure into which properties common across the architectures in
1141 // this os type will be stored.
1142 osInfo.Properties = osSpecificVariantPropertiesFactory()
1143
1144 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001145 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001146 var archTypes []android.ArchType
1147 for _, variant := range osTypeVariants {
1148 archType := variant.Target().Arch.ArchType
1149 archTypeName := archType.Name
1150 if _, ok := variantsByArchName[archTypeName]; !ok {
1151 archTypes = append(archTypes, archType)
1152 }
1153
1154 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1155 }
1156
1157 if commonVariants, ok := variantsByArchName["common"]; ok {
1158 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001159 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 +00001160 }
1161
1162 // A common arch type only has one variant and its properties should be treated
1163 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001164 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001165 } else {
1166 // Create an arch specific info for each supported architecture type.
1167 for _, archType := range archTypes {
1168 archTypeName := archType.Name
1169
1170 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001171 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001172
1173 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1174 }
1175 }
1176
1177 return osInfo
1178}
1179
1180// Optimize the properties by extracting common properties from arch type specific
1181// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001182func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001183 // Nothing to do if there is only a single common architecture.
1184 if len(osInfo.archInfos) == 0 {
1185 return
1186 }
1187
Paul Duffin9c3760e2020-03-16 19:52:08 +00001188 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001189 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001190 multilib = multilib.addArchType(archInfo.archType)
1191
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001192 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001193 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001194 }
1195
Paul Duffin4b8b7932020-05-06 12:35:38 +01001196 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001197
1198 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001199 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001200}
1201
1202// Add the properties for an os to a property set.
1203//
1204// Maps the properties related to the os variants through to an appropriate
1205// module structure that will produce equivalent set of variants when it is
1206// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001207func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001208
1209 var osPropertySet android.BpPropertySet
1210 var archPropertySet android.BpPropertySet
1211 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001212 if osInfo.Properties.Base().Os_count == 1 &&
1213 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1214 // There is only one OS type present in the variants and it shouldn't have a
1215 // variant-specific target. The latter is the case if it's either for device
1216 // where there is only one OS (android), or for host and the member type
1217 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001218
1219 // Create a structure that looks like:
1220 // module_type {
1221 // name: "...",
1222 // ...
1223 // <common properties>
1224 // ...
1225 // <single os type specific properties>
1226 //
1227 // arch: {
1228 // <arch specific sections>
1229 // }
1230 //
1231 osPropertySet = bpModule
1232 archPropertySet = osPropertySet.AddPropertySet("arch")
1233
1234 // Arch specific properties need to be added to an arch specific section
1235 // within arch.
1236 archOsPrefix = ""
1237 } else {
1238 // Create a structure that looks like:
1239 // module_type {
1240 // name: "...",
1241 // ...
1242 // <common properties>
1243 // ...
1244 // target: {
1245 // <arch independent os specific sections, e.g. android>
1246 // ...
1247 // <arch and os specific sections, e.g. android_x86>
1248 // }
1249 //
1250 osType := osInfo.osType
1251 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1252 archPropertySet = targetPropertySet
1253
1254 // Arch specific properties need to be added to an os and arch specific
1255 // section prefixed with <os>_.
1256 archOsPrefix = osType.Name + "_"
1257 }
1258
1259 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001260 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001261
1262 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1263 // os) specific properties.
1264 //
1265 // The archInfos list will be empty if the os contains variants for the common
1266 // architecture.
1267 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001268 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001269 }
1270}
1271
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001272func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1273 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001274 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001275}
1276
1277var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1278
Paul Duffin4b8b7932020-05-06 12:35:38 +01001279func (osInfo *osTypeSpecificInfo) String() string {
1280 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1281}
1282
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001283type archTypeSpecificInfo struct {
1284 baseInfo
1285
1286 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001287 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001288
1289 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001290}
1291
Paul Duffin4b8b7932020-05-06 12:35:38 +01001292var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1293
Paul Duffinfc8dd232020-03-17 12:51:37 +00001294// Create a new archTypeSpecificInfo for the specified arch type and its properties
1295// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001296func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001297
Paul Duffinfc8dd232020-03-17 12:51:37 +00001298 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001299 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001300
1301 // Create the properties into which the arch type specific properties will be
1302 // added.
1303 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001304
1305 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001306 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001307 } else {
1308 // There is more than one variant for this arch type which must be differentiated
1309 // by link type.
1310 for _, linkVariant := range archVariants {
1311 linkType := getLinkType(linkVariant)
1312 if linkType == "" {
1313 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1314 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001315 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001316
1317 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1318 }
1319 }
1320 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001321
1322 return archInfo
1323}
1324
Paul Duffinf34f6d82020-04-30 15:48:31 +01001325func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1326 return archInfo.Properties
1327}
1328
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001329// Get the link type of the variant
1330//
1331// If the variant is not differentiated by link type then it returns "",
1332// otherwise it returns one of "static" or "shared".
1333func getLinkType(variant android.Module) string {
1334 linkType := ""
1335 if linkable, ok := variant.(cc.LinkableInterface); ok {
1336 if linkable.Shared() && linkable.Static() {
1337 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1338 } else if linkable.Shared() {
1339 linkType = "shared"
1340 } else if linkable.Static() {
1341 linkType = "static"
1342 } else {
1343 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1344 }
1345 }
1346 return linkType
1347}
1348
1349// Optimize the properties by extracting common properties from link type specific
1350// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001351func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001352 if len(archInfo.linkInfos) == 0 {
1353 return
1354 }
1355
Paul Duffin4b8b7932020-05-06 12:35:38 +01001356 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001357}
1358
Paul Duffinfc8dd232020-03-17 12:51:37 +00001359// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001360func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001361 archTypeName := archInfo.archType.Name
1362 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001363 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1364 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1365 archTypePropertySet.AddProperty("enabled", true)
1366 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001367 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001368
1369 for _, linkInfo := range archInfo.linkInfos {
1370 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001371 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001372 }
1373}
1374
Paul Duffin4b8b7932020-05-06 12:35:38 +01001375func (archInfo *archTypeSpecificInfo) String() string {
1376 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1377}
1378
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001379type linkTypeSpecificInfo struct {
1380 baseInfo
1381
1382 linkType string
1383}
1384
Paul Duffin4b8b7932020-05-06 12:35:38 +01001385var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1386
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001387// Create a new linkTypeSpecificInfo for the specified link type and its properties
1388// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001389func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001390 linkInfo := &linkTypeSpecificInfo{
1391 baseInfo: baseInfo{
1392 // Create the properties into which the link type specific properties will be
1393 // added.
1394 Properties: variantPropertiesFactory(),
1395 },
1396 linkType: linkType,
1397 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001398 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001399 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001400}
1401
Paul Duffin4b8b7932020-05-06 12:35:38 +01001402func (l *linkTypeSpecificInfo) String() string {
1403 return fmt.Sprintf("LinkType{%s}", l.linkType)
1404}
1405
Paul Duffin3a4eb502020-03-19 16:11:18 +00001406type memberContext struct {
1407 sdkMemberContext android.ModuleContext
1408 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001409 memberType android.SdkMemberType
1410 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001411}
1412
1413func (m *memberContext) SdkModuleContext() android.ModuleContext {
1414 return m.sdkMemberContext
1415}
1416
1417func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1418 return m.builder
1419}
1420
Paul Duffina551a1c2020-03-17 21:04:24 +00001421func (m *memberContext) MemberType() android.SdkMemberType {
1422 return m.memberType
1423}
1424
1425func (m *memberContext) Name() string {
1426 return m.name
1427}
1428
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001429func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001430
1431 memberType := member.memberType
1432
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001433 // Do not add the prefer property if the member snapshot module is a source module type.
1434 if !memberType.UsesSourceModuleTypeInSnapshot() {
1435 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1436 // snapshot to be created that sets prefer: true.
1437 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1438 // dynamically at build time not at snapshot generation time.
1439 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001440
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001441 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1442 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1443 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1444 // behavior is for the module.
1445 bpModule.insertAfter("name", "prefer", prefer)
1446 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001447
Paul Duffina04c1072020-03-02 10:16:35 +00001448 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001449 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001450 variants := member.Variants()
1451 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001452 osType := variant.Target().Os
1453 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001454 }
1455
Paul Duffina04c1072020-03-02 10:16:35 +00001456 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001457 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001458 properties := memberType.CreateVariantPropertiesStruct()
1459 base := properties.Base()
1460 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001461 return properties
1462 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001463
Paul Duffina04c1072020-03-02 10:16:35 +00001464 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001465
Paul Duffina04c1072020-03-02 10:16:35 +00001466 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001467 commonProperties := variantPropertiesFactory()
1468 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001469
Paul Duffinc097e362020-03-10 22:50:03 +00001470 // Create common value extractor that can be used to optimize the properties.
1471 commonValueExtractor := newCommonValueExtractor(commonProperties)
1472
Paul Duffina04c1072020-03-02 10:16:35 +00001473 // The list of property structures which are os type specific but common across
1474 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001475 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001476
1477 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001478 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001479 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001480 // Add the os specific properties to a list of os type specific yet architecture
1481 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001482 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001483
Paul Duffin00e46802020-03-12 20:40:35 +00001484 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001485 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001486 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001487
Paul Duffina04c1072020-03-02 10:16:35 +00001488 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001489 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001490
Paul Duffina04c1072020-03-02 10:16:35 +00001491 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001492 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001493
Paul Duffina04c1072020-03-02 10:16:35 +00001494 // Create a target property set into which target specific properties can be
1495 // added.
1496 targetPropertySet := bpModule.AddPropertySet("target")
1497
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001498 // If the member is host OS dependent and has host_supported then disable by
1499 // default and enable each host OS variant explicitly. This avoids problems
1500 // with implicitly enabled OS variants when the snapshot is used, which might
1501 // be different from this run (e.g. different build OS).
1502 if ctx.memberType.IsHostOsDependent() {
1503 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1504 if hostSupported {
1505 hostPropertySet := targetPropertySet.AddPropertySet("host")
1506 hostPropertySet.AddProperty("enabled", false)
1507 }
1508 }
1509
Paul Duffina04c1072020-03-02 10:16:35 +00001510 // Iterate over the os types in a fixed order.
1511 for _, osType := range s.getPossibleOsTypes() {
1512 osInfo := osTypeToInfo[osType]
1513 if osInfo == nil {
1514 continue
1515 }
1516
Paul Duffin3a4eb502020-03-19 16:11:18 +00001517 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001518 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001519}
1520
Paul Duffina04c1072020-03-02 10:16:35 +00001521// Compute the list of possible os types that this sdk could support.
1522func (s *sdk) getPossibleOsTypes() []android.OsType {
1523 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001524 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001525 if s.DeviceSupported() {
1526 if osType.Class == android.Device && osType != android.Fuchsia {
1527 osTypes = append(osTypes, osType)
1528 }
1529 }
1530 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001531 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001532 osTypes = append(osTypes, osType)
1533 }
1534 }
1535 }
1536 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1537 return osTypes
1538}
1539
Paul Duffinb28369a2020-05-04 15:39:59 +01001540// Given a set of properties (struct value), return the value of the field within that
1541// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001542type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1543
Paul Duffinc459f892020-04-30 18:08:29 +01001544// Checks the metadata to determine whether the property should be ignored for the
1545// purposes of common value extraction or not.
1546type extractorMetadataPredicate func(metadata propertiesContainer) bool
1547
1548// Indicates whether optimizable properties are provided by a host variant or
1549// not.
1550type isHostVariant interface {
1551 isHostVariant() bool
1552}
1553
Paul Duffinb28369a2020-05-04 15:39:59 +01001554// A property that can be optimized by the commonValueExtractor.
1555type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001556 // The name of the field for this property. It is a "."-separated path for
1557 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001558 name string
1559
Paul Duffinc459f892020-04-30 18:08:29 +01001560 // Filter that can use metadata associated with the properties being optimized
1561 // to determine whether the field should be ignored during common value
1562 // optimization.
1563 filter extractorMetadataPredicate
1564
Paul Duffinb28369a2020-05-04 15:39:59 +01001565 // Retrieves the value on which common value optimization will be performed.
1566 getter fieldAccessorFunc
1567
1568 // The empty value for the field.
1569 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001570
1571 // True if the property can support arch variants false otherwise.
1572 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001573}
1574
Paul Duffin4b8b7932020-05-06 12:35:38 +01001575func (p extractorProperty) String() string {
1576 return p.name
1577}
1578
Paul Duffinc097e362020-03-10 22:50:03 +00001579// Supports extracting common values from a number of instances of a properties
1580// structure into a separate common set of properties.
1581type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001582 // The properties that the extractor can optimize.
1583 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001584}
1585
1586// Create a new common value extractor for the structure type for the supplied
1587// properties struct.
1588//
1589// The returned extractor can be used on any properties structure of the same type
1590// as the supplied set of properties.
1591func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1592 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1593 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001594 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001595 return extractor
1596}
1597
1598// Gather the fields from the supplied structure type from which common values will
1599// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001600//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001601// This is recursive function. If it encounters a struct then it will recurse
1602// into it, passing in the accessor for the field and the struct name as prefix
1603// for the nested fields. That will then be used in the accessors for the fields
1604// in the embedded struct.
1605func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001606 for f := 0; f < structType.NumField(); f++ {
1607 field := structType.Field(f)
1608 if field.PkgPath != "" {
1609 // Ignore unexported fields.
1610 continue
1611 }
1612
Paul Duffinb07fa512020-03-10 22:17:04 +00001613 // Ignore fields whose value should be kept.
1614 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001615 continue
1616 }
1617
Paul Duffinc459f892020-04-30 18:08:29 +01001618 var filter extractorMetadataPredicate
1619
1620 // Add a filter
1621 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1622 filter = func(metadata propertiesContainer) bool {
1623 if m, ok := metadata.(isHostVariant); ok {
1624 if m.isHostVariant() {
1625 return false
1626 }
1627 }
1628 return true
1629 }
1630 }
1631
Paul Duffinc097e362020-03-10 22:50:03 +00001632 // Save a copy of the field index for use in the function.
1633 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001634
Martin Stjernholmb0249572020-09-15 02:32:35 +01001635 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001636
Paul Duffinc097e362020-03-10 22:50:03 +00001637 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001638 if containingStructAccessor != nil {
1639 // This is an embedded structure so first access the field for the embedded
1640 // structure.
1641 value = containingStructAccessor(value)
1642 }
1643
Paul Duffinc097e362020-03-10 22:50:03 +00001644 // Skip through interface and pointer values to find the structure.
1645 value = getStructValue(value)
1646
Paul Duffin4b8b7932020-05-06 12:35:38 +01001647 defer func() {
1648 if r := recover(); r != nil {
1649 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1650 }
1651 }()
1652
Paul Duffinc097e362020-03-10 22:50:03 +00001653 // Return the field.
1654 return value.Field(fieldIndex)
1655 }
1656
Martin Stjernholmb0249572020-09-15 02:32:35 +01001657 if field.Type.Kind() == reflect.Struct {
1658 // Gather fields from the nested or embedded structure.
1659 var subNamePrefix string
1660 if field.Anonymous {
1661 subNamePrefix = namePrefix
1662 } else {
1663 subNamePrefix = name + "."
1664 }
1665 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001666 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001667 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001668 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001669 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001670 fieldGetter,
1671 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001672 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001673 }
1674 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001675 }
Paul Duffinc097e362020-03-10 22:50:03 +00001676 }
1677}
1678
1679func getStructValue(value reflect.Value) reflect.Value {
1680foundStruct:
1681 for {
1682 kind := value.Kind()
1683 switch kind {
1684 case reflect.Interface, reflect.Ptr:
1685 value = value.Elem()
1686 case reflect.Struct:
1687 break foundStruct
1688 default:
1689 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1690 }
1691 }
1692 return value
1693}
1694
Paul Duffinf34f6d82020-04-30 15:48:31 +01001695// A container of properties to be optimized.
1696//
1697// Allows additional information to be associated with the properties, e.g. for
1698// filtering.
1699type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001700 fmt.Stringer
1701
Paul Duffinf34f6d82020-04-30 15:48:31 +01001702 // Get the properties that need optimizing.
1703 optimizableProperties() interface{}
1704}
1705
Paul Duffin2d1bb892021-04-24 11:32:59 +01001706// A wrapper for sdk variant related properties to allow them to be optimized.
1707type sdkVariantPropertiesContainer struct {
1708 sdkVariant *sdk
1709 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001710}
1711
Paul Duffin2d1bb892021-04-24 11:32:59 +01001712func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1713 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001714}
1715
Paul Duffin2d1bb892021-04-24 11:32:59 +01001716func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001717 return c.sdkVariant.String()
1718}
1719
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001720// Extract common properties from a slice of property structures of the same type.
1721//
1722// All the property structures must be of the same type.
1723// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001724// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001725//
1726// Iterates over each exported field (capitalized name) and checks to see whether they
1727// have the same value (using DeepEquals) across all the input properties. If it does not then no
1728// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001729// and the field in each of the input properties structure is set to its default value. Nested
1730// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001731func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001732 commonPropertiesValue := reflect.ValueOf(commonProperties)
1733 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001734
Paul Duffinf34f6d82020-04-30 15:48:31 +01001735 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1736
Paul Duffinb28369a2020-05-04 15:39:59 +01001737 for _, property := range e.properties {
1738 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001739 filter := property.filter
1740 if filter == nil {
1741 filter = func(metadata propertiesContainer) bool {
1742 return true
1743 }
1744 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001745
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001746 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001747 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1748 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001749 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001750
Paul Duffin864e1b42020-05-06 10:23:19 +01001751 // Assume that all the values will be the same.
1752 //
1753 // While similar to this is not quite the same as commonValue == nil. If all the values
1754 // have been filtered out then this will be false but commonValue == nil will be true.
1755 valuesDiffer := false
1756
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001757 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001758 container := sliceValue.Index(i).Interface().(propertiesContainer)
1759 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001760 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001761
Paul Duffinc459f892020-04-30 18:08:29 +01001762 if !filter(container) {
1763 expectedValue := property.emptyValue.Interface()
1764 actualValue := fieldValue.Interface()
1765 if !reflect.DeepEqual(expectedValue, actualValue) {
1766 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1767 }
1768 continue
1769 }
1770
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001771 if commonValue == nil {
1772 // Use the first value as the commonProperties value.
1773 commonValue = &fieldValue
1774 } else {
1775 // If the value does not match the current common value then there is
1776 // no value in common so break out.
1777 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1778 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001779 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001780 break
1781 }
1782 }
1783 }
1784
Paul Duffin864e1b42020-05-06 10:23:19 +01001785 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001786 // and set the input struct's field to the empty value.
1787 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001788 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001789 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001790 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001791 container := sliceValue.Index(i).Interface().(propertiesContainer)
1792 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001793 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001794 fieldValue.Set(emptyValue)
1795 }
1796 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001797
1798 if valuesDiffer && !property.archVariant {
1799 // The values differ but the property does not support arch variants so it
1800 // is an error.
1801 var details strings.Builder
1802 for i := 0; i < sliceValue.Len(); i++ {
1803 container := sliceValue.Index(i).Interface().(propertiesContainer)
1804 itemValue := reflect.ValueOf(container.optimizableProperties())
1805 fieldValue := fieldGetter(itemValue)
1806
1807 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1808 }
1809
1810 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1811 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001812 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001813
1814 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001815}