blob: 476a4a5ea2c65770ff8069d7d91e46c907ad3a95 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
31var pctx = android.NewPackageContext("android/soong/sdk")
32
Paul Duffin375058f2019-11-29 20:17:53 +000033var (
34 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
35 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000036 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000037 CommandDeps: []string{
38 "${config.Zip2ZipCmd}",
39 },
40 },
41 "destdir")
42
43 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
44 blueprint.RuleParams{
45 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
46 CommandDeps: []string{
47 "${config.SoongZipCmd}",
48 },
49 Rspfile: "$out.rsp",
50 RspfileContent: "$in",
51 },
52 "basedir")
53
54 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
55 blueprint.RuleParams{
56 Command: `${config.MergeZipsCmd} $out $in`,
57 CommandDeps: []string{
58 "${config.MergeZipsCmd}",
59 },
60 })
61)
62
Paul Duffinb645ec82019-11-27 17:43:54 +000063type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090064 content strings.Builder
65 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090066}
67
Paul Duffinb645ec82019-11-27 17:43:54 +000068// generatedFile abstracts operations for writing contents into a file and emit a build rule
69// for the file.
70type generatedFile struct {
71 generatedContents
72 path android.OutputPath
73}
74
Jiyong Park232e7852019-11-04 12:23:40 +090075func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090076 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000077 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090078 }
79}
80
Paul Duffinb645ec82019-11-27 17:43:54 +000081func (gc *generatedContents) Indent() {
82 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090083}
84
Paul Duffinb645ec82019-11-27 17:43:54 +000085func (gc *generatedContents) Dedent() {
86 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090087}
88
Paul Duffinb645ec82019-11-27 17:43:54 +000089func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +010090 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090091}
92
93func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
94 rb := android.NewRuleBuilder()
Paul Duffin11108272020-05-11 22:59:25 +010095
96 content := gf.content.String()
97
98 // ninja consumes newline characters in rspfile_content. Prevent it by
99 // escaping the backslash in the newline character. The extra backslash
100 // is removed when the rspfile is written to the actual script file
101 content = strings.ReplaceAll(content, "\n", "\\n")
102
Jiyong Park9b409bc2019-10-11 14:59:13 +0900103 rb.Command().
104 Implicits(implicits).
Paul Duffin11108272020-05-11 22:59:25 +0100105 Text("echo").Text(proptools.ShellEscape(content)).
106 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900107 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
108 rb.Command().
109 Text("chmod a+x").Output(gf.path)
110 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
111}
112
Paul Duffin13879572019-11-28 14:31:38 +0000113// Collect all the members.
114//
Paul Duffin6a7e9532020-03-20 17:50:07 +0000115// Returns a list containing type (extracted from the dependency tag) and the variant
116// plus the multilib usages.
117func (s *sdk) collectMembers(ctx android.ModuleContext) {
118 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000119 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
120 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000121 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
122 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900123
Paul Duffin13879572019-11-28 14:31:38 +0000124 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000125 if !memberType.IsInstance(child) {
126 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900127 }
Paul Duffin13879572019-11-28 14:31:38 +0000128
Paul Duffin6a7e9532020-03-20 17:50:07 +0000129 // Keep track of which multilib variants are used by the sdk.
130 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
131
132 s.memberRefs = append(s.memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000133
134 // If the member type supports transitive sdk members then recurse down into
135 // its dependencies, otherwise exit traversal.
136 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900137 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000138
139 return false
Paul Duffin13879572019-11-28 14:31:38 +0000140 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000141}
142
143// Organize the members.
144//
145// The members are first grouped by type and then grouped by name. The order of
146// the types is the order they are referenced in android.SdkMemberTypesRegistry.
147// The names are in the order in which the dependencies were added.
148//
149// Returns the members as well as the multilib setting to use.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000150func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000151 byType := make(map[android.SdkMemberType][]*sdkMember)
152 byName := make(map[string]*sdkMember)
153
Paul Duffin1356d8c2020-02-25 19:26:33 +0000154 for _, memberRef := range memberRefs {
155 memberType := memberRef.memberType
156 variant := memberRef.variant
157
158 name := ctx.OtherModuleName(variant)
159 member := byName[name]
160 if member == nil {
161 member = &sdkMember{memberType: memberType, name: name}
162 byName[name] = member
163 byType[memberType] = append(byType[memberType], member)
164 }
165
Paul Duffin1356d8c2020-02-25 19:26:33 +0000166 // Only append new variants to the list. This is needed because a member can be both
167 // exported by the sdk and also be a transitive sdk member.
168 member.variants = appendUniqueVariants(member.variants, variant)
169 }
170
Paul Duffin13879572019-11-28 14:31:38 +0000171 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000172 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000173 membersOfType := byType[memberListProperty.memberType]
174 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900175 }
176
Paul Duffin6a7e9532020-03-20 17:50:07 +0000177 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900178}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900179
Paul Duffin72910952020-01-20 18:16:30 +0000180func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
181 for _, v := range variants {
182 if v == newVariant {
183 return variants
184 }
185 }
186 return append(variants, newVariant)
187}
188
Jiyong Park73c54ee2019-10-22 20:31:18 +0900189// SDK directory structure
190// <sdk_root>/
191// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
192// <api_ver>/ : below this directory are all auto-generated
193// Android.bp : definition of 'sdk_snapshot' module is here
194// aidl/
195// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
196// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900197// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900198// include/
199// bionic/libc/include/stdlib.h : an exported header file
200// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900201// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900202// <arch>/include/ : arch-specific exported headers
203// <arch>/include_gen/ : arch-specific generated headers
204// <arch>/lib/
205// libFoo.so : a stub library
206
Jiyong Park232e7852019-11-04 12:23:40 +0900207// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900208// This isn't visible to users, so could be changed in future.
209func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
210 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
211}
212
Jiyong Park232e7852019-11-04 12:23:40 +0900213// buildSnapshot is the main function in this source file. It creates rules to copy
214// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000215func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
216
Paul Duffin13f02712020-03-06 12:30:43 +0000217 allMembersByName := make(map[string]struct{})
218 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000219 var memberRefs []sdkMemberRef
220 for _, sdkVariant := range sdkVariants {
221 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000222
Paul Duffin13f02712020-03-06 12:30:43 +0000223 // Record the names of all the members, both explicitly specified and implicitly
224 // included.
225 for _, memberRef := range sdkVariant.memberRefs {
226 allMembersByName[memberRef.variant.Name()] = struct{}{}
227 }
228
Paul Duffin865171e2020-03-02 18:38:15 +0000229 // Merge the exported member sets from all sdk variants.
230 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000231 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000232 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000233 }
234
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000235 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900236
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000237 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000238
239 bpFile := &bpFile{
240 modules: make(map[string]*bpModule),
241 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000242
243 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000244 ctx: ctx,
245 sdk: s,
246 version: "current",
247 snapshotDir: snapshotDir.OutputPath,
248 copies: make(map[string]string),
249 filesToZip: []android.Path{bp.path},
250 bpFile: bpFile,
251 prebuiltModules: make(map[string]*bpModule),
252 allMembersByName: allMembersByName,
253 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900254 }
Paul Duffinac37c502019-11-26 18:02:20 +0000255 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900256
Paul Duffin6a7e9532020-03-20 17:50:07 +0000257 members := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000258 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000259 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000260
Paul Duffina551a1c2020-03-17 21:04:24 +0000261 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000262
263 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Paul Duffin495ffb92020-03-20 13:35:40 +0000264 s.createMemberSnapshot(memberCtx, member, prebuiltModule)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900265 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900266
Paul Duffine6c0d842020-01-15 14:08:51 +0000267 // Create a transformer that will transform an unversioned module into a versioned module.
268 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
269
Paul Duffin72910952020-01-20 18:16:30 +0000270 // Create a transformer that will transform an unversioned module by replacing any references
271 // to internal members with a unique module name and setting prefer: false.
272 unversionedTransformer := unversionedTransformation{builder: builder}
273
Paul Duffinb645ec82019-11-27 17:43:54 +0000274 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000275 // Prune any empty property sets.
276 unversioned = unversioned.transform(pruneEmptySetTransformer{})
277
Paul Duffinb645ec82019-11-27 17:43:54 +0000278 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000279 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000280
281 // Transform the unversioned module into a versioned one.
282 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000283 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000284
Paul Duffin72910952020-01-20 18:16:30 +0000285 // Transform the unversioned module to make it suitable for use in the snapshot.
286 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000287 bpFile.AddModule(unversioned)
288 }
289
290 // Create the snapshot module.
291 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000292 var snapshotModuleType string
293 if s.properties.Module_exports {
294 snapshotModuleType = "module_exports_snapshot"
295 } else {
296 snapshotModuleType = "sdk_snapshot"
297 }
298 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000299 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000300
301 // Make sure that the snapshot has the same visibility as the sdk.
302 visibility := android.EffectiveVisibilityRules(ctx, s)
303 if len(visibility) != 0 {
304 snapshotModule.AddProperty("visibility", visibility)
305 }
306
Paul Duffin865171e2020-03-02 18:38:15 +0000307 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000308
Paul Duffinf34f6d82020-04-30 15:48:31 +0100309 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffin865171e2020-03-02 18:38:15 +0000310 osTypeToMemberProperties := make(map[android.OsType]*sdk)
311 for _, sdkVariant := range sdkVariants {
312 properties := sdkVariant.dynamicMemberTypeListProperties
313 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffin4b8b7932020-05-06 12:35:38 +0100314 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000315 }
316
317 // Extract the common lists of members into a separate struct.
318 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000319 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin4b8b7932020-05-06 12:35:38 +0100320 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000321
322 // Add properties common to all os types.
323 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
324
325 // Iterate over the os types in a fixed order.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000326 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin865171e2020-03-02 18:38:15 +0000327 for _, osType := range s.getPossibleOsTypes() {
328 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
329 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000330
331 // Compile_multilib defaults to both and must always be set to both on the
332 // device and so only needs to be set when targeted at the host and is neither
333 // unspecified or both.
334 multilib := sdkVariant.multilibUsages
335 if (osType.Class == android.Host || osType.Class == android.HostCross) &&
336 multilib != multilibNone && multilib != multilibBoth {
337 osPropertySet.AddProperty("compile_multilib", multilib.String())
338 }
339
Paul Duffin865171e2020-03-02 18:38:15 +0000340 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000341 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000342 }
Paul Duffin865171e2020-03-02 18:38:15 +0000343
344 // Prune any empty property sets.
345 snapshotModule.transform(pruneEmptySetTransformer{})
346
Paul Duffinb645ec82019-11-27 17:43:54 +0000347 bpFile.AddModule(snapshotModule)
348
349 // generate Android.bp
350 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
351 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000352
353 bp.build(pctx, ctx, nil)
354
355 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900356
Jiyong Park232e7852019-11-04 12:23:40 +0900357 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000358 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000359 outputDesc := "Building snapshot for " + ctx.ModuleName()
360
361 // If there are no zips to merge then generate the output zip directly.
362 // Otherwise, generate an intermediate zip file into which other zips can be
363 // merged.
364 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000365 var desc string
366 if len(builder.zipsToMerge) == 0 {
367 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000368 desc = outputDesc
369 } else {
370 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000371 desc = "Building intermediate snapshot for " + ctx.ModuleName()
372 }
373
Paul Duffin375058f2019-11-29 20:17:53 +0000374 ctx.Build(pctx, android.BuildParams{
375 Description: desc,
376 Rule: zipFiles,
377 Inputs: filesToZip,
378 Output: zipFile,
379 Args: map[string]string{
380 "basedir": builder.snapshotDir.String(),
381 },
382 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900383
Paul Duffin91547182019-11-12 19:39:36 +0000384 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000385 ctx.Build(pctx, android.BuildParams{
386 Description: outputDesc,
387 Rule: mergeZips,
388 Input: zipFile,
389 Inputs: builder.zipsToMerge,
390 Output: outputZipFile,
391 })
Paul Duffin91547182019-11-12 19:39:36 +0000392 }
393
394 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900395}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000396
Paul Duffin4b8b7932020-05-06 12:35:38 +0100397func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
398 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
399 if err != nil {
400 ctx.ModuleErrorf("error extracting common properties: %s", err)
401 }
402}
403
Paul Duffin865171e2020-03-02 18:38:15 +0000404func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
405 for _, memberListProperty := range s.memberListProperties() {
406 names := memberListProperty.getter(dynamicMemberTypeListProperties)
407 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000408 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000409 }
410 }
411}
412
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000413type propertyTag struct {
414 name string
415}
416
Paul Duffin0cb37b92020-03-04 14:52:46 +0000417// A BpPropertyTag to add to a property that contains references to other sdk members.
418//
419// This will cause the references to be rewritten to a versioned reference in the version
420// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000421var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000422var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000423
Paul Duffin0cb37b92020-03-04 14:52:46 +0000424// A BpPropertyTag that indicates the property should only be present in the versioned
425// module.
426//
427// This will cause the property to be removed from the unversioned instance of a
428// snapshot module.
429var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
430
Paul Duffine6c0d842020-01-15 14:08:51 +0000431type unversionedToVersionedTransformation struct {
432 identityTransformation
433 builder *snapshotBuilder
434}
435
Paul Duffine6c0d842020-01-15 14:08:51 +0000436func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
437 // Use a versioned name for the module but remember the original name for the
438 // snapshot.
439 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000440 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000441 module.insertAfter("name", "sdk_member_name", name)
442 return module
443}
444
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000445func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000446 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
447 required := tag == requiredSdkMemberReferencePropertyTag
448 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000449 } else {
450 return value, tag
451 }
452}
453
Paul Duffin72910952020-01-20 18:16:30 +0000454type unversionedTransformation struct {
455 identityTransformation
456 builder *snapshotBuilder
457}
458
459func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
460 // If the module is an internal member then use a unique name for it.
461 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000462 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000463
464 // Set prefer: false - this is not strictly required as that is the default.
465 module.insertAfter("name", "prefer", false)
466
467 return module
468}
469
470func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000471 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
472 required := tag == requiredSdkMemberReferencePropertyTag
473 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000474 } else if tag == sdkVersionedOnlyPropertyTag {
475 // The property is not allowed in the unversioned module so remove it.
476 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000477 } else {
478 return value, tag
479 }
480}
481
Paul Duffina78f3a72020-02-21 16:29:35 +0000482type pruneEmptySetTransformer struct {
483 identityTransformation
484}
485
486var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
487
488func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
489 if len(propertySet.properties) == 0 {
490 return nil, nil
491 } else {
492 return propertySet, tag
493 }
494}
495
Paul Duffinb645ec82019-11-27 17:43:54 +0000496func generateBpContents(contents *generatedContents, bpFile *bpFile) {
497 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
498 for _, bpModule := range bpFile.order {
499 contents.Printfln("")
500 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000501 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000502 contents.Printfln("}")
503 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000504}
505
506func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
507 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000508
509 // Output the properties first, followed by the nested sets. This ensures a
510 // consistent output irrespective of whether property sets are created before
511 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000512 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000513 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000514
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000515 switch v := value.(type) {
516 case []string:
517 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000518 if length > 1 {
519 contents.Printfln("%s: [", name)
520 contents.Indent()
521 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000522 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000523 }
524 contents.Dedent()
525 contents.Printfln("],")
526 } else if length == 0 {
527 contents.Printfln("%s: [],", name)
528 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000529 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000530 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000531
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000532 case bool:
533 contents.Printfln("%s: %t,", name, v)
534
535 case *bpPropertySet:
536 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000537
538 default:
539 contents.Printfln("%s: %q,", name, value)
540 }
541 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000542
543 for _, name := range set.order {
544 value := set.getValue(name)
545
546 // Only write property sets in the sets phase.
547 switch v := value.(type) {
548 case *bpPropertySet:
549 contents.Printfln("%s: {", name)
550 outputPropertySet(contents, v)
551 contents.Printfln("},")
552 }
553 }
554
Paul Duffinb645ec82019-11-27 17:43:54 +0000555 contents.Dedent()
556}
557
Paul Duffinac37c502019-11-26 18:02:20 +0000558func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000559 contents := &generatedContents{}
560 generateBpContents(contents, s.builderForTests.bpFile)
561 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000562}
563
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000564type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000565 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000566 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000567 version string
568 snapshotDir android.OutputPath
569 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000570
571 // Map from destination to source of each copy - used to eliminate duplicates and
572 // detect conflicts.
573 copies map[string]string
574
Paul Duffinb645ec82019-11-27 17:43:54 +0000575 filesToZip android.Paths
576 zipsToMerge android.Paths
577
578 prebuiltModules map[string]*bpModule
579 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000580
581 // The set of all members by name.
582 allMembersByName map[string]struct{}
583
584 // The set of exported members by name.
585 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000586}
587
588func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000589 if existing, ok := s.copies[dest]; ok {
590 if existing != src.String() {
591 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
592 return
593 }
594 } else {
595 path := s.snapshotDir.Join(s.ctx, dest)
596 s.ctx.Build(pctx, android.BuildParams{
597 Rule: android.Cp,
598 Input: src,
599 Output: path,
600 })
601 s.filesToZip = append(s.filesToZip, path)
602
603 s.copies[dest] = src.String()
604 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000605}
606
Paul Duffin91547182019-11-12 19:39:36 +0000607func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
608 ctx := s.ctx
609
610 // Repackage the zip file so that the entries are in the destDir directory.
611 // This will allow the zip file to be merged into the snapshot.
612 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000613
614 ctx.Build(pctx, android.BuildParams{
615 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
616 Rule: repackageZip,
617 Input: zipPath,
618 Output: tmpZipPath,
619 Args: map[string]string{
620 "destdir": destDir,
621 },
622 })
Paul Duffin91547182019-11-12 19:39:36 +0000623
624 // Add the repackaged zip file to the files to merge.
625 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
626}
627
Paul Duffin9d8d6092019-12-05 18:19:29 +0000628func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
629 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000630 if s.prebuiltModules[name] != nil {
631 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
632 }
633
634 m := s.bpFile.newModule(moduleType)
635 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000636
Paul Duffinbefa4b92020-03-04 14:22:45 +0000637 variant := member.Variants()[0]
638
Paul Duffin13f02712020-03-06 12:30:43 +0000639 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000640 // An internal member is only referenced from the sdk snapshot which is in the
641 // same package so can be marked as private.
642 m.AddProperty("visibility", []string{"//visibility:private"})
643 } else {
644 // Extract visibility information from a member variant. All variants have the same
645 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000646 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000647 if len(visibility) != 0 {
648 m.AddProperty("visibility", visibility)
649 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000650 }
651
Paul Duffin865171e2020-03-02 18:38:15 +0000652 deviceSupported := false
653 hostSupported := false
654
655 for _, variant := range member.Variants() {
656 osClass := variant.Target().Os.Class
657 if osClass == android.Host || osClass == android.HostCross {
658 hostSupported = true
659 } else if osClass == android.Device {
660 deviceSupported = true
661 }
662 }
663
664 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000665
Paul Duffinbefa4b92020-03-04 14:22:45 +0000666 // Where available copy apex_available properties from the member.
667 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
668 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000669
670 // Add in any white listed apex available settings.
671 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
672
Paul Duffinbefa4b92020-03-04 14:22:45 +0000673 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000674 // Remove duplicates and sort.
675 apexAvailable = android.FirstUniqueStrings(apexAvailable)
676 sort.Strings(apexAvailable)
677
Paul Duffinbefa4b92020-03-04 14:22:45 +0000678 m.AddProperty("apex_available", apexAvailable)
679 }
680 }
681
Paul Duffin0cb37b92020-03-04 14:52:46 +0000682 // Disable installation in the versioned module of those modules that are ever installable.
683 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
684 if installable.EverInstallable() {
685 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
686 }
687 }
688
Paul Duffinb645ec82019-11-27 17:43:54 +0000689 s.prebuiltModules[name] = m
690 s.prebuiltOrder = append(s.prebuiltOrder, m)
691 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000692}
693
Paul Duffin865171e2020-03-02 18:38:15 +0000694func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
695 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000696 bpModule.AddProperty("device_supported", false)
697 }
Paul Duffin865171e2020-03-02 18:38:15 +0000698 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000699 bpModule.AddProperty("host_supported", true)
700 }
701}
702
Paul Duffin13f02712020-03-06 12:30:43 +0000703func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
704 if required {
705 return requiredSdkMemberReferencePropertyTag
706 } else {
707 return optionalSdkMemberReferencePropertyTag
708 }
709}
710
711func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
712 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000713}
714
Paul Duffinb645ec82019-11-27 17:43:54 +0000715// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000716func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
717 if _, ok := s.allMembersByName[unversionedName]; !ok {
718 if required {
719 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
720 }
721 return unversionedName
722 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000723 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
724}
Paul Duffinb645ec82019-11-27 17:43:54 +0000725
Paul Duffin13f02712020-03-06 12:30:43 +0000726func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000727 var references []string = nil
728 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000729 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000730 }
731 return references
732}
Paul Duffin13879572019-11-28 14:31:38 +0000733
Paul Duffin72910952020-01-20 18:16:30 +0000734// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000735func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
736 if _, ok := s.allMembersByName[unversionedName]; !ok {
737 if required {
738 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
739 }
740 return unversionedName
741 }
742
743 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000744 return s.ctx.ModuleName() + "_" + unversionedName
745 } else {
746 return unversionedName
747 }
748}
749
Paul Duffin13f02712020-03-06 12:30:43 +0000750func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000751 var references []string = nil
752 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000753 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000754 }
755 return references
756}
757
Paul Duffin13f02712020-03-06 12:30:43 +0000758func (s *snapshotBuilder) isInternalMember(memberName string) bool {
759 _, ok := s.exportedMembersByName[memberName]
760 return !ok
761}
762
Paul Duffin1356d8c2020-02-25 19:26:33 +0000763type sdkMemberRef struct {
764 memberType android.SdkMemberType
765 variant android.SdkAware
766}
767
Paul Duffin13879572019-11-28 14:31:38 +0000768var _ android.SdkMember = (*sdkMember)(nil)
769
770type sdkMember struct {
771 memberType android.SdkMemberType
772 name string
773 variants []android.SdkAware
774}
775
776func (m *sdkMember) Name() string {
777 return m.name
778}
779
780func (m *sdkMember) Variants() []android.SdkAware {
781 return m.variants
782}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000783
Paul Duffin9c3760e2020-03-16 19:52:08 +0000784// Track usages of multilib variants.
785type multilibUsage int
786
787const (
788 multilibNone multilibUsage = 0
789 multilib32 multilibUsage = 1
790 multilib64 multilibUsage = 2
791 multilibBoth = multilib32 | multilib64
792)
793
794// Add the multilib that is used in the arch type.
795func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
796 multilib := archType.Multilib
797 switch multilib {
798 case "":
799 return m
800 case "lib32":
801 return m | multilib32
802 case "lib64":
803 return m | multilib64
804 default:
805 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
806 }
807}
808
809func (m multilibUsage) String() string {
810 switch m {
811 case multilibNone:
812 return ""
813 case multilib32:
814 return "32"
815 case multilib64:
816 return "64"
817 case multilibBoth:
818 return "both"
819 default:
820 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
821 m, multilibNone, multilib32, multilib64, multilibBoth))
822 }
823}
824
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000825type baseInfo struct {
826 Properties android.SdkMemberProperties
827}
828
Paul Duffinf34f6d82020-04-30 15:48:31 +0100829func (b *baseInfo) optimizableProperties() interface{} {
830 return b.Properties
831}
832
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000833type osTypeSpecificInfo struct {
834 baseInfo
835
Paul Duffin00e46802020-03-12 20:40:35 +0000836 osType android.OsType
837
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000838 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000839 //
840 // Nil if there is one variant whose arch type is common
841 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000842}
843
Paul Duffin4b8b7932020-05-06 12:35:38 +0100844var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
845
Paul Duffinfc8dd232020-03-17 12:51:37 +0000846type variantPropertiesFactoryFunc func() android.SdkMemberProperties
847
Paul Duffin00e46802020-03-12 20:40:35 +0000848// Create a new osTypeSpecificInfo for the specified os type and its properties
849// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000850func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000851 osInfo := &osTypeSpecificInfo{
852 osType: osType,
853 }
854
855 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
856 properties := variantPropertiesFactory()
857 properties.Base().Os = osType
858 return properties
859 }
860
861 // Create a structure into which properties common across the architectures in
862 // this os type will be stored.
863 osInfo.Properties = osSpecificVariantPropertiesFactory()
864
865 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000866 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000867 var archTypes []android.ArchType
868 for _, variant := range osTypeVariants {
869 archType := variant.Target().Arch.ArchType
870 archTypeName := archType.Name
871 if _, ok := variantsByArchName[archTypeName]; !ok {
872 archTypes = append(archTypes, archType)
873 }
874
875 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
876 }
877
878 if commonVariants, ok := variantsByArchName["common"]; ok {
879 if len(osTypeVariants) != 1 {
880 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
881 }
882
883 // A common arch type only has one variant and its properties should be treated
884 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000885 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000886 } else {
887 // Create an arch specific info for each supported architecture type.
888 for _, archType := range archTypes {
889 archTypeName := archType.Name
890
891 archVariants := variantsByArchName[archTypeName]
Paul Duffin3a4eb502020-03-19 16:11:18 +0000892 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000893
894 osInfo.archInfos = append(osInfo.archInfos, archInfo)
895 }
896 }
897
898 return osInfo
899}
900
901// Optimize the properties by extracting common properties from arch type specific
902// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100903func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +0000904 // Nothing to do if there is only a single common architecture.
905 if len(osInfo.archInfos) == 0 {
906 return
907 }
908
Paul Duffin9c3760e2020-03-16 19:52:08 +0000909 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000910 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000911 multilib = multilib.addArchType(archInfo.archType)
912
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000913 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100914 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +0000915 }
916
Paul Duffin4b8b7932020-05-06 12:35:38 +0100917 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +0000918
919 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000920 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000921}
922
923// Add the properties for an os to a property set.
924//
925// Maps the properties related to the os variants through to an appropriate
926// module structure that will produce equivalent set of variants when it is
927// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000928func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +0000929
930 var osPropertySet android.BpPropertySet
931 var archPropertySet android.BpPropertySet
932 var archOsPrefix string
933 if osInfo.Properties.Base().Os_count == 1 {
934 // There is only one os type present in the variants so don't bother
935 // with adding target specific properties.
936
937 // Create a structure that looks like:
938 // module_type {
939 // name: "...",
940 // ...
941 // <common properties>
942 // ...
943 // <single os type specific properties>
944 //
945 // arch: {
946 // <arch specific sections>
947 // }
948 //
949 osPropertySet = bpModule
950 archPropertySet = osPropertySet.AddPropertySet("arch")
951
952 // Arch specific properties need to be added to an arch specific section
953 // within arch.
954 archOsPrefix = ""
955 } else {
956 // Create a structure that looks like:
957 // module_type {
958 // name: "...",
959 // ...
960 // <common properties>
961 // ...
962 // target: {
963 // <arch independent os specific sections, e.g. android>
964 // ...
965 // <arch and os specific sections, e.g. android_x86>
966 // }
967 //
968 osType := osInfo.osType
969 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
970 archPropertySet = targetPropertySet
971
972 // Arch specific properties need to be added to an os and arch specific
973 // section prefixed with <os>_.
974 archOsPrefix = osType.Name + "_"
975 }
976
977 // Add the os specific but arch independent properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000978 osInfo.Properties.AddToPropertySet(ctx, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +0000979
980 // Add arch (and possibly os) specific sections for each set of arch (and possibly
981 // os) specific properties.
982 //
983 // The archInfos list will be empty if the os contains variants for the common
984 // architecture.
985 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +0000986 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +0000987 }
988}
989
Paul Duffin7a1f7f32020-05-04 15:32:08 +0100990func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
991 osClass := osInfo.osType.Class
992 return osClass == android.Host || osClass == android.HostCross
993}
994
995var _ isHostVariant = (*osTypeSpecificInfo)(nil)
996
Paul Duffin4b8b7932020-05-06 12:35:38 +0100997func (osInfo *osTypeSpecificInfo) String() string {
998 return fmt.Sprintf("OsType{%s}", osInfo.osType)
999}
1000
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001001type archTypeSpecificInfo struct {
1002 baseInfo
1003
1004 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001005
1006 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001007}
1008
Paul Duffin4b8b7932020-05-06 12:35:38 +01001009var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1010
Paul Duffinfc8dd232020-03-17 12:51:37 +00001011// Create a new archTypeSpecificInfo for the specified arch type and its properties
1012// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001013func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001014
Paul Duffinfc8dd232020-03-17 12:51:37 +00001015 // Create an arch specific info into which the variant properties can be copied.
1016 archInfo := &archTypeSpecificInfo{archType: archType}
1017
1018 // Create the properties into which the arch type specific properties will be
1019 // added.
1020 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001021
1022 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001023 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001024 } else {
1025 // There is more than one variant for this arch type which must be differentiated
1026 // by link type.
1027 for _, linkVariant := range archVariants {
1028 linkType := getLinkType(linkVariant)
1029 if linkType == "" {
1030 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1031 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001032 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001033
1034 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1035 }
1036 }
1037 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001038
1039 return archInfo
1040}
1041
Paul Duffinf34f6d82020-04-30 15:48:31 +01001042func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1043 return archInfo.Properties
1044}
1045
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001046// Get the link type of the variant
1047//
1048// If the variant is not differentiated by link type then it returns "",
1049// otherwise it returns one of "static" or "shared".
1050func getLinkType(variant android.Module) string {
1051 linkType := ""
1052 if linkable, ok := variant.(cc.LinkableInterface); ok {
1053 if linkable.Shared() && linkable.Static() {
1054 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1055 } else if linkable.Shared() {
1056 linkType = "shared"
1057 } else if linkable.Static() {
1058 linkType = "static"
1059 } else {
1060 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1061 }
1062 }
1063 return linkType
1064}
1065
1066// Optimize the properties by extracting common properties from link type specific
1067// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001068func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001069 if len(archInfo.linkInfos) == 0 {
1070 return
1071 }
1072
Paul Duffin4b8b7932020-05-06 12:35:38 +01001073 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001074}
1075
Paul Duffinfc8dd232020-03-17 12:51:37 +00001076// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001077func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001078 archTypeName := archInfo.archType.Name
1079 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001080 archInfo.Properties.AddToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001081
1082 for _, linkInfo := range archInfo.linkInfos {
1083 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001084 linkInfo.Properties.AddToPropertySet(ctx, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001085 }
1086}
1087
Paul Duffin4b8b7932020-05-06 12:35:38 +01001088func (archInfo *archTypeSpecificInfo) String() string {
1089 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1090}
1091
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001092type linkTypeSpecificInfo struct {
1093 baseInfo
1094
1095 linkType string
1096}
1097
Paul Duffin4b8b7932020-05-06 12:35:38 +01001098var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1099
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001100// Create a new linkTypeSpecificInfo for the specified link type and its properties
1101// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001102func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001103 linkInfo := &linkTypeSpecificInfo{
1104 baseInfo: baseInfo{
1105 // Create the properties into which the link type specific properties will be
1106 // added.
1107 Properties: variantPropertiesFactory(),
1108 },
1109 linkType: linkType,
1110 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001111 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001112 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001113}
1114
Paul Duffin4b8b7932020-05-06 12:35:38 +01001115func (l *linkTypeSpecificInfo) String() string {
1116 return fmt.Sprintf("LinkType{%s}", l.linkType)
1117}
1118
Paul Duffin3a4eb502020-03-19 16:11:18 +00001119type memberContext struct {
1120 sdkMemberContext android.ModuleContext
1121 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001122 memberType android.SdkMemberType
1123 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001124}
1125
1126func (m *memberContext) SdkModuleContext() android.ModuleContext {
1127 return m.sdkMemberContext
1128}
1129
1130func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1131 return m.builder
1132}
1133
Paul Duffina551a1c2020-03-17 21:04:24 +00001134func (m *memberContext) MemberType() android.SdkMemberType {
1135 return m.memberType
1136}
1137
1138func (m *memberContext) Name() string {
1139 return m.name
1140}
1141
Paul Duffin3a4eb502020-03-19 16:11:18 +00001142func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001143
1144 memberType := member.memberType
1145
Paul Duffina04c1072020-03-02 10:16:35 +00001146 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001147 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001148 variants := member.Variants()
1149 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001150 osType := variant.Target().Os
1151 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001152 }
1153
Paul Duffina04c1072020-03-02 10:16:35 +00001154 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001155 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001156 properties := memberType.CreateVariantPropertiesStruct()
1157 base := properties.Base()
1158 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001159 return properties
1160 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001161
Paul Duffina04c1072020-03-02 10:16:35 +00001162 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001163
Paul Duffina04c1072020-03-02 10:16:35 +00001164 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001165 commonProperties := variantPropertiesFactory()
1166 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001167
Paul Duffinc097e362020-03-10 22:50:03 +00001168 // Create common value extractor that can be used to optimize the properties.
1169 commonValueExtractor := newCommonValueExtractor(commonProperties)
1170
Paul Duffina04c1072020-03-02 10:16:35 +00001171 // The list of property structures which are os type specific but common across
1172 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001173 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001174
1175 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001176 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001177 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001178 // Add the os specific properties to a list of os type specific yet architecture
1179 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001180 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001181
Paul Duffin00e46802020-03-12 20:40:35 +00001182 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001183 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001184 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001185
Paul Duffina04c1072020-03-02 10:16:35 +00001186 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001187 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001188
Paul Duffina04c1072020-03-02 10:16:35 +00001189 // Add the common properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001190 commonProperties.AddToPropertySet(ctx, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001191
Paul Duffina04c1072020-03-02 10:16:35 +00001192 // Create a target property set into which target specific properties can be
1193 // added.
1194 targetPropertySet := bpModule.AddPropertySet("target")
1195
1196 // Iterate over the os types in a fixed order.
1197 for _, osType := range s.getPossibleOsTypes() {
1198 osInfo := osTypeToInfo[osType]
1199 if osInfo == nil {
1200 continue
1201 }
1202
Paul Duffin3a4eb502020-03-19 16:11:18 +00001203 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001204 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001205}
1206
Paul Duffina04c1072020-03-02 10:16:35 +00001207// Compute the list of possible os types that this sdk could support.
1208func (s *sdk) getPossibleOsTypes() []android.OsType {
1209 var osTypes []android.OsType
1210 for _, osType := range android.OsTypeList {
1211 if s.DeviceSupported() {
1212 if osType.Class == android.Device && osType != android.Fuchsia {
1213 osTypes = append(osTypes, osType)
1214 }
1215 }
1216 if s.HostSupported() {
1217 if osType.Class == android.Host || osType.Class == android.HostCross {
1218 osTypes = append(osTypes, osType)
1219 }
1220 }
1221 }
1222 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1223 return osTypes
1224}
1225
Paul Duffinb28369a2020-05-04 15:39:59 +01001226// Given a set of properties (struct value), return the value of the field within that
1227// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001228type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1229
Paul Duffinc459f892020-04-30 18:08:29 +01001230// Checks the metadata to determine whether the property should be ignored for the
1231// purposes of common value extraction or not.
1232type extractorMetadataPredicate func(metadata propertiesContainer) bool
1233
1234// Indicates whether optimizable properties are provided by a host variant or
1235// not.
1236type isHostVariant interface {
1237 isHostVariant() bool
1238}
1239
Paul Duffinb28369a2020-05-04 15:39:59 +01001240// A property that can be optimized by the commonValueExtractor.
1241type extractorProperty struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001242 // The name of the field for this property.
1243 name string
1244
Paul Duffinc459f892020-04-30 18:08:29 +01001245 // Filter that can use metadata associated with the properties being optimized
1246 // to determine whether the field should be ignored during common value
1247 // optimization.
1248 filter extractorMetadataPredicate
1249
Paul Duffinb28369a2020-05-04 15:39:59 +01001250 // Retrieves the value on which common value optimization will be performed.
1251 getter fieldAccessorFunc
1252
1253 // The empty value for the field.
1254 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001255
1256 // True if the property can support arch variants false otherwise.
1257 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001258}
1259
Paul Duffin4b8b7932020-05-06 12:35:38 +01001260func (p extractorProperty) String() string {
1261 return p.name
1262}
1263
Paul Duffinc097e362020-03-10 22:50:03 +00001264// Supports extracting common values from a number of instances of a properties
1265// structure into a separate common set of properties.
1266type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001267 // The properties that the extractor can optimize.
1268 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001269}
1270
1271// Create a new common value extractor for the structure type for the supplied
1272// properties struct.
1273//
1274// The returned extractor can be used on any properties structure of the same type
1275// as the supplied set of properties.
1276func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1277 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1278 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001279 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001280 return extractor
1281}
1282
1283// Gather the fields from the supplied structure type from which common values will
1284// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001285//
1286// This is recursive function. If it encounters an embedded field (no field name)
1287// that is a struct then it will recurse into that struct passing in the accessor
1288// for the field. That will then be used in the accessors for the fields in the
1289// embedded struct.
1290func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001291 for f := 0; f < structType.NumField(); f++ {
1292 field := structType.Field(f)
1293 if field.PkgPath != "" {
1294 // Ignore unexported fields.
1295 continue
1296 }
1297
Paul Duffinb07fa512020-03-10 22:17:04 +00001298 // Ignore fields whose value should be kept.
1299 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001300 continue
1301 }
1302
Paul Duffinc459f892020-04-30 18:08:29 +01001303 var filter extractorMetadataPredicate
1304
1305 // Add a filter
1306 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1307 filter = func(metadata propertiesContainer) bool {
1308 if m, ok := metadata.(isHostVariant); ok {
1309 if m.isHostVariant() {
1310 return false
1311 }
1312 }
1313 return true
1314 }
1315 }
1316
Paul Duffinc097e362020-03-10 22:50:03 +00001317 // Save a copy of the field index for use in the function.
1318 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001319
1320 name := field.Name
1321
Paul Duffinc097e362020-03-10 22:50:03 +00001322 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001323 if containingStructAccessor != nil {
1324 // This is an embedded structure so first access the field for the embedded
1325 // structure.
1326 value = containingStructAccessor(value)
1327 }
1328
Paul Duffinc097e362020-03-10 22:50:03 +00001329 // Skip through interface and pointer values to find the structure.
1330 value = getStructValue(value)
1331
Paul Duffin4b8b7932020-05-06 12:35:38 +01001332 defer func() {
1333 if r := recover(); r != nil {
1334 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1335 }
1336 }()
1337
Paul Duffinc097e362020-03-10 22:50:03 +00001338 // Return the field.
1339 return value.Field(fieldIndex)
1340 }
1341
Paul Duffinb07fa512020-03-10 22:17:04 +00001342 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1343 // Gather fields from the embedded structure.
1344 e.gatherFields(field.Type, fieldGetter)
1345 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001346 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001347 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001348 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001349 fieldGetter,
1350 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001351 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001352 }
1353 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001354 }
Paul Duffinc097e362020-03-10 22:50:03 +00001355 }
1356}
1357
1358func getStructValue(value reflect.Value) reflect.Value {
1359foundStruct:
1360 for {
1361 kind := value.Kind()
1362 switch kind {
1363 case reflect.Interface, reflect.Ptr:
1364 value = value.Elem()
1365 case reflect.Struct:
1366 break foundStruct
1367 default:
1368 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1369 }
1370 }
1371 return value
1372}
1373
Paul Duffinf34f6d82020-04-30 15:48:31 +01001374// A container of properties to be optimized.
1375//
1376// Allows additional information to be associated with the properties, e.g. for
1377// filtering.
1378type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001379 fmt.Stringer
1380
Paul Duffinf34f6d82020-04-30 15:48:31 +01001381 // Get the properties that need optimizing.
1382 optimizableProperties() interface{}
1383}
1384
1385// A wrapper for dynamic member properties to allow them to be optimized.
1386type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001387 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001388 dynamicMemberProperties interface{}
1389}
1390
1391func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1392 return c.dynamicMemberProperties
1393}
1394
Paul Duffin4b8b7932020-05-06 12:35:38 +01001395func (c dynamicMemberPropertiesContainer) String() string {
1396 return c.sdkVariant.String()
1397}
1398
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001399// Extract common properties from a slice of property structures of the same type.
1400//
1401// All the property structures must be of the same type.
1402// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001403// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001404//
1405// Iterates over each exported field (capitalized name) and checks to see whether they
1406// have the same value (using DeepEquals) across all the input properties. If it does not then no
1407// change is made. Otherwise, the common value is stored in the field in the commonProperties
1408// and the field in each of the input properties structure is set to its default value.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001409func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001410 commonPropertiesValue := reflect.ValueOf(commonProperties)
1411 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001412
Paul Duffinf34f6d82020-04-30 15:48:31 +01001413 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1414
Paul Duffinb28369a2020-05-04 15:39:59 +01001415 for _, property := range e.properties {
1416 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001417 filter := property.filter
1418 if filter == nil {
1419 filter = func(metadata propertiesContainer) bool {
1420 return true
1421 }
1422 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001423
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001424 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001425 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1426 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001427 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001428
Paul Duffin864e1b42020-05-06 10:23:19 +01001429 // Assume that all the values will be the same.
1430 //
1431 // While similar to this is not quite the same as commonValue == nil. If all the values
1432 // have been filtered out then this will be false but commonValue == nil will be true.
1433 valuesDiffer := false
1434
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001435 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001436 container := sliceValue.Index(i).Interface().(propertiesContainer)
1437 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001438 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001439
Paul Duffinc459f892020-04-30 18:08:29 +01001440 if !filter(container) {
1441 expectedValue := property.emptyValue.Interface()
1442 actualValue := fieldValue.Interface()
1443 if !reflect.DeepEqual(expectedValue, actualValue) {
1444 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1445 }
1446 continue
1447 }
1448
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001449 if commonValue == nil {
1450 // Use the first value as the commonProperties value.
1451 commonValue = &fieldValue
1452 } else {
1453 // If the value does not match the current common value then there is
1454 // no value in common so break out.
1455 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1456 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001457 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001458 break
1459 }
1460 }
1461 }
1462
Paul Duffin864e1b42020-05-06 10:23:19 +01001463 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001464 // and set the input struct's field to the empty value.
1465 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001466 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001467 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001468 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001469 container := sliceValue.Index(i).Interface().(propertiesContainer)
1470 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001471 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001472 fieldValue.Set(emptyValue)
1473 }
1474 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001475
1476 if valuesDiffer && !property.archVariant {
1477 // The values differ but the property does not support arch variants so it
1478 // is an error.
1479 var details strings.Builder
1480 for i := 0; i < sliceValue.Len(); i++ {
1481 container := sliceValue.Index(i).Interface().(propertiesContainer)
1482 itemValue := reflect.ValueOf(container.optimizableProperties())
1483 fieldValue := fieldGetter(itemValue)
1484
1485 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1486 }
1487
1488 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1489 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001490 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001491
1492 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001493}