blob: 991428eec7de0c267ec1cad4c24c1f90d6d2d281 [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{}) {
Jiyong Park9b409bc2019-10-11 14:59:13 +090090 // ninja consumes newline characters in rspfile_content. Prevent it by
Paul Duffin0e0cf1d2019-11-12 19:39:25 +000091 // escaping the backslash in the newline character. The extra backslash
Jiyong Park9b409bc2019-10-11 14:59:13 +090092 // is removed when the rspfile is written to the actual script file
Paul Duffinb645ec82019-11-27 17:43:54 +000093 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090094}
95
96func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
97 rb := android.NewRuleBuilder()
98 // convert \\n to \n
99 rb.Command().
100 Implicits(implicits).
101 Text("echo").Text(proptools.ShellEscape(gf.content.String())).
102 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
103 rb.Command().
104 Text("chmod a+x").Output(gf.path)
105 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
106}
107
Paul Duffin13879572019-11-28 14:31:38 +0000108// Collect all the members.
109//
Paul Duffin6a7e9532020-03-20 17:50:07 +0000110// Returns a list containing type (extracted from the dependency tag) and the variant
111// plus the multilib usages.
112func (s *sdk) collectMembers(ctx android.ModuleContext) {
113 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000114 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
115 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000116 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
117 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900118
Paul Duffin13879572019-11-28 14:31:38 +0000119 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000120 if !memberType.IsInstance(child) {
121 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900122 }
Paul Duffin13879572019-11-28 14:31:38 +0000123
Paul Duffin6a7e9532020-03-20 17:50:07 +0000124 // Keep track of which multilib variants are used by the sdk.
125 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
126
127 s.memberRefs = append(s.memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000128
129 // If the member type supports transitive sdk members then recurse down into
130 // its dependencies, otherwise exit traversal.
131 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900132 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000133
134 return false
Paul Duffin13879572019-11-28 14:31:38 +0000135 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000136}
137
138// Organize the members.
139//
140// The members are first grouped by type and then grouped by name. The order of
141// the types is the order they are referenced in android.SdkMemberTypesRegistry.
142// The names are in the order in which the dependencies were added.
143//
144// Returns the members as well as the multilib setting to use.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000145func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000146 byType := make(map[android.SdkMemberType][]*sdkMember)
147 byName := make(map[string]*sdkMember)
148
Paul Duffin1356d8c2020-02-25 19:26:33 +0000149 for _, memberRef := range memberRefs {
150 memberType := memberRef.memberType
151 variant := memberRef.variant
152
153 name := ctx.OtherModuleName(variant)
154 member := byName[name]
155 if member == nil {
156 member = &sdkMember{memberType: memberType, name: name}
157 byName[name] = member
158 byType[memberType] = append(byType[memberType], member)
159 }
160
Paul Duffin1356d8c2020-02-25 19:26:33 +0000161 // Only append new variants to the list. This is needed because a member can be both
162 // exported by the sdk and also be a transitive sdk member.
163 member.variants = appendUniqueVariants(member.variants, variant)
164 }
165
Paul Duffin13879572019-11-28 14:31:38 +0000166 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000167 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000168 membersOfType := byType[memberListProperty.memberType]
169 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900170 }
171
Paul Duffin6a7e9532020-03-20 17:50:07 +0000172 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900173}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900174
Paul Duffin72910952020-01-20 18:16:30 +0000175func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
176 for _, v := range variants {
177 if v == newVariant {
178 return variants
179 }
180 }
181 return append(variants, newVariant)
182}
183
Jiyong Park73c54ee2019-10-22 20:31:18 +0900184// SDK directory structure
185// <sdk_root>/
186// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
187// <api_ver>/ : below this directory are all auto-generated
188// Android.bp : definition of 'sdk_snapshot' module is here
189// aidl/
190// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
191// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900192// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900193// include/
194// bionic/libc/include/stdlib.h : an exported header file
195// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900196// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900197// <arch>/include/ : arch-specific exported headers
198// <arch>/include_gen/ : arch-specific generated headers
199// <arch>/lib/
200// libFoo.so : a stub library
201
Jiyong Park232e7852019-11-04 12:23:40 +0900202// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900203// This isn't visible to users, so could be changed in future.
204func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
205 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
206}
207
Jiyong Park232e7852019-11-04 12:23:40 +0900208// buildSnapshot is the main function in this source file. It creates rules to copy
209// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000210func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
211
Paul Duffin13f02712020-03-06 12:30:43 +0000212 allMembersByName := make(map[string]struct{})
213 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000214 var memberRefs []sdkMemberRef
215 for _, sdkVariant := range sdkVariants {
216 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000217
Paul Duffin13f02712020-03-06 12:30:43 +0000218 // Record the names of all the members, both explicitly specified and implicitly
219 // included.
220 for _, memberRef := range sdkVariant.memberRefs {
221 allMembersByName[memberRef.variant.Name()] = struct{}{}
222 }
223
Paul Duffin865171e2020-03-02 18:38:15 +0000224 // Merge the exported member sets from all sdk variants.
225 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000226 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000227 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000228 }
229
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000230 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900231
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000232 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000233
234 bpFile := &bpFile{
235 modules: make(map[string]*bpModule),
236 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000237
238 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000239 ctx: ctx,
240 sdk: s,
241 version: "current",
242 snapshotDir: snapshotDir.OutputPath,
243 copies: make(map[string]string),
244 filesToZip: []android.Path{bp.path},
245 bpFile: bpFile,
246 prebuiltModules: make(map[string]*bpModule),
247 allMembersByName: allMembersByName,
248 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900249 }
Paul Duffinac37c502019-11-26 18:02:20 +0000250 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900251
Paul Duffin6a7e9532020-03-20 17:50:07 +0000252 members := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000253 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000254 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000255
Paul Duffina551a1c2020-03-17 21:04:24 +0000256 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000257
258 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Paul Duffin495ffb92020-03-20 13:35:40 +0000259 s.createMemberSnapshot(memberCtx, member, prebuiltModule)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900260 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900261
Paul Duffine6c0d842020-01-15 14:08:51 +0000262 // Create a transformer that will transform an unversioned module into a versioned module.
263 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
264
Paul Duffin72910952020-01-20 18:16:30 +0000265 // Create a transformer that will transform an unversioned module by replacing any references
266 // to internal members with a unique module name and setting prefer: false.
267 unversionedTransformer := unversionedTransformation{builder: builder}
268
Paul Duffinb645ec82019-11-27 17:43:54 +0000269 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000270 // Prune any empty property sets.
271 unversioned = unversioned.transform(pruneEmptySetTransformer{})
272
Paul Duffinb645ec82019-11-27 17:43:54 +0000273 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000274 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000275
276 // Transform the unversioned module into a versioned one.
277 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000278 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000279
Paul Duffin72910952020-01-20 18:16:30 +0000280 // Transform the unversioned module to make it suitable for use in the snapshot.
281 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000282 bpFile.AddModule(unversioned)
283 }
284
285 // Create the snapshot module.
286 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000287 var snapshotModuleType string
288 if s.properties.Module_exports {
289 snapshotModuleType = "module_exports_snapshot"
290 } else {
291 snapshotModuleType = "sdk_snapshot"
292 }
293 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000294 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000295
296 // Make sure that the snapshot has the same visibility as the sdk.
297 visibility := android.EffectiveVisibilityRules(ctx, s)
298 if len(visibility) != 0 {
299 snapshotModule.AddProperty("visibility", visibility)
300 }
301
Paul Duffin865171e2020-03-02 18:38:15 +0000302 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000303
Paul Duffinf34f6d82020-04-30 15:48:31 +0100304 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffin865171e2020-03-02 18:38:15 +0000305 osTypeToMemberProperties := make(map[android.OsType]*sdk)
306 for _, sdkVariant := range sdkVariants {
307 properties := sdkVariant.dynamicMemberTypeListProperties
308 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffin4b8b7932020-05-06 12:35:38 +0100309 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000310 }
311
312 // Extract the common lists of members into a separate struct.
313 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000314 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin4b8b7932020-05-06 12:35:38 +0100315 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000316
317 // Add properties common to all os types.
318 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
319
320 // Iterate over the os types in a fixed order.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000321 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin865171e2020-03-02 18:38:15 +0000322 for _, osType := range s.getPossibleOsTypes() {
323 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
324 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000325
326 // Compile_multilib defaults to both and must always be set to both on the
327 // device and so only needs to be set when targeted at the host and is neither
328 // unspecified or both.
329 multilib := sdkVariant.multilibUsages
330 if (osType.Class == android.Host || osType.Class == android.HostCross) &&
331 multilib != multilibNone && multilib != multilibBoth {
332 osPropertySet.AddProperty("compile_multilib", multilib.String())
333 }
334
Paul Duffin865171e2020-03-02 18:38:15 +0000335 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000336 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000337 }
Paul Duffin865171e2020-03-02 18:38:15 +0000338
339 // Prune any empty property sets.
340 snapshotModule.transform(pruneEmptySetTransformer{})
341
Paul Duffinb645ec82019-11-27 17:43:54 +0000342 bpFile.AddModule(snapshotModule)
343
344 // generate Android.bp
345 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
346 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000347
348 bp.build(pctx, ctx, nil)
349
350 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900351
Jiyong Park232e7852019-11-04 12:23:40 +0900352 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000353 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000354 outputDesc := "Building snapshot for " + ctx.ModuleName()
355
356 // If there are no zips to merge then generate the output zip directly.
357 // Otherwise, generate an intermediate zip file into which other zips can be
358 // merged.
359 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000360 var desc string
361 if len(builder.zipsToMerge) == 0 {
362 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000363 desc = outputDesc
364 } else {
365 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000366 desc = "Building intermediate snapshot for " + ctx.ModuleName()
367 }
368
Paul Duffin375058f2019-11-29 20:17:53 +0000369 ctx.Build(pctx, android.BuildParams{
370 Description: desc,
371 Rule: zipFiles,
372 Inputs: filesToZip,
373 Output: zipFile,
374 Args: map[string]string{
375 "basedir": builder.snapshotDir.String(),
376 },
377 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900378
Paul Duffin91547182019-11-12 19:39:36 +0000379 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000380 ctx.Build(pctx, android.BuildParams{
381 Description: outputDesc,
382 Rule: mergeZips,
383 Input: zipFile,
384 Inputs: builder.zipsToMerge,
385 Output: outputZipFile,
386 })
Paul Duffin91547182019-11-12 19:39:36 +0000387 }
388
389 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900390}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000391
Paul Duffin4b8b7932020-05-06 12:35:38 +0100392func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
393 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
394 if err != nil {
395 ctx.ModuleErrorf("error extracting common properties: %s", err)
396 }
397}
398
Paul Duffin865171e2020-03-02 18:38:15 +0000399func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
400 for _, memberListProperty := range s.memberListProperties() {
401 names := memberListProperty.getter(dynamicMemberTypeListProperties)
402 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000403 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000404 }
405 }
406}
407
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000408type propertyTag struct {
409 name string
410}
411
Paul Duffin0cb37b92020-03-04 14:52:46 +0000412// A BpPropertyTag to add to a property that contains references to other sdk members.
413//
414// This will cause the references to be rewritten to a versioned reference in the version
415// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000416var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000417var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000418
Paul Duffin0cb37b92020-03-04 14:52:46 +0000419// A BpPropertyTag that indicates the property should only be present in the versioned
420// module.
421//
422// This will cause the property to be removed from the unversioned instance of a
423// snapshot module.
424var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
425
Paul Duffine6c0d842020-01-15 14:08:51 +0000426type unversionedToVersionedTransformation struct {
427 identityTransformation
428 builder *snapshotBuilder
429}
430
Paul Duffine6c0d842020-01-15 14:08:51 +0000431func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
432 // Use a versioned name for the module but remember the original name for the
433 // snapshot.
434 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000435 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000436 module.insertAfter("name", "sdk_member_name", name)
437 return module
438}
439
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000440func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000441 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
442 required := tag == requiredSdkMemberReferencePropertyTag
443 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000444 } else {
445 return value, tag
446 }
447}
448
Paul Duffin72910952020-01-20 18:16:30 +0000449type unversionedTransformation struct {
450 identityTransformation
451 builder *snapshotBuilder
452}
453
454func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
455 // If the module is an internal member then use a unique name for it.
456 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000457 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000458
459 // Set prefer: false - this is not strictly required as that is the default.
460 module.insertAfter("name", "prefer", false)
461
462 return module
463}
464
465func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000466 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
467 required := tag == requiredSdkMemberReferencePropertyTag
468 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000469 } else if tag == sdkVersionedOnlyPropertyTag {
470 // The property is not allowed in the unversioned module so remove it.
471 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000472 } else {
473 return value, tag
474 }
475}
476
Paul Duffina78f3a72020-02-21 16:29:35 +0000477type pruneEmptySetTransformer struct {
478 identityTransformation
479}
480
481var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
482
483func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
484 if len(propertySet.properties) == 0 {
485 return nil, nil
486 } else {
487 return propertySet, tag
488 }
489}
490
Paul Duffinb645ec82019-11-27 17:43:54 +0000491func generateBpContents(contents *generatedContents, bpFile *bpFile) {
492 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
493 for _, bpModule := range bpFile.order {
494 contents.Printfln("")
495 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000496 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000497 contents.Printfln("}")
498 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000499}
500
501func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
502 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000503
504 // Output the properties first, followed by the nested sets. This ensures a
505 // consistent output irrespective of whether property sets are created before
506 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000507 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000508 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000509
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000510 switch v := value.(type) {
511 case []string:
512 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000513 if length > 1 {
514 contents.Printfln("%s: [", name)
515 contents.Indent()
516 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000517 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000518 }
519 contents.Dedent()
520 contents.Printfln("],")
521 } else if length == 0 {
522 contents.Printfln("%s: [],", name)
523 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000524 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000525 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000526
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000527 case bool:
528 contents.Printfln("%s: %t,", name, v)
529
530 case *bpPropertySet:
531 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000532
533 default:
534 contents.Printfln("%s: %q,", name, value)
535 }
536 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000537
538 for _, name := range set.order {
539 value := set.getValue(name)
540
541 // Only write property sets in the sets phase.
542 switch v := value.(type) {
543 case *bpPropertySet:
544 contents.Printfln("%s: {", name)
545 outputPropertySet(contents, v)
546 contents.Printfln("},")
547 }
548 }
549
Paul Duffinb645ec82019-11-27 17:43:54 +0000550 contents.Dedent()
551}
552
Paul Duffinac37c502019-11-26 18:02:20 +0000553func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000554 contents := &generatedContents{}
555 generateBpContents(contents, s.builderForTests.bpFile)
556 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000557}
558
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000559type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000560 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000561 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000562 version string
563 snapshotDir android.OutputPath
564 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000565
566 // Map from destination to source of each copy - used to eliminate duplicates and
567 // detect conflicts.
568 copies map[string]string
569
Paul Duffinb645ec82019-11-27 17:43:54 +0000570 filesToZip android.Paths
571 zipsToMerge android.Paths
572
573 prebuiltModules map[string]*bpModule
574 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000575
576 // The set of all members by name.
577 allMembersByName map[string]struct{}
578
579 // The set of exported members by name.
580 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000581}
582
583func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000584 if existing, ok := s.copies[dest]; ok {
585 if existing != src.String() {
586 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
587 return
588 }
589 } else {
590 path := s.snapshotDir.Join(s.ctx, dest)
591 s.ctx.Build(pctx, android.BuildParams{
592 Rule: android.Cp,
593 Input: src,
594 Output: path,
595 })
596 s.filesToZip = append(s.filesToZip, path)
597
598 s.copies[dest] = src.String()
599 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000600}
601
Paul Duffin91547182019-11-12 19:39:36 +0000602func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
603 ctx := s.ctx
604
605 // Repackage the zip file so that the entries are in the destDir directory.
606 // This will allow the zip file to be merged into the snapshot.
607 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000608
609 ctx.Build(pctx, android.BuildParams{
610 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
611 Rule: repackageZip,
612 Input: zipPath,
613 Output: tmpZipPath,
614 Args: map[string]string{
615 "destdir": destDir,
616 },
617 })
Paul Duffin91547182019-11-12 19:39:36 +0000618
619 // Add the repackaged zip file to the files to merge.
620 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
621}
622
Paul Duffin9d8d6092019-12-05 18:19:29 +0000623func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
624 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000625 if s.prebuiltModules[name] != nil {
626 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
627 }
628
629 m := s.bpFile.newModule(moduleType)
630 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000631
Paul Duffinbefa4b92020-03-04 14:22:45 +0000632 variant := member.Variants()[0]
633
Paul Duffin13f02712020-03-06 12:30:43 +0000634 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000635 // An internal member is only referenced from the sdk snapshot which is in the
636 // same package so can be marked as private.
637 m.AddProperty("visibility", []string{"//visibility:private"})
638 } else {
639 // Extract visibility information from a member variant. All variants have the same
640 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000641 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000642 if len(visibility) != 0 {
643 m.AddProperty("visibility", visibility)
644 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000645 }
646
Paul Duffin865171e2020-03-02 18:38:15 +0000647 deviceSupported := false
648 hostSupported := false
649
650 for _, variant := range member.Variants() {
651 osClass := variant.Target().Os.Class
652 if osClass == android.Host || osClass == android.HostCross {
653 hostSupported = true
654 } else if osClass == android.Device {
655 deviceSupported = true
656 }
657 }
658
659 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000660
Paul Duffinbefa4b92020-03-04 14:22:45 +0000661 // Where available copy apex_available properties from the member.
662 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
663 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000664
665 // Add in any white listed apex available settings.
666 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
667
Paul Duffinbefa4b92020-03-04 14:22:45 +0000668 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000669 // Remove duplicates and sort.
670 apexAvailable = android.FirstUniqueStrings(apexAvailable)
671 sort.Strings(apexAvailable)
672
Paul Duffinbefa4b92020-03-04 14:22:45 +0000673 m.AddProperty("apex_available", apexAvailable)
674 }
675 }
676
Paul Duffin0cb37b92020-03-04 14:52:46 +0000677 // Disable installation in the versioned module of those modules that are ever installable.
678 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
679 if installable.EverInstallable() {
680 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
681 }
682 }
683
Paul Duffinb645ec82019-11-27 17:43:54 +0000684 s.prebuiltModules[name] = m
685 s.prebuiltOrder = append(s.prebuiltOrder, m)
686 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000687}
688
Paul Duffin865171e2020-03-02 18:38:15 +0000689func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
690 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000691 bpModule.AddProperty("device_supported", false)
692 }
Paul Duffin865171e2020-03-02 18:38:15 +0000693 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000694 bpModule.AddProperty("host_supported", true)
695 }
696}
697
Paul Duffin13f02712020-03-06 12:30:43 +0000698func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
699 if required {
700 return requiredSdkMemberReferencePropertyTag
701 } else {
702 return optionalSdkMemberReferencePropertyTag
703 }
704}
705
706func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
707 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000708}
709
Paul Duffinb645ec82019-11-27 17:43:54 +0000710// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000711func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
712 if _, ok := s.allMembersByName[unversionedName]; !ok {
713 if required {
714 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
715 }
716 return unversionedName
717 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000718 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
719}
Paul Duffinb645ec82019-11-27 17:43:54 +0000720
Paul Duffin13f02712020-03-06 12:30:43 +0000721func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000722 var references []string = nil
723 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000724 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000725 }
726 return references
727}
Paul Duffin13879572019-11-28 14:31:38 +0000728
Paul Duffin72910952020-01-20 18:16:30 +0000729// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000730func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
731 if _, ok := s.allMembersByName[unversionedName]; !ok {
732 if required {
733 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
734 }
735 return unversionedName
736 }
737
738 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000739 return s.ctx.ModuleName() + "_" + unversionedName
740 } else {
741 return unversionedName
742 }
743}
744
Paul Duffin13f02712020-03-06 12:30:43 +0000745func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000746 var references []string = nil
747 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000748 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000749 }
750 return references
751}
752
Paul Duffin13f02712020-03-06 12:30:43 +0000753func (s *snapshotBuilder) isInternalMember(memberName string) bool {
754 _, ok := s.exportedMembersByName[memberName]
755 return !ok
756}
757
Paul Duffin1356d8c2020-02-25 19:26:33 +0000758type sdkMemberRef struct {
759 memberType android.SdkMemberType
760 variant android.SdkAware
761}
762
Paul Duffin13879572019-11-28 14:31:38 +0000763var _ android.SdkMember = (*sdkMember)(nil)
764
765type sdkMember struct {
766 memberType android.SdkMemberType
767 name string
768 variants []android.SdkAware
769}
770
771func (m *sdkMember) Name() string {
772 return m.name
773}
774
775func (m *sdkMember) Variants() []android.SdkAware {
776 return m.variants
777}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000778
Paul Duffin9c3760e2020-03-16 19:52:08 +0000779// Track usages of multilib variants.
780type multilibUsage int
781
782const (
783 multilibNone multilibUsage = 0
784 multilib32 multilibUsage = 1
785 multilib64 multilibUsage = 2
786 multilibBoth = multilib32 | multilib64
787)
788
789// Add the multilib that is used in the arch type.
790func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
791 multilib := archType.Multilib
792 switch multilib {
793 case "":
794 return m
795 case "lib32":
796 return m | multilib32
797 case "lib64":
798 return m | multilib64
799 default:
800 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
801 }
802}
803
804func (m multilibUsage) String() string {
805 switch m {
806 case multilibNone:
807 return ""
808 case multilib32:
809 return "32"
810 case multilib64:
811 return "64"
812 case multilibBoth:
813 return "both"
814 default:
815 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
816 m, multilibNone, multilib32, multilib64, multilibBoth))
817 }
818}
819
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000820type baseInfo struct {
821 Properties android.SdkMemberProperties
822}
823
Paul Duffinf34f6d82020-04-30 15:48:31 +0100824func (b *baseInfo) optimizableProperties() interface{} {
825 return b.Properties
826}
827
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000828type osTypeSpecificInfo struct {
829 baseInfo
830
Paul Duffin00e46802020-03-12 20:40:35 +0000831 osType android.OsType
832
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000833 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000834 //
835 // Nil if there is one variant whose arch type is common
836 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000837}
838
Paul Duffin4b8b7932020-05-06 12:35:38 +0100839var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
840
Paul Duffinfc8dd232020-03-17 12:51:37 +0000841type variantPropertiesFactoryFunc func() android.SdkMemberProperties
842
Paul Duffin00e46802020-03-12 20:40:35 +0000843// Create a new osTypeSpecificInfo for the specified os type and its properties
844// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000845func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000846 osInfo := &osTypeSpecificInfo{
847 osType: osType,
848 }
849
850 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
851 properties := variantPropertiesFactory()
852 properties.Base().Os = osType
853 return properties
854 }
855
856 // Create a structure into which properties common across the architectures in
857 // this os type will be stored.
858 osInfo.Properties = osSpecificVariantPropertiesFactory()
859
860 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000861 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000862 var archTypes []android.ArchType
863 for _, variant := range osTypeVariants {
864 archType := variant.Target().Arch.ArchType
865 archTypeName := archType.Name
866 if _, ok := variantsByArchName[archTypeName]; !ok {
867 archTypes = append(archTypes, archType)
868 }
869
870 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
871 }
872
873 if commonVariants, ok := variantsByArchName["common"]; ok {
874 if len(osTypeVariants) != 1 {
875 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
876 }
877
878 // A common arch type only has one variant and its properties should be treated
879 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000880 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000881 } else {
882 // Create an arch specific info for each supported architecture type.
883 for _, archType := range archTypes {
884 archTypeName := archType.Name
885
886 archVariants := variantsByArchName[archTypeName]
Paul Duffin3a4eb502020-03-19 16:11:18 +0000887 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000888
889 osInfo.archInfos = append(osInfo.archInfos, archInfo)
890 }
891 }
892
893 return osInfo
894}
895
896// Optimize the properties by extracting common properties from arch type specific
897// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100898func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +0000899 // Nothing to do if there is only a single common architecture.
900 if len(osInfo.archInfos) == 0 {
901 return
902 }
903
Paul Duffin9c3760e2020-03-16 19:52:08 +0000904 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000905 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000906 multilib = multilib.addArchType(archInfo.archType)
907
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000908 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +0100909 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +0000910 }
911
Paul Duffin4b8b7932020-05-06 12:35:38 +0100912 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +0000913
914 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000915 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000916}
917
918// Add the properties for an os to a property set.
919//
920// Maps the properties related to the os variants through to an appropriate
921// module structure that will produce equivalent set of variants when it is
922// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000923func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +0000924
925 var osPropertySet android.BpPropertySet
926 var archPropertySet android.BpPropertySet
927 var archOsPrefix string
928 if osInfo.Properties.Base().Os_count == 1 {
929 // There is only one os type present in the variants so don't bother
930 // with adding target specific properties.
931
932 // Create a structure that looks like:
933 // module_type {
934 // name: "...",
935 // ...
936 // <common properties>
937 // ...
938 // <single os type specific properties>
939 //
940 // arch: {
941 // <arch specific sections>
942 // }
943 //
944 osPropertySet = bpModule
945 archPropertySet = osPropertySet.AddPropertySet("arch")
946
947 // Arch specific properties need to be added to an arch specific section
948 // within arch.
949 archOsPrefix = ""
950 } else {
951 // Create a structure that looks like:
952 // module_type {
953 // name: "...",
954 // ...
955 // <common properties>
956 // ...
957 // target: {
958 // <arch independent os specific sections, e.g. android>
959 // ...
960 // <arch and os specific sections, e.g. android_x86>
961 // }
962 //
963 osType := osInfo.osType
964 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
965 archPropertySet = targetPropertySet
966
967 // Arch specific properties need to be added to an os and arch specific
968 // section prefixed with <os>_.
969 archOsPrefix = osType.Name + "_"
970 }
971
972 // Add the os specific but arch independent properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000973 osInfo.Properties.AddToPropertySet(ctx, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +0000974
975 // Add arch (and possibly os) specific sections for each set of arch (and possibly
976 // os) specific properties.
977 //
978 // The archInfos list will be empty if the os contains variants for the common
979 // architecture.
980 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +0000981 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +0000982 }
983}
984
Paul Duffin4b8b7932020-05-06 12:35:38 +0100985func (osInfo *osTypeSpecificInfo) String() string {
986 return fmt.Sprintf("OsType{%s}", osInfo.osType)
987}
988
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000989type archTypeSpecificInfo struct {
990 baseInfo
991
992 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000993
994 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000995}
996
Paul Duffin4b8b7932020-05-06 12:35:38 +0100997var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
998
Paul Duffinfc8dd232020-03-17 12:51:37 +0000999// Create a new archTypeSpecificInfo for the specified arch type and its properties
1000// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001001func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001002
Paul Duffinfc8dd232020-03-17 12:51:37 +00001003 // Create an arch specific info into which the variant properties can be copied.
1004 archInfo := &archTypeSpecificInfo{archType: archType}
1005
1006 // Create the properties into which the arch type specific properties will be
1007 // added.
1008 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001009
1010 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001011 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001012 } else {
1013 // There is more than one variant for this arch type which must be differentiated
1014 // by link type.
1015 for _, linkVariant := range archVariants {
1016 linkType := getLinkType(linkVariant)
1017 if linkType == "" {
1018 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1019 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001020 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001021
1022 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1023 }
1024 }
1025 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001026
1027 return archInfo
1028}
1029
Paul Duffinf34f6d82020-04-30 15:48:31 +01001030func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1031 return archInfo.Properties
1032}
1033
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001034// Get the link type of the variant
1035//
1036// If the variant is not differentiated by link type then it returns "",
1037// otherwise it returns one of "static" or "shared".
1038func getLinkType(variant android.Module) string {
1039 linkType := ""
1040 if linkable, ok := variant.(cc.LinkableInterface); ok {
1041 if linkable.Shared() && linkable.Static() {
1042 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1043 } else if linkable.Shared() {
1044 linkType = "shared"
1045 } else if linkable.Static() {
1046 linkType = "static"
1047 } else {
1048 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1049 }
1050 }
1051 return linkType
1052}
1053
1054// Optimize the properties by extracting common properties from link type specific
1055// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001056func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001057 if len(archInfo.linkInfos) == 0 {
1058 return
1059 }
1060
Paul Duffin4b8b7932020-05-06 12:35:38 +01001061 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001062}
1063
Paul Duffinfc8dd232020-03-17 12:51:37 +00001064// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001065func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001066 archTypeName := archInfo.archType.Name
1067 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001068 archInfo.Properties.AddToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001069
1070 for _, linkInfo := range archInfo.linkInfos {
1071 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001072 linkInfo.Properties.AddToPropertySet(ctx, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001073 }
1074}
1075
Paul Duffin4b8b7932020-05-06 12:35:38 +01001076func (archInfo *archTypeSpecificInfo) String() string {
1077 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1078}
1079
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001080type linkTypeSpecificInfo struct {
1081 baseInfo
1082
1083 linkType string
1084}
1085
Paul Duffin4b8b7932020-05-06 12:35:38 +01001086var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1087
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001088// Create a new linkTypeSpecificInfo for the specified link type and its properties
1089// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001090func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001091 linkInfo := &linkTypeSpecificInfo{
1092 baseInfo: baseInfo{
1093 // Create the properties into which the link type specific properties will be
1094 // added.
1095 Properties: variantPropertiesFactory(),
1096 },
1097 linkType: linkType,
1098 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001099 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001100 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001101}
1102
Paul Duffin4b8b7932020-05-06 12:35:38 +01001103func (l *linkTypeSpecificInfo) String() string {
1104 return fmt.Sprintf("LinkType{%s}", l.linkType)
1105}
1106
Paul Duffin3a4eb502020-03-19 16:11:18 +00001107type memberContext struct {
1108 sdkMemberContext android.ModuleContext
1109 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001110 memberType android.SdkMemberType
1111 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001112}
1113
1114func (m *memberContext) SdkModuleContext() android.ModuleContext {
1115 return m.sdkMemberContext
1116}
1117
1118func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1119 return m.builder
1120}
1121
Paul Duffina551a1c2020-03-17 21:04:24 +00001122func (m *memberContext) MemberType() android.SdkMemberType {
1123 return m.memberType
1124}
1125
1126func (m *memberContext) Name() string {
1127 return m.name
1128}
1129
Paul Duffin3a4eb502020-03-19 16:11:18 +00001130func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001131
1132 memberType := member.memberType
1133
Paul Duffina04c1072020-03-02 10:16:35 +00001134 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001135 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001136 variants := member.Variants()
1137 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001138 osType := variant.Target().Os
1139 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001140 }
1141
Paul Duffina04c1072020-03-02 10:16:35 +00001142 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001143 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001144 properties := memberType.CreateVariantPropertiesStruct()
1145 base := properties.Base()
1146 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001147 return properties
1148 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001149
Paul Duffina04c1072020-03-02 10:16:35 +00001150 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001151
Paul Duffina04c1072020-03-02 10:16:35 +00001152 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001153 commonProperties := variantPropertiesFactory()
1154 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001155
Paul Duffinc097e362020-03-10 22:50:03 +00001156 // Create common value extractor that can be used to optimize the properties.
1157 commonValueExtractor := newCommonValueExtractor(commonProperties)
1158
Paul Duffina04c1072020-03-02 10:16:35 +00001159 // The list of property structures which are os type specific but common across
1160 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001161 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001162
1163 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001164 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001165 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001166 // Add the os specific properties to a list of os type specific yet architecture
1167 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001168 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001169
Paul Duffin00e46802020-03-12 20:40:35 +00001170 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001171 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001172 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001173
Paul Duffina04c1072020-03-02 10:16:35 +00001174 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001175 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001176
Paul Duffina04c1072020-03-02 10:16:35 +00001177 // Add the common properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001178 commonProperties.AddToPropertySet(ctx, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001179
Paul Duffina04c1072020-03-02 10:16:35 +00001180 // Create a target property set into which target specific properties can be
1181 // added.
1182 targetPropertySet := bpModule.AddPropertySet("target")
1183
1184 // Iterate over the os types in a fixed order.
1185 for _, osType := range s.getPossibleOsTypes() {
1186 osInfo := osTypeToInfo[osType]
1187 if osInfo == nil {
1188 continue
1189 }
1190
Paul Duffin3a4eb502020-03-19 16:11:18 +00001191 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001192 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001193}
1194
Paul Duffina04c1072020-03-02 10:16:35 +00001195// Compute the list of possible os types that this sdk could support.
1196func (s *sdk) getPossibleOsTypes() []android.OsType {
1197 var osTypes []android.OsType
1198 for _, osType := range android.OsTypeList {
1199 if s.DeviceSupported() {
1200 if osType.Class == android.Device && osType != android.Fuchsia {
1201 osTypes = append(osTypes, osType)
1202 }
1203 }
1204 if s.HostSupported() {
1205 if osType.Class == android.Host || osType.Class == android.HostCross {
1206 osTypes = append(osTypes, osType)
1207 }
1208 }
1209 }
1210 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1211 return osTypes
1212}
1213
Paul Duffinb28369a2020-05-04 15:39:59 +01001214// Given a set of properties (struct value), return the value of the field within that
1215// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001216type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1217
Paul Duffinc459f892020-04-30 18:08:29 +01001218// Checks the metadata to determine whether the property should be ignored for the
1219// purposes of common value extraction or not.
1220type extractorMetadataPredicate func(metadata propertiesContainer) bool
1221
1222// Indicates whether optimizable properties are provided by a host variant or
1223// not.
1224type isHostVariant interface {
1225 isHostVariant() bool
1226}
1227
Paul Duffinb28369a2020-05-04 15:39:59 +01001228// A property that can be optimized by the commonValueExtractor.
1229type extractorProperty struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001230 // The name of the field for this property.
1231 name string
1232
Paul Duffinc459f892020-04-30 18:08:29 +01001233 // Filter that can use metadata associated with the properties being optimized
1234 // to determine whether the field should be ignored during common value
1235 // optimization.
1236 filter extractorMetadataPredicate
1237
Paul Duffinb28369a2020-05-04 15:39:59 +01001238 // Retrieves the value on which common value optimization will be performed.
1239 getter fieldAccessorFunc
1240
1241 // The empty value for the field.
1242 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001243
1244 // True if the property can support arch variants false otherwise.
1245 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001246}
1247
Paul Duffin4b8b7932020-05-06 12:35:38 +01001248func (p extractorProperty) String() string {
1249 return p.name
1250}
1251
Paul Duffinc097e362020-03-10 22:50:03 +00001252// Supports extracting common values from a number of instances of a properties
1253// structure into a separate common set of properties.
1254type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001255 // The properties that the extractor can optimize.
1256 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001257}
1258
1259// Create a new common value extractor for the structure type for the supplied
1260// properties struct.
1261//
1262// The returned extractor can be used on any properties structure of the same type
1263// as the supplied set of properties.
1264func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1265 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1266 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001267 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001268 return extractor
1269}
1270
1271// Gather the fields from the supplied structure type from which common values will
1272// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001273//
1274// This is recursive function. If it encounters an embedded field (no field name)
1275// that is a struct then it will recurse into that struct passing in the accessor
1276// for the field. That will then be used in the accessors for the fields in the
1277// embedded struct.
1278func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001279 for f := 0; f < structType.NumField(); f++ {
1280 field := structType.Field(f)
1281 if field.PkgPath != "" {
1282 // Ignore unexported fields.
1283 continue
1284 }
1285
Paul Duffinb07fa512020-03-10 22:17:04 +00001286 // Ignore fields whose value should be kept.
1287 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001288 continue
1289 }
1290
Paul Duffinc459f892020-04-30 18:08:29 +01001291 var filter extractorMetadataPredicate
1292
1293 // Add a filter
1294 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1295 filter = func(metadata propertiesContainer) bool {
1296 if m, ok := metadata.(isHostVariant); ok {
1297 if m.isHostVariant() {
1298 return false
1299 }
1300 }
1301 return true
1302 }
1303 }
1304
Paul Duffinc097e362020-03-10 22:50:03 +00001305 // Save a copy of the field index for use in the function.
1306 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001307
1308 name := field.Name
1309
Paul Duffinc097e362020-03-10 22:50:03 +00001310 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001311 if containingStructAccessor != nil {
1312 // This is an embedded structure so first access the field for the embedded
1313 // structure.
1314 value = containingStructAccessor(value)
1315 }
1316
Paul Duffinc097e362020-03-10 22:50:03 +00001317 // Skip through interface and pointer values to find the structure.
1318 value = getStructValue(value)
1319
Paul Duffin4b8b7932020-05-06 12:35:38 +01001320 defer func() {
1321 if r := recover(); r != nil {
1322 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1323 }
1324 }()
1325
Paul Duffinc097e362020-03-10 22:50:03 +00001326 // Return the field.
1327 return value.Field(fieldIndex)
1328 }
1329
Paul Duffinb07fa512020-03-10 22:17:04 +00001330 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1331 // Gather fields from the embedded structure.
1332 e.gatherFields(field.Type, fieldGetter)
1333 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001334 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001335 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001336 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001337 fieldGetter,
1338 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001339 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001340 }
1341 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001342 }
Paul Duffinc097e362020-03-10 22:50:03 +00001343 }
1344}
1345
1346func getStructValue(value reflect.Value) reflect.Value {
1347foundStruct:
1348 for {
1349 kind := value.Kind()
1350 switch kind {
1351 case reflect.Interface, reflect.Ptr:
1352 value = value.Elem()
1353 case reflect.Struct:
1354 break foundStruct
1355 default:
1356 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1357 }
1358 }
1359 return value
1360}
1361
Paul Duffinf34f6d82020-04-30 15:48:31 +01001362// A container of properties to be optimized.
1363//
1364// Allows additional information to be associated with the properties, e.g. for
1365// filtering.
1366type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001367 fmt.Stringer
1368
Paul Duffinf34f6d82020-04-30 15:48:31 +01001369 // Get the properties that need optimizing.
1370 optimizableProperties() interface{}
1371}
1372
1373// A wrapper for dynamic member properties to allow them to be optimized.
1374type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001375 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001376 dynamicMemberProperties interface{}
1377}
1378
1379func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1380 return c.dynamicMemberProperties
1381}
1382
Paul Duffin4b8b7932020-05-06 12:35:38 +01001383func (c dynamicMemberPropertiesContainer) String() string {
1384 return c.sdkVariant.String()
1385}
1386
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001387// Extract common properties from a slice of property structures of the same type.
1388//
1389// All the property structures must be of the same type.
1390// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001391// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001392//
1393// Iterates over each exported field (capitalized name) and checks to see whether they
1394// have the same value (using DeepEquals) across all the input properties. If it does not then no
1395// change is made. Otherwise, the common value is stored in the field in the commonProperties
1396// and the field in each of the input properties structure is set to its default value.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001397func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001398 commonPropertiesValue := reflect.ValueOf(commonProperties)
1399 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001400
Paul Duffinf34f6d82020-04-30 15:48:31 +01001401 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1402
Paul Duffinb28369a2020-05-04 15:39:59 +01001403 for _, property := range e.properties {
1404 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001405 filter := property.filter
1406 if filter == nil {
1407 filter = func(metadata propertiesContainer) bool {
1408 return true
1409 }
1410 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001411
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001412 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001413 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1414 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001415 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001416
Paul Duffin864e1b42020-05-06 10:23:19 +01001417 // Assume that all the values will be the same.
1418 //
1419 // While similar to this is not quite the same as commonValue == nil. If all the values
1420 // have been filtered out then this will be false but commonValue == nil will be true.
1421 valuesDiffer := false
1422
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001423 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001424 container := sliceValue.Index(i).Interface().(propertiesContainer)
1425 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001426 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001427
Paul Duffinc459f892020-04-30 18:08:29 +01001428 if !filter(container) {
1429 expectedValue := property.emptyValue.Interface()
1430 actualValue := fieldValue.Interface()
1431 if !reflect.DeepEqual(expectedValue, actualValue) {
1432 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1433 }
1434 continue
1435 }
1436
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001437 if commonValue == nil {
1438 // Use the first value as the commonProperties value.
1439 commonValue = &fieldValue
1440 } else {
1441 // If the value does not match the current common value then there is
1442 // no value in common so break out.
1443 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1444 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001445 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001446 break
1447 }
1448 }
1449 }
1450
Paul Duffin864e1b42020-05-06 10:23:19 +01001451 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001452 // and set the input struct's field to the empty value.
1453 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001454 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001455 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001456 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001457 container := sliceValue.Index(i).Interface().(propertiesContainer)
1458 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001459 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001460 fieldValue.Set(emptyValue)
1461 }
1462 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001463
1464 if valuesDiffer && !property.archVariant {
1465 // The values differ but the property does not support arch variants so it
1466 // is an error.
1467 var details strings.Builder
1468 for i := 0; i < sliceValue.Len(); i++ {
1469 container := sliceValue.Index(i).Interface().(propertiesContainer)
1470 itemValue := reflect.ValueOf(container.optimizableProperties())
1471 fieldValue := fieldGetter(itemValue)
1472
1473 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1474 }
1475
1476 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1477 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001478 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001479
1480 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001481}