blob: c706d1c15e96b3b6f1a3b85d4565400d5d4daa2c [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
31var pctx = android.NewPackageContext("android/soong/sdk")
32
Paul Duffin375058f2019-11-29 20:17:53 +000033var (
34 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
35 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000036 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000037 CommandDeps: []string{
38 "${config.Zip2ZipCmd}",
39 },
40 },
41 "destdir")
42
43 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
44 blueprint.RuleParams{
45 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
46 CommandDeps: []string{
47 "${config.SoongZipCmd}",
48 },
49 Rspfile: "$out.rsp",
50 RspfileContent: "$in",
51 },
52 "basedir")
53
54 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
55 blueprint.RuleParams{
56 Command: `${config.MergeZipsCmd} $out $in`,
57 CommandDeps: []string{
58 "${config.MergeZipsCmd}",
59 },
60 })
61)
62
Paul Duffinb645ec82019-11-27 17:43:54 +000063type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090064 content strings.Builder
65 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090066}
67
Paul Duffinb645ec82019-11-27 17:43:54 +000068// generatedFile abstracts operations for writing contents into a file and emit a build rule
69// for the file.
70type generatedFile struct {
71 generatedContents
72 path android.OutputPath
73}
74
Jiyong Park232e7852019-11-04 12:23:40 +090075func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090076 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000077 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090078 }
79}
80
Paul Duffinb645ec82019-11-27 17:43:54 +000081func (gc *generatedContents) Indent() {
82 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090083}
84
Paul Duffinb645ec82019-11-27 17:43:54 +000085func (gc *generatedContents) Dedent() {
86 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090087}
88
Paul Duffinb645ec82019-11-27 17:43:54 +000089func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Jiyong Park9b409bc2019-10-11 14:59:13 +090090 // ninja consumes newline characters in rspfile_content. Prevent it by
Paul Duffin0e0cf1d2019-11-12 19:39:25 +000091 // escaping the backslash in the newline character. The extra backslash
Jiyong Park9b409bc2019-10-11 14:59:13 +090092 // is removed when the rspfile is written to the actual script file
Paul Duffinb645ec82019-11-27 17:43:54 +000093 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090094}
95
96func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
97 rb := android.NewRuleBuilder()
98 // convert \\n to \n
99 rb.Command().
100 Implicits(implicits).
101 Text("echo").Text(proptools.ShellEscape(gf.content.String())).
102 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
103 rb.Command().
104 Text("chmod a+x").Output(gf.path)
105 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
106}
107
Paul Duffin13879572019-11-28 14:31:38 +0000108// Collect all the members.
109//
Paul Duffin1356d8c2020-02-25 19:26:33 +0000110// Returns a list containing type (extracted from the dependency tag) and the variant.
111func (s *sdk) collectMembers(ctx android.ModuleContext) []sdkMemberRef {
112 var memberRefs []sdkMemberRef
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000113 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
114 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000115 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
116 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900117
Paul Duffin13879572019-11-28 14:31:38 +0000118 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000119 if !memberType.IsInstance(child) {
120 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900121 }
Paul Duffin13879572019-11-28 14:31:38 +0000122
Paul Duffin1356d8c2020-02-25 19:26:33 +0000123 memberRefs = append(memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000124
125 // If the member type supports transitive sdk members then recurse down into
126 // its dependencies, otherwise exit traversal.
127 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000129
130 return false
Paul Duffin13879572019-11-28 14:31:38 +0000131 })
132
Paul Duffin1356d8c2020-02-25 19:26:33 +0000133 return memberRefs
134}
135
136// Organize the members.
137//
138// The members are first grouped by type and then grouped by name. The order of
139// the types is the order they are referenced in android.SdkMemberTypesRegistry.
140// The names are in the order in which the dependencies were added.
141//
142// Returns the members as well as the multilib setting to use.
143func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) ([]*sdkMember, string) {
144 byType := make(map[android.SdkMemberType][]*sdkMember)
145 byName := make(map[string]*sdkMember)
146
Paul Duffin9c3760e2020-03-16 19:52:08 +0000147 multilib := multilibNone
Paul Duffin1356d8c2020-02-25 19:26:33 +0000148
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
Paul Duffin9c3760e2020-03-16 19:52:08 +0000161 multilib = multilib.addArchType(variant.Target().Arch.ArchType)
Paul Duffin1356d8c2020-02-25 19:26:33 +0000162
163 // Only append new variants to the list. This is needed because a member can be both
164 // exported by the sdk and also be a transitive sdk member.
165 member.variants = appendUniqueVariants(member.variants, variant)
166 }
167
Paul Duffin13879572019-11-28 14:31:38 +0000168 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000169 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000170 membersOfType := byType[memberListProperty.memberType]
171 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900172 }
173
Paul Duffin9c3760e2020-03-16 19:52:08 +0000174 return members, multilib.String()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900175}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900176
Paul Duffin72910952020-01-20 18:16:30 +0000177func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
178 for _, v := range variants {
179 if v == newVariant {
180 return variants
181 }
182 }
183 return append(variants, newVariant)
184}
185
Jiyong Park73c54ee2019-10-22 20:31:18 +0900186// SDK directory structure
187// <sdk_root>/
188// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
189// <api_ver>/ : below this directory are all auto-generated
190// Android.bp : definition of 'sdk_snapshot' module is here
191// aidl/
192// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
193// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900194// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900195// include/
196// bionic/libc/include/stdlib.h : an exported header file
197// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900198// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199// <arch>/include/ : arch-specific exported headers
200// <arch>/include_gen/ : arch-specific generated headers
201// <arch>/lib/
202// libFoo.so : a stub library
203
Jiyong Park232e7852019-11-04 12:23:40 +0900204// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900205// This isn't visible to users, so could be changed in future.
206func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
207 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
208}
209
Jiyong Park232e7852019-11-04 12:23:40 +0900210// buildSnapshot is the main function in this source file. It creates rules to copy
211// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000212func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
213
Paul Duffin13f02712020-03-06 12:30:43 +0000214 allMembersByName := make(map[string]struct{})
215 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000216 var memberRefs []sdkMemberRef
217 for _, sdkVariant := range sdkVariants {
218 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000219
Paul Duffin13f02712020-03-06 12:30:43 +0000220 // Record the names of all the members, both explicitly specified and implicitly
221 // included.
222 for _, memberRef := range sdkVariant.memberRefs {
223 allMembersByName[memberRef.variant.Name()] = struct{}{}
224 }
225
Paul Duffin865171e2020-03-02 18:38:15 +0000226 // Merge the exported member sets from all sdk variants.
227 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000228 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000229 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000230 }
231
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000232 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900233
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000234 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000235
236 bpFile := &bpFile{
237 modules: make(map[string]*bpModule),
238 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000239
240 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000241 ctx: ctx,
242 sdk: s,
243 version: "current",
244 snapshotDir: snapshotDir.OutputPath,
245 copies: make(map[string]string),
246 filesToZip: []android.Path{bp.path},
247 bpFile: bpFile,
248 prebuiltModules: make(map[string]*bpModule),
249 allMembersByName: allMembersByName,
250 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900251 }
Paul Duffinac37c502019-11-26 18:02:20 +0000252 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900253
Paul Duffin1356d8c2020-02-25 19:26:33 +0000254 members, multilib := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000255 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000256 memberType := member.memberType
257 prebuiltModule := memberType.AddPrebuiltModule(ctx, builder, member)
258 if prebuiltModule == nil {
259 // Fall back to legacy method of building a snapshot
260 memberType.BuildSnapshot(ctx, builder, member)
261 } else {
262 s.createMemberSnapshot(ctx, builder, member, prebuiltModule)
263 }
Jiyong Park73c54ee2019-10-22 20:31:18 +0900264 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900265
Paul Duffine6c0d842020-01-15 14:08:51 +0000266 // Create a transformer that will transform an unversioned module into a versioned module.
267 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
268
Paul Duffin72910952020-01-20 18:16:30 +0000269 // Create a transformer that will transform an unversioned module by replacing any references
270 // to internal members with a unique module name and setting prefer: false.
271 unversionedTransformer := unversionedTransformation{builder: builder}
272
Paul Duffinb645ec82019-11-27 17:43:54 +0000273 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000274 // Prune any empty property sets.
275 unversioned = unversioned.transform(pruneEmptySetTransformer{})
276
Paul Duffinb645ec82019-11-27 17:43:54 +0000277 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000278 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000279
280 // Transform the unversioned module into a versioned one.
281 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000282 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000283
Paul Duffin72910952020-01-20 18:16:30 +0000284 // Transform the unversioned module to make it suitable for use in the snapshot.
285 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000286 bpFile.AddModule(unversioned)
287 }
288
289 // Create the snapshot module.
290 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000291 var snapshotModuleType string
292 if s.properties.Module_exports {
293 snapshotModuleType = "module_exports_snapshot"
294 } else {
295 snapshotModuleType = "sdk_snapshot"
296 }
297 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000298 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000299
300 // Make sure that the snapshot has the same visibility as the sdk.
301 visibility := android.EffectiveVisibilityRules(ctx, s)
302 if len(visibility) != 0 {
303 snapshotModule.AddProperty("visibility", visibility)
304 }
305
Paul Duffin865171e2020-03-02 18:38:15 +0000306 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000307
308 // Compile_multilib defaults to both and must always be set to both on the
309 // device and so only needs to be set when targeted at the host and is neither
310 // unspecified or both.
Paul Duffin865171e2020-03-02 18:38:15 +0000311 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000312 if s.HostSupported() && multilib != "" && multilib != "both" {
Paul Duffin865171e2020-03-02 18:38:15 +0000313 hostSet := targetPropertySet.AddPropertySet("host")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000314 hostSet.AddProperty("compile_multilib", multilib)
315 }
316
Paul Duffin865171e2020-03-02 18:38:15 +0000317 var dynamicMemberPropertiesList []interface{}
318 osTypeToMemberProperties := make(map[android.OsType]*sdk)
319 for _, sdkVariant := range sdkVariants {
320 properties := sdkVariant.dynamicMemberTypeListProperties
321 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
322 dynamicMemberPropertiesList = append(dynamicMemberPropertiesList, properties)
323 }
324
325 // Extract the common lists of members into a separate struct.
326 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000327 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
328 extractor.extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000329
330 // Add properties common to all os types.
331 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
332
333 // Iterate over the os types in a fixed order.
334 for _, osType := range s.getPossibleOsTypes() {
335 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
336 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
337 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000338 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000339 }
Paul Duffin865171e2020-03-02 18:38:15 +0000340
341 // Prune any empty property sets.
342 snapshotModule.transform(pruneEmptySetTransformer{})
343
Paul Duffinb645ec82019-11-27 17:43:54 +0000344 bpFile.AddModule(snapshotModule)
345
346 // generate Android.bp
347 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
348 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000349
350 bp.build(pctx, ctx, nil)
351
352 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900353
Jiyong Park232e7852019-11-04 12:23:40 +0900354 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000355 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000356 outputDesc := "Building snapshot for " + ctx.ModuleName()
357
358 // If there are no zips to merge then generate the output zip directly.
359 // Otherwise, generate an intermediate zip file into which other zips can be
360 // merged.
361 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000362 var desc string
363 if len(builder.zipsToMerge) == 0 {
364 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000365 desc = outputDesc
366 } else {
367 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000368 desc = "Building intermediate snapshot for " + ctx.ModuleName()
369 }
370
Paul Duffin375058f2019-11-29 20:17:53 +0000371 ctx.Build(pctx, android.BuildParams{
372 Description: desc,
373 Rule: zipFiles,
374 Inputs: filesToZip,
375 Output: zipFile,
376 Args: map[string]string{
377 "basedir": builder.snapshotDir.String(),
378 },
379 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900380
Paul Duffin91547182019-11-12 19:39:36 +0000381 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000382 ctx.Build(pctx, android.BuildParams{
383 Description: outputDesc,
384 Rule: mergeZips,
385 Input: zipFile,
386 Inputs: builder.zipsToMerge,
387 Output: outputZipFile,
388 })
Paul Duffin91547182019-11-12 19:39:36 +0000389 }
390
391 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900392}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000393
Paul Duffin865171e2020-03-02 18:38:15 +0000394func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
395 for _, memberListProperty := range s.memberListProperties() {
396 names := memberListProperty.getter(dynamicMemberTypeListProperties)
397 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000398 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000399 }
400 }
401}
402
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000403type propertyTag struct {
404 name string
405}
406
Paul Duffin0cb37b92020-03-04 14:52:46 +0000407// A BpPropertyTag to add to a property that contains references to other sdk members.
408//
409// This will cause the references to be rewritten to a versioned reference in the version
410// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000411var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000412var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000413
Paul Duffin0cb37b92020-03-04 14:52:46 +0000414// A BpPropertyTag that indicates the property should only be present in the versioned
415// module.
416//
417// This will cause the property to be removed from the unversioned instance of a
418// snapshot module.
419var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
420
Paul Duffine6c0d842020-01-15 14:08:51 +0000421type unversionedToVersionedTransformation struct {
422 identityTransformation
423 builder *snapshotBuilder
424}
425
Paul Duffine6c0d842020-01-15 14:08:51 +0000426func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
427 // Use a versioned name for the module but remember the original name for the
428 // snapshot.
429 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000430 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000431 module.insertAfter("name", "sdk_member_name", name)
432 return module
433}
434
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000435func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000436 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
437 required := tag == requiredSdkMemberReferencePropertyTag
438 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000439 } else {
440 return value, tag
441 }
442}
443
Paul Duffin72910952020-01-20 18:16:30 +0000444type unversionedTransformation struct {
445 identityTransformation
446 builder *snapshotBuilder
447}
448
449func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
450 // If the module is an internal member then use a unique name for it.
451 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000452 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000453
454 // Set prefer: false - this is not strictly required as that is the default.
455 module.insertAfter("name", "prefer", false)
456
457 return module
458}
459
460func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000461 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
462 required := tag == requiredSdkMemberReferencePropertyTag
463 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000464 } else if tag == sdkVersionedOnlyPropertyTag {
465 // The property is not allowed in the unversioned module so remove it.
466 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000467 } else {
468 return value, tag
469 }
470}
471
Paul Duffina78f3a72020-02-21 16:29:35 +0000472type pruneEmptySetTransformer struct {
473 identityTransformation
474}
475
476var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
477
478func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
479 if len(propertySet.properties) == 0 {
480 return nil, nil
481 } else {
482 return propertySet, tag
483 }
484}
485
Paul Duffinb645ec82019-11-27 17:43:54 +0000486func generateBpContents(contents *generatedContents, bpFile *bpFile) {
487 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
488 for _, bpModule := range bpFile.order {
489 contents.Printfln("")
490 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000491 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000492 contents.Printfln("}")
493 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000494}
495
496func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
497 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000498
499 // Output the properties first, followed by the nested sets. This ensures a
500 // consistent output irrespective of whether property sets are created before
501 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000502 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
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000505 switch v := value.(type) {
506 case []string:
507 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000508 if length > 1 {
509 contents.Printfln("%s: [", name)
510 contents.Indent()
511 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000512 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000513 }
514 contents.Dedent()
515 contents.Printfln("],")
516 } else if length == 0 {
517 contents.Printfln("%s: [],", name)
518 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000519 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000520 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000521
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000522 case bool:
523 contents.Printfln("%s: %t,", name, v)
524
525 case *bpPropertySet:
526 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000527
528 default:
529 contents.Printfln("%s: %q,", name, value)
530 }
531 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000532
533 for _, name := range set.order {
534 value := set.getValue(name)
535
536 // Only write property sets in the sets phase.
537 switch v := value.(type) {
538 case *bpPropertySet:
539 contents.Printfln("%s: {", name)
540 outputPropertySet(contents, v)
541 contents.Printfln("},")
542 }
543 }
544
Paul Duffinb645ec82019-11-27 17:43:54 +0000545 contents.Dedent()
546}
547
Paul Duffinac37c502019-11-26 18:02:20 +0000548func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000549 contents := &generatedContents{}
550 generateBpContents(contents, s.builderForTests.bpFile)
551 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000552}
553
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000554type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000555 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000556 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000557 version string
558 snapshotDir android.OutputPath
559 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000560
561 // Map from destination to source of each copy - used to eliminate duplicates and
562 // detect conflicts.
563 copies map[string]string
564
Paul Duffinb645ec82019-11-27 17:43:54 +0000565 filesToZip android.Paths
566 zipsToMerge android.Paths
567
568 prebuiltModules map[string]*bpModule
569 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000570
571 // The set of all members by name.
572 allMembersByName map[string]struct{}
573
574 // The set of exported members by name.
575 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000576}
577
578func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000579 if existing, ok := s.copies[dest]; ok {
580 if existing != src.String() {
581 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
582 return
583 }
584 } else {
585 path := s.snapshotDir.Join(s.ctx, dest)
586 s.ctx.Build(pctx, android.BuildParams{
587 Rule: android.Cp,
588 Input: src,
589 Output: path,
590 })
591 s.filesToZip = append(s.filesToZip, path)
592
593 s.copies[dest] = src.String()
594 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000595}
596
Paul Duffin91547182019-11-12 19:39:36 +0000597func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
598 ctx := s.ctx
599
600 // Repackage the zip file so that the entries are in the destDir directory.
601 // This will allow the zip file to be merged into the snapshot.
602 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000603
604 ctx.Build(pctx, android.BuildParams{
605 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
606 Rule: repackageZip,
607 Input: zipPath,
608 Output: tmpZipPath,
609 Args: map[string]string{
610 "destdir": destDir,
611 },
612 })
Paul Duffin91547182019-11-12 19:39:36 +0000613
614 // Add the repackaged zip file to the files to merge.
615 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
616}
617
Paul Duffin9d8d6092019-12-05 18:19:29 +0000618func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
619 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000620 if s.prebuiltModules[name] != nil {
621 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
622 }
623
624 m := s.bpFile.newModule(moduleType)
625 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000626
Paul Duffinbefa4b92020-03-04 14:22:45 +0000627 variant := member.Variants()[0]
628
Paul Duffin13f02712020-03-06 12:30:43 +0000629 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000630 // An internal member is only referenced from the sdk snapshot which is in the
631 // same package so can be marked as private.
632 m.AddProperty("visibility", []string{"//visibility:private"})
633 } else {
634 // Extract visibility information from a member variant. All variants have the same
635 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000636 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000637 if len(visibility) != 0 {
638 m.AddProperty("visibility", visibility)
639 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000640 }
641
Paul Duffin865171e2020-03-02 18:38:15 +0000642 deviceSupported := false
643 hostSupported := false
644
645 for _, variant := range member.Variants() {
646 osClass := variant.Target().Os.Class
647 if osClass == android.Host || osClass == android.HostCross {
648 hostSupported = true
649 } else if osClass == android.Device {
650 deviceSupported = true
651 }
652 }
653
654 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000655
Paul Duffinbefa4b92020-03-04 14:22:45 +0000656 // Where available copy apex_available properties from the member.
657 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
658 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000659
660 // Add in any white listed apex available settings.
661 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
662
Paul Duffinbefa4b92020-03-04 14:22:45 +0000663 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000664 // Remove duplicates and sort.
665 apexAvailable = android.FirstUniqueStrings(apexAvailable)
666 sort.Strings(apexAvailable)
667
Paul Duffinbefa4b92020-03-04 14:22:45 +0000668 m.AddProperty("apex_available", apexAvailable)
669 }
670 }
671
Paul Duffin0cb37b92020-03-04 14:52:46 +0000672 // Disable installation in the versioned module of those modules that are ever installable.
673 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
674 if installable.EverInstallable() {
675 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
676 }
677 }
678
Paul Duffinb645ec82019-11-27 17:43:54 +0000679 s.prebuiltModules[name] = m
680 s.prebuiltOrder = append(s.prebuiltOrder, m)
681 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000682}
683
Paul Duffin865171e2020-03-02 18:38:15 +0000684func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
685 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000686 bpModule.AddProperty("device_supported", false)
687 }
Paul Duffin865171e2020-03-02 18:38:15 +0000688 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000689 bpModule.AddProperty("host_supported", true)
690 }
691}
692
Paul Duffin13f02712020-03-06 12:30:43 +0000693func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
694 if required {
695 return requiredSdkMemberReferencePropertyTag
696 } else {
697 return optionalSdkMemberReferencePropertyTag
698 }
699}
700
701func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
702 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000703}
704
Paul Duffinb645ec82019-11-27 17:43:54 +0000705// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000706func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
707 if _, ok := s.allMembersByName[unversionedName]; !ok {
708 if required {
709 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
710 }
711 return unversionedName
712 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000713 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
714}
Paul Duffinb645ec82019-11-27 17:43:54 +0000715
Paul Duffin13f02712020-03-06 12:30:43 +0000716func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000717 var references []string = nil
718 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000719 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000720 }
721 return references
722}
Paul Duffin13879572019-11-28 14:31:38 +0000723
Paul Duffin72910952020-01-20 18:16:30 +0000724// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000725func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
726 if _, ok := s.allMembersByName[unversionedName]; !ok {
727 if required {
728 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
729 }
730 return unversionedName
731 }
732
733 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000734 return s.ctx.ModuleName() + "_" + unversionedName
735 } else {
736 return unversionedName
737 }
738}
739
Paul Duffin13f02712020-03-06 12:30:43 +0000740func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000741 var references []string = nil
742 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000743 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000744 }
745 return references
746}
747
Paul Duffin13f02712020-03-06 12:30:43 +0000748func (s *snapshotBuilder) isInternalMember(memberName string) bool {
749 _, ok := s.exportedMembersByName[memberName]
750 return !ok
751}
752
Paul Duffin1356d8c2020-02-25 19:26:33 +0000753type sdkMemberRef struct {
754 memberType android.SdkMemberType
755 variant android.SdkAware
756}
757
Paul Duffin13879572019-11-28 14:31:38 +0000758var _ android.SdkMember = (*sdkMember)(nil)
759
760type sdkMember struct {
761 memberType android.SdkMemberType
762 name string
763 variants []android.SdkAware
764}
765
766func (m *sdkMember) Name() string {
767 return m.name
768}
769
770func (m *sdkMember) Variants() []android.SdkAware {
771 return m.variants
772}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000773
Paul Duffin9c3760e2020-03-16 19:52:08 +0000774// Track usages of multilib variants.
775type multilibUsage int
776
777const (
778 multilibNone multilibUsage = 0
779 multilib32 multilibUsage = 1
780 multilib64 multilibUsage = 2
781 multilibBoth = multilib32 | multilib64
782)
783
784// Add the multilib that is used in the arch type.
785func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
786 multilib := archType.Multilib
787 switch multilib {
788 case "":
789 return m
790 case "lib32":
791 return m | multilib32
792 case "lib64":
793 return m | multilib64
794 default:
795 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
796 }
797}
798
799func (m multilibUsage) String() string {
800 switch m {
801 case multilibNone:
802 return ""
803 case multilib32:
804 return "32"
805 case multilib64:
806 return "64"
807 case multilibBoth:
808 return "both"
809 default:
810 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
811 m, multilibNone, multilib32, multilib64, multilibBoth))
812 }
813}
814
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000815type baseInfo struct {
816 Properties android.SdkMemberProperties
817}
818
819type osTypeSpecificInfo struct {
820 baseInfo
821
Paul Duffin00e46802020-03-12 20:40:35 +0000822 osType android.OsType
823
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000824 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000825 //
826 // Nil if there is one variant whose arch type is common
827 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000828}
829
Paul Duffinfc8dd232020-03-17 12:51:37 +0000830type variantPropertiesFactoryFunc func() android.SdkMemberProperties
831
Paul Duffin00e46802020-03-12 20:40:35 +0000832// Create a new osTypeSpecificInfo for the specified os type and its properties
833// structures populated with information from the variants.
834func newOsTypeSpecificInfo(osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.SdkAware) *osTypeSpecificInfo {
835 osInfo := &osTypeSpecificInfo{
836 osType: osType,
837 }
838
839 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
840 properties := variantPropertiesFactory()
841 properties.Base().Os = osType
842 return properties
843 }
844
845 // Create a structure into which properties common across the architectures in
846 // this os type will be stored.
847 osInfo.Properties = osSpecificVariantPropertiesFactory()
848
849 // Group the variants by arch type.
850 var variantsByArchName = make(map[string][]android.SdkAware)
851 var archTypes []android.ArchType
852 for _, variant := range osTypeVariants {
853 archType := variant.Target().Arch.ArchType
854 archTypeName := archType.Name
855 if _, ok := variantsByArchName[archTypeName]; !ok {
856 archTypes = append(archTypes, archType)
857 }
858
859 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
860 }
861
862 if commonVariants, ok := variantsByArchName["common"]; ok {
863 if len(osTypeVariants) != 1 {
864 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
865 }
866
867 // A common arch type only has one variant and its properties should be treated
868 // as common to the os type.
869 osInfo.Properties.PopulateFromVariant(commonVariants[0])
870 } else {
871 // Create an arch specific info for each supported architecture type.
872 for _, archType := range archTypes {
873 archTypeName := archType.Name
874
875 archVariants := variantsByArchName[archTypeName]
876 archInfo := newArchSpecificInfo(archType, osSpecificVariantPropertiesFactory, archVariants)
877
878 osInfo.archInfos = append(osInfo.archInfos, archInfo)
879 }
880 }
881
882 return osInfo
883}
884
885// Optimize the properties by extracting common properties from arch type specific
886// properties into os type specific properties.
887func (osInfo *osTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
888 // Nothing to do if there is only a single common architecture.
889 if len(osInfo.archInfos) == 0 {
890 return
891 }
892
Paul Duffin9c3760e2020-03-16 19:52:08 +0000893 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000894 var archPropertiesList []android.SdkMemberProperties
895 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000896 multilib = multilib.addArchType(archInfo.archType)
897
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000898 // Optimize the arch properties first.
899 archInfo.optimizeProperties(commonValueExtractor)
900
Paul Duffin00e46802020-03-12 20:40:35 +0000901 archPropertiesList = append(archPropertiesList, archInfo.Properties)
902 }
903
904 commonValueExtractor.extractCommonProperties(osInfo.Properties, archPropertiesList)
905
906 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000907 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000908}
909
910// Add the properties for an os to a property set.
911//
912// Maps the properties related to the os variants through to an appropriate
913// module structure that will produce equivalent set of variants when it is
914// processed in a build.
915func (osInfo *osTypeSpecificInfo) addToPropertySet(
916 builder *snapshotBuilder,
917 bpModule android.BpModule,
918 targetPropertySet android.BpPropertySet) {
919
920 var osPropertySet android.BpPropertySet
921 var archPropertySet android.BpPropertySet
922 var archOsPrefix string
923 if osInfo.Properties.Base().Os_count == 1 {
924 // There is only one os type present in the variants so don't bother
925 // with adding target specific properties.
926
927 // Create a structure that looks like:
928 // module_type {
929 // name: "...",
930 // ...
931 // <common properties>
932 // ...
933 // <single os type specific properties>
934 //
935 // arch: {
936 // <arch specific sections>
937 // }
938 //
939 osPropertySet = bpModule
940 archPropertySet = osPropertySet.AddPropertySet("arch")
941
942 // Arch specific properties need to be added to an arch specific section
943 // within arch.
944 archOsPrefix = ""
945 } else {
946 // Create a structure that looks like:
947 // module_type {
948 // name: "...",
949 // ...
950 // <common properties>
951 // ...
952 // target: {
953 // <arch independent os specific sections, e.g. android>
954 // ...
955 // <arch and os specific sections, e.g. android_x86>
956 // }
957 //
958 osType := osInfo.osType
959 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
960 archPropertySet = targetPropertySet
961
962 // Arch specific properties need to be added to an os and arch specific
963 // section prefixed with <os>_.
964 archOsPrefix = osType.Name + "_"
965 }
966
967 // Add the os specific but arch independent properties to the module.
968 osInfo.Properties.AddToPropertySet(builder.ctx, builder, osPropertySet)
969
970 // Add arch (and possibly os) specific sections for each set of arch (and possibly
971 // os) specific properties.
972 //
973 // The archInfos list will be empty if the os contains variants for the common
974 // architecture.
975 for _, archInfo := range osInfo.archInfos {
976 archInfo.addToPropertySet(builder, archPropertySet, archOsPrefix)
977 }
978}
979
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000980type archTypeSpecificInfo struct {
981 baseInfo
982
983 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000984
985 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000986}
987
Paul Duffinfc8dd232020-03-17 12:51:37 +0000988// Create a new archTypeSpecificInfo for the specified arch type and its properties
989// structures populated with information from the variants.
990func newArchSpecificInfo(archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.SdkAware) *archTypeSpecificInfo {
991
Paul Duffinfc8dd232020-03-17 12:51:37 +0000992 // Create an arch specific info into which the variant properties can be copied.
993 archInfo := &archTypeSpecificInfo{archType: archType}
994
995 // Create the properties into which the arch type specific properties will be
996 // added.
997 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000998
999 if len(archVariants) == 1 {
1000 archInfo.Properties.PopulateFromVariant(archVariants[0])
1001 } else {
1002 // There is more than one variant for this arch type which must be differentiated
1003 // by link type.
1004 for _, linkVariant := range archVariants {
1005 linkType := getLinkType(linkVariant)
1006 if linkType == "" {
1007 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1008 } else {
1009 linkInfo := newLinkSpecificInfo(linkType, variantPropertiesFactory, linkVariant)
1010
1011 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1012 }
1013 }
1014 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001015
1016 return archInfo
1017}
1018
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001019// Get the link type of the variant
1020//
1021// If the variant is not differentiated by link type then it returns "",
1022// otherwise it returns one of "static" or "shared".
1023func getLinkType(variant android.Module) string {
1024 linkType := ""
1025 if linkable, ok := variant.(cc.LinkableInterface); ok {
1026 if linkable.Shared() && linkable.Static() {
1027 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1028 } else if linkable.Shared() {
1029 linkType = "shared"
1030 } else if linkable.Static() {
1031 linkType = "static"
1032 } else {
1033 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1034 }
1035 }
1036 return linkType
1037}
1038
1039// Optimize the properties by extracting common properties from link type specific
1040// properties into arch type specific properties.
1041func (archInfo *archTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
1042 if len(archInfo.linkInfos) == 0 {
1043 return
1044 }
1045
1046 var propertiesList []android.SdkMemberProperties
1047 for _, linkInfo := range archInfo.linkInfos {
1048 propertiesList = append(propertiesList, linkInfo.Properties)
1049 }
1050
1051 commonValueExtractor.extractCommonProperties(archInfo.Properties, propertiesList)
1052}
1053
Paul Duffinfc8dd232020-03-17 12:51:37 +00001054// Add the properties for an arch type to a property set.
1055func (archInfo *archTypeSpecificInfo) addToPropertySet(builder *snapshotBuilder, archPropertySet android.BpPropertySet, archOsPrefix string) {
1056 archTypeName := archInfo.archType.Name
1057 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
1058 archInfo.Properties.AddToPropertySet(builder.ctx, builder, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001059
1060 for _, linkInfo := range archInfo.linkInfos {
1061 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
1062 linkInfo.Properties.AddToPropertySet(builder.ctx, builder, linkPropertySet)
1063 }
1064}
1065
1066type linkTypeSpecificInfo struct {
1067 baseInfo
1068
1069 linkType string
1070}
1071
1072// Create a new linkTypeSpecificInfo for the specified link type and its properties
1073// structures populated with information from the variant.
1074func newLinkSpecificInfo(linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.SdkAware) *linkTypeSpecificInfo {
1075 linkInfo := &linkTypeSpecificInfo{
1076 baseInfo: baseInfo{
1077 // Create the properties into which the link type specific properties will be
1078 // added.
1079 Properties: variantPropertiesFactory(),
1080 },
1081 linkType: linkType,
1082 }
1083 linkInfo.Properties.PopulateFromVariant(linkVariant)
1084 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001085}
1086
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001087func (s *sdk) createMemberSnapshot(sdkModuleContext android.ModuleContext, builder *snapshotBuilder, member *sdkMember, bpModule android.BpModule) {
1088
1089 memberType := member.memberType
1090
Paul Duffina04c1072020-03-02 10:16:35 +00001091 // Group the variants by os type.
1092 variantsByOsType := make(map[android.OsType][]android.SdkAware)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001093 variants := member.Variants()
1094 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001095 osType := variant.Target().Os
1096 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001097 }
1098
Paul Duffina04c1072020-03-02 10:16:35 +00001099 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001100 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001101 properties := memberType.CreateVariantPropertiesStruct()
1102 base := properties.Base()
1103 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001104 return properties
1105 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001106
Paul Duffina04c1072020-03-02 10:16:35 +00001107 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001108
Paul Duffina04c1072020-03-02 10:16:35 +00001109 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001110 commonProperties := variantPropertiesFactory()
1111 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001112
Paul Duffinc097e362020-03-10 22:50:03 +00001113 // Create common value extractor that can be used to optimize the properties.
1114 commonValueExtractor := newCommonValueExtractor(commonProperties)
1115
Paul Duffina04c1072020-03-02 10:16:35 +00001116 // The list of property structures which are os type specific but common across
1117 // architectures within that os type.
1118 var osSpecificPropertiesList []android.SdkMemberProperties
1119
1120 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin00e46802020-03-12 20:40:35 +00001121 osInfo := newOsTypeSpecificInfo(osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001122 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001123 // Add the os specific properties to a list of os type specific yet architecture
1124 // independent properties structs.
Paul Duffina04c1072020-03-02 10:16:35 +00001125 osSpecificPropertiesList = append(osSpecificPropertiesList, osInfo.Properties)
1126
Paul Duffin00e46802020-03-12 20:40:35 +00001127 // Optimize the properties across all the variants for a specific os type.
1128 osInfo.optimizeProperties(commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001129 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001130
Paul Duffina04c1072020-03-02 10:16:35 +00001131 // Extract properties which are common across all architectures and os types.
Paul Duffinc097e362020-03-10 22:50:03 +00001132 commonValueExtractor.extractCommonProperties(commonProperties, osSpecificPropertiesList)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001133
Paul Duffina04c1072020-03-02 10:16:35 +00001134 // Add the common properties to the module.
1135 commonProperties.AddToPropertySet(sdkModuleContext, builder, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001136
Paul Duffina04c1072020-03-02 10:16:35 +00001137 // Create a target property set into which target specific properties can be
1138 // added.
1139 targetPropertySet := bpModule.AddPropertySet("target")
1140
1141 // Iterate over the os types in a fixed order.
1142 for _, osType := range s.getPossibleOsTypes() {
1143 osInfo := osTypeToInfo[osType]
1144 if osInfo == nil {
1145 continue
1146 }
1147
Paul Duffin00e46802020-03-12 20:40:35 +00001148 osInfo.addToPropertySet(builder, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001149 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001150}
1151
Paul Duffina04c1072020-03-02 10:16:35 +00001152// Compute the list of possible os types that this sdk could support.
1153func (s *sdk) getPossibleOsTypes() []android.OsType {
1154 var osTypes []android.OsType
1155 for _, osType := range android.OsTypeList {
1156 if s.DeviceSupported() {
1157 if osType.Class == android.Device && osType != android.Fuchsia {
1158 osTypes = append(osTypes, osType)
1159 }
1160 }
1161 if s.HostSupported() {
1162 if osType.Class == android.Host || osType.Class == android.HostCross {
1163 osTypes = append(osTypes, osType)
1164 }
1165 }
1166 }
1167 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1168 return osTypes
1169}
1170
Paul Duffinb07fa512020-03-10 22:17:04 +00001171// Given a struct value, access a field within that struct (or one of its embedded
1172// structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001173type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1174
1175// Supports extracting common values from a number of instances of a properties
1176// structure into a separate common set of properties.
1177type commonValueExtractor struct {
1178 // The getters for every field from which common values can be extracted.
1179 fieldGetters []fieldAccessorFunc
1180}
1181
1182// Create a new common value extractor for the structure type for the supplied
1183// properties struct.
1184//
1185// The returned extractor can be used on any properties structure of the same type
1186// as the supplied set of properties.
1187func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1188 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1189 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001190 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001191 return extractor
1192}
1193
1194// Gather the fields from the supplied structure type from which common values will
1195// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001196//
1197// This is recursive function. If it encounters an embedded field (no field name)
1198// that is a struct then it will recurse into that struct passing in the accessor
1199// for the field. That will then be used in the accessors for the fields in the
1200// embedded struct.
1201func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001202 for f := 0; f < structType.NumField(); f++ {
1203 field := structType.Field(f)
1204 if field.PkgPath != "" {
1205 // Ignore unexported fields.
1206 continue
1207 }
1208
Paul Duffinb07fa512020-03-10 22:17:04 +00001209 // Ignore fields whose value should be kept.
1210 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001211 continue
1212 }
1213
1214 // Save a copy of the field index for use in the function.
1215 fieldIndex := f
1216 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001217 if containingStructAccessor != nil {
1218 // This is an embedded structure so first access the field for the embedded
1219 // structure.
1220 value = containingStructAccessor(value)
1221 }
1222
Paul Duffinc097e362020-03-10 22:50:03 +00001223 // Skip through interface and pointer values to find the structure.
1224 value = getStructValue(value)
1225
1226 // Return the field.
1227 return value.Field(fieldIndex)
1228 }
1229
Paul Duffinb07fa512020-03-10 22:17:04 +00001230 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1231 // Gather fields from the embedded structure.
1232 e.gatherFields(field.Type, fieldGetter)
1233 } else {
1234 e.fieldGetters = append(e.fieldGetters, fieldGetter)
1235 }
Paul Duffinc097e362020-03-10 22:50:03 +00001236 }
1237}
1238
1239func getStructValue(value reflect.Value) reflect.Value {
1240foundStruct:
1241 for {
1242 kind := value.Kind()
1243 switch kind {
1244 case reflect.Interface, reflect.Ptr:
1245 value = value.Elem()
1246 case reflect.Struct:
1247 break foundStruct
1248 default:
1249 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1250 }
1251 }
1252 return value
1253}
1254
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001255// Extract common properties from a slice of property structures of the same type.
1256//
1257// All the property structures must be of the same type.
1258// commonProperties - must be a pointer to the structure into which common properties will be added.
1259// inputPropertiesSlice - must be a slice of input properties structures.
1260//
1261// Iterates over each exported field (capitalized name) and checks to see whether they
1262// have the same value (using DeepEquals) across all the input properties. If it does not then no
1263// change is made. Otherwise, the common value is stored in the field in the commonProperties
1264// and the field in each of the input properties structure is set to its default value.
Paul Duffinc097e362020-03-10 22:50:03 +00001265func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001266 commonPropertiesValue := reflect.ValueOf(commonProperties)
1267 commonStructValue := commonPropertiesValue.Elem()
1268 propertiesStructType := commonStructValue.Type()
1269
1270 // Create an empty structure from which default values for the field can be copied.
1271 emptyStructValue := reflect.New(propertiesStructType).Elem()
1272
Paul Duffinc097e362020-03-10 22:50:03 +00001273 for _, fieldGetter := range e.fieldGetters {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001274 // Check to see if all the structures have the same value for the field. The commonValue
1275 // is nil on entry to the loop and if it is nil on exit then there is no common value,
1276 // otherwise it points to the common value.
1277 var commonValue *reflect.Value
1278 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1279
1280 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001281 itemValue := sliceValue.Index(i)
1282 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001283
1284 if commonValue == nil {
1285 // Use the first value as the commonProperties value.
1286 commonValue = &fieldValue
1287 } else {
1288 // If the value does not match the current common value then there is
1289 // no value in common so break out.
1290 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1291 commonValue = nil
1292 break
1293 }
1294 }
1295 }
1296
1297 // If the fields all have a common value then store it in the common struct field
1298 // and set the input struct's field to the empty value.
1299 if commonValue != nil {
Paul Duffinc097e362020-03-10 22:50:03 +00001300 emptyValue := fieldGetter(emptyStructValue)
1301 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001302 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001303 itemValue := sliceValue.Index(i)
1304 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001305 fieldValue.Set(emptyValue)
1306 }
1307 }
1308 }
1309}