blob: cf2500826461d88bbe4ae4953c3dace4a176a89f [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
326 // Iterate over the os types in a fixed order.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000327 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin865171e2020-03-02 18:38:15 +0000328 for _, osType := range s.getPossibleOsTypes() {
329 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
330 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000331
332 // Compile_multilib defaults to both and must always be set to both on the
333 // device and so only needs to be set when targeted at the host and is neither
334 // unspecified or both.
335 multilib := sdkVariant.multilibUsages
336 if (osType.Class == android.Host || osType.Class == android.HostCross) &&
337 multilib != multilibNone && multilib != multilibBoth {
338 osPropertySet.AddProperty("compile_multilib", multilib.String())
339 }
340
Paul Duffin865171e2020-03-02 18:38:15 +0000341 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000342 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000343 }
Paul Duffin865171e2020-03-02 18:38:15 +0000344
345 // Prune any empty property sets.
346 snapshotModule.transform(pruneEmptySetTransformer{})
347
Paul Duffinb645ec82019-11-27 17:43:54 +0000348 bpFile.AddModule(snapshotModule)
349
350 // generate Android.bp
351 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
352 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000353
Paul Duffinf88d8e02020-05-07 20:21:34 +0100354 contents := bp.content.String()
355 syntaxCheckSnapshotBpFile(ctx, contents)
356
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000357 bp.build(pctx, ctx, nil)
358
359 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900360
Jiyong Park232e7852019-11-04 12:23:40 +0900361 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000362 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000363 outputDesc := "Building snapshot for " + ctx.ModuleName()
364
365 // If there are no zips to merge then generate the output zip directly.
366 // Otherwise, generate an intermediate zip file into which other zips can be
367 // merged.
368 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000369 var desc string
370 if len(builder.zipsToMerge) == 0 {
371 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000372 desc = outputDesc
373 } else {
374 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000375 desc = "Building intermediate snapshot for " + ctx.ModuleName()
376 }
377
Paul Duffin375058f2019-11-29 20:17:53 +0000378 ctx.Build(pctx, android.BuildParams{
379 Description: desc,
380 Rule: zipFiles,
381 Inputs: filesToZip,
382 Output: zipFile,
383 Args: map[string]string{
384 "basedir": builder.snapshotDir.String(),
385 },
386 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900387
Paul Duffin91547182019-11-12 19:39:36 +0000388 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000389 ctx.Build(pctx, android.BuildParams{
390 Description: outputDesc,
391 Rule: mergeZips,
392 Input: zipFile,
393 Inputs: builder.zipsToMerge,
394 Output: outputZipFile,
395 })
Paul Duffin91547182019-11-12 19:39:36 +0000396 }
397
398 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900399}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000400
Paul Duffinf88d8e02020-05-07 20:21:34 +0100401// Check the syntax of the generated Android.bp file contents and if they are
402// invalid then log an error with the contents (tagged with line numbers) and the
403// errors that were found so that it is easy to see where the problem lies.
404func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
405 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
406 if len(errs) != 0 {
407 message := &strings.Builder{}
408 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
409
410Generated Android.bp contents
411========================================================================
412`)
413 for i, line := range strings.Split(contents, "\n") {
414 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
415 }
416
417 _, _ = fmt.Fprint(message, `
418========================================================================
419
420Errors found:
421`)
422
423 for _, err := range errs {
424 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
425 }
426
427 ctx.ModuleErrorf("%s", message.String())
428 }
429}
430
Paul Duffin4b8b7932020-05-06 12:35:38 +0100431func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
432 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
433 if err != nil {
434 ctx.ModuleErrorf("error extracting common properties: %s", err)
435 }
436}
437
Paul Duffin865171e2020-03-02 18:38:15 +0000438func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
439 for _, memberListProperty := range s.memberListProperties() {
440 names := memberListProperty.getter(dynamicMemberTypeListProperties)
441 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000442 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000443 }
444 }
445}
446
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000447type propertyTag struct {
448 name string
449}
450
Paul Duffin0cb37b92020-03-04 14:52:46 +0000451// A BpPropertyTag to add to a property that contains references to other sdk members.
452//
453// This will cause the references to be rewritten to a versioned reference in the version
454// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000455var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000456var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000457
Paul Duffin0cb37b92020-03-04 14:52:46 +0000458// A BpPropertyTag that indicates the property should only be present in the versioned
459// module.
460//
461// This will cause the property to be removed from the unversioned instance of a
462// snapshot module.
463var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
464
Paul Duffine6c0d842020-01-15 14:08:51 +0000465type unversionedToVersionedTransformation struct {
466 identityTransformation
467 builder *snapshotBuilder
468}
469
Paul Duffine6c0d842020-01-15 14:08:51 +0000470func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
471 // Use a versioned name for the module but remember the original name for the
472 // snapshot.
473 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000474 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000475 module.insertAfter("name", "sdk_member_name", name)
476 return module
477}
478
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000479func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000480 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
481 required := tag == requiredSdkMemberReferencePropertyTag
482 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000483 } else {
484 return value, tag
485 }
486}
487
Paul Duffin72910952020-01-20 18:16:30 +0000488type unversionedTransformation struct {
489 identityTransformation
490 builder *snapshotBuilder
491}
492
493func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
494 // If the module is an internal member then use a unique name for it.
495 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000496 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000497
498 // Set prefer: false - this is not strictly required as that is the default.
499 module.insertAfter("name", "prefer", false)
500
501 return module
502}
503
504func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000505 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
506 required := tag == requiredSdkMemberReferencePropertyTag
507 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000508 } else if tag == sdkVersionedOnlyPropertyTag {
509 // The property is not allowed in the unversioned module so remove it.
510 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000511 } else {
512 return value, tag
513 }
514}
515
Paul Duffina78f3a72020-02-21 16:29:35 +0000516type pruneEmptySetTransformer struct {
517 identityTransformation
518}
519
520var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
521
522func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
523 if len(propertySet.properties) == 0 {
524 return nil, nil
525 } else {
526 return propertySet, tag
527 }
528}
529
Paul Duffinb645ec82019-11-27 17:43:54 +0000530func generateBpContents(contents *generatedContents, bpFile *bpFile) {
531 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
532 for _, bpModule := range bpFile.order {
533 contents.Printfln("")
534 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000535 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000536 contents.Printfln("}")
537 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000538}
539
540func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
541 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000542
543 // Output the properties first, followed by the nested sets. This ensures a
544 // consistent output irrespective of whether property sets are created before
545 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000546 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000547 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000548
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000549 switch v := value.(type) {
550 case []string:
551 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000552 if length > 1 {
553 contents.Printfln("%s: [", name)
554 contents.Indent()
555 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000556 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000557 }
558 contents.Dedent()
559 contents.Printfln("],")
560 } else if length == 0 {
561 contents.Printfln("%s: [],", name)
562 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000563 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000564 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000565
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000566 case bool:
567 contents.Printfln("%s: %t,", name, v)
568
569 case *bpPropertySet:
570 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000571
572 default:
573 contents.Printfln("%s: %q,", name, value)
574 }
575 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000576
577 for _, name := range set.order {
578 value := set.getValue(name)
579
580 // Only write property sets in the sets phase.
581 switch v := value.(type) {
582 case *bpPropertySet:
583 contents.Printfln("%s: {", name)
584 outputPropertySet(contents, v)
585 contents.Printfln("},")
586 }
587 }
588
Paul Duffinb645ec82019-11-27 17:43:54 +0000589 contents.Dedent()
590}
591
Paul Duffinac37c502019-11-26 18:02:20 +0000592func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000593 contents := &generatedContents{}
594 generateBpContents(contents, s.builderForTests.bpFile)
595 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000596}
597
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000598type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000599 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000600 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000601 version string
602 snapshotDir android.OutputPath
603 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000604
605 // Map from destination to source of each copy - used to eliminate duplicates and
606 // detect conflicts.
607 copies map[string]string
608
Paul Duffinb645ec82019-11-27 17:43:54 +0000609 filesToZip android.Paths
610 zipsToMerge android.Paths
611
612 prebuiltModules map[string]*bpModule
613 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000614
615 // The set of all members by name.
616 allMembersByName map[string]struct{}
617
618 // The set of exported members by name.
619 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000620}
621
622func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000623 if existing, ok := s.copies[dest]; ok {
624 if existing != src.String() {
625 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
626 return
627 }
628 } else {
629 path := s.snapshotDir.Join(s.ctx, dest)
630 s.ctx.Build(pctx, android.BuildParams{
631 Rule: android.Cp,
632 Input: src,
633 Output: path,
634 })
635 s.filesToZip = append(s.filesToZip, path)
636
637 s.copies[dest] = src.String()
638 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000639}
640
Paul Duffin91547182019-11-12 19:39:36 +0000641func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
642 ctx := s.ctx
643
644 // Repackage the zip file so that the entries are in the destDir directory.
645 // This will allow the zip file to be merged into the snapshot.
646 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000647
648 ctx.Build(pctx, android.BuildParams{
649 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
650 Rule: repackageZip,
651 Input: zipPath,
652 Output: tmpZipPath,
653 Args: map[string]string{
654 "destdir": destDir,
655 },
656 })
Paul Duffin91547182019-11-12 19:39:36 +0000657
658 // Add the repackaged zip file to the files to merge.
659 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
660}
661
Paul Duffin9d8d6092019-12-05 18:19:29 +0000662func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
663 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000664 if s.prebuiltModules[name] != nil {
665 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
666 }
667
668 m := s.bpFile.newModule(moduleType)
669 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000670
Paul Duffinbefa4b92020-03-04 14:22:45 +0000671 variant := member.Variants()[0]
672
Paul Duffin13f02712020-03-06 12:30:43 +0000673 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000674 // An internal member is only referenced from the sdk snapshot which is in the
675 // same package so can be marked as private.
676 m.AddProperty("visibility", []string{"//visibility:private"})
677 } else {
678 // Extract visibility information from a member variant. All variants have the same
679 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000680 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000681 if len(visibility) != 0 {
682 m.AddProperty("visibility", visibility)
683 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000684 }
685
Paul Duffin865171e2020-03-02 18:38:15 +0000686 deviceSupported := false
687 hostSupported := false
688
689 for _, variant := range member.Variants() {
690 osClass := variant.Target().Os.Class
691 if osClass == android.Host || osClass == android.HostCross {
692 hostSupported = true
693 } else if osClass == android.Device {
694 deviceSupported = true
695 }
696 }
697
698 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000699
Paul Duffinbefa4b92020-03-04 14:22:45 +0000700 // Where available copy apex_available properties from the member.
701 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
702 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000703
Colin Cross440e0d02020-06-11 11:32:11 -0700704 // Add in any baseline apex available settings.
705 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000706
Paul Duffinbefa4b92020-03-04 14:22:45 +0000707 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000708 // Remove duplicates and sort.
709 apexAvailable = android.FirstUniqueStrings(apexAvailable)
710 sort.Strings(apexAvailable)
711
Paul Duffinbefa4b92020-03-04 14:22:45 +0000712 m.AddProperty("apex_available", apexAvailable)
713 }
714 }
715
Paul Duffin0cb37b92020-03-04 14:52:46 +0000716 // Disable installation in the versioned module of those modules that are ever installable.
717 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
718 if installable.EverInstallable() {
719 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
720 }
721 }
722
Paul Duffinb645ec82019-11-27 17:43:54 +0000723 s.prebuiltModules[name] = m
724 s.prebuiltOrder = append(s.prebuiltOrder, m)
725 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000726}
727
Paul Duffin865171e2020-03-02 18:38:15 +0000728func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
729 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000730 bpModule.AddProperty("device_supported", false)
731 }
Paul Duffin865171e2020-03-02 18:38:15 +0000732 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000733 bpModule.AddProperty("host_supported", true)
734 }
735}
736
Paul Duffin13f02712020-03-06 12:30:43 +0000737func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
738 if required {
739 return requiredSdkMemberReferencePropertyTag
740 } else {
741 return optionalSdkMemberReferencePropertyTag
742 }
743}
744
745func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
746 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000747}
748
Paul Duffinb645ec82019-11-27 17:43:54 +0000749// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000750func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
751 if _, ok := s.allMembersByName[unversionedName]; !ok {
752 if required {
753 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
754 }
755 return unversionedName
756 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000757 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
758}
Paul Duffinb645ec82019-11-27 17:43:54 +0000759
Paul Duffin13f02712020-03-06 12:30:43 +0000760func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000761 var references []string = nil
762 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000763 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000764 }
765 return references
766}
Paul Duffin13879572019-11-28 14:31:38 +0000767
Paul Duffin72910952020-01-20 18:16:30 +0000768// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000769func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
770 if _, ok := s.allMembersByName[unversionedName]; !ok {
771 if required {
772 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
773 }
774 return unversionedName
775 }
776
777 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000778 return s.ctx.ModuleName() + "_" + unversionedName
779 } else {
780 return unversionedName
781 }
782}
783
Paul Duffin13f02712020-03-06 12:30:43 +0000784func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000785 var references []string = nil
786 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000787 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000788 }
789 return references
790}
791
Paul Duffin13f02712020-03-06 12:30:43 +0000792func (s *snapshotBuilder) isInternalMember(memberName string) bool {
793 _, ok := s.exportedMembersByName[memberName]
794 return !ok
795}
796
Paul Duffin1356d8c2020-02-25 19:26:33 +0000797type sdkMemberRef struct {
798 memberType android.SdkMemberType
799 variant android.SdkAware
800}
801
Paul Duffin13879572019-11-28 14:31:38 +0000802var _ android.SdkMember = (*sdkMember)(nil)
803
804type sdkMember struct {
805 memberType android.SdkMemberType
806 name string
807 variants []android.SdkAware
808}
809
810func (m *sdkMember) Name() string {
811 return m.name
812}
813
814func (m *sdkMember) Variants() []android.SdkAware {
815 return m.variants
816}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000817
Paul Duffin9c3760e2020-03-16 19:52:08 +0000818// Track usages of multilib variants.
819type multilibUsage int
820
821const (
822 multilibNone multilibUsage = 0
823 multilib32 multilibUsage = 1
824 multilib64 multilibUsage = 2
825 multilibBoth = multilib32 | multilib64
826)
827
828// Add the multilib that is used in the arch type.
829func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
830 multilib := archType.Multilib
831 switch multilib {
832 case "":
833 return m
834 case "lib32":
835 return m | multilib32
836 case "lib64":
837 return m | multilib64
838 default:
839 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
840 }
841}
842
843func (m multilibUsage) String() string {
844 switch m {
845 case multilibNone:
846 return ""
847 case multilib32:
848 return "32"
849 case multilib64:
850 return "64"
851 case multilibBoth:
852 return "both"
853 default:
854 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
855 m, multilibNone, multilib32, multilib64, multilibBoth))
856 }
857}
858
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000859type baseInfo struct {
860 Properties android.SdkMemberProperties
861}
862
Paul Duffinf34f6d82020-04-30 15:48:31 +0100863func (b *baseInfo) optimizableProperties() interface{} {
864 return b.Properties
865}
866
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000867type osTypeSpecificInfo struct {
868 baseInfo
869
Paul Duffin00e46802020-03-12 20:40:35 +0000870 osType android.OsType
871
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000872 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000873 //
874 // Nil if there is one variant whose arch type is common
875 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000876}
877
Paul Duffin4b8b7932020-05-06 12:35:38 +0100878var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
879
Paul Duffinfc8dd232020-03-17 12:51:37 +0000880type variantPropertiesFactoryFunc func() android.SdkMemberProperties
881
Paul Duffin00e46802020-03-12 20:40:35 +0000882// Create a new osTypeSpecificInfo for the specified os type and its properties
883// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000884func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000885 osInfo := &osTypeSpecificInfo{
886 osType: osType,
887 }
888
889 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
890 properties := variantPropertiesFactory()
891 properties.Base().Os = osType
892 return properties
893 }
894
895 // Create a structure into which properties common across the architectures in
896 // this os type will be stored.
897 osInfo.Properties = osSpecificVariantPropertiesFactory()
898
899 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000900 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000901 var archTypes []android.ArchType
902 for _, variant := range osTypeVariants {
903 archType := variant.Target().Arch.ArchType
904 archTypeName := archType.Name
905 if _, ok := variantsByArchName[archTypeName]; !ok {
906 archTypes = append(archTypes, archType)
907 }
908
909 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
910 }
911
912 if commonVariants, ok := variantsByArchName["common"]; ok {
913 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -0700914 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 +0000915 }
916
917 // A common arch type only has one variant and its properties should be treated
918 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000919 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000920 } else {
921 // Create an arch specific info for each supported architecture type.
922 for _, archType := range archTypes {
923 archTypeName := archType.Name
924
925 archVariants := variantsByArchName[archTypeName]
Paul Duffin3a4eb502020-03-19 16:11:18 +0000926 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000927
928 osInfo.archInfos = append(osInfo.archInfos, archInfo)
929 }
930 }
931
932 return osInfo
933}
934
935// Optimize the properties by extracting common properties from arch type specific
936// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100937func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +0000938 // Nothing to do if there is only a single common architecture.
939 if len(osInfo.archInfos) == 0 {
940 return
941 }
942
Paul Duffin9c3760e2020-03-16 19:52:08 +0000943 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000944 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000945 multilib = multilib.addArchType(archInfo.archType)
946
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000947 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100948 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +0000949 }
950
Paul Duffin4b8b7932020-05-06 12:35:38 +0100951 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +0000952
953 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000954 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000955}
956
957// Add the properties for an os to a property set.
958//
959// Maps the properties related to the os variants through to an appropriate
960// module structure that will produce equivalent set of variants when it is
961// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000962func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +0000963
964 var osPropertySet android.BpPropertySet
965 var archPropertySet android.BpPropertySet
966 var archOsPrefix string
967 if osInfo.Properties.Base().Os_count == 1 {
968 // There is only one os type present in the variants so don't bother
969 // with adding target specific properties.
970
971 // Create a structure that looks like:
972 // module_type {
973 // name: "...",
974 // ...
975 // <common properties>
976 // ...
977 // <single os type specific properties>
978 //
979 // arch: {
980 // <arch specific sections>
981 // }
982 //
983 osPropertySet = bpModule
984 archPropertySet = osPropertySet.AddPropertySet("arch")
985
986 // Arch specific properties need to be added to an arch specific section
987 // within arch.
988 archOsPrefix = ""
989 } else {
990 // Create a structure that looks like:
991 // module_type {
992 // name: "...",
993 // ...
994 // <common properties>
995 // ...
996 // target: {
997 // <arch independent os specific sections, e.g. android>
998 // ...
999 // <arch and os specific sections, e.g. android_x86>
1000 // }
1001 //
1002 osType := osInfo.osType
1003 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1004 archPropertySet = targetPropertySet
1005
1006 // Arch specific properties need to be added to an os and arch specific
1007 // section prefixed with <os>_.
1008 archOsPrefix = osType.Name + "_"
1009 }
1010
1011 // Add the os specific but arch independent properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001012 osInfo.Properties.AddToPropertySet(ctx, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001013
1014 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1015 // os) specific properties.
1016 //
1017 // The archInfos list will be empty if the os contains variants for the common
1018 // architecture.
1019 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001020 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001021 }
1022}
1023
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001024func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1025 osClass := osInfo.osType.Class
1026 return osClass == android.Host || osClass == android.HostCross
1027}
1028
1029var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1030
Paul Duffin4b8b7932020-05-06 12:35:38 +01001031func (osInfo *osTypeSpecificInfo) String() string {
1032 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1033}
1034
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001035type archTypeSpecificInfo struct {
1036 baseInfo
1037
1038 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001039
1040 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001041}
1042
Paul Duffin4b8b7932020-05-06 12:35:38 +01001043var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1044
Paul Duffinfc8dd232020-03-17 12:51:37 +00001045// Create a new archTypeSpecificInfo for the specified arch type and its properties
1046// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001047func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001048
Paul Duffinfc8dd232020-03-17 12:51:37 +00001049 // Create an arch specific info into which the variant properties can be copied.
1050 archInfo := &archTypeSpecificInfo{archType: archType}
1051
1052 // Create the properties into which the arch type specific properties will be
1053 // added.
1054 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001055
1056 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001057 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001058 } else {
1059 // There is more than one variant for this arch type which must be differentiated
1060 // by link type.
1061 for _, linkVariant := range archVariants {
1062 linkType := getLinkType(linkVariant)
1063 if linkType == "" {
1064 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1065 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001066 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001067
1068 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1069 }
1070 }
1071 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001072
1073 return archInfo
1074}
1075
Paul Duffinf34f6d82020-04-30 15:48:31 +01001076func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1077 return archInfo.Properties
1078}
1079
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001080// Get the link type of the variant
1081//
1082// If the variant is not differentiated by link type then it returns "",
1083// otherwise it returns one of "static" or "shared".
1084func getLinkType(variant android.Module) string {
1085 linkType := ""
1086 if linkable, ok := variant.(cc.LinkableInterface); ok {
1087 if linkable.Shared() && linkable.Static() {
1088 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1089 } else if linkable.Shared() {
1090 linkType = "shared"
1091 } else if linkable.Static() {
1092 linkType = "static"
1093 } else {
1094 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1095 }
1096 }
1097 return linkType
1098}
1099
1100// Optimize the properties by extracting common properties from link type specific
1101// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001102func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001103 if len(archInfo.linkInfos) == 0 {
1104 return
1105 }
1106
Paul Duffin4b8b7932020-05-06 12:35:38 +01001107 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001108}
1109
Paul Duffinfc8dd232020-03-17 12:51:37 +00001110// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001111func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001112 archTypeName := archInfo.archType.Name
1113 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001114 archInfo.Properties.AddToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001115
1116 for _, linkInfo := range archInfo.linkInfos {
1117 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001118 linkInfo.Properties.AddToPropertySet(ctx, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001119 }
1120}
1121
Paul Duffin4b8b7932020-05-06 12:35:38 +01001122func (archInfo *archTypeSpecificInfo) String() string {
1123 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1124}
1125
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001126type linkTypeSpecificInfo struct {
1127 baseInfo
1128
1129 linkType string
1130}
1131
Paul Duffin4b8b7932020-05-06 12:35:38 +01001132var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1133
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001134// Create a new linkTypeSpecificInfo for the specified link type and its properties
1135// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001136func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001137 linkInfo := &linkTypeSpecificInfo{
1138 baseInfo: baseInfo{
1139 // Create the properties into which the link type specific properties will be
1140 // added.
1141 Properties: variantPropertiesFactory(),
1142 },
1143 linkType: linkType,
1144 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001145 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001146 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001147}
1148
Paul Duffin4b8b7932020-05-06 12:35:38 +01001149func (l *linkTypeSpecificInfo) String() string {
1150 return fmt.Sprintf("LinkType{%s}", l.linkType)
1151}
1152
Paul Duffin3a4eb502020-03-19 16:11:18 +00001153type memberContext struct {
1154 sdkMemberContext android.ModuleContext
1155 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001156 memberType android.SdkMemberType
1157 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001158}
1159
1160func (m *memberContext) SdkModuleContext() android.ModuleContext {
1161 return m.sdkMemberContext
1162}
1163
1164func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1165 return m.builder
1166}
1167
Paul Duffina551a1c2020-03-17 21:04:24 +00001168func (m *memberContext) MemberType() android.SdkMemberType {
1169 return m.memberType
1170}
1171
1172func (m *memberContext) Name() string {
1173 return m.name
1174}
1175
Paul Duffin3a4eb502020-03-19 16:11:18 +00001176func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001177
1178 memberType := member.memberType
1179
Paul Duffina04c1072020-03-02 10:16:35 +00001180 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001181 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001182 variants := member.Variants()
1183 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001184 osType := variant.Target().Os
1185 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001186 }
1187
Paul Duffina04c1072020-03-02 10:16:35 +00001188 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001189 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001190 properties := memberType.CreateVariantPropertiesStruct()
1191 base := properties.Base()
1192 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001193 return properties
1194 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001195
Paul Duffina04c1072020-03-02 10:16:35 +00001196 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001197
Paul Duffina04c1072020-03-02 10:16:35 +00001198 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001199 commonProperties := variantPropertiesFactory()
1200 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001201
Paul Duffinc097e362020-03-10 22:50:03 +00001202 // Create common value extractor that can be used to optimize the properties.
1203 commonValueExtractor := newCommonValueExtractor(commonProperties)
1204
Paul Duffina04c1072020-03-02 10:16:35 +00001205 // The list of property structures which are os type specific but common across
1206 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001207 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001208
1209 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001210 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001211 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001212 // Add the os specific properties to a list of os type specific yet architecture
1213 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001214 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001215
Paul Duffin00e46802020-03-12 20:40:35 +00001216 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001217 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001218 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001219
Paul Duffina04c1072020-03-02 10:16:35 +00001220 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001221 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001222
Paul Duffina04c1072020-03-02 10:16:35 +00001223 // Add the common properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001224 commonProperties.AddToPropertySet(ctx, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001225
Paul Duffina04c1072020-03-02 10:16:35 +00001226 // Create a target property set into which target specific properties can be
1227 // added.
1228 targetPropertySet := bpModule.AddPropertySet("target")
1229
1230 // Iterate over the os types in a fixed order.
1231 for _, osType := range s.getPossibleOsTypes() {
1232 osInfo := osTypeToInfo[osType]
1233 if osInfo == nil {
1234 continue
1235 }
1236
Paul Duffin3a4eb502020-03-19 16:11:18 +00001237 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001238 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001239}
1240
Paul Duffina04c1072020-03-02 10:16:35 +00001241// Compute the list of possible os types that this sdk could support.
1242func (s *sdk) getPossibleOsTypes() []android.OsType {
1243 var osTypes []android.OsType
1244 for _, osType := range android.OsTypeList {
1245 if s.DeviceSupported() {
1246 if osType.Class == android.Device && osType != android.Fuchsia {
1247 osTypes = append(osTypes, osType)
1248 }
1249 }
1250 if s.HostSupported() {
1251 if osType.Class == android.Host || osType.Class == android.HostCross {
1252 osTypes = append(osTypes, osType)
1253 }
1254 }
1255 }
1256 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1257 return osTypes
1258}
1259
Paul Duffinb28369a2020-05-04 15:39:59 +01001260// Given a set of properties (struct value), return the value of the field within that
1261// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001262type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1263
Paul Duffinc459f892020-04-30 18:08:29 +01001264// Checks the metadata to determine whether the property should be ignored for the
1265// purposes of common value extraction or not.
1266type extractorMetadataPredicate func(metadata propertiesContainer) bool
1267
1268// Indicates whether optimizable properties are provided by a host variant or
1269// not.
1270type isHostVariant interface {
1271 isHostVariant() bool
1272}
1273
Paul Duffinb28369a2020-05-04 15:39:59 +01001274// A property that can be optimized by the commonValueExtractor.
1275type extractorProperty struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001276 // The name of the field for this property.
1277 name string
1278
Paul Duffinc459f892020-04-30 18:08:29 +01001279 // Filter that can use metadata associated with the properties being optimized
1280 // to determine whether the field should be ignored during common value
1281 // optimization.
1282 filter extractorMetadataPredicate
1283
Paul Duffinb28369a2020-05-04 15:39:59 +01001284 // Retrieves the value on which common value optimization will be performed.
1285 getter fieldAccessorFunc
1286
1287 // The empty value for the field.
1288 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001289
1290 // True if the property can support arch variants false otherwise.
1291 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001292}
1293
Paul Duffin4b8b7932020-05-06 12:35:38 +01001294func (p extractorProperty) String() string {
1295 return p.name
1296}
1297
Paul Duffinc097e362020-03-10 22:50:03 +00001298// Supports extracting common values from a number of instances of a properties
1299// structure into a separate common set of properties.
1300type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001301 // The properties that the extractor can optimize.
1302 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001303}
1304
1305// Create a new common value extractor for the structure type for the supplied
1306// properties struct.
1307//
1308// The returned extractor can be used on any properties structure of the same type
1309// as the supplied set of properties.
1310func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1311 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1312 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001313 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001314 return extractor
1315}
1316
1317// Gather the fields from the supplied structure type from which common values will
1318// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001319//
1320// This is recursive function. If it encounters an embedded field (no field name)
1321// that is a struct then it will recurse into that struct passing in the accessor
1322// for the field. That will then be used in the accessors for the fields in the
1323// embedded struct.
1324func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001325 for f := 0; f < structType.NumField(); f++ {
1326 field := structType.Field(f)
1327 if field.PkgPath != "" {
1328 // Ignore unexported fields.
1329 continue
1330 }
1331
Paul Duffinb07fa512020-03-10 22:17:04 +00001332 // Ignore fields whose value should be kept.
1333 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001334 continue
1335 }
1336
Paul Duffinc459f892020-04-30 18:08:29 +01001337 var filter extractorMetadataPredicate
1338
1339 // Add a filter
1340 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1341 filter = func(metadata propertiesContainer) bool {
1342 if m, ok := metadata.(isHostVariant); ok {
1343 if m.isHostVariant() {
1344 return false
1345 }
1346 }
1347 return true
1348 }
1349 }
1350
Paul Duffinc097e362020-03-10 22:50:03 +00001351 // Save a copy of the field index for use in the function.
1352 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001353
1354 name := field.Name
1355
Paul Duffinc097e362020-03-10 22:50:03 +00001356 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001357 if containingStructAccessor != nil {
1358 // This is an embedded structure so first access the field for the embedded
1359 // structure.
1360 value = containingStructAccessor(value)
1361 }
1362
Paul Duffinc097e362020-03-10 22:50:03 +00001363 // Skip through interface and pointer values to find the structure.
1364 value = getStructValue(value)
1365
Paul Duffin4b8b7932020-05-06 12:35:38 +01001366 defer func() {
1367 if r := recover(); r != nil {
1368 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1369 }
1370 }()
1371
Paul Duffinc097e362020-03-10 22:50:03 +00001372 // Return the field.
1373 return value.Field(fieldIndex)
1374 }
1375
Paul Duffinb07fa512020-03-10 22:17:04 +00001376 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1377 // Gather fields from the embedded structure.
1378 e.gatherFields(field.Type, fieldGetter)
1379 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001380 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001381 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001382 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001383 fieldGetter,
1384 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001385 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001386 }
1387 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001388 }
Paul Duffinc097e362020-03-10 22:50:03 +00001389 }
1390}
1391
1392func getStructValue(value reflect.Value) reflect.Value {
1393foundStruct:
1394 for {
1395 kind := value.Kind()
1396 switch kind {
1397 case reflect.Interface, reflect.Ptr:
1398 value = value.Elem()
1399 case reflect.Struct:
1400 break foundStruct
1401 default:
1402 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1403 }
1404 }
1405 return value
1406}
1407
Paul Duffinf34f6d82020-04-30 15:48:31 +01001408// A container of properties to be optimized.
1409//
1410// Allows additional information to be associated with the properties, e.g. for
1411// filtering.
1412type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001413 fmt.Stringer
1414
Paul Duffinf34f6d82020-04-30 15:48:31 +01001415 // Get the properties that need optimizing.
1416 optimizableProperties() interface{}
1417}
1418
1419// A wrapper for dynamic member properties to allow them to be optimized.
1420type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001421 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001422 dynamicMemberProperties interface{}
1423}
1424
1425func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1426 return c.dynamicMemberProperties
1427}
1428
Paul Duffin4b8b7932020-05-06 12:35:38 +01001429func (c dynamicMemberPropertiesContainer) String() string {
1430 return c.sdkVariant.String()
1431}
1432
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001433// Extract common properties from a slice of property structures of the same type.
1434//
1435// All the property structures must be of the same type.
1436// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001437// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001438//
1439// Iterates over each exported field (capitalized name) and checks to see whether they
1440// have the same value (using DeepEquals) across all the input properties. If it does not then no
1441// change is made. Otherwise, the common value is stored in the field in the commonProperties
1442// and the field in each of the input properties structure is set to its default value.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001443func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001444 commonPropertiesValue := reflect.ValueOf(commonProperties)
1445 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001446
Paul Duffinf34f6d82020-04-30 15:48:31 +01001447 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1448
Paul Duffinb28369a2020-05-04 15:39:59 +01001449 for _, property := range e.properties {
1450 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001451 filter := property.filter
1452 if filter == nil {
1453 filter = func(metadata propertiesContainer) bool {
1454 return true
1455 }
1456 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001457
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001458 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001459 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1460 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001461 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001462
Paul Duffin864e1b42020-05-06 10:23:19 +01001463 // Assume that all the values will be the same.
1464 //
1465 // While similar to this is not quite the same as commonValue == nil. If all the values
1466 // have been filtered out then this will be false but commonValue == nil will be true.
1467 valuesDiffer := false
1468
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001469 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001470 container := sliceValue.Index(i).Interface().(propertiesContainer)
1471 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001472 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001473
Paul Duffinc459f892020-04-30 18:08:29 +01001474 if !filter(container) {
1475 expectedValue := property.emptyValue.Interface()
1476 actualValue := fieldValue.Interface()
1477 if !reflect.DeepEqual(expectedValue, actualValue) {
1478 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1479 }
1480 continue
1481 }
1482
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001483 if commonValue == nil {
1484 // Use the first value as the commonProperties value.
1485 commonValue = &fieldValue
1486 } else {
1487 // If the value does not match the current common value then there is
1488 // no value in common so break out.
1489 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1490 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001491 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001492 break
1493 }
1494 }
1495 }
1496
Paul Duffin864e1b42020-05-06 10:23:19 +01001497 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001498 // and set the input struct's field to the empty value.
1499 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001500 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001501 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001502 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001503 container := sliceValue.Index(i).Interface().(propertiesContainer)
1504 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001505 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001506 fieldValue.Set(emptyValue)
1507 }
1508 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001509
1510 if valuesDiffer && !property.archVariant {
1511 // The values differ but the property does not support arch variants so it
1512 // is an error.
1513 var details strings.Builder
1514 for i := 0; i < sliceValue.Len(); i++ {
1515 container := sliceValue.Index(i).Interface().(propertiesContainer)
1516 itemValue := reflect.ValueOf(container.optimizableProperties())
1517 fieldValue := fieldGetter(itemValue)
1518
1519 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1520 }
1521
1522 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1523 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001524 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001525
1526 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001527}