blob: 54d4c792532b1ba12388eb65641aa864b88ab138 [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 Duffin375058f2019-11-29 20:17:53 +000024 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090025 "github.com/google/blueprint/proptools"
26
27 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090028)
29
30var pctx = android.NewPackageContext("android/soong/sdk")
31
Paul Duffin375058f2019-11-29 20:17:53 +000032var (
33 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
34 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000035 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000036 CommandDeps: []string{
37 "${config.Zip2ZipCmd}",
38 },
39 },
40 "destdir")
41
42 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
43 blueprint.RuleParams{
44 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
45 CommandDeps: []string{
46 "${config.SoongZipCmd}",
47 },
48 Rspfile: "$out.rsp",
49 RspfileContent: "$in",
50 },
51 "basedir")
52
53 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
54 blueprint.RuleParams{
55 Command: `${config.MergeZipsCmd} $out $in`,
56 CommandDeps: []string{
57 "${config.MergeZipsCmd}",
58 },
59 })
60)
61
Paul Duffinb645ec82019-11-27 17:43:54 +000062type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090063 content strings.Builder
64 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090065}
66
Paul Duffinb645ec82019-11-27 17:43:54 +000067// generatedFile abstracts operations for writing contents into a file and emit a build rule
68// for the file.
69type generatedFile struct {
70 generatedContents
71 path android.OutputPath
72}
73
Jiyong Park232e7852019-11-04 12:23:40 +090074func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090075 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000076 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090077 }
78}
79
Paul Duffinb645ec82019-11-27 17:43:54 +000080func (gc *generatedContents) Indent() {
81 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090082}
83
Paul Duffinb645ec82019-11-27 17:43:54 +000084func (gc *generatedContents) Dedent() {
85 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090086}
87
Paul Duffinb645ec82019-11-27 17:43:54 +000088func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Jiyong Park9b409bc2019-10-11 14:59:13 +090089 // ninja consumes newline characters in rspfile_content. Prevent it by
Paul Duffin0e0cf1d2019-11-12 19:39:25 +000090 // escaping the backslash in the newline character. The extra backslash
Jiyong Park9b409bc2019-10-11 14:59:13 +090091 // is removed when the rspfile is written to the actual script file
Paul Duffinb645ec82019-11-27 17:43:54 +000092 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090093}
94
95func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
96 rb := android.NewRuleBuilder()
97 // convert \\n to \n
98 rb.Command().
99 Implicits(implicits).
100 Text("echo").Text(proptools.ShellEscape(gf.content.String())).
101 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
102 rb.Command().
103 Text("chmod a+x").Output(gf.path)
104 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
105}
106
Paul Duffin13879572019-11-28 14:31:38 +0000107// Collect all the members.
108//
Paul Duffin1356d8c2020-02-25 19:26:33 +0000109// Returns a list containing type (extracted from the dependency tag) and the variant.
110func (s *sdk) collectMembers(ctx android.ModuleContext) []sdkMemberRef {
111 var memberRefs []sdkMemberRef
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000112 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
113 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000114 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
115 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900116
Paul Duffin13879572019-11-28 14:31:38 +0000117 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000118 if !memberType.IsInstance(child) {
119 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900120 }
Paul Duffin13879572019-11-28 14:31:38 +0000121
Paul Duffin1356d8c2020-02-25 19:26:33 +0000122 memberRefs = append(memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000123
124 // If the member type supports transitive sdk members then recurse down into
125 // its dependencies, otherwise exit traversal.
126 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900127 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000128
129 return false
Paul Duffin13879572019-11-28 14:31:38 +0000130 })
131
Paul Duffin1356d8c2020-02-25 19:26:33 +0000132 return memberRefs
133}
134
135// Organize the members.
136//
137// The members are first grouped by type and then grouped by name. The order of
138// the types is the order they are referenced in android.SdkMemberTypesRegistry.
139// The names are in the order in which the dependencies were added.
140//
141// Returns the members as well as the multilib setting to use.
142func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) ([]*sdkMember, string) {
143 byType := make(map[android.SdkMemberType][]*sdkMember)
144 byName := make(map[string]*sdkMember)
145
146 lib32 := false // True if any of the members have 32 bit version.
147 lib64 := false // True if any of the members have 64 bit version.
148
149 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
161 multilib := variant.Target().Arch.ArchType.Multilib
162 if multilib == "lib32" {
163 lib32 = true
164 } else if multilib == "lib64" {
165 lib64 = true
166 }
167
168 // Only append new variants to the list. This is needed because a member can be both
169 // exported by the sdk and also be a transitive sdk member.
170 member.variants = appendUniqueVariants(member.variants, variant)
171 }
172
Paul Duffin13879572019-11-28 14:31:38 +0000173 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000174 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000175 membersOfType := byType[memberListProperty.memberType]
176 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900177 }
178
Paul Duffin13ad94f2020-02-19 16:19:27 +0000179 // Compute the setting of multilib.
180 var multilib string
181 if lib32 && lib64 {
182 multilib = "both"
183 } else if lib32 {
184 multilib = "32"
185 } else if lib64 {
186 multilib = "64"
187 }
188
189 return members, multilib
Jiyong Park73c54ee2019-10-22 20:31:18 +0900190}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900191
Paul Duffin72910952020-01-20 18:16:30 +0000192func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
193 for _, v := range variants {
194 if v == newVariant {
195 return variants
196 }
197 }
198 return append(variants, newVariant)
199}
200
Jiyong Park73c54ee2019-10-22 20:31:18 +0900201// SDK directory structure
202// <sdk_root>/
203// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
204// <api_ver>/ : below this directory are all auto-generated
205// Android.bp : definition of 'sdk_snapshot' module is here
206// aidl/
207// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
208// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900209// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900210// include/
211// bionic/libc/include/stdlib.h : an exported header file
212// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900213// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900214// <arch>/include/ : arch-specific exported headers
215// <arch>/include_gen/ : arch-specific generated headers
216// <arch>/lib/
217// libFoo.so : a stub library
218
Jiyong Park232e7852019-11-04 12:23:40 +0900219// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900220// This isn't visible to users, so could be changed in future.
221func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
222 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
223}
224
Jiyong Park232e7852019-11-04 12:23:40 +0900225// buildSnapshot is the main function in this source file. It creates rules to copy
226// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000227func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
228
Paul Duffin865171e2020-03-02 18:38:15 +0000229 exportedMembers := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000230 var memberRefs []sdkMemberRef
231 for _, sdkVariant := range sdkVariants {
232 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000233
234 // Merge the exported member sets from all sdk variants.
235 for key, _ := range sdkVariant.getExportedMembers() {
236 exportedMembers[key] = struct{}{}
237 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000238 }
Paul Duffin865171e2020-03-02 18:38:15 +0000239 s.exportedMembers = exportedMembers
Paul Duffin1356d8c2020-02-25 19:26:33 +0000240
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000241 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900242
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000243 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000244
245 bpFile := &bpFile{
246 modules: make(map[string]*bpModule),
247 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000248
249 builder := &snapshotBuilder{
Paul Duffinb645ec82019-11-27 17:43:54 +0000250 ctx: ctx,
Paul Duffine44358f2019-11-26 18:04:12 +0000251 sdk: s,
Paul Duffinb645ec82019-11-27 17:43:54 +0000252 version: "current",
253 snapshotDir: snapshotDir.OutputPath,
Paul Duffinc62a5102019-12-11 18:34:15 +0000254 copies: make(map[string]string),
Paul Duffinb645ec82019-11-27 17:43:54 +0000255 filesToZip: []android.Path{bp.path},
256 bpFile: bpFile,
257 prebuiltModules: make(map[string]*bpModule),
Jiyong Park73c54ee2019-10-22 20:31:18 +0900258 }
Paul Duffinac37c502019-11-26 18:02:20 +0000259 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900260
Paul Duffin1356d8c2020-02-25 19:26:33 +0000261 members, multilib := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000262 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000263 memberType := member.memberType
264 prebuiltModule := memberType.AddPrebuiltModule(ctx, builder, member)
265 if prebuiltModule == nil {
266 // Fall back to legacy method of building a snapshot
267 memberType.BuildSnapshot(ctx, builder, member)
268 } else {
269 s.createMemberSnapshot(ctx, builder, member, prebuiltModule)
270 }
Jiyong Park73c54ee2019-10-22 20:31:18 +0900271 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900272
Paul Duffine6c0d842020-01-15 14:08:51 +0000273 // Create a transformer that will transform an unversioned module into a versioned module.
274 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
275
Paul Duffin72910952020-01-20 18:16:30 +0000276 // Create a transformer that will transform an unversioned module by replacing any references
277 // to internal members with a unique module name and setting prefer: false.
278 unversionedTransformer := unversionedTransformation{builder: builder}
279
Paul Duffinb645ec82019-11-27 17:43:54 +0000280 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000281 // Prune any empty property sets.
282 unversioned = unversioned.transform(pruneEmptySetTransformer{})
283
Paul Duffinb645ec82019-11-27 17:43:54 +0000284 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000285 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000286
287 // Transform the unversioned module into a versioned one.
288 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000289 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000290
Paul Duffin72910952020-01-20 18:16:30 +0000291 // Transform the unversioned module to make it suitable for use in the snapshot.
292 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000293 bpFile.AddModule(unversioned)
294 }
295
296 // Create the snapshot module.
297 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000298 var snapshotModuleType string
299 if s.properties.Module_exports {
300 snapshotModuleType = "module_exports_snapshot"
301 } else {
302 snapshotModuleType = "sdk_snapshot"
303 }
304 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000305 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000306
307 // Make sure that the snapshot has the same visibility as the sdk.
308 visibility := android.EffectiveVisibilityRules(ctx, s)
309 if len(visibility) != 0 {
310 snapshotModule.AddProperty("visibility", visibility)
311 }
312
Paul Duffin865171e2020-03-02 18:38:15 +0000313 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000314
315 // Compile_multilib defaults to both and must always be set to both on the
316 // device and so only needs to be set when targeted at the host and is neither
317 // unspecified or both.
Paul Duffin865171e2020-03-02 18:38:15 +0000318 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000319 if s.HostSupported() && multilib != "" && multilib != "both" {
Paul Duffin865171e2020-03-02 18:38:15 +0000320 hostSet := targetPropertySet.AddPropertySet("host")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000321 hostSet.AddProperty("compile_multilib", multilib)
322 }
323
Paul Duffin865171e2020-03-02 18:38:15 +0000324 var dynamicMemberPropertiesList []interface{}
325 osTypeToMemberProperties := make(map[android.OsType]*sdk)
326 for _, sdkVariant := range sdkVariants {
327 properties := sdkVariant.dynamicMemberTypeListProperties
328 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
329 dynamicMemberPropertiesList = append(dynamicMemberPropertiesList, properties)
330 }
331
332 // Extract the common lists of members into a separate struct.
333 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000334 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
335 extractor.extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000336
337 // Add properties common to all os types.
338 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
339
340 // Iterate over the os types in a fixed order.
341 for _, osType := range s.getPossibleOsTypes() {
342 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
343 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
344 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000345 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000346 }
Paul Duffin865171e2020-03-02 18:38:15 +0000347
348 // Prune any empty property sets.
349 snapshotModule.transform(pruneEmptySetTransformer{})
350
Paul Duffinb645ec82019-11-27 17:43:54 +0000351 bpFile.AddModule(snapshotModule)
352
353 // generate Android.bp
354 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
355 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000356
357 bp.build(pctx, ctx, nil)
358
359 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900360
Jiyong Park232e7852019-11-04 12:23:40 +0900361 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000362 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000363 outputDesc := "Building snapshot for " + ctx.ModuleName()
364
365 // If there are no zips to merge then generate the output zip directly.
366 // Otherwise, generate an intermediate zip file into which other zips can be
367 // merged.
368 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000369 var desc string
370 if len(builder.zipsToMerge) == 0 {
371 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000372 desc = outputDesc
373 } else {
374 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000375 desc = "Building intermediate snapshot for " + ctx.ModuleName()
376 }
377
Paul Duffin375058f2019-11-29 20:17:53 +0000378 ctx.Build(pctx, android.BuildParams{
379 Description: desc,
380 Rule: zipFiles,
381 Inputs: filesToZip,
382 Output: zipFile,
383 Args: map[string]string{
384 "basedir": builder.snapshotDir.String(),
385 },
386 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900387
Paul Duffin91547182019-11-12 19:39:36 +0000388 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000389 ctx.Build(pctx, android.BuildParams{
390 Description: outputDesc,
391 Rule: mergeZips,
392 Input: zipFile,
393 Inputs: builder.zipsToMerge,
394 Output: outputZipFile,
395 })
Paul Duffin91547182019-11-12 19:39:36 +0000396 }
397
398 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900399}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000400
Paul Duffin865171e2020-03-02 18:38:15 +0000401func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
402 for _, memberListProperty := range s.memberListProperties() {
403 names := memberListProperty.getter(dynamicMemberTypeListProperties)
404 if len(names) > 0 {
405 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names))
406 }
407 }
408}
409
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000410type propertyTag struct {
411 name string
412}
413
Paul Duffin0cb37b92020-03-04 14:52:46 +0000414// A BpPropertyTag to add to a property that contains references to other sdk members.
415//
416// This will cause the references to be rewritten to a versioned reference in the version
417// specific instance of a snapshot module.
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000418var sdkMemberReferencePropertyTag = propertyTag{"sdkMemberReferencePropertyTag"}
419
Paul Duffin0cb37b92020-03-04 14:52:46 +0000420// A BpPropertyTag that indicates the property should only be present in the versioned
421// module.
422//
423// This will cause the property to be removed from the unversioned instance of a
424// snapshot module.
425var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
426
Paul Duffine6c0d842020-01-15 14:08:51 +0000427type unversionedToVersionedTransformation struct {
428 identityTransformation
429 builder *snapshotBuilder
430}
431
Paul Duffine6c0d842020-01-15 14:08:51 +0000432func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
433 // Use a versioned name for the module but remember the original name for the
434 // snapshot.
435 name := module.getValue("name").(string)
436 module.setProperty("name", t.builder.versionedSdkMemberName(name))
437 module.insertAfter("name", "sdk_member_name", name)
438 return module
439}
440
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000441func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
442 if tag == sdkMemberReferencePropertyTag {
443 return t.builder.versionedSdkMemberNames(value.([]string)), tag
444 } 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)
457 module.setProperty("name", t.builder.unversionedSdkMemberName(name))
458
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) {
466 if tag == sdkMemberReferencePropertyTag {
467 return t.builder.unversionedSdkMemberNames(value.([]string)), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000468 } else if tag == sdkVersionedOnlyPropertyTag {
469 // The property is not allowed in the unversioned module so remove it.
470 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000471 } else {
472 return value, tag
473 }
474}
475
Paul Duffina78f3a72020-02-21 16:29:35 +0000476type pruneEmptySetTransformer struct {
477 identityTransformation
478}
479
480var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
481
482func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
483 if len(propertySet.properties) == 0 {
484 return nil, nil
485 } else {
486 return propertySet, tag
487 }
488}
489
Paul Duffinb645ec82019-11-27 17:43:54 +0000490func generateBpContents(contents *generatedContents, bpFile *bpFile) {
491 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
492 for _, bpModule := range bpFile.order {
493 contents.Printfln("")
494 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000495 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000496 contents.Printfln("}")
497 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000498}
499
500func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
501 contents.Indent()
502 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000503 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000504
505 reflectedValue := reflect.ValueOf(value)
506 t := reflectedValue.Type()
507
508 kind := t.Kind()
509 switch kind {
510 case reflect.Slice:
511 length := reflectedValue.Len()
512 if length > 1 {
513 contents.Printfln("%s: [", name)
514 contents.Indent()
515 for i := 0; i < length; i = i + 1 {
516 contents.Printfln("%q,", reflectedValue.Index(i).Interface())
517 }
518 contents.Dedent()
519 contents.Printfln("],")
520 } else if length == 0 {
521 contents.Printfln("%s: [],", name)
522 } else {
523 contents.Printfln("%s: [%q],", name, reflectedValue.Index(0).Interface())
524 }
525 case reflect.Bool:
526 contents.Printfln("%s: %t,", name, reflectedValue.Bool())
527
528 case reflect.Ptr:
529 contents.Printfln("%s: {", name)
530 outputPropertySet(contents, reflectedValue.Interface().(*bpPropertySet))
531 contents.Printfln("},")
532
533 default:
534 contents.Printfln("%s: %q,", name, value)
535 }
536 }
537 contents.Dedent()
538}
539
Paul Duffinac37c502019-11-26 18:02:20 +0000540func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000541 contents := &generatedContents{}
542 generateBpContents(contents, s.builderForTests.bpFile)
543 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000544}
545
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000546type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000547 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000548 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000549 version string
550 snapshotDir android.OutputPath
551 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000552
553 // Map from destination to source of each copy - used to eliminate duplicates and
554 // detect conflicts.
555 copies map[string]string
556
Paul Duffinb645ec82019-11-27 17:43:54 +0000557 filesToZip android.Paths
558 zipsToMerge android.Paths
559
560 prebuiltModules map[string]*bpModule
561 prebuiltOrder []*bpModule
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000562}
563
564func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000565 if existing, ok := s.copies[dest]; ok {
566 if existing != src.String() {
567 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
568 return
569 }
570 } else {
571 path := s.snapshotDir.Join(s.ctx, dest)
572 s.ctx.Build(pctx, android.BuildParams{
573 Rule: android.Cp,
574 Input: src,
575 Output: path,
576 })
577 s.filesToZip = append(s.filesToZip, path)
578
579 s.copies[dest] = src.String()
580 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000581}
582
Paul Duffin91547182019-11-12 19:39:36 +0000583func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
584 ctx := s.ctx
585
586 // Repackage the zip file so that the entries are in the destDir directory.
587 // This will allow the zip file to be merged into the snapshot.
588 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000589
590 ctx.Build(pctx, android.BuildParams{
591 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
592 Rule: repackageZip,
593 Input: zipPath,
594 Output: tmpZipPath,
595 Args: map[string]string{
596 "destdir": destDir,
597 },
598 })
Paul Duffin91547182019-11-12 19:39:36 +0000599
600 // Add the repackaged zip file to the files to merge.
601 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
602}
603
Paul Duffin9d8d6092019-12-05 18:19:29 +0000604func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
605 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000606 if s.prebuiltModules[name] != nil {
607 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
608 }
609
610 m := s.bpFile.newModule(moduleType)
611 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000612
Paul Duffinbefa4b92020-03-04 14:22:45 +0000613 variant := member.Variants()[0]
614
Paul Duffin72910952020-01-20 18:16:30 +0000615 if s.sdk.isInternalMember(name) {
616 // An internal member is only referenced from the sdk snapshot which is in the
617 // same package so can be marked as private.
618 m.AddProperty("visibility", []string{"//visibility:private"})
619 } else {
620 // Extract visibility information from a member variant. All variants have the same
621 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000622 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000623 if len(visibility) != 0 {
624 m.AddProperty("visibility", visibility)
625 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000626 }
627
Paul Duffin865171e2020-03-02 18:38:15 +0000628 deviceSupported := false
629 hostSupported := false
630
631 for _, variant := range member.Variants() {
632 osClass := variant.Target().Os.Class
633 if osClass == android.Host || osClass == android.HostCross {
634 hostSupported = true
635 } else if osClass == android.Device {
636 deviceSupported = true
637 }
638 }
639
640 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000641
Paul Duffinbefa4b92020-03-04 14:22:45 +0000642 // Where available copy apex_available properties from the member.
643 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
644 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000645
646 // Add in any white listed apex available settings.
647 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
648
Paul Duffinbefa4b92020-03-04 14:22:45 +0000649 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000650 // Remove duplicates and sort.
651 apexAvailable = android.FirstUniqueStrings(apexAvailable)
652 sort.Strings(apexAvailable)
653
Paul Duffinbefa4b92020-03-04 14:22:45 +0000654 m.AddProperty("apex_available", apexAvailable)
655 }
656 }
657
Paul Duffin0cb37b92020-03-04 14:52:46 +0000658 // Disable installation in the versioned module of those modules that are ever installable.
659 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
660 if installable.EverInstallable() {
661 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
662 }
663 }
664
Paul Duffinb645ec82019-11-27 17:43:54 +0000665 s.prebuiltModules[name] = m
666 s.prebuiltOrder = append(s.prebuiltOrder, m)
667 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000668}
669
Paul Duffin865171e2020-03-02 18:38:15 +0000670func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
671 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000672 bpModule.AddProperty("device_supported", false)
673 }
Paul Duffin865171e2020-03-02 18:38:15 +0000674 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000675 bpModule.AddProperty("host_supported", true)
676 }
677}
678
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000679func (s *snapshotBuilder) SdkMemberReferencePropertyTag() android.BpPropertyTag {
680 return sdkMemberReferencePropertyTag
681}
682
Paul Duffinb645ec82019-11-27 17:43:54 +0000683// Get a versioned name appropriate for the SDK snapshot version being taken.
684func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string) string {
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000685 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
686}
Paul Duffinb645ec82019-11-27 17:43:54 +0000687
688func (s *snapshotBuilder) versionedSdkMemberNames(members []string) []string {
689 var references []string = nil
690 for _, m := range members {
691 references = append(references, s.versionedSdkMemberName(m))
692 }
693 return references
694}
Paul Duffin13879572019-11-28 14:31:38 +0000695
Paul Duffin72910952020-01-20 18:16:30 +0000696// Get an internal name unique to the sdk.
697func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string) string {
698 if s.sdk.isInternalMember(unversionedName) {
699 return s.ctx.ModuleName() + "_" + unversionedName
700 } else {
701 return unversionedName
702 }
703}
704
705func (s *snapshotBuilder) unversionedSdkMemberNames(members []string) []string {
706 var references []string = nil
707 for _, m := range members {
708 references = append(references, s.unversionedSdkMemberName(m))
709 }
710 return references
711}
712
Paul Duffin1356d8c2020-02-25 19:26:33 +0000713type sdkMemberRef struct {
714 memberType android.SdkMemberType
715 variant android.SdkAware
716}
717
Paul Duffin13879572019-11-28 14:31:38 +0000718var _ android.SdkMember = (*sdkMember)(nil)
719
720type sdkMember struct {
721 memberType android.SdkMemberType
722 name string
723 variants []android.SdkAware
724}
725
726func (m *sdkMember) Name() string {
727 return m.name
728}
729
730func (m *sdkMember) Variants() []android.SdkAware {
731 return m.variants
732}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000733
734type baseInfo struct {
735 Properties android.SdkMemberProperties
736}
737
738type osTypeSpecificInfo struct {
739 baseInfo
740
741 // The list of arch type specific info for this os type.
742 archTypes []*archTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +0000743
744 // True if the member has common arch variants for this os type.
745 commonArch bool
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000746}
747
748type archTypeSpecificInfo struct {
749 baseInfo
750
751 archType android.ArchType
752}
753
754func (s *sdk) createMemberSnapshot(sdkModuleContext android.ModuleContext, builder *snapshotBuilder, member *sdkMember, bpModule android.BpModule) {
755
756 memberType := member.memberType
757
Paul Duffina04c1072020-03-02 10:16:35 +0000758 // Group the variants by os type.
759 variantsByOsType := make(map[android.OsType][]android.SdkAware)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000760 variants := member.Variants()
761 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +0000762 osType := variant.Target().Os
763 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000764 }
765
Paul Duffina04c1072020-03-02 10:16:35 +0000766 osCount := len(variantsByOsType)
767 createVariantPropertiesStruct := func(os android.OsType) android.SdkMemberProperties {
768 properties := memberType.CreateVariantPropertiesStruct()
769 base := properties.Base()
770 base.Os_count = osCount
771 base.Os = os
772 return properties
773 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000774
Paul Duffina04c1072020-03-02 10:16:35 +0000775 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +0000776
Paul Duffina04c1072020-03-02 10:16:35 +0000777 // The set of properties that are common across all architectures and os types.
778 commonProperties := createVariantPropertiesStruct(android.CommonOS)
779
Paul Duffinc097e362020-03-10 22:50:03 +0000780 // Create common value extractor that can be used to optimize the properties.
781 commonValueExtractor := newCommonValueExtractor(commonProperties)
782
Paul Duffina04c1072020-03-02 10:16:35 +0000783 // The list of property structures which are os type specific but common across
784 // architectures within that os type.
785 var osSpecificPropertiesList []android.SdkMemberProperties
786
787 for osType, osTypeVariants := range variantsByOsType {
788 // Group the properties for each variant by arch type within the os.
789 osInfo := &osTypeSpecificInfo{}
790 osTypeToInfo[osType] = osInfo
791
792 // Create a structure into which properties common across the architectures in
793 // this os type will be stored. Add it to the list of os type specific yet
794 // architecture independent properties structs.
795 osInfo.Properties = createVariantPropertiesStruct(osType)
796 osSpecificPropertiesList = append(osSpecificPropertiesList, osInfo.Properties)
797
798 commonArch := false
799 for _, variant := range osTypeVariants {
800 var properties android.SdkMemberProperties
801
802 // Get the info associated with the arch type inside the os info.
803 archType := variant.Target().Arch.ArchType
804
805 if archType.Name == "common" {
806 // The arch type is common so populate the common properties directly.
807 properties = osInfo.Properties
808
809 commonArch = true
Paul Duffin14eb4672020-03-02 11:33:02 +0000810 } else {
Paul Duffina04c1072020-03-02 10:16:35 +0000811 archInfo := &archTypeSpecificInfo{archType: archType}
812 properties = createVariantPropertiesStruct(osType)
813 archInfo.Properties = properties
814
815 osInfo.archTypes = append(osInfo.archTypes, archInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +0000816 }
Paul Duffina04c1072020-03-02 10:16:35 +0000817
818 properties.PopulateFromVariant(variant)
Paul Duffin14eb4672020-03-02 11:33:02 +0000819 }
820
Paul Duffina04c1072020-03-02 10:16:35 +0000821 if commonArch {
822 if len(osTypeVariants) != 1 {
823 panic("Expected to only have 1 variant when arch type is common but found " + string(len(variants)))
824 }
825 } else {
826 var archPropertiesList []android.SdkMemberProperties
827 for _, archInfo := range osInfo.archTypes {
828 archPropertiesList = append(archPropertiesList, archInfo.Properties)
829 }
830
Paul Duffinc097e362020-03-10 22:50:03 +0000831 commonValueExtractor.extractCommonProperties(osInfo.Properties, archPropertiesList)
Paul Duffina04c1072020-03-02 10:16:35 +0000832
833 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
834 var multilib string
835 archVariantCount := len(osInfo.archTypes)
836 if archVariantCount == 2 {
837 multilib = "both"
838 } else if archVariantCount == 1 {
839 if strings.HasSuffix(osInfo.archTypes[0].archType.Name, "64") {
840 multilib = "64"
841 } else {
842 multilib = "32"
843 }
844 }
845
846 osInfo.commonArch = commonArch
847 osInfo.Properties.Base().Compile_multilib = multilib
848 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000849 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000850
Paul Duffina04c1072020-03-02 10:16:35 +0000851 // Extract properties which are common across all architectures and os types.
Paul Duffinc097e362020-03-10 22:50:03 +0000852 commonValueExtractor.extractCommonProperties(commonProperties, osSpecificPropertiesList)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000853
Paul Duffina04c1072020-03-02 10:16:35 +0000854 // Add the common properties to the module.
855 commonProperties.AddToPropertySet(sdkModuleContext, builder, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000856
Paul Duffina04c1072020-03-02 10:16:35 +0000857 // Create a target property set into which target specific properties can be
858 // added.
859 targetPropertySet := bpModule.AddPropertySet("target")
860
861 // Iterate over the os types in a fixed order.
862 for _, osType := range s.getPossibleOsTypes() {
863 osInfo := osTypeToInfo[osType]
864 if osInfo == nil {
865 continue
866 }
867
868 var osPropertySet android.BpPropertySet
869 var archOsPrefix string
870 if len(osTypeToInfo) == 1 {
871 // There is only one os type present in the variants sp don't bother
872 // with adding target specific properties.
873
874 // Create a structure that looks like:
875 // module_type {
876 // name: "...",
877 // ...
878 // <common properties>
879 // ...
880 // <single os type specific properties>
881 //
882 // arch: {
883 // <arch specific sections>
884 // }
885 //
886 osPropertySet = bpModule
887
888 // Arch specific properties need to be added to an arch specific section
889 // within arch.
890 archOsPrefix = ""
891 } else {
892 // Create a structure that looks like:
893 // module_type {
894 // name: "...",
895 // ...
896 // <common properties>
897 // ...
898 // target: {
899 // <arch independent os specific sections, e.g. android>
900 // ...
901 // <arch and os specific sections, e.g. android_x86>
902 // }
903 //
904 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
905
906 // Arch specific properties need to be added to an os and arch specific
907 // section prefixed with <os>_.
908 archOsPrefix = osType.Name + "_"
909 }
910
911 osInfo.Properties.AddToPropertySet(sdkModuleContext, builder, osPropertySet)
912 if !osInfo.commonArch {
913 // Either add the arch specific sections into the target or arch sections
914 // depending on whether they will also be os specific.
915 var archPropertySet android.BpPropertySet
916 if archOsPrefix == "" {
917 archPropertySet = osPropertySet.AddPropertySet("arch")
918 } else {
919 archPropertySet = targetPropertySet
920 }
921
922 // Add arch (and possibly os) specific sections for each set of
923 // arch (and possibly os) specific properties.
924 for _, av := range osInfo.archTypes {
925 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + av.archType.Name)
926
927 av.Properties.AddToPropertySet(sdkModuleContext, builder, archTypePropertySet)
928 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000929 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000930 }
931
932 memberType.FinalizeModule(sdkModuleContext, builder, member, bpModule)
933}
934
Paul Duffina04c1072020-03-02 10:16:35 +0000935// Compute the list of possible os types that this sdk could support.
936func (s *sdk) getPossibleOsTypes() []android.OsType {
937 var osTypes []android.OsType
938 for _, osType := range android.OsTypeList {
939 if s.DeviceSupported() {
940 if osType.Class == android.Device && osType != android.Fuchsia {
941 osTypes = append(osTypes, osType)
942 }
943 }
944 if s.HostSupported() {
945 if osType.Class == android.Host || osType.Class == android.HostCross {
946 osTypes = append(osTypes, osType)
947 }
948 }
949 }
950 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
951 return osTypes
952}
953
Paul Duffinb07fa512020-03-10 22:17:04 +0000954// Given a struct value, access a field within that struct (or one of its embedded
955// structs).
Paul Duffinc097e362020-03-10 22:50:03 +0000956type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
957
958// Supports extracting common values from a number of instances of a properties
959// structure into a separate common set of properties.
960type commonValueExtractor struct {
961 // The getters for every field from which common values can be extracted.
962 fieldGetters []fieldAccessorFunc
963}
964
965// Create a new common value extractor for the structure type for the supplied
966// properties struct.
967//
968// The returned extractor can be used on any properties structure of the same type
969// as the supplied set of properties.
970func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
971 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
972 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +0000973 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +0000974 return extractor
975}
976
977// Gather the fields from the supplied structure type from which common values will
978// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +0000979//
980// This is recursive function. If it encounters an embedded field (no field name)
981// that is a struct then it will recurse into that struct passing in the accessor
982// for the field. That will then be used in the accessors for the fields in the
983// embedded struct.
984func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +0000985 for f := 0; f < structType.NumField(); f++ {
986 field := structType.Field(f)
987 if field.PkgPath != "" {
988 // Ignore unexported fields.
989 continue
990 }
991
Paul Duffinb07fa512020-03-10 22:17:04 +0000992 // Ignore fields whose value should be kept.
993 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +0000994 continue
995 }
996
997 // Save a copy of the field index for use in the function.
998 fieldIndex := f
999 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001000 if containingStructAccessor != nil {
1001 // This is an embedded structure so first access the field for the embedded
1002 // structure.
1003 value = containingStructAccessor(value)
1004 }
1005
Paul Duffinc097e362020-03-10 22:50:03 +00001006 // Skip through interface and pointer values to find the structure.
1007 value = getStructValue(value)
1008
1009 // Return the field.
1010 return value.Field(fieldIndex)
1011 }
1012
Paul Duffinb07fa512020-03-10 22:17:04 +00001013 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1014 // Gather fields from the embedded structure.
1015 e.gatherFields(field.Type, fieldGetter)
1016 } else {
1017 e.fieldGetters = append(e.fieldGetters, fieldGetter)
1018 }
Paul Duffinc097e362020-03-10 22:50:03 +00001019 }
1020}
1021
1022func getStructValue(value reflect.Value) reflect.Value {
1023foundStruct:
1024 for {
1025 kind := value.Kind()
1026 switch kind {
1027 case reflect.Interface, reflect.Ptr:
1028 value = value.Elem()
1029 case reflect.Struct:
1030 break foundStruct
1031 default:
1032 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1033 }
1034 }
1035 return value
1036}
1037
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001038// Extract common properties from a slice of property structures of the same type.
1039//
1040// All the property structures must be of the same type.
1041// commonProperties - must be a pointer to the structure into which common properties will be added.
1042// inputPropertiesSlice - must be a slice of input properties structures.
1043//
1044// Iterates over each exported field (capitalized name) and checks to see whether they
1045// have the same value (using DeepEquals) across all the input properties. If it does not then no
1046// change is made. Otherwise, the common value is stored in the field in the commonProperties
1047// and the field in each of the input properties structure is set to its default value.
Paul Duffinc097e362020-03-10 22:50:03 +00001048func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001049 commonPropertiesValue := reflect.ValueOf(commonProperties)
1050 commonStructValue := commonPropertiesValue.Elem()
1051 propertiesStructType := commonStructValue.Type()
1052
1053 // Create an empty structure from which default values for the field can be copied.
1054 emptyStructValue := reflect.New(propertiesStructType).Elem()
1055
Paul Duffinc097e362020-03-10 22:50:03 +00001056 for _, fieldGetter := range e.fieldGetters {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001057 // Check to see if all the structures have the same value for the field. The commonValue
1058 // is nil on entry to the loop and if it is nil on exit then there is no common value,
1059 // otherwise it points to the common value.
1060 var commonValue *reflect.Value
1061 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1062
1063 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001064 itemValue := sliceValue.Index(i)
1065 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001066
1067 if commonValue == nil {
1068 // Use the first value as the commonProperties value.
1069 commonValue = &fieldValue
1070 } else {
1071 // If the value does not match the current common value then there is
1072 // no value in common so break out.
1073 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1074 commonValue = nil
1075 break
1076 }
1077 }
1078 }
1079
1080 // If the fields all have a common value then store it in the common struct field
1081 // and set the input struct's field to the empty value.
1082 if commonValue != nil {
Paul Duffinc097e362020-03-10 22:50:03 +00001083 emptyValue := fieldGetter(emptyStructValue)
1084 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001085 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001086 itemValue := sliceValue.Index(i)
1087 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001088 fieldValue.Set(emptyValue)
1089 }
1090 }
1091 }
1092}