blob: 98937ae5771171b2630244d6013e09fd7e9e0486 [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 Duffin13f02712020-03-06 12:30:43 +0000229 allMembersByName := make(map[string]struct{})
230 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000231 var memberRefs []sdkMemberRef
232 for _, sdkVariant := range sdkVariants {
233 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000234
Paul Duffin13f02712020-03-06 12:30:43 +0000235 // Record the names of all the members, both explicitly specified and implicitly
236 // included.
237 for _, memberRef := range sdkVariant.memberRefs {
238 allMembersByName[memberRef.variant.Name()] = struct{}{}
239 }
240
Paul Duffin865171e2020-03-02 18:38:15 +0000241 // Merge the exported member sets from all sdk variants.
242 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000243 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000244 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000245 }
246
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000247 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900248
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000249 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000250
251 bpFile := &bpFile{
252 modules: make(map[string]*bpModule),
253 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000254
255 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000256 ctx: ctx,
257 sdk: s,
258 version: "current",
259 snapshotDir: snapshotDir.OutputPath,
260 copies: make(map[string]string),
261 filesToZip: []android.Path{bp.path},
262 bpFile: bpFile,
263 prebuiltModules: make(map[string]*bpModule),
264 allMembersByName: allMembersByName,
265 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900266 }
Paul Duffinac37c502019-11-26 18:02:20 +0000267 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900268
Paul Duffin1356d8c2020-02-25 19:26:33 +0000269 members, multilib := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000270 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000271 memberType := member.memberType
272 prebuiltModule := memberType.AddPrebuiltModule(ctx, builder, member)
273 if prebuiltModule == nil {
274 // Fall back to legacy method of building a snapshot
275 memberType.BuildSnapshot(ctx, builder, member)
276 } else {
277 s.createMemberSnapshot(ctx, builder, member, prebuiltModule)
278 }
Jiyong Park73c54ee2019-10-22 20:31:18 +0900279 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900280
Paul Duffine6c0d842020-01-15 14:08:51 +0000281 // Create a transformer that will transform an unversioned module into a versioned module.
282 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
283
Paul Duffin72910952020-01-20 18:16:30 +0000284 // Create a transformer that will transform an unversioned module by replacing any references
285 // to internal members with a unique module name and setting prefer: false.
286 unversionedTransformer := unversionedTransformation{builder: builder}
287
Paul Duffinb645ec82019-11-27 17:43:54 +0000288 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000289 // Prune any empty property sets.
290 unversioned = unversioned.transform(pruneEmptySetTransformer{})
291
Paul Duffinb645ec82019-11-27 17:43:54 +0000292 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000293 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000294
295 // Transform the unversioned module into a versioned one.
296 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000297 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000298
Paul Duffin72910952020-01-20 18:16:30 +0000299 // Transform the unversioned module to make it suitable for use in the snapshot.
300 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000301 bpFile.AddModule(unversioned)
302 }
303
304 // Create the snapshot module.
305 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000306 var snapshotModuleType string
307 if s.properties.Module_exports {
308 snapshotModuleType = "module_exports_snapshot"
309 } else {
310 snapshotModuleType = "sdk_snapshot"
311 }
312 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000313 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000314
315 // Make sure that the snapshot has the same visibility as the sdk.
316 visibility := android.EffectiveVisibilityRules(ctx, s)
317 if len(visibility) != 0 {
318 snapshotModule.AddProperty("visibility", visibility)
319 }
320
Paul Duffin865171e2020-03-02 18:38:15 +0000321 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000322
323 // Compile_multilib defaults to both and must always be set to both on the
324 // device and so only needs to be set when targeted at the host and is neither
325 // unspecified or both.
Paul Duffin865171e2020-03-02 18:38:15 +0000326 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000327 if s.HostSupported() && multilib != "" && multilib != "both" {
Paul Duffin865171e2020-03-02 18:38:15 +0000328 hostSet := targetPropertySet.AddPropertySet("host")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000329 hostSet.AddProperty("compile_multilib", multilib)
330 }
331
Paul Duffin865171e2020-03-02 18:38:15 +0000332 var dynamicMemberPropertiesList []interface{}
333 osTypeToMemberProperties := make(map[android.OsType]*sdk)
334 for _, sdkVariant := range sdkVariants {
335 properties := sdkVariant.dynamicMemberTypeListProperties
336 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
337 dynamicMemberPropertiesList = append(dynamicMemberPropertiesList, properties)
338 }
339
340 // Extract the common lists of members into a separate struct.
341 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000342 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
343 extractor.extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000344
345 // Add properties common to all os types.
346 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
347
348 // Iterate over the os types in a fixed order.
349 for _, osType := range s.getPossibleOsTypes() {
350 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
351 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
352 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000353 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000354 }
Paul Duffin865171e2020-03-02 18:38:15 +0000355
356 // Prune any empty property sets.
357 snapshotModule.transform(pruneEmptySetTransformer{})
358
Paul Duffinb645ec82019-11-27 17:43:54 +0000359 bpFile.AddModule(snapshotModule)
360
361 // generate Android.bp
362 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
363 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000364
365 bp.build(pctx, ctx, nil)
366
367 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900368
Jiyong Park232e7852019-11-04 12:23:40 +0900369 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000370 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000371 outputDesc := "Building snapshot for " + ctx.ModuleName()
372
373 // If there are no zips to merge then generate the output zip directly.
374 // Otherwise, generate an intermediate zip file into which other zips can be
375 // merged.
376 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000377 var desc string
378 if len(builder.zipsToMerge) == 0 {
379 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000380 desc = outputDesc
381 } else {
382 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000383 desc = "Building intermediate snapshot for " + ctx.ModuleName()
384 }
385
Paul Duffin375058f2019-11-29 20:17:53 +0000386 ctx.Build(pctx, android.BuildParams{
387 Description: desc,
388 Rule: zipFiles,
389 Inputs: filesToZip,
390 Output: zipFile,
391 Args: map[string]string{
392 "basedir": builder.snapshotDir.String(),
393 },
394 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900395
Paul Duffin91547182019-11-12 19:39:36 +0000396 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000397 ctx.Build(pctx, android.BuildParams{
398 Description: outputDesc,
399 Rule: mergeZips,
400 Input: zipFile,
401 Inputs: builder.zipsToMerge,
402 Output: outputZipFile,
403 })
Paul Duffin91547182019-11-12 19:39:36 +0000404 }
405
406 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900407}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000408
Paul Duffin865171e2020-03-02 18:38:15 +0000409func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
410 for _, memberListProperty := range s.memberListProperties() {
411 names := memberListProperty.getter(dynamicMemberTypeListProperties)
412 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000413 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000414 }
415 }
416}
417
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000418type propertyTag struct {
419 name string
420}
421
Paul Duffin0cb37b92020-03-04 14:52:46 +0000422// A BpPropertyTag to add to a property that contains references to other sdk members.
423//
424// This will cause the references to be rewritten to a versioned reference in the version
425// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000426var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
427
428// A BpPropertyTag to add to a property that contains references to other sdk members.
429//
430// This will cause the references to be rewritten to a versioned reference in the version
431// specific instance of a snapshot module.
432var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000433
Paul Duffin0cb37b92020-03-04 14:52:46 +0000434// A BpPropertyTag that indicates the property should only be present in the versioned
435// module.
436//
437// This will cause the property to be removed from the unversioned instance of a
438// snapshot module.
439var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
440
Paul Duffine6c0d842020-01-15 14:08:51 +0000441type unversionedToVersionedTransformation struct {
442 identityTransformation
443 builder *snapshotBuilder
444}
445
Paul Duffine6c0d842020-01-15 14:08:51 +0000446func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
447 // Use a versioned name for the module but remember the original name for the
448 // snapshot.
449 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000450 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000451 module.insertAfter("name", "sdk_member_name", name)
452 return module
453}
454
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000455func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000456 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
457 required := tag == requiredSdkMemberReferencePropertyTag
458 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000459 } else {
460 return value, tag
461 }
462}
463
Paul Duffin72910952020-01-20 18:16:30 +0000464type unversionedTransformation struct {
465 identityTransformation
466 builder *snapshotBuilder
467}
468
469func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
470 // If the module is an internal member then use a unique name for it.
471 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000472 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000473
474 // Set prefer: false - this is not strictly required as that is the default.
475 module.insertAfter("name", "prefer", false)
476
477 return module
478}
479
480func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000481 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
482 required := tag == requiredSdkMemberReferencePropertyTag
483 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000484 } else if tag == sdkVersionedOnlyPropertyTag {
485 // The property is not allowed in the unversioned module so remove it.
486 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000487 } else {
488 return value, tag
489 }
490}
491
Paul Duffina78f3a72020-02-21 16:29:35 +0000492type pruneEmptySetTransformer struct {
493 identityTransformation
494}
495
496var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
497
498func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
499 if len(propertySet.properties) == 0 {
500 return nil, nil
501 } else {
502 return propertySet, tag
503 }
504}
505
Paul Duffinb645ec82019-11-27 17:43:54 +0000506func generateBpContents(contents *generatedContents, bpFile *bpFile) {
507 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
508 for _, bpModule := range bpFile.order {
509 contents.Printfln("")
510 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000511 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000512 contents.Printfln("}")
513 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000514}
515
516func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
517 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000518
519 // Output the properties first, followed by the nested sets. This ensures a
520 // consistent output irrespective of whether property sets are created before
521 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000522 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000523 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000524
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000525 switch v := value.(type) {
526 case []string:
527 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000528 if length > 1 {
529 contents.Printfln("%s: [", name)
530 contents.Indent()
531 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000532 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000533 }
534 contents.Dedent()
535 contents.Printfln("],")
536 } else if length == 0 {
537 contents.Printfln("%s: [],", name)
538 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000539 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000540 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000541
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000542 case bool:
543 contents.Printfln("%s: %t,", name, v)
544
545 case *bpPropertySet:
546 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000547
548 default:
549 contents.Printfln("%s: %q,", name, value)
550 }
551 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000552
553 for _, name := range set.order {
554 value := set.getValue(name)
555
556 // Only write property sets in the sets phase.
557 switch v := value.(type) {
558 case *bpPropertySet:
559 contents.Printfln("%s: {", name)
560 outputPropertySet(contents, v)
561 contents.Printfln("},")
562 }
563 }
564
Paul Duffinb645ec82019-11-27 17:43:54 +0000565 contents.Dedent()
566}
567
Paul Duffinac37c502019-11-26 18:02:20 +0000568func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000569 contents := &generatedContents{}
570 generateBpContents(contents, s.builderForTests.bpFile)
571 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000572}
573
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000574type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000575 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000576 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000577 version string
578 snapshotDir android.OutputPath
579 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000580
581 // Map from destination to source of each copy - used to eliminate duplicates and
582 // detect conflicts.
583 copies map[string]string
584
Paul Duffinb645ec82019-11-27 17:43:54 +0000585 filesToZip android.Paths
586 zipsToMerge android.Paths
587
588 prebuiltModules map[string]*bpModule
589 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000590
591 // The set of all members by name.
592 allMembersByName map[string]struct{}
593
594 // The set of exported members by name.
595 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000596}
597
598func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000599 if existing, ok := s.copies[dest]; ok {
600 if existing != src.String() {
601 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
602 return
603 }
604 } else {
605 path := s.snapshotDir.Join(s.ctx, dest)
606 s.ctx.Build(pctx, android.BuildParams{
607 Rule: android.Cp,
608 Input: src,
609 Output: path,
610 })
611 s.filesToZip = append(s.filesToZip, path)
612
613 s.copies[dest] = src.String()
614 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000615}
616
Paul Duffin91547182019-11-12 19:39:36 +0000617func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
618 ctx := s.ctx
619
620 // Repackage the zip file so that the entries are in the destDir directory.
621 // This will allow the zip file to be merged into the snapshot.
622 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000623
624 ctx.Build(pctx, android.BuildParams{
625 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
626 Rule: repackageZip,
627 Input: zipPath,
628 Output: tmpZipPath,
629 Args: map[string]string{
630 "destdir": destDir,
631 },
632 })
Paul Duffin91547182019-11-12 19:39:36 +0000633
634 // Add the repackaged zip file to the files to merge.
635 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
636}
637
Paul Duffin9d8d6092019-12-05 18:19:29 +0000638func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
639 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000640 if s.prebuiltModules[name] != nil {
641 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
642 }
643
644 m := s.bpFile.newModule(moduleType)
645 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000646
Paul Duffinbefa4b92020-03-04 14:22:45 +0000647 variant := member.Variants()[0]
648
Paul Duffin13f02712020-03-06 12:30:43 +0000649 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000650 // An internal member is only referenced from the sdk snapshot which is in the
651 // same package so can be marked as private.
652 m.AddProperty("visibility", []string{"//visibility:private"})
653 } else {
654 // Extract visibility information from a member variant. All variants have the same
655 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000656 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000657 if len(visibility) != 0 {
658 m.AddProperty("visibility", visibility)
659 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000660 }
661
Paul Duffin865171e2020-03-02 18:38:15 +0000662 deviceSupported := false
663 hostSupported := false
664
665 for _, variant := range member.Variants() {
666 osClass := variant.Target().Os.Class
667 if osClass == android.Host || osClass == android.HostCross {
668 hostSupported = true
669 } else if osClass == android.Device {
670 deviceSupported = true
671 }
672 }
673
674 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000675
Paul Duffinbefa4b92020-03-04 14:22:45 +0000676 // Where available copy apex_available properties from the member.
677 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
678 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000679
680 // Add in any white listed apex available settings.
681 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
682
Paul Duffinbefa4b92020-03-04 14:22:45 +0000683 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000684 // Remove duplicates and sort.
685 apexAvailable = android.FirstUniqueStrings(apexAvailable)
686 sort.Strings(apexAvailable)
687
Paul Duffinbefa4b92020-03-04 14:22:45 +0000688 m.AddProperty("apex_available", apexAvailable)
689 }
690 }
691
Paul Duffin0cb37b92020-03-04 14:52:46 +0000692 // Disable installation in the versioned module of those modules that are ever installable.
693 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
694 if installable.EverInstallable() {
695 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
696 }
697 }
698
Paul Duffinb645ec82019-11-27 17:43:54 +0000699 s.prebuiltModules[name] = m
700 s.prebuiltOrder = append(s.prebuiltOrder, m)
701 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000702}
703
Paul Duffin865171e2020-03-02 18:38:15 +0000704func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
705 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000706 bpModule.AddProperty("device_supported", false)
707 }
Paul Duffin865171e2020-03-02 18:38:15 +0000708 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000709 bpModule.AddProperty("host_supported", true)
710 }
711}
712
Paul Duffin13f02712020-03-06 12:30:43 +0000713func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
714 if required {
715 return requiredSdkMemberReferencePropertyTag
716 } else {
717 return optionalSdkMemberReferencePropertyTag
718 }
719}
720
721func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
722 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000723}
724
Paul Duffinb645ec82019-11-27 17:43:54 +0000725// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000726func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
727 if _, ok := s.allMembersByName[unversionedName]; !ok {
728 if required {
729 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
730 }
731 return unversionedName
732 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000733 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
734}
Paul Duffinb645ec82019-11-27 17:43:54 +0000735
Paul Duffin13f02712020-03-06 12:30:43 +0000736func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000737 var references []string = nil
738 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000739 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000740 }
741 return references
742}
Paul Duffin13879572019-11-28 14:31:38 +0000743
Paul Duffin72910952020-01-20 18:16:30 +0000744// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000745func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
746 if _, ok := s.allMembersByName[unversionedName]; !ok {
747 if required {
748 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
749 }
750 return unversionedName
751 }
752
753 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000754 return s.ctx.ModuleName() + "_" + unversionedName
755 } else {
756 return unversionedName
757 }
758}
759
Paul Duffin13f02712020-03-06 12:30:43 +0000760func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000761 var references []string = nil
762 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000763 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000764 }
765 return references
766}
767
Paul Duffin13f02712020-03-06 12:30:43 +0000768func (s *snapshotBuilder) isInternalMember(memberName string) bool {
769 _, ok := s.exportedMembersByName[memberName]
770 return !ok
771}
772
Paul Duffin1356d8c2020-02-25 19:26:33 +0000773type sdkMemberRef struct {
774 memberType android.SdkMemberType
775 variant android.SdkAware
776}
777
Paul Duffin13879572019-11-28 14:31:38 +0000778var _ android.SdkMember = (*sdkMember)(nil)
779
780type sdkMember struct {
781 memberType android.SdkMemberType
782 name string
783 variants []android.SdkAware
784}
785
786func (m *sdkMember) Name() string {
787 return m.name
788}
789
790func (m *sdkMember) Variants() []android.SdkAware {
791 return m.variants
792}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000793
794type baseInfo struct {
795 Properties android.SdkMemberProperties
796}
797
798type osTypeSpecificInfo struct {
799 baseInfo
800
801 // The list of arch type specific info for this os type.
802 archTypes []*archTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +0000803
804 // True if the member has common arch variants for this os type.
805 commonArch bool
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000806}
807
808type archTypeSpecificInfo struct {
809 baseInfo
810
811 archType android.ArchType
812}
813
814func (s *sdk) createMemberSnapshot(sdkModuleContext android.ModuleContext, builder *snapshotBuilder, member *sdkMember, bpModule android.BpModule) {
815
816 memberType := member.memberType
817
Paul Duffina04c1072020-03-02 10:16:35 +0000818 // Group the variants by os type.
819 variantsByOsType := make(map[android.OsType][]android.SdkAware)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000820 variants := member.Variants()
821 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +0000822 osType := variant.Target().Os
823 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000824 }
825
Paul Duffina04c1072020-03-02 10:16:35 +0000826 osCount := len(variantsByOsType)
827 createVariantPropertiesStruct := func(os android.OsType) android.SdkMemberProperties {
828 properties := memberType.CreateVariantPropertiesStruct()
829 base := properties.Base()
830 base.Os_count = osCount
831 base.Os = os
832 return properties
833 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000834
Paul Duffina04c1072020-03-02 10:16:35 +0000835 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +0000836
Paul Duffina04c1072020-03-02 10:16:35 +0000837 // The set of properties that are common across all architectures and os types.
838 commonProperties := createVariantPropertiesStruct(android.CommonOS)
839
Paul Duffinc097e362020-03-10 22:50:03 +0000840 // Create common value extractor that can be used to optimize the properties.
841 commonValueExtractor := newCommonValueExtractor(commonProperties)
842
Paul Duffina04c1072020-03-02 10:16:35 +0000843 // The list of property structures which are os type specific but common across
844 // architectures within that os type.
845 var osSpecificPropertiesList []android.SdkMemberProperties
846
847 for osType, osTypeVariants := range variantsByOsType {
848 // Group the properties for each variant by arch type within the os.
849 osInfo := &osTypeSpecificInfo{}
850 osTypeToInfo[osType] = osInfo
851
852 // Create a structure into which properties common across the architectures in
853 // this os type will be stored. Add it to the list of os type specific yet
854 // architecture independent properties structs.
855 osInfo.Properties = createVariantPropertiesStruct(osType)
856 osSpecificPropertiesList = append(osSpecificPropertiesList, osInfo.Properties)
857
858 commonArch := false
859 for _, variant := range osTypeVariants {
860 var properties android.SdkMemberProperties
861
862 // Get the info associated with the arch type inside the os info.
863 archType := variant.Target().Arch.ArchType
864
865 if archType.Name == "common" {
866 // The arch type is common so populate the common properties directly.
867 properties = osInfo.Properties
868
869 commonArch = true
Paul Duffin14eb4672020-03-02 11:33:02 +0000870 } else {
Paul Duffina04c1072020-03-02 10:16:35 +0000871 archInfo := &archTypeSpecificInfo{archType: archType}
872 properties = createVariantPropertiesStruct(osType)
873 archInfo.Properties = properties
874
875 osInfo.archTypes = append(osInfo.archTypes, archInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +0000876 }
Paul Duffina04c1072020-03-02 10:16:35 +0000877
878 properties.PopulateFromVariant(variant)
Paul Duffin14eb4672020-03-02 11:33:02 +0000879 }
880
Paul Duffina04c1072020-03-02 10:16:35 +0000881 if commonArch {
882 if len(osTypeVariants) != 1 {
883 panic("Expected to only have 1 variant when arch type is common but found " + string(len(variants)))
884 }
885 } else {
886 var archPropertiesList []android.SdkMemberProperties
887 for _, archInfo := range osInfo.archTypes {
888 archPropertiesList = append(archPropertiesList, archInfo.Properties)
889 }
890
Paul Duffinc097e362020-03-10 22:50:03 +0000891 commonValueExtractor.extractCommonProperties(osInfo.Properties, archPropertiesList)
Paul Duffina04c1072020-03-02 10:16:35 +0000892
893 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
894 var multilib string
895 archVariantCount := len(osInfo.archTypes)
896 if archVariantCount == 2 {
897 multilib = "both"
898 } else if archVariantCount == 1 {
899 if strings.HasSuffix(osInfo.archTypes[0].archType.Name, "64") {
900 multilib = "64"
901 } else {
902 multilib = "32"
903 }
904 }
905
906 osInfo.commonArch = commonArch
907 osInfo.Properties.Base().Compile_multilib = multilib
908 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000909 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000910
Paul Duffina04c1072020-03-02 10:16:35 +0000911 // Extract properties which are common across all architectures and os types.
Paul Duffinc097e362020-03-10 22:50:03 +0000912 commonValueExtractor.extractCommonProperties(commonProperties, osSpecificPropertiesList)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000913
Paul Duffina04c1072020-03-02 10:16:35 +0000914 // Add the common properties to the module.
915 commonProperties.AddToPropertySet(sdkModuleContext, builder, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000916
Paul Duffina04c1072020-03-02 10:16:35 +0000917 // Create a target property set into which target specific properties can be
918 // added.
919 targetPropertySet := bpModule.AddPropertySet("target")
920
921 // Iterate over the os types in a fixed order.
922 for _, osType := range s.getPossibleOsTypes() {
923 osInfo := osTypeToInfo[osType]
924 if osInfo == nil {
925 continue
926 }
927
928 var osPropertySet android.BpPropertySet
929 var archOsPrefix string
930 if len(osTypeToInfo) == 1 {
931 // There is only one os type present in the variants sp don't bother
932 // with adding target specific properties.
933
934 // Create a structure that looks like:
935 // module_type {
936 // name: "...",
937 // ...
938 // <common properties>
939 // ...
940 // <single os type specific properties>
941 //
942 // arch: {
943 // <arch specific sections>
944 // }
945 //
946 osPropertySet = bpModule
947
948 // Arch specific properties need to be added to an arch specific section
949 // within arch.
950 archOsPrefix = ""
951 } else {
952 // Create a structure that looks like:
953 // module_type {
954 // name: "...",
955 // ...
956 // <common properties>
957 // ...
958 // target: {
959 // <arch independent os specific sections, e.g. android>
960 // ...
961 // <arch and os specific sections, e.g. android_x86>
962 // }
963 //
964 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
965
966 // Arch specific properties need to be added to an os and arch specific
967 // section prefixed with <os>_.
968 archOsPrefix = osType.Name + "_"
969 }
970
971 osInfo.Properties.AddToPropertySet(sdkModuleContext, builder, osPropertySet)
972 if !osInfo.commonArch {
973 // Either add the arch specific sections into the target or arch sections
974 // depending on whether they will also be os specific.
975 var archPropertySet android.BpPropertySet
976 if archOsPrefix == "" {
977 archPropertySet = osPropertySet.AddPropertySet("arch")
978 } else {
979 archPropertySet = targetPropertySet
980 }
981
982 // Add arch (and possibly os) specific sections for each set of
983 // arch (and possibly os) specific properties.
984 for _, av := range osInfo.archTypes {
985 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + av.archType.Name)
986
987 av.Properties.AddToPropertySet(sdkModuleContext, builder, archTypePropertySet)
988 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000989 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000990 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000991}
992
Paul Duffina04c1072020-03-02 10:16:35 +0000993// Compute the list of possible os types that this sdk could support.
994func (s *sdk) getPossibleOsTypes() []android.OsType {
995 var osTypes []android.OsType
996 for _, osType := range android.OsTypeList {
997 if s.DeviceSupported() {
998 if osType.Class == android.Device && osType != android.Fuchsia {
999 osTypes = append(osTypes, osType)
1000 }
1001 }
1002 if s.HostSupported() {
1003 if osType.Class == android.Host || osType.Class == android.HostCross {
1004 osTypes = append(osTypes, osType)
1005 }
1006 }
1007 }
1008 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1009 return osTypes
1010}
1011
Paul Duffinb07fa512020-03-10 22:17:04 +00001012// Given a struct value, access a field within that struct (or one of its embedded
1013// structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001014type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1015
1016// Supports extracting common values from a number of instances of a properties
1017// structure into a separate common set of properties.
1018type commonValueExtractor struct {
1019 // The getters for every field from which common values can be extracted.
1020 fieldGetters []fieldAccessorFunc
1021}
1022
1023// Create a new common value extractor for the structure type for the supplied
1024// properties struct.
1025//
1026// The returned extractor can be used on any properties structure of the same type
1027// as the supplied set of properties.
1028func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1029 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1030 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001031 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001032 return extractor
1033}
1034
1035// Gather the fields from the supplied structure type from which common values will
1036// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001037//
1038// This is recursive function. If it encounters an embedded field (no field name)
1039// that is a struct then it will recurse into that struct passing in the accessor
1040// for the field. That will then be used in the accessors for the fields in the
1041// embedded struct.
1042func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001043 for f := 0; f < structType.NumField(); f++ {
1044 field := structType.Field(f)
1045 if field.PkgPath != "" {
1046 // Ignore unexported fields.
1047 continue
1048 }
1049
Paul Duffinb07fa512020-03-10 22:17:04 +00001050 // Ignore fields whose value should be kept.
1051 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001052 continue
1053 }
1054
1055 // Save a copy of the field index for use in the function.
1056 fieldIndex := f
1057 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001058 if containingStructAccessor != nil {
1059 // This is an embedded structure so first access the field for the embedded
1060 // structure.
1061 value = containingStructAccessor(value)
1062 }
1063
Paul Duffinc097e362020-03-10 22:50:03 +00001064 // Skip through interface and pointer values to find the structure.
1065 value = getStructValue(value)
1066
1067 // Return the field.
1068 return value.Field(fieldIndex)
1069 }
1070
Paul Duffinb07fa512020-03-10 22:17:04 +00001071 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1072 // Gather fields from the embedded structure.
1073 e.gatherFields(field.Type, fieldGetter)
1074 } else {
1075 e.fieldGetters = append(e.fieldGetters, fieldGetter)
1076 }
Paul Duffinc097e362020-03-10 22:50:03 +00001077 }
1078}
1079
1080func getStructValue(value reflect.Value) reflect.Value {
1081foundStruct:
1082 for {
1083 kind := value.Kind()
1084 switch kind {
1085 case reflect.Interface, reflect.Ptr:
1086 value = value.Elem()
1087 case reflect.Struct:
1088 break foundStruct
1089 default:
1090 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1091 }
1092 }
1093 return value
1094}
1095
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001096// Extract common properties from a slice of property structures of the same type.
1097//
1098// All the property structures must be of the same type.
1099// commonProperties - must be a pointer to the structure into which common properties will be added.
1100// inputPropertiesSlice - must be a slice of input properties structures.
1101//
1102// Iterates over each exported field (capitalized name) and checks to see whether they
1103// have the same value (using DeepEquals) across all the input properties. If it does not then no
1104// change is made. Otherwise, the common value is stored in the field in the commonProperties
1105// and the field in each of the input properties structure is set to its default value.
Paul Duffinc097e362020-03-10 22:50:03 +00001106func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001107 commonPropertiesValue := reflect.ValueOf(commonProperties)
1108 commonStructValue := commonPropertiesValue.Elem()
1109 propertiesStructType := commonStructValue.Type()
1110
1111 // Create an empty structure from which default values for the field can be copied.
1112 emptyStructValue := reflect.New(propertiesStructType).Elem()
1113
Paul Duffinc097e362020-03-10 22:50:03 +00001114 for _, fieldGetter := range e.fieldGetters {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001115 // Check to see if all the structures have the same value for the field. The commonValue
1116 // is nil on entry to the loop and if it is nil on exit then there is no common value,
1117 // otherwise it points to the common value.
1118 var commonValue *reflect.Value
1119 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1120
1121 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001122 itemValue := sliceValue.Index(i)
1123 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001124
1125 if commonValue == nil {
1126 // Use the first value as the commonProperties value.
1127 commonValue = &fieldValue
1128 } else {
1129 // If the value does not match the current common value then there is
1130 // no value in common so break out.
1131 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1132 commonValue = nil
1133 break
1134 }
1135 }
1136 }
1137
1138 // If the fields all have a common value then store it in the common struct field
1139 // and set the input struct's field to the empty value.
1140 if commonValue != nil {
Paul Duffinc097e362020-03-10 22:50:03 +00001141 emptyValue := fieldGetter(emptyStructValue)
1142 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001143 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001144 itemValue := sliceValue.Index(i)
1145 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001146 fieldValue.Set(emptyValue)
1147 }
1148 }
1149 }
1150}