blob: 59a7640017515d28f70bf34ad4ed56dd98522788 [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 Duffin9b358d72020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin404db3f2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin6cb8f172020-03-12 10:24:35 +000024 "android/soong/cc"
Colin Cross95f7b342020-06-11 11:32:11 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
32var pctx = android.NewPackageContext("android/soong/sdk")
33
Paul Duffin375058f2019-11-29 20:17:53 +000034var (
35 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
36 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000037 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000038 CommandDeps: []string{
39 "${config.Zip2ZipCmd}",
40 },
41 },
42 "destdir")
43
44 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
45 blueprint.RuleParams{
46 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
47 CommandDeps: []string{
48 "${config.SoongZipCmd}",
49 },
50 Rspfile: "$out.rsp",
51 RspfileContent: "$in",
52 },
53 "basedir")
54
55 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
56 blueprint.RuleParams{
57 Command: `${config.MergeZipsCmd} $out $in`,
58 CommandDeps: []string{
59 "${config.MergeZipsCmd}",
60 },
61 })
62)
63
Paul Duffinb645ec82019-11-27 17:43:54 +000064type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090065 content strings.Builder
66 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090067}
68
Paul Duffinb645ec82019-11-27 17:43:54 +000069// generatedFile abstracts operations for writing contents into a file and emit a build rule
70// for the file.
71type generatedFile struct {
72 generatedContents
73 path android.OutputPath
74}
75
Jiyong Park232e7852019-11-04 12:23:40 +090076func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090077 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000078 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090079 }
80}
81
Paul Duffinb645ec82019-11-27 17:43:54 +000082func (gc *generatedContents) Indent() {
83 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090084}
85
Paul Duffinb645ec82019-11-27 17:43:54 +000086func (gc *generatedContents) Dedent() {
87 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090088}
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffinece64f62020-05-11 22:59:25 +010091 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090092}
93
94func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
95 rb := android.NewRuleBuilder()
Paul Duffinece64f62020-05-11 22:59:25 +010096
97 content := gf.content.String()
98
99 // ninja consumes newline characters in rspfile_content. Prevent it by
100 // escaping the backslash in the newline character. The extra backslash
101 // is removed when the rspfile is written to the actual script file
102 content = strings.ReplaceAll(content, "\n", "\\n")
103
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 rb.Command().
105 Implicits(implicits).
Paul Duffinece64f62020-05-11 22:59:25 +0100106 Text("echo").Text(proptools.ShellEscape(content)).
107 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900108 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
109 rb.Command().
110 Text("chmod a+x").Output(gf.path)
111 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
112}
113
Paul Duffin13879572019-11-28 14:31:38 +0000114// Collect all the members.
115//
Paul Duffin2b5887a2020-03-20 17:50:07 +0000116// Returns a list containing type (extracted from the dependency tag) and the variant
117// plus the multilib usages.
118func (s *sdk) collectMembers(ctx android.ModuleContext) {
119 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000120 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
121 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000122 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
123 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900124
Paul Duffin13879572019-11-28 14:31:38 +0000125 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000126 if !memberType.IsInstance(child) {
127 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128 }
Paul Duffin13879572019-11-28 14:31:38 +0000129
Paul Duffin2b5887a2020-03-20 17:50:07 +0000130 // Keep track of which multilib variants are used by the sdk.
131 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
132
133 s.memberRefs = append(s.memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000134
135 // If the member type supports transitive sdk members then recurse down into
136 // its dependencies, otherwise exit traversal.
137 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900138 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000139
140 return false
Paul Duffin13879572019-11-28 14:31:38 +0000141 })
Paul Duffinb0cbec32020-02-25 19:26:33 +0000142}
143
144// Organize the members.
145//
146// The members are first grouped by type and then grouped by name. The order of
147// the types is the order they are referenced in android.SdkMemberTypesRegistry.
148// The names are in the order in which the dependencies were added.
149//
150// Returns the members as well as the multilib setting to use.
Paul Duffin2b5887a2020-03-20 17:50:07 +0000151func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) []*sdkMember {
Paul Duffinb0cbec32020-02-25 19:26:33 +0000152 byType := make(map[android.SdkMemberType][]*sdkMember)
153 byName := make(map[string]*sdkMember)
154
Paul Duffinb0cbec32020-02-25 19:26:33 +0000155 for _, memberRef := range memberRefs {
156 memberType := memberRef.memberType
157 variant := memberRef.variant
158
159 name := ctx.OtherModuleName(variant)
160 member := byName[name]
161 if member == nil {
162 member = &sdkMember{memberType: memberType, name: name}
163 byName[name] = member
164 byType[memberType] = append(byType[memberType], member)
165 }
166
Paul Duffinb0cbec32020-02-25 19:26:33 +0000167 // Only append new variants to the list. This is needed because a member can be both
168 // exported by the sdk and also be a transitive sdk member.
169 member.variants = appendUniqueVariants(member.variants, variant)
170 }
171
Paul Duffin13879572019-11-28 14:31:38 +0000172 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000173 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000174 membersOfType := byType[memberListProperty.memberType]
175 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900176 }
177
Paul Duffin2b5887a2020-03-20 17:50:07 +0000178 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900179}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900180
Paul Duffin72910952020-01-20 18:16:30 +0000181func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
182 for _, v := range variants {
183 if v == newVariant {
184 return variants
185 }
186 }
187 return append(variants, newVariant)
188}
189
Jiyong Park73c54ee2019-10-22 20:31:18 +0900190// SDK directory structure
191// <sdk_root>/
192// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
193// <api_ver>/ : below this directory are all auto-generated
194// Android.bp : definition of 'sdk_snapshot' module is here
195// aidl/
196// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
197// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900198// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199// include/
200// bionic/libc/include/stdlib.h : an exported header file
201// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900202// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900203// <arch>/include/ : arch-specific exported headers
204// <arch>/include_gen/ : arch-specific generated headers
205// <arch>/lib/
206// libFoo.so : a stub library
207
Jiyong Park232e7852019-11-04 12:23:40 +0900208// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900209// This isn't visible to users, so could be changed in future.
210func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
211 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
212}
213
Jiyong Park232e7852019-11-04 12:23:40 +0900214// buildSnapshot is the main function in this source file. It creates rules to copy
215// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinb0cbec32020-02-25 19:26:33 +0000216func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
217
Paul Duffin206433a2020-03-06 12:30:43 +0000218 allMembersByName := make(map[string]struct{})
219 exportedMembersByName := make(map[string]struct{})
Paul Duffinb0cbec32020-02-25 19:26:33 +0000220 var memberRefs []sdkMemberRef
221 for _, sdkVariant := range sdkVariants {
222 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffinacdd3082020-03-02 18:38:15 +0000223
Paul Duffin206433a2020-03-06 12:30:43 +0000224 // Record the names of all the members, both explicitly specified and implicitly
225 // included.
226 for _, memberRef := range sdkVariant.memberRefs {
227 allMembersByName[memberRef.variant.Name()] = struct{}{}
228 }
229
Paul Duffinacdd3082020-03-02 18:38:15 +0000230 // Merge the exported member sets from all sdk variants.
231 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin206433a2020-03-06 12:30:43 +0000232 exportedMembersByName[key] = struct{}{}
Paul Duffinacdd3082020-03-02 18:38:15 +0000233 }
Paul Duffinb0cbec32020-02-25 19:26:33 +0000234 }
235
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000236 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900237
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000238 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000239
240 bpFile := &bpFile{
241 modules: make(map[string]*bpModule),
242 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000243
244 builder := &snapshotBuilder{
Paul Duffin206433a2020-03-06 12:30:43 +0000245 ctx: ctx,
246 sdk: s,
247 version: "current",
248 snapshotDir: snapshotDir.OutputPath,
249 copies: make(map[string]string),
250 filesToZip: []android.Path{bp.path},
251 bpFile: bpFile,
252 prebuiltModules: make(map[string]*bpModule),
253 allMembersByName: allMembersByName,
254 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900255 }
Paul Duffinac37c502019-11-26 18:02:20 +0000256 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900257
Paul Duffin2b5887a2020-03-20 17:50:07 +0000258 members := s.organizeMembers(ctx, memberRefs)
Paul Duffinac897cf2020-02-19 16:19:27 +0000259 for _, member := range members {
Paul Duffin33cedcc2020-02-27 16:00:53 +0000260 memberType := member.memberType
Paul Duffin17ab8832020-03-19 16:11:18 +0000261
Paul Duffinc9103932020-03-17 21:04:24 +0000262 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin17ab8832020-03-19 16:11:18 +0000263
264 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Paul Duffin93520ed2020-03-20 13:35:40 +0000265 s.createMemberSnapshot(memberCtx, member, prebuiltModule)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900266 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900267
Paul Duffine6c0d842020-01-15 14:08:51 +0000268 // Create a transformer that will transform an unversioned module into a versioned module.
269 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
270
Paul Duffin72910952020-01-20 18:16:30 +0000271 // Create a transformer that will transform an unversioned module by replacing any references
272 // to internal members with a unique module name and setting prefer: false.
273 unversionedTransformer := unversionedTransformation{builder: builder}
274
Paul Duffinb645ec82019-11-27 17:43:54 +0000275 for _, unversioned := range builder.prebuiltOrder {
Paul Duffin5b473582020-02-21 16:29:35 +0000276 // Prune any empty property sets.
277 unversioned = unversioned.transform(pruneEmptySetTransformer{})
278
Paul Duffinb645ec82019-11-27 17:43:54 +0000279 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000280 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000281
282 // Transform the unversioned module into a versioned one.
283 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000284 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000285
Paul Duffin72910952020-01-20 18:16:30 +0000286 // Transform the unversioned module to make it suitable for use in the snapshot.
287 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000288 bpFile.AddModule(unversioned)
289 }
290
291 // Create the snapshot module.
292 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000293 var snapshotModuleType string
294 if s.properties.Module_exports {
295 snapshotModuleType = "module_exports_snapshot"
296 } else {
297 snapshotModuleType = "sdk_snapshot"
298 }
299 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000300 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000301
302 // Make sure that the snapshot has the same visibility as the sdk.
303 visibility := android.EffectiveVisibilityRules(ctx, s)
304 if len(visibility) != 0 {
305 snapshotModule.AddProperty("visibility", visibility)
306 }
307
Paul Duffinacdd3082020-03-02 18:38:15 +0000308 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffinac897cf2020-02-19 16:19:27 +0000309
Paul Duffinf3644f12020-04-30 15:48:31 +0100310 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffinacdd3082020-03-02 18:38:15 +0000311 osTypeToMemberProperties := make(map[android.OsType]*sdk)
312 for _, sdkVariant := range sdkVariants {
313 properties := sdkVariant.dynamicMemberTypeListProperties
314 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffin1c58f572020-05-06 12:35:38 +0100315 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffinacdd3082020-03-02 18:38:15 +0000316 }
317
318 // Extract the common lists of members into a separate struct.
319 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin89937322020-03-10 22:50:03 +0000320 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin1c58f572020-05-06 12:35:38 +0100321 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffinacdd3082020-03-02 18:38:15 +0000322
323 // Add properties common to all os types.
324 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
325
326 // Iterate over the os types in a fixed order.
Paul Duffin2b5887a2020-03-20 17:50:07 +0000327 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffinacdd3082020-03-02 18:38:15 +0000328 for _, osType := range s.getPossibleOsTypes() {
329 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
330 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin2b5887a2020-03-20 17:50:07 +0000331
332 // Compile_multilib defaults to both and must always be set to both on the
333 // device and so only needs to be set when targeted at the host and is neither
334 // unspecified or both.
335 multilib := sdkVariant.multilibUsages
336 if (osType.Class == android.Host || osType.Class == android.HostCross) &&
337 multilib != multilibNone && multilib != multilibBoth {
338 osPropertySet.AddProperty("compile_multilib", multilib.String())
339 }
340
Paul Duffinacdd3082020-03-02 18:38:15 +0000341 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000342 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000343 }
Paul Duffinacdd3082020-03-02 18:38:15 +0000344
345 // Prune any empty property sets.
346 snapshotModule.transform(pruneEmptySetTransformer{})
347
Paul Duffinb645ec82019-11-27 17:43:54 +0000348 bpFile.AddModule(snapshotModule)
349
350 // generate Android.bp
351 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
352 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000353
354 bp.build(pctx, ctx, nil)
355
356 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900357
Jiyong Park232e7852019-11-04 12:23:40 +0900358 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000359 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000360 outputDesc := "Building snapshot for " + ctx.ModuleName()
361
362 // If there are no zips to merge then generate the output zip directly.
363 // Otherwise, generate an intermediate zip file into which other zips can be
364 // merged.
365 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000366 var desc string
367 if len(builder.zipsToMerge) == 0 {
368 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000369 desc = outputDesc
370 } else {
371 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000372 desc = "Building intermediate snapshot for " + ctx.ModuleName()
373 }
374
Paul Duffin375058f2019-11-29 20:17:53 +0000375 ctx.Build(pctx, android.BuildParams{
376 Description: desc,
377 Rule: zipFiles,
378 Inputs: filesToZip,
379 Output: zipFile,
380 Args: map[string]string{
381 "basedir": builder.snapshotDir.String(),
382 },
383 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900384
Paul Duffin91547182019-11-12 19:39:36 +0000385 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000386 ctx.Build(pctx, android.BuildParams{
387 Description: outputDesc,
388 Rule: mergeZips,
389 Input: zipFile,
390 Inputs: builder.zipsToMerge,
391 Output: outputZipFile,
392 })
Paul Duffin91547182019-11-12 19:39:36 +0000393 }
394
395 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900396}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000397
Paul Duffin1c58f572020-05-06 12:35:38 +0100398func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
399 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
400 if err != nil {
401 ctx.ModuleErrorf("error extracting common properties: %s", err)
402 }
403}
404
Paul Duffinacdd3082020-03-02 18:38:15 +0000405func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
406 for _, memberListProperty := range s.memberListProperties() {
407 names := memberListProperty.getter(dynamicMemberTypeListProperties)
408 if len(names) > 0 {
Paul Duffin206433a2020-03-06 12:30:43 +0000409 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffinacdd3082020-03-02 18:38:15 +0000410 }
411 }
412}
413
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000414type propertyTag struct {
415 name string
416}
417
Paul Duffinf51768a2020-03-04 14:52:46 +0000418// A BpPropertyTag to add to a property that contains references to other sdk members.
419//
420// This will cause the references to be rewritten to a versioned reference in the version
421// specific instance of a snapshot module.
Paul Duffin206433a2020-03-06 12:30:43 +0000422var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin206433a2020-03-06 12:30:43 +0000423var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000424
Paul Duffinf51768a2020-03-04 14:52:46 +0000425// A BpPropertyTag that indicates the property should only be present in the versioned
426// module.
427//
428// This will cause the property to be removed from the unversioned instance of a
429// snapshot module.
430var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
431
Paul Duffine6c0d842020-01-15 14:08:51 +0000432type unversionedToVersionedTransformation struct {
433 identityTransformation
434 builder *snapshotBuilder
435}
436
Paul Duffine6c0d842020-01-15 14:08:51 +0000437func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
438 // Use a versioned name for the module but remember the original name for the
439 // snapshot.
440 name := module.getValue("name").(string)
Paul Duffin206433a2020-03-06 12:30:43 +0000441 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000442 module.insertAfter("name", "sdk_member_name", name)
443 return module
444}
445
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000446func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin206433a2020-03-06 12:30:43 +0000447 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
448 required := tag == requiredSdkMemberReferencePropertyTag
449 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000450 } else {
451 return value, tag
452 }
453}
454
Paul Duffin72910952020-01-20 18:16:30 +0000455type unversionedTransformation struct {
456 identityTransformation
457 builder *snapshotBuilder
458}
459
460func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
461 // If the module is an internal member then use a unique name for it.
462 name := module.getValue("name").(string)
Paul Duffin206433a2020-03-06 12:30:43 +0000463 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000464
465 // Set prefer: false - this is not strictly required as that is the default.
466 module.insertAfter("name", "prefer", false)
467
468 return module
469}
470
471func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin206433a2020-03-06 12:30:43 +0000472 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
473 required := tag == requiredSdkMemberReferencePropertyTag
474 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffinf51768a2020-03-04 14:52:46 +0000475 } else if tag == sdkVersionedOnlyPropertyTag {
476 // The property is not allowed in the unversioned module so remove it.
477 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000478 } else {
479 return value, tag
480 }
481}
482
Paul Duffin5b473582020-02-21 16:29:35 +0000483type pruneEmptySetTransformer struct {
484 identityTransformation
485}
486
487var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
488
489func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
490 if len(propertySet.properties) == 0 {
491 return nil, nil
492 } else {
493 return propertySet, tag
494 }
495}
496
Paul Duffinb645ec82019-11-27 17:43:54 +0000497func generateBpContents(contents *generatedContents, bpFile *bpFile) {
498 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
499 for _, bpModule := range bpFile.order {
500 contents.Printfln("")
501 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000502 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000503 contents.Printfln("}")
504 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000505}
506
507func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
508 contents.Indent()
Paul Duffin35dbafc2020-03-11 18:17:42 +0000509
510 // Output the properties first, followed by the nested sets. This ensures a
511 // consistent output irrespective of whether property sets are created before
512 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000513 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000514 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000515
Paul Duffin35dbafc2020-03-11 18:17:42 +0000516 switch v := value.(type) {
517 case []string:
518 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000519 if length > 1 {
520 contents.Printfln("%s: [", name)
521 contents.Indent()
522 for i := 0; i < length; i = i + 1 {
Paul Duffin35dbafc2020-03-11 18:17:42 +0000523 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000524 }
525 contents.Dedent()
526 contents.Printfln("],")
527 } else if length == 0 {
528 contents.Printfln("%s: [],", name)
529 } else {
Paul Duffin35dbafc2020-03-11 18:17:42 +0000530 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000531 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000532
Paul Duffin35dbafc2020-03-11 18:17:42 +0000533 case bool:
534 contents.Printfln("%s: %t,", name, v)
535
536 case *bpPropertySet:
537 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000538
539 default:
540 contents.Printfln("%s: %q,", name, value)
541 }
542 }
Paul Duffin35dbafc2020-03-11 18:17:42 +0000543
544 for _, name := range set.order {
545 value := set.getValue(name)
546
547 // Only write property sets in the sets phase.
548 switch v := value.(type) {
549 case *bpPropertySet:
550 contents.Printfln("%s: {", name)
551 outputPropertySet(contents, v)
552 contents.Printfln("},")
553 }
554 }
555
Paul Duffinb645ec82019-11-27 17:43:54 +0000556 contents.Dedent()
557}
558
Paul Duffinac37c502019-11-26 18:02:20 +0000559func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000560 contents := &generatedContents{}
561 generateBpContents(contents, s.builderForTests.bpFile)
562 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000563}
564
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000565type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000566 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000567 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000568 version string
569 snapshotDir android.OutputPath
570 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000571
572 // Map from destination to source of each copy - used to eliminate duplicates and
573 // detect conflicts.
574 copies map[string]string
575
Paul Duffinb645ec82019-11-27 17:43:54 +0000576 filesToZip android.Paths
577 zipsToMerge android.Paths
578
579 prebuiltModules map[string]*bpModule
580 prebuiltOrder []*bpModule
Paul Duffin206433a2020-03-06 12:30:43 +0000581
582 // The set of all members by name.
583 allMembersByName map[string]struct{}
584
585 // The set of exported members by name.
586 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000587}
588
589func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000590 if existing, ok := s.copies[dest]; ok {
591 if existing != src.String() {
592 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
593 return
594 }
595 } else {
596 path := s.snapshotDir.Join(s.ctx, dest)
597 s.ctx.Build(pctx, android.BuildParams{
598 Rule: android.Cp,
599 Input: src,
600 Output: path,
601 })
602 s.filesToZip = append(s.filesToZip, path)
603
604 s.copies[dest] = src.String()
605 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000606}
607
Paul Duffin91547182019-11-12 19:39:36 +0000608func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
609 ctx := s.ctx
610
611 // Repackage the zip file so that the entries are in the destDir directory.
612 // This will allow the zip file to be merged into the snapshot.
613 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000614
615 ctx.Build(pctx, android.BuildParams{
616 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
617 Rule: repackageZip,
618 Input: zipPath,
619 Output: tmpZipPath,
620 Args: map[string]string{
621 "destdir": destDir,
622 },
623 })
Paul Duffin91547182019-11-12 19:39:36 +0000624
625 // Add the repackaged zip file to the files to merge.
626 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
627}
628
Paul Duffin9d8d6092019-12-05 18:19:29 +0000629func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
630 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000631 if s.prebuiltModules[name] != nil {
632 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
633 }
634
635 m := s.bpFile.newModule(moduleType)
636 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000637
Paul Duffin3a6c0952020-03-04 14:22:45 +0000638 variant := member.Variants()[0]
639
Paul Duffin206433a2020-03-06 12:30:43 +0000640 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000641 // An internal member is only referenced from the sdk snapshot which is in the
642 // same package so can be marked as private.
643 m.AddProperty("visibility", []string{"//visibility:private"})
644 } else {
645 // Extract visibility information from a member variant. All variants have the same
646 // visibility so it doesn't matter which one is used.
Paul Duffin3a6c0952020-03-04 14:22:45 +0000647 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000648 if len(visibility) != 0 {
649 m.AddProperty("visibility", visibility)
650 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000651 }
652
Paul Duffinacdd3082020-03-02 18:38:15 +0000653 deviceSupported := false
654 hostSupported := false
655
656 for _, variant := range member.Variants() {
657 osClass := variant.Target().Os.Class
658 if osClass == android.Host || osClass == android.HostCross {
659 hostSupported = true
660 } else if osClass == android.Device {
661 deviceSupported = true
662 }
663 }
664
665 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000666
Paul Duffin3a6c0952020-03-04 14:22:45 +0000667 // Where available copy apex_available properties from the member.
668 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
669 apexAvailable := apexAware.ApexAvailable()
Paul Duffin404db3f2020-03-06 12:30:13 +0000670
Colin Cross95f7b342020-06-11 11:32:11 -0700671 // Add in any baseline apex available settings.
672 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
Paul Duffin404db3f2020-03-06 12:30:13 +0000673
Paul Duffin3a6c0952020-03-04 14:22:45 +0000674 if len(apexAvailable) > 0 {
Paul Duffin404db3f2020-03-06 12:30:13 +0000675 // Remove duplicates and sort.
676 apexAvailable = android.FirstUniqueStrings(apexAvailable)
677 sort.Strings(apexAvailable)
678
Paul Duffin3a6c0952020-03-04 14:22:45 +0000679 m.AddProperty("apex_available", apexAvailable)
680 }
681 }
682
Paul Duffinf51768a2020-03-04 14:52:46 +0000683 // Disable installation in the versioned module of those modules that are ever installable.
684 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
685 if installable.EverInstallable() {
686 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
687 }
688 }
689
Paul Duffinb645ec82019-11-27 17:43:54 +0000690 s.prebuiltModules[name] = m
691 s.prebuiltOrder = append(s.prebuiltOrder, m)
692 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000693}
694
Paul Duffinacdd3082020-03-02 18:38:15 +0000695func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
696 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000697 bpModule.AddProperty("device_supported", false)
698 }
Paul Duffinacdd3082020-03-02 18:38:15 +0000699 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000700 bpModule.AddProperty("host_supported", true)
701 }
702}
703
Paul Duffin206433a2020-03-06 12:30:43 +0000704func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
705 if required {
706 return requiredSdkMemberReferencePropertyTag
707 } else {
708 return optionalSdkMemberReferencePropertyTag
709 }
710}
711
712func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
713 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000714}
715
Paul Duffinb645ec82019-11-27 17:43:54 +0000716// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin206433a2020-03-06 12:30:43 +0000717func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
718 if _, ok := s.allMembersByName[unversionedName]; !ok {
719 if required {
720 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
721 }
722 return unversionedName
723 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000724 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
725}
Paul Duffinb645ec82019-11-27 17:43:54 +0000726
Paul Duffin206433a2020-03-06 12:30:43 +0000727func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000728 var references []string = nil
729 for _, m := range members {
Paul Duffin206433a2020-03-06 12:30:43 +0000730 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000731 }
732 return references
733}
Paul Duffin13879572019-11-28 14:31:38 +0000734
Paul Duffin72910952020-01-20 18:16:30 +0000735// Get an internal name unique to the sdk.
Paul Duffin206433a2020-03-06 12:30:43 +0000736func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
737 if _, ok := s.allMembersByName[unversionedName]; !ok {
738 if required {
739 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
740 }
741 return unversionedName
742 }
743
744 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000745 return s.ctx.ModuleName() + "_" + unversionedName
746 } else {
747 return unversionedName
748 }
749}
750
Paul Duffin206433a2020-03-06 12:30:43 +0000751func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000752 var references []string = nil
753 for _, m := range members {
Paul Duffin206433a2020-03-06 12:30:43 +0000754 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000755 }
756 return references
757}
758
Paul Duffin206433a2020-03-06 12:30:43 +0000759func (s *snapshotBuilder) isInternalMember(memberName string) bool {
760 _, ok := s.exportedMembersByName[memberName]
761 return !ok
762}
763
Paul Duffinb0cbec32020-02-25 19:26:33 +0000764type sdkMemberRef struct {
765 memberType android.SdkMemberType
766 variant android.SdkAware
767}
768
Paul Duffin13879572019-11-28 14:31:38 +0000769var _ android.SdkMember = (*sdkMember)(nil)
770
771type sdkMember struct {
772 memberType android.SdkMemberType
773 name string
774 variants []android.SdkAware
775}
776
777func (m *sdkMember) Name() string {
778 return m.name
779}
780
781func (m *sdkMember) Variants() []android.SdkAware {
782 return m.variants
783}
Paul Duffin33cedcc2020-02-27 16:00:53 +0000784
Paul Duffin5e2e0fd2020-03-16 19:52:08 +0000785// Track usages of multilib variants.
786type multilibUsage int
787
788const (
789 multilibNone multilibUsage = 0
790 multilib32 multilibUsage = 1
791 multilib64 multilibUsage = 2
792 multilibBoth = multilib32 | multilib64
793)
794
795// Add the multilib that is used in the arch type.
796func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
797 multilib := archType.Multilib
798 switch multilib {
799 case "":
800 return m
801 case "lib32":
802 return m | multilib32
803 case "lib64":
804 return m | multilib64
805 default:
806 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
807 }
808}
809
810func (m multilibUsage) String() string {
811 switch m {
812 case multilibNone:
813 return ""
814 case multilib32:
815 return "32"
816 case multilib64:
817 return "64"
818 case multilibBoth:
819 return "both"
820 default:
821 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
822 m, multilibNone, multilib32, multilib64, multilibBoth))
823 }
824}
825
Paul Duffin33cedcc2020-02-27 16:00:53 +0000826type baseInfo struct {
827 Properties android.SdkMemberProperties
828}
829
Paul Duffinf3644f12020-04-30 15:48:31 +0100830func (b *baseInfo) optimizableProperties() interface{} {
831 return b.Properties
832}
833
Paul Duffin33cedcc2020-02-27 16:00:53 +0000834type osTypeSpecificInfo struct {
835 baseInfo
836
Paul Duffin57ee1772020-03-12 20:40:35 +0000837 osType android.OsType
838
Paul Duffin33cedcc2020-02-27 16:00:53 +0000839 // The list of arch type specific info for this os type.
Paul Duffin6562ce12020-03-17 10:58:23 +0000840 //
841 // Nil if there is one variant whose arch type is common
842 archInfos []*archTypeSpecificInfo
Paul Duffin33cedcc2020-02-27 16:00:53 +0000843}
844
Paul Duffin1c58f572020-05-06 12:35:38 +0100845var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
846
Paul Duffin4a4b2d02020-03-17 12:51:37 +0000847type variantPropertiesFactoryFunc func() android.SdkMemberProperties
848
Paul Duffin57ee1772020-03-12 20:40:35 +0000849// Create a new osTypeSpecificInfo for the specified os type and its properties
850// structures populated with information from the variants.
Paul Duffin17ab8832020-03-19 16:11:18 +0000851func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin57ee1772020-03-12 20:40:35 +0000852 osInfo := &osTypeSpecificInfo{
853 osType: osType,
854 }
855
856 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
857 properties := variantPropertiesFactory()
858 properties.Base().Os = osType
859 return properties
860 }
861
862 // Create a structure into which properties common across the architectures in
863 // this os type will be stored.
864 osInfo.Properties = osSpecificVariantPropertiesFactory()
865
866 // Group the variants by arch type.
Paul Duffin17ab8832020-03-19 16:11:18 +0000867 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin57ee1772020-03-12 20:40:35 +0000868 var archTypes []android.ArchType
869 for _, variant := range osTypeVariants {
870 archType := variant.Target().Arch.ArchType
871 archTypeName := archType.Name
872 if _, ok := variantsByArchName[archTypeName]; !ok {
873 archTypes = append(archTypes, archType)
874 }
875
876 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
877 }
878
879 if commonVariants, ok := variantsByArchName["common"]; ok {
880 if len(osTypeVariants) != 1 {
881 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
882 }
883
884 // A common arch type only has one variant and its properties should be treated
885 // as common to the os type.
Paul Duffin17ab8832020-03-19 16:11:18 +0000886 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin57ee1772020-03-12 20:40:35 +0000887 } else {
888 // Create an arch specific info for each supported architecture type.
889 for _, archType := range archTypes {
890 archTypeName := archType.Name
891
892 archVariants := variantsByArchName[archTypeName]
Paul Duffin17ab8832020-03-19 16:11:18 +0000893 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin57ee1772020-03-12 20:40:35 +0000894
895 osInfo.archInfos = append(osInfo.archInfos, archInfo)
896 }
897 }
898
899 return osInfo
900}
901
902// Optimize the properties by extracting common properties from arch type specific
903// properties into os type specific properties.
Paul Duffin1c58f572020-05-06 12:35:38 +0100904func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin57ee1772020-03-12 20:40:35 +0000905 // Nothing to do if there is only a single common architecture.
906 if len(osInfo.archInfos) == 0 {
907 return
908 }
909
Paul Duffin5e2e0fd2020-03-16 19:52:08 +0000910 multilib := multilibNone
Paul Duffin57ee1772020-03-12 20:40:35 +0000911 for _, archInfo := range osInfo.archInfos {
Paul Duffin5e2e0fd2020-03-16 19:52:08 +0000912 multilib = multilib.addArchType(archInfo.archType)
913
Paul Duffin6cb8f172020-03-12 10:24:35 +0000914 // Optimize the arch properties first.
Paul Duffin1c58f572020-05-06 12:35:38 +0100915 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin57ee1772020-03-12 20:40:35 +0000916 }
917
Paul Duffin1c58f572020-05-06 12:35:38 +0100918 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin57ee1772020-03-12 20:40:35 +0000919
920 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin5e2e0fd2020-03-16 19:52:08 +0000921 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin57ee1772020-03-12 20:40:35 +0000922}
923
924// Add the properties for an os to a property set.
925//
926// Maps the properties related to the os variants through to an appropriate
927// module structure that will produce equivalent set of variants when it is
928// processed in a build.
Paul Duffin17ab8832020-03-19 16:11:18 +0000929func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin57ee1772020-03-12 20:40:35 +0000930
931 var osPropertySet android.BpPropertySet
932 var archPropertySet android.BpPropertySet
933 var archOsPrefix string
934 if osInfo.Properties.Base().Os_count == 1 {
935 // There is only one os type present in the variants so don't bother
936 // with adding target specific properties.
937
938 // Create a structure that looks like:
939 // module_type {
940 // name: "...",
941 // ...
942 // <common properties>
943 // ...
944 // <single os type specific properties>
945 //
946 // arch: {
947 // <arch specific sections>
948 // }
949 //
950 osPropertySet = bpModule
951 archPropertySet = osPropertySet.AddPropertySet("arch")
952
953 // Arch specific properties need to be added to an arch specific section
954 // within arch.
955 archOsPrefix = ""
956 } else {
957 // Create a structure that looks like:
958 // module_type {
959 // name: "...",
960 // ...
961 // <common properties>
962 // ...
963 // target: {
964 // <arch independent os specific sections, e.g. android>
965 // ...
966 // <arch and os specific sections, e.g. android_x86>
967 // }
968 //
969 osType := osInfo.osType
970 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
971 archPropertySet = targetPropertySet
972
973 // Arch specific properties need to be added to an os and arch specific
974 // section prefixed with <os>_.
975 archOsPrefix = osType.Name + "_"
976 }
977
978 // Add the os specific but arch independent properties to the module.
Paul Duffin17ab8832020-03-19 16:11:18 +0000979 osInfo.Properties.AddToPropertySet(ctx, osPropertySet)
Paul Duffin57ee1772020-03-12 20:40:35 +0000980
981 // Add arch (and possibly os) specific sections for each set of arch (and possibly
982 // os) specific properties.
983 //
984 // The archInfos list will be empty if the os contains variants for the common
985 // architecture.
986 for _, archInfo := range osInfo.archInfos {
Paul Duffin17ab8832020-03-19 16:11:18 +0000987 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin57ee1772020-03-12 20:40:35 +0000988 }
989}
990
Paul Duffin129171b2020-05-04 15:32:08 +0100991func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
992 osClass := osInfo.osType.Class
993 return osClass == android.Host || osClass == android.HostCross
994}
995
996var _ isHostVariant = (*osTypeSpecificInfo)(nil)
997
Paul Duffin1c58f572020-05-06 12:35:38 +0100998func (osInfo *osTypeSpecificInfo) String() string {
999 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1000}
1001
Paul Duffin33cedcc2020-02-27 16:00:53 +00001002type archTypeSpecificInfo struct {
1003 baseInfo
1004
1005 archType android.ArchType
Paul Duffin6cb8f172020-03-12 10:24:35 +00001006
1007 linkInfos []*linkTypeSpecificInfo
Paul Duffin33cedcc2020-02-27 16:00:53 +00001008}
1009
Paul Duffin1c58f572020-05-06 12:35:38 +01001010var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1011
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001012// Create a new archTypeSpecificInfo for the specified arch type and its properties
1013// structures populated with information from the variants.
Paul Duffin17ab8832020-03-19 16:11:18 +00001014func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001015
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001016 // Create an arch specific info into which the variant properties can be copied.
1017 archInfo := &archTypeSpecificInfo{archType: archType}
1018
1019 // Create the properties into which the arch type specific properties will be
1020 // added.
1021 archInfo.Properties = variantPropertiesFactory()
Paul Duffin6cb8f172020-03-12 10:24:35 +00001022
1023 if len(archVariants) == 1 {
Paul Duffin17ab8832020-03-19 16:11:18 +00001024 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin6cb8f172020-03-12 10:24:35 +00001025 } else {
1026 // There is more than one variant for this arch type which must be differentiated
1027 // by link type.
1028 for _, linkVariant := range archVariants {
1029 linkType := getLinkType(linkVariant)
1030 if linkType == "" {
1031 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1032 } else {
Paul Duffin17ab8832020-03-19 16:11:18 +00001033 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin6cb8f172020-03-12 10:24:35 +00001034
1035 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1036 }
1037 }
1038 }
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001039
1040 return archInfo
1041}
1042
Paul Duffinf3644f12020-04-30 15:48:31 +01001043func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1044 return archInfo.Properties
1045}
1046
Paul Duffin6cb8f172020-03-12 10:24:35 +00001047// Get the link type of the variant
1048//
1049// If the variant is not differentiated by link type then it returns "",
1050// otherwise it returns one of "static" or "shared".
1051func getLinkType(variant android.Module) string {
1052 linkType := ""
1053 if linkable, ok := variant.(cc.LinkableInterface); ok {
1054 if linkable.Shared() && linkable.Static() {
1055 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1056 } else if linkable.Shared() {
1057 linkType = "shared"
1058 } else if linkable.Static() {
1059 linkType = "static"
1060 } else {
1061 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1062 }
1063 }
1064 return linkType
1065}
1066
1067// Optimize the properties by extracting common properties from link type specific
1068// properties into arch type specific properties.
Paul Duffin1c58f572020-05-06 12:35:38 +01001069func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin6cb8f172020-03-12 10:24:35 +00001070 if len(archInfo.linkInfos) == 0 {
1071 return
1072 }
1073
Paul Duffin1c58f572020-05-06 12:35:38 +01001074 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin6cb8f172020-03-12 10:24:35 +00001075}
1076
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001077// Add the properties for an arch type to a property set.
Paul Duffin17ab8832020-03-19 16:11:18 +00001078func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001079 archTypeName := archInfo.archType.Name
1080 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Paul Duffin17ab8832020-03-19 16:11:18 +00001081 archInfo.Properties.AddToPropertySet(ctx, archTypePropertySet)
Paul Duffin6cb8f172020-03-12 10:24:35 +00001082
1083 for _, linkInfo := range archInfo.linkInfos {
1084 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Paul Duffin17ab8832020-03-19 16:11:18 +00001085 linkInfo.Properties.AddToPropertySet(ctx, linkPropertySet)
Paul Duffin6cb8f172020-03-12 10:24:35 +00001086 }
1087}
1088
Paul Duffin1c58f572020-05-06 12:35:38 +01001089func (archInfo *archTypeSpecificInfo) String() string {
1090 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1091}
1092
Paul Duffin6cb8f172020-03-12 10:24:35 +00001093type linkTypeSpecificInfo struct {
1094 baseInfo
1095
1096 linkType string
1097}
1098
Paul Duffin1c58f572020-05-06 12:35:38 +01001099var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1100
Paul Duffin6cb8f172020-03-12 10:24:35 +00001101// Create a new linkTypeSpecificInfo for the specified link type and its properties
1102// structures populated with information from the variant.
Paul Duffin17ab8832020-03-19 16:11:18 +00001103func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin6cb8f172020-03-12 10:24:35 +00001104 linkInfo := &linkTypeSpecificInfo{
1105 baseInfo: baseInfo{
1106 // Create the properties into which the link type specific properties will be
1107 // added.
1108 Properties: variantPropertiesFactory(),
1109 },
1110 linkType: linkType,
1111 }
Paul Duffin17ab8832020-03-19 16:11:18 +00001112 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin6cb8f172020-03-12 10:24:35 +00001113 return linkInfo
Paul Duffin4a4b2d02020-03-17 12:51:37 +00001114}
1115
Paul Duffin1c58f572020-05-06 12:35:38 +01001116func (l *linkTypeSpecificInfo) String() string {
1117 return fmt.Sprintf("LinkType{%s}", l.linkType)
1118}
1119
Paul Duffin17ab8832020-03-19 16:11:18 +00001120type memberContext struct {
1121 sdkMemberContext android.ModuleContext
1122 builder *snapshotBuilder
Paul Duffinc9103932020-03-17 21:04:24 +00001123 memberType android.SdkMemberType
1124 name string
Paul Duffin17ab8832020-03-19 16:11:18 +00001125}
1126
1127func (m *memberContext) SdkModuleContext() android.ModuleContext {
1128 return m.sdkMemberContext
1129}
1130
1131func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1132 return m.builder
1133}
1134
Paul Duffinc9103932020-03-17 21:04:24 +00001135func (m *memberContext) MemberType() android.SdkMemberType {
1136 return m.memberType
1137}
1138
1139func (m *memberContext) Name() string {
1140 return m.name
1141}
1142
Paul Duffin17ab8832020-03-19 16:11:18 +00001143func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin33cedcc2020-02-27 16:00:53 +00001144
1145 memberType := member.memberType
1146
Paul Duffin9b358d72020-03-02 10:16:35 +00001147 // Group the variants by os type.
Paul Duffin17ab8832020-03-19 16:11:18 +00001148 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001149 variants := member.Variants()
1150 for _, variant := range variants {
Paul Duffin9b358d72020-03-02 10:16:35 +00001151 osType := variant.Target().Os
1152 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001153 }
1154
Paul Duffin9b358d72020-03-02 10:16:35 +00001155 osCount := len(variantsByOsType)
Paul Duffin6562ce12020-03-17 10:58:23 +00001156 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffin9b358d72020-03-02 10:16:35 +00001157 properties := memberType.CreateVariantPropertiesStruct()
1158 base := properties.Base()
1159 base.Os_count = osCount
Paul Duffin9b358d72020-03-02 10:16:35 +00001160 return properties
1161 }
Paul Duffin33cedcc2020-02-27 16:00:53 +00001162
Paul Duffin9b358d72020-03-02 10:16:35 +00001163 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffind76209b2020-03-02 11:33:02 +00001164
Paul Duffin9b358d72020-03-02 10:16:35 +00001165 // The set of properties that are common across all architectures and os types.
Paul Duffin6562ce12020-03-17 10:58:23 +00001166 commonProperties := variantPropertiesFactory()
1167 commonProperties.Base().Os = android.CommonOS
Paul Duffin9b358d72020-03-02 10:16:35 +00001168
Paul Duffin89937322020-03-10 22:50:03 +00001169 // Create common value extractor that can be used to optimize the properties.
1170 commonValueExtractor := newCommonValueExtractor(commonProperties)
1171
Paul Duffin9b358d72020-03-02 10:16:35 +00001172 // The list of property structures which are os type specific but common across
1173 // architectures within that os type.
Paul Duffinf3644f12020-04-30 15:48:31 +01001174 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffin9b358d72020-03-02 10:16:35 +00001175
1176 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin17ab8832020-03-19 16:11:18 +00001177 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffin9b358d72020-03-02 10:16:35 +00001178 osTypeToInfo[osType] = osInfo
Paul Duffin6562ce12020-03-17 10:58:23 +00001179 // Add the os specific properties to a list of os type specific yet architecture
1180 // independent properties structs.
Paul Duffinf3644f12020-04-30 15:48:31 +01001181 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffin9b358d72020-03-02 10:16:35 +00001182
Paul Duffin57ee1772020-03-12 20:40:35 +00001183 // Optimize the properties across all the variants for a specific os type.
Paul Duffin1c58f572020-05-06 12:35:38 +01001184 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffind76209b2020-03-02 11:33:02 +00001185 }
Paul Duffin33cedcc2020-02-27 16:00:53 +00001186
Paul Duffin9b358d72020-03-02 10:16:35 +00001187 // Extract properties which are common across all architectures and os types.
Paul Duffin1c58f572020-05-06 12:35:38 +01001188 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001189
Paul Duffin9b358d72020-03-02 10:16:35 +00001190 // Add the common properties to the module.
Paul Duffin17ab8832020-03-19 16:11:18 +00001191 commonProperties.AddToPropertySet(ctx, bpModule)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001192
Paul Duffin9b358d72020-03-02 10:16:35 +00001193 // Create a target property set into which target specific properties can be
1194 // added.
1195 targetPropertySet := bpModule.AddPropertySet("target")
1196
1197 // Iterate over the os types in a fixed order.
1198 for _, osType := range s.getPossibleOsTypes() {
1199 osInfo := osTypeToInfo[osType]
1200 if osInfo == nil {
1201 continue
1202 }
1203
Paul Duffin17ab8832020-03-19 16:11:18 +00001204 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001205 }
Paul Duffin33cedcc2020-02-27 16:00:53 +00001206}
1207
Paul Duffin9b358d72020-03-02 10:16:35 +00001208// Compute the list of possible os types that this sdk could support.
1209func (s *sdk) getPossibleOsTypes() []android.OsType {
1210 var osTypes []android.OsType
1211 for _, osType := range android.OsTypeList {
1212 if s.DeviceSupported() {
1213 if osType.Class == android.Device && osType != android.Fuchsia {
1214 osTypes = append(osTypes, osType)
1215 }
1216 }
1217 if s.HostSupported() {
1218 if osType.Class == android.Host || osType.Class == android.HostCross {
1219 osTypes = append(osTypes, osType)
1220 }
1221 }
1222 }
1223 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1224 return osTypes
1225}
1226
Paul Duffin8de6aa42020-05-04 15:39:59 +01001227// Given a set of properties (struct value), return the value of the field within that
1228// struct (or one of its embedded structs).
Paul Duffin89937322020-03-10 22:50:03 +00001229type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1230
Paul Duffin4d125bd2020-04-30 18:08:29 +01001231// Checks the metadata to determine whether the property should be ignored for the
1232// purposes of common value extraction or not.
1233type extractorMetadataPredicate func(metadata propertiesContainer) bool
1234
1235// Indicates whether optimizable properties are provided by a host variant or
1236// not.
1237type isHostVariant interface {
1238 isHostVariant() bool
1239}
1240
Paul Duffin8de6aa42020-05-04 15:39:59 +01001241// A property that can be optimized by the commonValueExtractor.
1242type extractorProperty struct {
Paul Duffin1c58f572020-05-06 12:35:38 +01001243 // The name of the field for this property.
1244 name string
1245
Paul Duffin4d125bd2020-04-30 18:08:29 +01001246 // Filter that can use metadata associated with the properties being optimized
1247 // to determine whether the field should be ignored during common value
1248 // optimization.
1249 filter extractorMetadataPredicate
1250
Paul Duffin8de6aa42020-05-04 15:39:59 +01001251 // Retrieves the value on which common value optimization will be performed.
1252 getter fieldAccessorFunc
1253
1254 // The empty value for the field.
1255 emptyValue reflect.Value
Paul Duffin08385bf2020-05-06 10:23:19 +01001256
1257 // True if the property can support arch variants false otherwise.
1258 archVariant bool
Paul Duffin8de6aa42020-05-04 15:39:59 +01001259}
1260
Paul Duffin1c58f572020-05-06 12:35:38 +01001261func (p extractorProperty) String() string {
1262 return p.name
1263}
1264
Paul Duffin89937322020-03-10 22:50:03 +00001265// Supports extracting common values from a number of instances of a properties
1266// structure into a separate common set of properties.
1267type commonValueExtractor struct {
Paul Duffin8de6aa42020-05-04 15:39:59 +01001268 // The properties that the extractor can optimize.
1269 properties []extractorProperty
Paul Duffin89937322020-03-10 22:50:03 +00001270}
1271
1272// Create a new common value extractor for the structure type for the supplied
1273// properties struct.
1274//
1275// The returned extractor can be used on any properties structure of the same type
1276// as the supplied set of properties.
1277func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1278 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1279 extractor := &commonValueExtractor{}
Paul Duffin49096812020-03-10 22:17:04 +00001280 extractor.gatherFields(structType, nil)
Paul Duffin89937322020-03-10 22:50:03 +00001281 return extractor
1282}
1283
1284// Gather the fields from the supplied structure type from which common values will
1285// be extracted.
Paul Duffin49096812020-03-10 22:17:04 +00001286//
1287// This is recursive function. If it encounters an embedded field (no field name)
1288// that is a struct then it will recurse into that struct passing in the accessor
1289// for the field. That will then be used in the accessors for the fields in the
1290// embedded struct.
1291func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffin89937322020-03-10 22:50:03 +00001292 for f := 0; f < structType.NumField(); f++ {
1293 field := structType.Field(f)
1294 if field.PkgPath != "" {
1295 // Ignore unexported fields.
1296 continue
1297 }
1298
Paul Duffin49096812020-03-10 22:17:04 +00001299 // Ignore fields whose value should be kept.
1300 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffin89937322020-03-10 22:50:03 +00001301 continue
1302 }
1303
Paul Duffin4d125bd2020-04-30 18:08:29 +01001304 var filter extractorMetadataPredicate
1305
1306 // Add a filter
1307 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1308 filter = func(metadata propertiesContainer) bool {
1309 if m, ok := metadata.(isHostVariant); ok {
1310 if m.isHostVariant() {
1311 return false
1312 }
1313 }
1314 return true
1315 }
1316 }
1317
Paul Duffin89937322020-03-10 22:50:03 +00001318 // Save a copy of the field index for use in the function.
1319 fieldIndex := f
Paul Duffin1c58f572020-05-06 12:35:38 +01001320
1321 name := field.Name
1322
Paul Duffin89937322020-03-10 22:50:03 +00001323 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffin49096812020-03-10 22:17:04 +00001324 if containingStructAccessor != nil {
1325 // This is an embedded structure so first access the field for the embedded
1326 // structure.
1327 value = containingStructAccessor(value)
1328 }
1329
Paul Duffin89937322020-03-10 22:50:03 +00001330 // Skip through interface and pointer values to find the structure.
1331 value = getStructValue(value)
1332
Paul Duffin1c58f572020-05-06 12:35:38 +01001333 defer func() {
1334 if r := recover(); r != nil {
1335 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1336 }
1337 }()
1338
Paul Duffin89937322020-03-10 22:50:03 +00001339 // Return the field.
1340 return value.Field(fieldIndex)
1341 }
1342
Paul Duffin49096812020-03-10 22:17:04 +00001343 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1344 // Gather fields from the embedded structure.
1345 e.gatherFields(field.Type, fieldGetter)
1346 } else {
Paul Duffin8de6aa42020-05-04 15:39:59 +01001347 property := extractorProperty{
Paul Duffin1c58f572020-05-06 12:35:38 +01001348 name,
Paul Duffin4d125bd2020-04-30 18:08:29 +01001349 filter,
Paul Duffin8de6aa42020-05-04 15:39:59 +01001350 fieldGetter,
1351 reflect.Zero(field.Type),
Paul Duffin08385bf2020-05-06 10:23:19 +01001352 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffin8de6aa42020-05-04 15:39:59 +01001353 }
1354 e.properties = append(e.properties, property)
Paul Duffin49096812020-03-10 22:17:04 +00001355 }
Paul Duffin89937322020-03-10 22:50:03 +00001356 }
1357}
1358
1359func getStructValue(value reflect.Value) reflect.Value {
1360foundStruct:
1361 for {
1362 kind := value.Kind()
1363 switch kind {
1364 case reflect.Interface, reflect.Ptr:
1365 value = value.Elem()
1366 case reflect.Struct:
1367 break foundStruct
1368 default:
1369 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1370 }
1371 }
1372 return value
1373}
1374
Paul Duffinf3644f12020-04-30 15:48:31 +01001375// A container of properties to be optimized.
1376//
1377// Allows additional information to be associated with the properties, e.g. for
1378// filtering.
1379type propertiesContainer interface {
Paul Duffin1c58f572020-05-06 12:35:38 +01001380 fmt.Stringer
1381
Paul Duffinf3644f12020-04-30 15:48:31 +01001382 // Get the properties that need optimizing.
1383 optimizableProperties() interface{}
1384}
1385
1386// A wrapper for dynamic member properties to allow them to be optimized.
1387type dynamicMemberPropertiesContainer struct {
Paul Duffin1c58f572020-05-06 12:35:38 +01001388 sdkVariant *sdk
Paul Duffinf3644f12020-04-30 15:48:31 +01001389 dynamicMemberProperties interface{}
1390}
1391
1392func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1393 return c.dynamicMemberProperties
1394}
1395
Paul Duffin1c58f572020-05-06 12:35:38 +01001396func (c dynamicMemberPropertiesContainer) String() string {
1397 return c.sdkVariant.String()
1398}
1399
Paul Duffin33cedcc2020-02-27 16:00:53 +00001400// Extract common properties from a slice of property structures of the same type.
1401//
1402// All the property structures must be of the same type.
1403// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf3644f12020-04-30 15:48:31 +01001404// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin33cedcc2020-02-27 16:00:53 +00001405//
1406// Iterates over each exported field (capitalized name) and checks to see whether they
1407// have the same value (using DeepEquals) across all the input properties. If it does not then no
1408// change is made. Otherwise, the common value is stored in the field in the commonProperties
1409// and the field in each of the input properties structure is set to its default value.
Paul Duffin1c58f572020-05-06 12:35:38 +01001410func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin33cedcc2020-02-27 16:00:53 +00001411 commonPropertiesValue := reflect.ValueOf(commonProperties)
1412 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin33cedcc2020-02-27 16:00:53 +00001413
Paul Duffinf3644f12020-04-30 15:48:31 +01001414 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1415
Paul Duffin8de6aa42020-05-04 15:39:59 +01001416 for _, property := range e.properties {
1417 fieldGetter := property.getter
Paul Duffin4d125bd2020-04-30 18:08:29 +01001418 filter := property.filter
1419 if filter == nil {
1420 filter = func(metadata propertiesContainer) bool {
1421 return true
1422 }
1423 }
Paul Duffin8de6aa42020-05-04 15:39:59 +01001424
Paul Duffin33cedcc2020-02-27 16:00:53 +00001425 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin08385bf2020-05-06 10:23:19 +01001426 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1427 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin33cedcc2020-02-27 16:00:53 +00001428 var commonValue *reflect.Value
Paul Duffin33cedcc2020-02-27 16:00:53 +00001429
Paul Duffin08385bf2020-05-06 10:23:19 +01001430 // Assume that all the values will be the same.
1431 //
1432 // While similar to this is not quite the same as commonValue == nil. If all the values
1433 // have been filtered out then this will be false but commonValue == nil will be true.
1434 valuesDiffer := false
1435
Paul Duffin33cedcc2020-02-27 16:00:53 +00001436 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf3644f12020-04-30 15:48:31 +01001437 container := sliceValue.Index(i).Interface().(propertiesContainer)
1438 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffin89937322020-03-10 22:50:03 +00001439 fieldValue := fieldGetter(itemValue)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001440
Paul Duffin4d125bd2020-04-30 18:08:29 +01001441 if !filter(container) {
1442 expectedValue := property.emptyValue.Interface()
1443 actualValue := fieldValue.Interface()
1444 if !reflect.DeepEqual(expectedValue, actualValue) {
1445 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1446 }
1447 continue
1448 }
1449
Paul Duffin33cedcc2020-02-27 16:00:53 +00001450 if commonValue == nil {
1451 // Use the first value as the commonProperties value.
1452 commonValue = &fieldValue
1453 } else {
1454 // If the value does not match the current common value then there is
1455 // no value in common so break out.
1456 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1457 commonValue = nil
Paul Duffin08385bf2020-05-06 10:23:19 +01001458 valuesDiffer = true
Paul Duffin33cedcc2020-02-27 16:00:53 +00001459 break
1460 }
1461 }
1462 }
1463
Paul Duffin08385bf2020-05-06 10:23:19 +01001464 // If the fields all have common value then store it in the common struct field
Paul Duffin33cedcc2020-02-27 16:00:53 +00001465 // and set the input struct's field to the empty value.
1466 if commonValue != nil {
Paul Duffin8de6aa42020-05-04 15:39:59 +01001467 emptyValue := property.emptyValue
Paul Duffin89937322020-03-10 22:50:03 +00001468 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001469 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf3644f12020-04-30 15:48:31 +01001470 container := sliceValue.Index(i).Interface().(propertiesContainer)
1471 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffin89937322020-03-10 22:50:03 +00001472 fieldValue := fieldGetter(itemValue)
Paul Duffin33cedcc2020-02-27 16:00:53 +00001473 fieldValue.Set(emptyValue)
1474 }
1475 }
Paul Duffin08385bf2020-05-06 10:23:19 +01001476
1477 if valuesDiffer && !property.archVariant {
1478 // The values differ but the property does not support arch variants so it
1479 // is an error.
1480 var details strings.Builder
1481 for i := 0; i < sliceValue.Len(); i++ {
1482 container := sliceValue.Index(i).Interface().(propertiesContainer)
1483 itemValue := reflect.ValueOf(container.optimizableProperties())
1484 fieldValue := fieldGetter(itemValue)
1485
1486 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1487 }
1488
1489 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1490 }
Paul Duffin33cedcc2020-02-27 16:00:53 +00001491 }
Paul Duffin1c58f572020-05-06 12:35:38 +01001492
1493 return nil
Paul Duffin33cedcc2020-02-27 16:00:53 +00001494}