blob: 25d50d217fece9108d65a78bd6bd49a0775ec807 [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
32var pctx = android.NewPackageContext("android/soong/sdk")
33
Paul Duffin375058f2019-11-29 20:17:53 +000034var (
35 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
36 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000037 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000038 CommandDeps: []string{
39 "${config.Zip2ZipCmd}",
40 },
41 },
42 "destdir")
43
44 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
45 blueprint.RuleParams{
46 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
47 CommandDeps: []string{
48 "${config.SoongZipCmd}",
49 },
50 Rspfile: "$out.rsp",
51 RspfileContent: "$in",
52 },
53 "basedir")
54
55 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
56 blueprint.RuleParams{
57 Command: `${config.MergeZipsCmd} $out $in`,
58 CommandDeps: []string{
59 "${config.MergeZipsCmd}",
60 },
61 })
62)
63
Paul Duffinb645ec82019-11-27 17:43:54 +000064type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090065 content strings.Builder
66 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090067}
68
Paul Duffinb645ec82019-11-27 17:43:54 +000069// generatedFile abstracts operations for writing contents into a file and emit a build rule
70// for the file.
71type generatedFile struct {
72 generatedContents
73 path android.OutputPath
74}
75
Jiyong Park232e7852019-11-04 12:23:40 +090076func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090077 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000078 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090079 }
80}
81
Paul Duffinb645ec82019-11-27 17:43:54 +000082func (gc *generatedContents) Indent() {
83 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090084}
85
Paul Duffinb645ec82019-11-27 17:43:54 +000086func (gc *generatedContents) Dedent() {
87 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090088}
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +010091 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090092}
93
94func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
95 rb := android.NewRuleBuilder()
Paul Duffin11108272020-05-11 22:59:25 +010096
97 content := gf.content.String()
98
99 // ninja consumes newline characters in rspfile_content. Prevent it by
100 // escaping the backslash in the newline character. The extra backslash
101 // is removed when the rspfile is written to the actual script file
102 content = strings.ReplaceAll(content, "\n", "\\n")
103
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 rb.Command().
105 Implicits(implicits).
Paul Duffin11108272020-05-11 22:59:25 +0100106 Text("echo").Text(proptools.ShellEscape(content)).
107 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900108 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
109 rb.Command().
110 Text("chmod a+x").Output(gf.path)
111 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
112}
113
Paul Duffin13879572019-11-28 14:31:38 +0000114// Collect all the members.
115//
Paul Duffin6a7e9532020-03-20 17:50:07 +0000116// Returns a list containing type (extracted from the dependency tag) and the variant
117// plus the multilib usages.
118func (s *sdk) collectMembers(ctx android.ModuleContext) {
119 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000120 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
121 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000122 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
123 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900124
Paul Duffin13879572019-11-28 14:31:38 +0000125 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000126 if !memberType.IsInstance(child) {
127 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128 }
Paul Duffin13879572019-11-28 14:31:38 +0000129
Paul Duffin6a7e9532020-03-20 17:50:07 +0000130 // Keep track of which multilib variants are used by the sdk.
131 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
132
133 s.memberRefs = append(s.memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000134
135 // If the member type supports transitive sdk members then recurse down into
136 // its dependencies, otherwise exit traversal.
137 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900138 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000139
140 return false
Paul Duffin13879572019-11-28 14:31:38 +0000141 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000142}
143
144// Organize the members.
145//
146// The members are first grouped by type and then grouped by name. The order of
147// the types is the order they are referenced in android.SdkMemberTypesRegistry.
148// The names are in the order in which the dependencies were added.
149//
150// Returns the members as well as the multilib setting to use.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000151func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000152 byType := make(map[android.SdkMemberType][]*sdkMember)
153 byName := make(map[string]*sdkMember)
154
Paul Duffin1356d8c2020-02-25 19:26:33 +0000155 for _, memberRef := range memberRefs {
156 memberType := memberRef.memberType
157 variant := memberRef.variant
158
159 name := ctx.OtherModuleName(variant)
160 member := byName[name]
161 if member == nil {
162 member = &sdkMember{memberType: memberType, name: name}
163 byName[name] = member
164 byType[memberType] = append(byType[memberType], member)
165 }
166
Paul Duffin1356d8c2020-02-25 19:26:33 +0000167 // Only append new variants to the list. This is needed because a member can be both
168 // exported by the sdk and also be a transitive sdk member.
169 member.variants = appendUniqueVariants(member.variants, variant)
170 }
171
Paul Duffin13879572019-11-28 14:31:38 +0000172 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000173 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000174 membersOfType := byType[memberListProperty.memberType]
175 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900176 }
177
Paul Duffin6a7e9532020-03-20 17:50:07 +0000178 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900179}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900180
Paul Duffin72910952020-01-20 18:16:30 +0000181func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
182 for _, v := range variants {
183 if v == newVariant {
184 return variants
185 }
186 }
187 return append(variants, newVariant)
188}
189
Jiyong Park73c54ee2019-10-22 20:31:18 +0900190// SDK directory structure
191// <sdk_root>/
192// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
193// <api_ver>/ : below this directory are all auto-generated
194// Android.bp : definition of 'sdk_snapshot' module is here
195// aidl/
196// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
197// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900198// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199// include/
200// bionic/libc/include/stdlib.h : an exported header file
201// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900202// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900203// <arch>/include/ : arch-specific exported headers
204// <arch>/include_gen/ : arch-specific generated headers
205// <arch>/lib/
206// libFoo.so : a stub library
207
Jiyong Park232e7852019-11-04 12:23:40 +0900208// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900209// This isn't visible to users, so could be changed in future.
210func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
211 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
212}
213
Jiyong Park232e7852019-11-04 12:23:40 +0900214// buildSnapshot is the main function in this source file. It creates rules to copy
215// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000216func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
217
Paul Duffin13f02712020-03-06 12:30:43 +0000218 allMembersByName := make(map[string]struct{})
219 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000220 var memberRefs []sdkMemberRef
221 for _, sdkVariant := range sdkVariants {
222 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000223
Paul Duffin13f02712020-03-06 12:30:43 +0000224 // Record the names of all the members, both explicitly specified and implicitly
225 // included.
226 for _, memberRef := range sdkVariant.memberRefs {
227 allMembersByName[memberRef.variant.Name()] = struct{}{}
228 }
229
Paul Duffin865171e2020-03-02 18:38:15 +0000230 // Merge the exported member sets from all sdk variants.
231 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000232 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000233 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000234 }
235
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000236 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900237
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000238 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000239
240 bpFile := &bpFile{
241 modules: make(map[string]*bpModule),
242 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000243
244 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000245 ctx: ctx,
246 sdk: s,
247 version: "current",
248 snapshotDir: snapshotDir.OutputPath,
249 copies: make(map[string]string),
250 filesToZip: []android.Path{bp.path},
251 bpFile: bpFile,
252 prebuiltModules: make(map[string]*bpModule),
253 allMembersByName: allMembersByName,
254 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900255 }
Paul Duffinac37c502019-11-26 18:02:20 +0000256 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900257
Paul Duffin6a7e9532020-03-20 17:50:07 +0000258 members := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000259 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000260 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000261
Paul Duffina551a1c2020-03-17 21:04:24 +0000262 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000263
264 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Paul Duffin495ffb92020-03-20 13:35:40 +0000265 s.createMemberSnapshot(memberCtx, member, prebuiltModule)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900266 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900267
Paul Duffine6c0d842020-01-15 14:08:51 +0000268 // Create a transformer that will transform an unversioned module into a versioned module.
269 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
270
Paul Duffin72910952020-01-20 18:16:30 +0000271 // Create a transformer that will transform an unversioned module by replacing any references
272 // to internal members with a unique module name and setting prefer: false.
273 unversionedTransformer := unversionedTransformation{builder: builder}
274
Paul Duffinb645ec82019-11-27 17:43:54 +0000275 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000276 // Prune any empty property sets.
277 unversioned = unversioned.transform(pruneEmptySetTransformer{})
278
Paul Duffinb645ec82019-11-27 17:43:54 +0000279 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000280 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000281
282 // Transform the unversioned module into a versioned one.
283 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000284 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000285
Paul Duffin72910952020-01-20 18:16:30 +0000286 // Transform the unversioned module to make it suitable for use in the snapshot.
287 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000288 bpFile.AddModule(unversioned)
289 }
290
291 // Create the snapshot module.
292 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000293 var snapshotModuleType string
294 if s.properties.Module_exports {
295 snapshotModuleType = "module_exports_snapshot"
296 } else {
297 snapshotModuleType = "sdk_snapshot"
298 }
299 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000300 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000301
302 // Make sure that the snapshot has the same visibility as the sdk.
303 visibility := android.EffectiveVisibilityRules(ctx, s)
304 if len(visibility) != 0 {
305 snapshotModule.AddProperty("visibility", visibility)
306 }
307
Paul Duffin865171e2020-03-02 18:38:15 +0000308 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000309
Paul Duffinf34f6d82020-04-30 15:48:31 +0100310 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffin865171e2020-03-02 18:38:15 +0000311 osTypeToMemberProperties := make(map[android.OsType]*sdk)
312 for _, sdkVariant := range sdkVariants {
313 properties := sdkVariant.dynamicMemberTypeListProperties
314 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffin4b8b7932020-05-06 12:35:38 +0100315 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000316 }
317
318 // Extract the common lists of members into a separate struct.
319 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000320 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin4b8b7932020-05-06 12:35:38 +0100321 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000322
323 // Add properties common to all os types.
324 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
325
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100326 // Optimize other per-variant properties, besides the dynamic member lists.
327 type variantProperties struct {
328 Compile_multilib string `android:"arch_variant"`
329 }
330 var variantPropertiesContainers []propertiesContainer
331 variantToProperties := make(map[*sdk]*variantProperties)
332 for _, sdkVariant := range sdkVariants {
333 props := &variantProperties{
334 Compile_multilib: sdkVariant.multilibUsages.String(),
335 }
336 variantPropertiesContainers = append(variantPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, props})
337 variantToProperties[sdkVariant] = props
338 }
339 commonVariantProperties := variantProperties{}
340 extractor = newCommonValueExtractor(commonVariantProperties)
341 extractCommonProperties(ctx, extractor, &commonVariantProperties, variantPropertiesContainers)
342 if commonVariantProperties.Compile_multilib != "" && commonVariantProperties.Compile_multilib != "both" {
343 // Compile_multilib defaults to both so only needs to be set when it's
344 // specified and not both.
345 snapshotModule.AddProperty("compile_multilib", commonVariantProperties.Compile_multilib)
346 }
347
Paul Duffin865171e2020-03-02 18:38:15 +0000348 // Iterate over the os types in a fixed order.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000349 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin865171e2020-03-02 18:38:15 +0000350 for _, osType := range s.getPossibleOsTypes() {
351 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
352 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000353
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100354 variantProps := variantToProperties[sdkVariant]
355 if variantProps.Compile_multilib != "" && variantProps.Compile_multilib != "both" {
356 osPropertySet.AddProperty("compile_multilib", variantProps.Compile_multilib)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000357 }
358
Paul Duffin865171e2020-03-02 18:38:15 +0000359 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000360 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000361 }
Paul Duffin865171e2020-03-02 18:38:15 +0000362
363 // Prune any empty property sets.
364 snapshotModule.transform(pruneEmptySetTransformer{})
365
Paul Duffinb645ec82019-11-27 17:43:54 +0000366 bpFile.AddModule(snapshotModule)
367
368 // generate Android.bp
369 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
370 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000371
Paul Duffinf88d8e02020-05-07 20:21:34 +0100372 contents := bp.content.String()
373 syntaxCheckSnapshotBpFile(ctx, contents)
374
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000375 bp.build(pctx, ctx, nil)
376
377 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900378
Jiyong Park232e7852019-11-04 12:23:40 +0900379 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000380 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000381 outputDesc := "Building snapshot for " + ctx.ModuleName()
382
383 // If there are no zips to merge then generate the output zip directly.
384 // Otherwise, generate an intermediate zip file into which other zips can be
385 // merged.
386 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000387 var desc string
388 if len(builder.zipsToMerge) == 0 {
389 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000390 desc = outputDesc
391 } else {
392 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000393 desc = "Building intermediate snapshot for " + ctx.ModuleName()
394 }
395
Paul Duffin375058f2019-11-29 20:17:53 +0000396 ctx.Build(pctx, android.BuildParams{
397 Description: desc,
398 Rule: zipFiles,
399 Inputs: filesToZip,
400 Output: zipFile,
401 Args: map[string]string{
402 "basedir": builder.snapshotDir.String(),
403 },
404 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900405
Paul Duffin91547182019-11-12 19:39:36 +0000406 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000407 ctx.Build(pctx, android.BuildParams{
408 Description: outputDesc,
409 Rule: mergeZips,
410 Input: zipFile,
411 Inputs: builder.zipsToMerge,
412 Output: outputZipFile,
413 })
Paul Duffin91547182019-11-12 19:39:36 +0000414 }
415
416 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900417}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000418
Paul Duffinf88d8e02020-05-07 20:21:34 +0100419// Check the syntax of the generated Android.bp file contents and if they are
420// invalid then log an error with the contents (tagged with line numbers) and the
421// errors that were found so that it is easy to see where the problem lies.
422func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
423 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
424 if len(errs) != 0 {
425 message := &strings.Builder{}
426 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
427
428Generated Android.bp contents
429========================================================================
430`)
431 for i, line := range strings.Split(contents, "\n") {
432 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
433 }
434
435 _, _ = fmt.Fprint(message, `
436========================================================================
437
438Errors found:
439`)
440
441 for _, err := range errs {
442 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
443 }
444
445 ctx.ModuleErrorf("%s", message.String())
446 }
447}
448
Paul Duffin4b8b7932020-05-06 12:35:38 +0100449func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
450 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
451 if err != nil {
452 ctx.ModuleErrorf("error extracting common properties: %s", err)
453 }
454}
455
Paul Duffin865171e2020-03-02 18:38:15 +0000456func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
457 for _, memberListProperty := range s.memberListProperties() {
458 names := memberListProperty.getter(dynamicMemberTypeListProperties)
459 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000460 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000461 }
462 }
463}
464
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000465type propertyTag struct {
466 name string
467}
468
Paul Duffin0cb37b92020-03-04 14:52:46 +0000469// A BpPropertyTag to add to a property that contains references to other sdk members.
470//
471// This will cause the references to be rewritten to a versioned reference in the version
472// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000473var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000474var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000475
Paul Duffin0cb37b92020-03-04 14:52:46 +0000476// A BpPropertyTag that indicates the property should only be present in the versioned
477// module.
478//
479// This will cause the property to be removed from the unversioned instance of a
480// snapshot module.
481var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
482
Paul Duffine6c0d842020-01-15 14:08:51 +0000483type unversionedToVersionedTransformation struct {
484 identityTransformation
485 builder *snapshotBuilder
486}
487
Paul Duffine6c0d842020-01-15 14:08:51 +0000488func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
489 // Use a versioned name for the module but remember the original name for the
490 // snapshot.
491 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000492 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000493 module.insertAfter("name", "sdk_member_name", name)
494 return module
495}
496
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000497func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000498 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
499 required := tag == requiredSdkMemberReferencePropertyTag
500 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000501 } else {
502 return value, tag
503 }
504}
505
Paul Duffin72910952020-01-20 18:16:30 +0000506type unversionedTransformation struct {
507 identityTransformation
508 builder *snapshotBuilder
509}
510
511func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
512 // If the module is an internal member then use a unique name for it.
513 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000514 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000515
516 // Set prefer: false - this is not strictly required as that is the default.
517 module.insertAfter("name", "prefer", false)
518
519 return module
520}
521
522func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000523 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
524 required := tag == requiredSdkMemberReferencePropertyTag
525 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000526 } else if tag == sdkVersionedOnlyPropertyTag {
527 // The property is not allowed in the unversioned module so remove it.
528 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000529 } else {
530 return value, tag
531 }
532}
533
Paul Duffina78f3a72020-02-21 16:29:35 +0000534type pruneEmptySetTransformer struct {
535 identityTransformation
536}
537
538var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
539
540func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
541 if len(propertySet.properties) == 0 {
542 return nil, nil
543 } else {
544 return propertySet, tag
545 }
546}
547
Paul Duffinb645ec82019-11-27 17:43:54 +0000548func generateBpContents(contents *generatedContents, bpFile *bpFile) {
549 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
550 for _, bpModule := range bpFile.order {
551 contents.Printfln("")
552 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000553 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000554 contents.Printfln("}")
555 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000556}
557
558func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
559 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000560
561 // Output the properties first, followed by the nested sets. This ensures a
562 // consistent output irrespective of whether property sets are created before
563 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000564 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000565 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000566
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000567 switch v := value.(type) {
568 case []string:
569 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000570 if length > 1 {
571 contents.Printfln("%s: [", name)
572 contents.Indent()
573 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000574 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000575 }
576 contents.Dedent()
577 contents.Printfln("],")
578 } else if length == 0 {
579 contents.Printfln("%s: [],", name)
580 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000581 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000582 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000583
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000584 case bool:
585 contents.Printfln("%s: %t,", name, v)
586
587 case *bpPropertySet:
588 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000589
590 default:
591 contents.Printfln("%s: %q,", name, value)
592 }
593 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000594
595 for _, name := range set.order {
596 value := set.getValue(name)
597
598 // Only write property sets in the sets phase.
599 switch v := value.(type) {
600 case *bpPropertySet:
601 contents.Printfln("%s: {", name)
602 outputPropertySet(contents, v)
603 contents.Printfln("},")
604 }
605 }
606
Paul Duffinb645ec82019-11-27 17:43:54 +0000607 contents.Dedent()
608}
609
Paul Duffinac37c502019-11-26 18:02:20 +0000610func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000611 contents := &generatedContents{}
612 generateBpContents(contents, s.builderForTests.bpFile)
613 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000614}
615
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000616type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000617 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000618 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000619 version string
620 snapshotDir android.OutputPath
621 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000622
623 // Map from destination to source of each copy - used to eliminate duplicates and
624 // detect conflicts.
625 copies map[string]string
626
Paul Duffinb645ec82019-11-27 17:43:54 +0000627 filesToZip android.Paths
628 zipsToMerge android.Paths
629
630 prebuiltModules map[string]*bpModule
631 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000632
633 // The set of all members by name.
634 allMembersByName map[string]struct{}
635
636 // The set of exported members by name.
637 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000638}
639
640func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000641 if existing, ok := s.copies[dest]; ok {
642 if existing != src.String() {
643 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
644 return
645 }
646 } else {
647 path := s.snapshotDir.Join(s.ctx, dest)
648 s.ctx.Build(pctx, android.BuildParams{
649 Rule: android.Cp,
650 Input: src,
651 Output: path,
652 })
653 s.filesToZip = append(s.filesToZip, path)
654
655 s.copies[dest] = src.String()
656 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000657}
658
Paul Duffin91547182019-11-12 19:39:36 +0000659func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
660 ctx := s.ctx
661
662 // Repackage the zip file so that the entries are in the destDir directory.
663 // This will allow the zip file to be merged into the snapshot.
664 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000665
666 ctx.Build(pctx, android.BuildParams{
667 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
668 Rule: repackageZip,
669 Input: zipPath,
670 Output: tmpZipPath,
671 Args: map[string]string{
672 "destdir": destDir,
673 },
674 })
Paul Duffin91547182019-11-12 19:39:36 +0000675
676 // Add the repackaged zip file to the files to merge.
677 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
678}
679
Paul Duffin9d8d6092019-12-05 18:19:29 +0000680func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
681 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000682 if s.prebuiltModules[name] != nil {
683 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
684 }
685
686 m := s.bpFile.newModule(moduleType)
687 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000688
Paul Duffinbefa4b92020-03-04 14:22:45 +0000689 variant := member.Variants()[0]
690
Paul Duffin13f02712020-03-06 12:30:43 +0000691 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000692 // An internal member is only referenced from the sdk snapshot which is in the
693 // same package so can be marked as private.
694 m.AddProperty("visibility", []string{"//visibility:private"})
695 } else {
696 // Extract visibility information from a member variant. All variants have the same
697 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000698 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000699 if len(visibility) != 0 {
700 m.AddProperty("visibility", visibility)
701 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000702 }
703
Paul Duffin865171e2020-03-02 18:38:15 +0000704 deviceSupported := false
705 hostSupported := false
706
707 for _, variant := range member.Variants() {
708 osClass := variant.Target().Os.Class
709 if osClass == android.Host || osClass == android.HostCross {
710 hostSupported = true
711 } else if osClass == android.Device {
712 deviceSupported = true
713 }
714 }
715
716 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000717
Paul Duffinbefa4b92020-03-04 14:22:45 +0000718 // Where available copy apex_available properties from the member.
719 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
720 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000721
Colin Cross440e0d02020-06-11 11:32:11 -0700722 // Add in any baseline apex available settings.
723 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000724
Paul Duffinbefa4b92020-03-04 14:22:45 +0000725 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000726 // Remove duplicates and sort.
727 apexAvailable = android.FirstUniqueStrings(apexAvailable)
728 sort.Strings(apexAvailable)
729
Paul Duffinbefa4b92020-03-04 14:22:45 +0000730 m.AddProperty("apex_available", apexAvailable)
731 }
732 }
733
Paul Duffin0cb37b92020-03-04 14:52:46 +0000734 // Disable installation in the versioned module of those modules that are ever installable.
735 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
736 if installable.EverInstallable() {
737 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
738 }
739 }
740
Paul Duffinb645ec82019-11-27 17:43:54 +0000741 s.prebuiltModules[name] = m
742 s.prebuiltOrder = append(s.prebuiltOrder, m)
743 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000744}
745
Paul Duffin865171e2020-03-02 18:38:15 +0000746func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
747 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000748 bpModule.AddProperty("device_supported", false)
749 }
Paul Duffin865171e2020-03-02 18:38:15 +0000750 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000751 bpModule.AddProperty("host_supported", true)
752 }
753}
754
Paul Duffin13f02712020-03-06 12:30:43 +0000755func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
756 if required {
757 return requiredSdkMemberReferencePropertyTag
758 } else {
759 return optionalSdkMemberReferencePropertyTag
760 }
761}
762
763func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
764 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000765}
766
Paul Duffinb645ec82019-11-27 17:43:54 +0000767// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000768func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
769 if _, ok := s.allMembersByName[unversionedName]; !ok {
770 if required {
771 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
772 }
773 return unversionedName
774 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000775 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
776}
Paul Duffinb645ec82019-11-27 17:43:54 +0000777
Paul Duffin13f02712020-03-06 12:30:43 +0000778func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000779 var references []string = nil
780 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000781 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000782 }
783 return references
784}
Paul Duffin13879572019-11-28 14:31:38 +0000785
Paul Duffin72910952020-01-20 18:16:30 +0000786// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000787func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
788 if _, ok := s.allMembersByName[unversionedName]; !ok {
789 if required {
790 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
791 }
792 return unversionedName
793 }
794
795 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000796 return s.ctx.ModuleName() + "_" + unversionedName
797 } else {
798 return unversionedName
799 }
800}
801
Paul Duffin13f02712020-03-06 12:30:43 +0000802func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000803 var references []string = nil
804 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000805 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000806 }
807 return references
808}
809
Paul Duffin13f02712020-03-06 12:30:43 +0000810func (s *snapshotBuilder) isInternalMember(memberName string) bool {
811 _, ok := s.exportedMembersByName[memberName]
812 return !ok
813}
814
Martin Stjernholm89238f42020-07-10 00:14:03 +0100815// Add the properties from the given SdkMemberProperties to the blueprint
816// property set. This handles common properties in SdkMemberPropertiesBase and
817// calls the member-specific AddToPropertySet for the rest.
818func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
819 if memberProperties.Base().Compile_multilib != "" {
820 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
821 }
822
823 memberProperties.AddToPropertySet(ctx, targetPropertySet)
824}
825
Paul Duffin1356d8c2020-02-25 19:26:33 +0000826type sdkMemberRef struct {
827 memberType android.SdkMemberType
828 variant android.SdkAware
829}
830
Paul Duffin13879572019-11-28 14:31:38 +0000831var _ android.SdkMember = (*sdkMember)(nil)
832
833type sdkMember struct {
834 memberType android.SdkMemberType
835 name string
836 variants []android.SdkAware
837}
838
839func (m *sdkMember) Name() string {
840 return m.name
841}
842
843func (m *sdkMember) Variants() []android.SdkAware {
844 return m.variants
845}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000846
Paul Duffin9c3760e2020-03-16 19:52:08 +0000847// Track usages of multilib variants.
848type multilibUsage int
849
850const (
851 multilibNone multilibUsage = 0
852 multilib32 multilibUsage = 1
853 multilib64 multilibUsage = 2
854 multilibBoth = multilib32 | multilib64
855)
856
857// Add the multilib that is used in the arch type.
858func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
859 multilib := archType.Multilib
860 switch multilib {
861 case "":
862 return m
863 case "lib32":
864 return m | multilib32
865 case "lib64":
866 return m | multilib64
867 default:
868 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
869 }
870}
871
872func (m multilibUsage) String() string {
873 switch m {
874 case multilibNone:
875 return ""
876 case multilib32:
877 return "32"
878 case multilib64:
879 return "64"
880 case multilibBoth:
881 return "both"
882 default:
883 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
884 m, multilibNone, multilib32, multilib64, multilibBoth))
885 }
886}
887
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000888type baseInfo struct {
889 Properties android.SdkMemberProperties
890}
891
Paul Duffinf34f6d82020-04-30 15:48:31 +0100892func (b *baseInfo) optimizableProperties() interface{} {
893 return b.Properties
894}
895
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000896type osTypeSpecificInfo struct {
897 baseInfo
898
Paul Duffin00e46802020-03-12 20:40:35 +0000899 osType android.OsType
900
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000901 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000902 //
903 // Nil if there is one variant whose arch type is common
904 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000905}
906
Paul Duffin4b8b7932020-05-06 12:35:38 +0100907var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
908
Paul Duffinfc8dd232020-03-17 12:51:37 +0000909type variantPropertiesFactoryFunc func() android.SdkMemberProperties
910
Paul Duffin00e46802020-03-12 20:40:35 +0000911// Create a new osTypeSpecificInfo for the specified os type and its properties
912// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000913func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000914 osInfo := &osTypeSpecificInfo{
915 osType: osType,
916 }
917
918 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
919 properties := variantPropertiesFactory()
920 properties.Base().Os = osType
921 return properties
922 }
923
924 // Create a structure into which properties common across the architectures in
925 // this os type will be stored.
926 osInfo.Properties = osSpecificVariantPropertiesFactory()
927
928 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000929 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000930 var archTypes []android.ArchType
931 for _, variant := range osTypeVariants {
932 archType := variant.Target().Arch.ArchType
933 archTypeName := archType.Name
934 if _, ok := variantsByArchName[archTypeName]; !ok {
935 archTypes = append(archTypes, archType)
936 }
937
938 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
939 }
940
941 if commonVariants, ok := variantsByArchName["common"]; ok {
942 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -0700943 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 +0000944 }
945
946 // A common arch type only has one variant and its properties should be treated
947 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000948 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000949 } else {
950 // Create an arch specific info for each supported architecture type.
951 for _, archType := range archTypes {
952 archTypeName := archType.Name
953
954 archVariants := variantsByArchName[archTypeName]
Paul Duffin3a4eb502020-03-19 16:11:18 +0000955 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000956
957 osInfo.archInfos = append(osInfo.archInfos, archInfo)
958 }
959 }
960
961 return osInfo
962}
963
964// Optimize the properties by extracting common properties from arch type specific
965// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100966func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +0000967 // Nothing to do if there is only a single common architecture.
968 if len(osInfo.archInfos) == 0 {
969 return
970 }
971
Paul Duffin9c3760e2020-03-16 19:52:08 +0000972 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000973 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000974 multilib = multilib.addArchType(archInfo.archType)
975
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000976 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100977 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +0000978 }
979
Paul Duffin4b8b7932020-05-06 12:35:38 +0100980 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +0000981
982 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000983 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000984}
985
986// Add the properties for an os to a property set.
987//
988// Maps the properties related to the os variants through to an appropriate
989// module structure that will produce equivalent set of variants when it is
990// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000991func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +0000992
993 var osPropertySet android.BpPropertySet
994 var archPropertySet android.BpPropertySet
995 var archOsPrefix string
996 if osInfo.Properties.Base().Os_count == 1 {
997 // There is only one os type present in the variants so don't bother
998 // with adding target specific properties.
999
1000 // Create a structure that looks like:
1001 // module_type {
1002 // name: "...",
1003 // ...
1004 // <common properties>
1005 // ...
1006 // <single os type specific properties>
1007 //
1008 // arch: {
1009 // <arch specific sections>
1010 // }
1011 //
1012 osPropertySet = bpModule
1013 archPropertySet = osPropertySet.AddPropertySet("arch")
1014
1015 // Arch specific properties need to be added to an arch specific section
1016 // within arch.
1017 archOsPrefix = ""
1018 } else {
1019 // Create a structure that looks like:
1020 // module_type {
1021 // name: "...",
1022 // ...
1023 // <common properties>
1024 // ...
1025 // target: {
1026 // <arch independent os specific sections, e.g. android>
1027 // ...
1028 // <arch and os specific sections, e.g. android_x86>
1029 // }
1030 //
1031 osType := osInfo.osType
1032 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1033 archPropertySet = targetPropertySet
1034
1035 // Arch specific properties need to be added to an os and arch specific
1036 // section prefixed with <os>_.
1037 archOsPrefix = osType.Name + "_"
1038 }
1039
1040 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001041 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001042
1043 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1044 // os) specific properties.
1045 //
1046 // The archInfos list will be empty if the os contains variants for the common
1047 // architecture.
1048 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001049 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001050 }
1051}
1052
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001053func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1054 osClass := osInfo.osType.Class
1055 return osClass == android.Host || osClass == android.HostCross
1056}
1057
1058var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1059
Paul Duffin4b8b7932020-05-06 12:35:38 +01001060func (osInfo *osTypeSpecificInfo) String() string {
1061 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1062}
1063
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001064type archTypeSpecificInfo struct {
1065 baseInfo
1066
1067 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001068
1069 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001070}
1071
Paul Duffin4b8b7932020-05-06 12:35:38 +01001072var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1073
Paul Duffinfc8dd232020-03-17 12:51:37 +00001074// Create a new archTypeSpecificInfo for the specified arch type and its properties
1075// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001076func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001077
Paul Duffinfc8dd232020-03-17 12:51:37 +00001078 // Create an arch specific info into which the variant properties can be copied.
1079 archInfo := &archTypeSpecificInfo{archType: archType}
1080
1081 // Create the properties into which the arch type specific properties will be
1082 // added.
1083 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001084
1085 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001086 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001087 } else {
1088 // There is more than one variant for this arch type which must be differentiated
1089 // by link type.
1090 for _, linkVariant := range archVariants {
1091 linkType := getLinkType(linkVariant)
1092 if linkType == "" {
1093 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1094 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001095 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001096
1097 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1098 }
1099 }
1100 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001101
1102 return archInfo
1103}
1104
Paul Duffinf34f6d82020-04-30 15:48:31 +01001105func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1106 return archInfo.Properties
1107}
1108
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001109// Get the link type of the variant
1110//
1111// If the variant is not differentiated by link type then it returns "",
1112// otherwise it returns one of "static" or "shared".
1113func getLinkType(variant android.Module) string {
1114 linkType := ""
1115 if linkable, ok := variant.(cc.LinkableInterface); ok {
1116 if linkable.Shared() && linkable.Static() {
1117 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1118 } else if linkable.Shared() {
1119 linkType = "shared"
1120 } else if linkable.Static() {
1121 linkType = "static"
1122 } else {
1123 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1124 }
1125 }
1126 return linkType
1127}
1128
1129// Optimize the properties by extracting common properties from link type specific
1130// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001131func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001132 if len(archInfo.linkInfos) == 0 {
1133 return
1134 }
1135
Paul Duffin4b8b7932020-05-06 12:35:38 +01001136 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001137}
1138
Paul Duffinfc8dd232020-03-17 12:51:37 +00001139// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001140func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001141 archTypeName := archInfo.archType.Name
1142 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001143 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001144
1145 for _, linkInfo := range archInfo.linkInfos {
1146 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001147 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001148 }
1149}
1150
Paul Duffin4b8b7932020-05-06 12:35:38 +01001151func (archInfo *archTypeSpecificInfo) String() string {
1152 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1153}
1154
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001155type linkTypeSpecificInfo struct {
1156 baseInfo
1157
1158 linkType string
1159}
1160
Paul Duffin4b8b7932020-05-06 12:35:38 +01001161var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1162
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001163// Create a new linkTypeSpecificInfo for the specified link type and its properties
1164// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001165func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001166 linkInfo := &linkTypeSpecificInfo{
1167 baseInfo: baseInfo{
1168 // Create the properties into which the link type specific properties will be
1169 // added.
1170 Properties: variantPropertiesFactory(),
1171 },
1172 linkType: linkType,
1173 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001174 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001175 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001176}
1177
Paul Duffin4b8b7932020-05-06 12:35:38 +01001178func (l *linkTypeSpecificInfo) String() string {
1179 return fmt.Sprintf("LinkType{%s}", l.linkType)
1180}
1181
Paul Duffin3a4eb502020-03-19 16:11:18 +00001182type memberContext struct {
1183 sdkMemberContext android.ModuleContext
1184 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001185 memberType android.SdkMemberType
1186 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001187}
1188
1189func (m *memberContext) SdkModuleContext() android.ModuleContext {
1190 return m.sdkMemberContext
1191}
1192
1193func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1194 return m.builder
1195}
1196
Paul Duffina551a1c2020-03-17 21:04:24 +00001197func (m *memberContext) MemberType() android.SdkMemberType {
1198 return m.memberType
1199}
1200
1201func (m *memberContext) Name() string {
1202 return m.name
1203}
1204
Paul Duffin3a4eb502020-03-19 16:11:18 +00001205func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001206
1207 memberType := member.memberType
1208
Paul Duffina04c1072020-03-02 10:16:35 +00001209 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001210 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001211 variants := member.Variants()
1212 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001213 osType := variant.Target().Os
1214 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001215 }
1216
Paul Duffina04c1072020-03-02 10:16:35 +00001217 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001218 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001219 properties := memberType.CreateVariantPropertiesStruct()
1220 base := properties.Base()
1221 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001222 return properties
1223 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001224
Paul Duffina04c1072020-03-02 10:16:35 +00001225 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001226
Paul Duffina04c1072020-03-02 10:16:35 +00001227 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001228 commonProperties := variantPropertiesFactory()
1229 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001230
Paul Duffinc097e362020-03-10 22:50:03 +00001231 // Create common value extractor that can be used to optimize the properties.
1232 commonValueExtractor := newCommonValueExtractor(commonProperties)
1233
Paul Duffina04c1072020-03-02 10:16:35 +00001234 // The list of property structures which are os type specific but common across
1235 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001236 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001237
1238 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001239 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001240 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001241 // Add the os specific properties to a list of os type specific yet architecture
1242 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001243 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001244
Paul Duffin00e46802020-03-12 20:40:35 +00001245 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001246 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001247 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001248
Paul Duffina04c1072020-03-02 10:16:35 +00001249 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001250 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001251
Paul Duffina04c1072020-03-02 10:16:35 +00001252 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001253 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001254
Paul Duffina04c1072020-03-02 10:16:35 +00001255 // Create a target property set into which target specific properties can be
1256 // added.
1257 targetPropertySet := bpModule.AddPropertySet("target")
1258
1259 // Iterate over the os types in a fixed order.
1260 for _, osType := range s.getPossibleOsTypes() {
1261 osInfo := osTypeToInfo[osType]
1262 if osInfo == nil {
1263 continue
1264 }
1265
Paul Duffin3a4eb502020-03-19 16:11:18 +00001266 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001267 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001268}
1269
Paul Duffina04c1072020-03-02 10:16:35 +00001270// Compute the list of possible os types that this sdk could support.
1271func (s *sdk) getPossibleOsTypes() []android.OsType {
1272 var osTypes []android.OsType
1273 for _, osType := range android.OsTypeList {
1274 if s.DeviceSupported() {
1275 if osType.Class == android.Device && osType != android.Fuchsia {
1276 osTypes = append(osTypes, osType)
1277 }
1278 }
1279 if s.HostSupported() {
1280 if osType.Class == android.Host || osType.Class == android.HostCross {
1281 osTypes = append(osTypes, osType)
1282 }
1283 }
1284 }
1285 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1286 return osTypes
1287}
1288
Paul Duffinb28369a2020-05-04 15:39:59 +01001289// Given a set of properties (struct value), return the value of the field within that
1290// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001291type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1292
Paul Duffinc459f892020-04-30 18:08:29 +01001293// Checks the metadata to determine whether the property should be ignored for the
1294// purposes of common value extraction or not.
1295type extractorMetadataPredicate func(metadata propertiesContainer) bool
1296
1297// Indicates whether optimizable properties are provided by a host variant or
1298// not.
1299type isHostVariant interface {
1300 isHostVariant() bool
1301}
1302
Paul Duffinb28369a2020-05-04 15:39:59 +01001303// A property that can be optimized by the commonValueExtractor.
1304type extractorProperty struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001305 // The name of the field for this property.
1306 name string
1307
Paul Duffinc459f892020-04-30 18:08:29 +01001308 // Filter that can use metadata associated with the properties being optimized
1309 // to determine whether the field should be ignored during common value
1310 // optimization.
1311 filter extractorMetadataPredicate
1312
Paul Duffinb28369a2020-05-04 15:39:59 +01001313 // Retrieves the value on which common value optimization will be performed.
1314 getter fieldAccessorFunc
1315
1316 // The empty value for the field.
1317 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001318
1319 // True if the property can support arch variants false otherwise.
1320 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001321}
1322
Paul Duffin4b8b7932020-05-06 12:35:38 +01001323func (p extractorProperty) String() string {
1324 return p.name
1325}
1326
Paul Duffinc097e362020-03-10 22:50:03 +00001327// Supports extracting common values from a number of instances of a properties
1328// structure into a separate common set of properties.
1329type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001330 // The properties that the extractor can optimize.
1331 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001332}
1333
1334// Create a new common value extractor for the structure type for the supplied
1335// properties struct.
1336//
1337// The returned extractor can be used on any properties structure of the same type
1338// as the supplied set of properties.
1339func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1340 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1341 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001342 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001343 return extractor
1344}
1345
1346// Gather the fields from the supplied structure type from which common values will
1347// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001348//
1349// This is recursive function. If it encounters an embedded field (no field name)
1350// that is a struct then it will recurse into that struct passing in the accessor
1351// for the field. That will then be used in the accessors for the fields in the
1352// embedded struct.
1353func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001354 for f := 0; f < structType.NumField(); f++ {
1355 field := structType.Field(f)
1356 if field.PkgPath != "" {
1357 // Ignore unexported fields.
1358 continue
1359 }
1360
Paul Duffinb07fa512020-03-10 22:17:04 +00001361 // Ignore fields whose value should be kept.
1362 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001363 continue
1364 }
1365
Paul Duffinc459f892020-04-30 18:08:29 +01001366 var filter extractorMetadataPredicate
1367
1368 // Add a filter
1369 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1370 filter = func(metadata propertiesContainer) bool {
1371 if m, ok := metadata.(isHostVariant); ok {
1372 if m.isHostVariant() {
1373 return false
1374 }
1375 }
1376 return true
1377 }
1378 }
1379
Paul Duffinc097e362020-03-10 22:50:03 +00001380 // Save a copy of the field index for use in the function.
1381 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001382
1383 name := field.Name
1384
Paul Duffinc097e362020-03-10 22:50:03 +00001385 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001386 if containingStructAccessor != nil {
1387 // This is an embedded structure so first access the field for the embedded
1388 // structure.
1389 value = containingStructAccessor(value)
1390 }
1391
Paul Duffinc097e362020-03-10 22:50:03 +00001392 // Skip through interface and pointer values to find the structure.
1393 value = getStructValue(value)
1394
Paul Duffin4b8b7932020-05-06 12:35:38 +01001395 defer func() {
1396 if r := recover(); r != nil {
1397 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1398 }
1399 }()
1400
Paul Duffinc097e362020-03-10 22:50:03 +00001401 // Return the field.
1402 return value.Field(fieldIndex)
1403 }
1404
Paul Duffinb07fa512020-03-10 22:17:04 +00001405 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1406 // Gather fields from the embedded structure.
1407 e.gatherFields(field.Type, fieldGetter)
1408 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001409 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001410 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001411 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001412 fieldGetter,
1413 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001414 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001415 }
1416 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001417 }
Paul Duffinc097e362020-03-10 22:50:03 +00001418 }
1419}
1420
1421func getStructValue(value reflect.Value) reflect.Value {
1422foundStruct:
1423 for {
1424 kind := value.Kind()
1425 switch kind {
1426 case reflect.Interface, reflect.Ptr:
1427 value = value.Elem()
1428 case reflect.Struct:
1429 break foundStruct
1430 default:
1431 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1432 }
1433 }
1434 return value
1435}
1436
Paul Duffinf34f6d82020-04-30 15:48:31 +01001437// A container of properties to be optimized.
1438//
1439// Allows additional information to be associated with the properties, e.g. for
1440// filtering.
1441type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001442 fmt.Stringer
1443
Paul Duffinf34f6d82020-04-30 15:48:31 +01001444 // Get the properties that need optimizing.
1445 optimizableProperties() interface{}
1446}
1447
1448// A wrapper for dynamic member properties to allow them to be optimized.
1449type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001450 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001451 dynamicMemberProperties interface{}
1452}
1453
1454func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1455 return c.dynamicMemberProperties
1456}
1457
Paul Duffin4b8b7932020-05-06 12:35:38 +01001458func (c dynamicMemberPropertiesContainer) String() string {
1459 return c.sdkVariant.String()
1460}
1461
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001462// Extract common properties from a slice of property structures of the same type.
1463//
1464// All the property structures must be of the same type.
1465// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001466// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001467//
1468// Iterates over each exported field (capitalized name) and checks to see whether they
1469// have the same value (using DeepEquals) across all the input properties. If it does not then no
1470// change is made. Otherwise, the common value is stored in the field in the commonProperties
1471// and the field in each of the input properties structure is set to its default value.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001472func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001473 commonPropertiesValue := reflect.ValueOf(commonProperties)
1474 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001475
Paul Duffinf34f6d82020-04-30 15:48:31 +01001476 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1477
Paul Duffinb28369a2020-05-04 15:39:59 +01001478 for _, property := range e.properties {
1479 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001480 filter := property.filter
1481 if filter == nil {
1482 filter = func(metadata propertiesContainer) bool {
1483 return true
1484 }
1485 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001486
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001487 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001488 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1489 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001490 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001491
Paul Duffin864e1b42020-05-06 10:23:19 +01001492 // Assume that all the values will be the same.
1493 //
1494 // While similar to this is not quite the same as commonValue == nil. If all the values
1495 // have been filtered out then this will be false but commonValue == nil will be true.
1496 valuesDiffer := false
1497
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001498 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001499 container := sliceValue.Index(i).Interface().(propertiesContainer)
1500 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001501 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001502
Paul Duffinc459f892020-04-30 18:08:29 +01001503 if !filter(container) {
1504 expectedValue := property.emptyValue.Interface()
1505 actualValue := fieldValue.Interface()
1506 if !reflect.DeepEqual(expectedValue, actualValue) {
1507 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1508 }
1509 continue
1510 }
1511
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001512 if commonValue == nil {
1513 // Use the first value as the commonProperties value.
1514 commonValue = &fieldValue
1515 } else {
1516 // If the value does not match the current common value then there is
1517 // no value in common so break out.
1518 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1519 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001520 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001521 break
1522 }
1523 }
1524 }
1525
Paul Duffin864e1b42020-05-06 10:23:19 +01001526 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001527 // and set the input struct's field to the empty value.
1528 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001529 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001530 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001531 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001532 container := sliceValue.Index(i).Interface().(propertiesContainer)
1533 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001534 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001535 fieldValue.Set(emptyValue)
1536 }
1537 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001538
1539 if valuesDiffer && !property.archVariant {
1540 // The values differ but the property does not support arch variants so it
1541 // is an error.
1542 var details strings.Builder
1543 for i := 0; i < sliceValue.Len(); i++ {
1544 container := sliceValue.Index(i).Interface().(propertiesContainer)
1545 itemValue := reflect.ValueOf(container.optimizableProperties())
1546 fieldValue := fieldGetter(itemValue)
1547
1548 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1549 }
1550
1551 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1552 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001553 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001554
1555 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001556}