blob: ce25fc40aef16386780bf3bbd15b8d01f44721e2 [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
147 lib32 := false // True if any of the members have 32 bit version.
148 lib64 := false // True if any of the members have 64 bit version.
149
150 for _, memberRef := range memberRefs {
151 memberType := memberRef.memberType
152 variant := memberRef.variant
153
154 name := ctx.OtherModuleName(variant)
155 member := byName[name]
156 if member == nil {
157 member = &sdkMember{memberType: memberType, name: name}
158 byName[name] = member
159 byType[memberType] = append(byType[memberType], member)
160 }
161
162 multilib := variant.Target().Arch.ArchType.Multilib
163 if multilib == "lib32" {
164 lib32 = true
165 } else if multilib == "lib64" {
166 lib64 = true
167 }
168
169 // Only append new variants to the list. This is needed because a member can be both
170 // exported by the sdk and also be a transitive sdk member.
171 member.variants = appendUniqueVariants(member.variants, variant)
172 }
173
Paul Duffin13879572019-11-28 14:31:38 +0000174 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000175 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000176 membersOfType := byType[memberListProperty.memberType]
177 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900178 }
179
Paul Duffin13ad94f2020-02-19 16:19:27 +0000180 // Compute the setting of multilib.
181 var multilib string
182 if lib32 && lib64 {
183 multilib = "both"
184 } else if lib32 {
185 multilib = "32"
186 } else if lib64 {
187 multilib = "64"
188 }
189
190 return members, multilib
Jiyong Park73c54ee2019-10-22 20:31:18 +0900191}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900192
Paul Duffin72910952020-01-20 18:16:30 +0000193func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
194 for _, v := range variants {
195 if v == newVariant {
196 return variants
197 }
198 }
199 return append(variants, newVariant)
200}
201
Jiyong Park73c54ee2019-10-22 20:31:18 +0900202// SDK directory structure
203// <sdk_root>/
204// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
205// <api_ver>/ : below this directory are all auto-generated
206// Android.bp : definition of 'sdk_snapshot' module is here
207// aidl/
208// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
209// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900210// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900211// include/
212// bionic/libc/include/stdlib.h : an exported header file
213// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900214// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900215// <arch>/include/ : arch-specific exported headers
216// <arch>/include_gen/ : arch-specific generated headers
217// <arch>/lib/
218// libFoo.so : a stub library
219
Jiyong Park232e7852019-11-04 12:23:40 +0900220// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900221// This isn't visible to users, so could be changed in future.
222func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
223 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
224}
225
Jiyong Park232e7852019-11-04 12:23:40 +0900226// buildSnapshot is the main function in this source file. It creates rules to copy
227// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000228func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
229
Paul Duffin13f02712020-03-06 12:30:43 +0000230 allMembersByName := make(map[string]struct{})
231 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000232 var memberRefs []sdkMemberRef
233 for _, sdkVariant := range sdkVariants {
234 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000235
Paul Duffin13f02712020-03-06 12:30:43 +0000236 // Record the names of all the members, both explicitly specified and implicitly
237 // included.
238 for _, memberRef := range sdkVariant.memberRefs {
239 allMembersByName[memberRef.variant.Name()] = struct{}{}
240 }
241
Paul Duffin865171e2020-03-02 18:38:15 +0000242 // Merge the exported member sets from all sdk variants.
243 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000244 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000245 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000246 }
247
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000248 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900249
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000250 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000251
252 bpFile := &bpFile{
253 modules: make(map[string]*bpModule),
254 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000255
256 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000257 ctx: ctx,
258 sdk: s,
259 version: "current",
260 snapshotDir: snapshotDir.OutputPath,
261 copies: make(map[string]string),
262 filesToZip: []android.Path{bp.path},
263 bpFile: bpFile,
264 prebuiltModules: make(map[string]*bpModule),
265 allMembersByName: allMembersByName,
266 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900267 }
Paul Duffinac37c502019-11-26 18:02:20 +0000268 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900269
Paul Duffin1356d8c2020-02-25 19:26:33 +0000270 members, multilib := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000271 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000272 memberType := member.memberType
273 prebuiltModule := memberType.AddPrebuiltModule(ctx, builder, member)
274 if prebuiltModule == nil {
275 // Fall back to legacy method of building a snapshot
276 memberType.BuildSnapshot(ctx, builder, member)
277 } else {
278 s.createMemberSnapshot(ctx, builder, member, prebuiltModule)
279 }
Jiyong Park73c54ee2019-10-22 20:31:18 +0900280 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900281
Paul Duffine6c0d842020-01-15 14:08:51 +0000282 // Create a transformer that will transform an unversioned module into a versioned module.
283 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
284
Paul Duffin72910952020-01-20 18:16:30 +0000285 // Create a transformer that will transform an unversioned module by replacing any references
286 // to internal members with a unique module name and setting prefer: false.
287 unversionedTransformer := unversionedTransformation{builder: builder}
288
Paul Duffinb645ec82019-11-27 17:43:54 +0000289 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000290 // Prune any empty property sets.
291 unversioned = unversioned.transform(pruneEmptySetTransformer{})
292
Paul Duffinb645ec82019-11-27 17:43:54 +0000293 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000294 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000295
296 // Transform the unversioned module into a versioned one.
297 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000298 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000299
Paul Duffin72910952020-01-20 18:16:30 +0000300 // Transform the unversioned module to make it suitable for use in the snapshot.
301 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000302 bpFile.AddModule(unversioned)
303 }
304
305 // Create the snapshot module.
306 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000307 var snapshotModuleType string
308 if s.properties.Module_exports {
309 snapshotModuleType = "module_exports_snapshot"
310 } else {
311 snapshotModuleType = "sdk_snapshot"
312 }
313 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000314 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000315
316 // Make sure that the snapshot has the same visibility as the sdk.
317 visibility := android.EffectiveVisibilityRules(ctx, s)
318 if len(visibility) != 0 {
319 snapshotModule.AddProperty("visibility", visibility)
320 }
321
Paul Duffin865171e2020-03-02 18:38:15 +0000322 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000323
324 // Compile_multilib defaults to both and must always be set to both on the
325 // device and so only needs to be set when targeted at the host and is neither
326 // unspecified or both.
Paul Duffin865171e2020-03-02 18:38:15 +0000327 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000328 if s.HostSupported() && multilib != "" && multilib != "both" {
Paul Duffin865171e2020-03-02 18:38:15 +0000329 hostSet := targetPropertySet.AddPropertySet("host")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000330 hostSet.AddProperty("compile_multilib", multilib)
331 }
332
Paul Duffin865171e2020-03-02 18:38:15 +0000333 var dynamicMemberPropertiesList []interface{}
334 osTypeToMemberProperties := make(map[android.OsType]*sdk)
335 for _, sdkVariant := range sdkVariants {
336 properties := sdkVariant.dynamicMemberTypeListProperties
337 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
338 dynamicMemberPropertiesList = append(dynamicMemberPropertiesList, properties)
339 }
340
341 // Extract the common lists of members into a separate struct.
342 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000343 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
344 extractor.extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000345
346 // Add properties common to all os types.
347 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
348
349 // Iterate over the os types in a fixed order.
350 for _, osType := range s.getPossibleOsTypes() {
351 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
352 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
353 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000354 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000355 }
Paul Duffin865171e2020-03-02 18:38:15 +0000356
357 // Prune any empty property sets.
358 snapshotModule.transform(pruneEmptySetTransformer{})
359
Paul Duffinb645ec82019-11-27 17:43:54 +0000360 bpFile.AddModule(snapshotModule)
361
362 // generate Android.bp
363 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
364 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000365
366 bp.build(pctx, ctx, nil)
367
368 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900369
Jiyong Park232e7852019-11-04 12:23:40 +0900370 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000371 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000372 outputDesc := "Building snapshot for " + ctx.ModuleName()
373
374 // If there are no zips to merge then generate the output zip directly.
375 // Otherwise, generate an intermediate zip file into which other zips can be
376 // merged.
377 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000378 var desc string
379 if len(builder.zipsToMerge) == 0 {
380 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000381 desc = outputDesc
382 } else {
383 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000384 desc = "Building intermediate snapshot for " + ctx.ModuleName()
385 }
386
Paul Duffin375058f2019-11-29 20:17:53 +0000387 ctx.Build(pctx, android.BuildParams{
388 Description: desc,
389 Rule: zipFiles,
390 Inputs: filesToZip,
391 Output: zipFile,
392 Args: map[string]string{
393 "basedir": builder.snapshotDir.String(),
394 },
395 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900396
Paul Duffin91547182019-11-12 19:39:36 +0000397 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000398 ctx.Build(pctx, android.BuildParams{
399 Description: outputDesc,
400 Rule: mergeZips,
401 Input: zipFile,
402 Inputs: builder.zipsToMerge,
403 Output: outputZipFile,
404 })
Paul Duffin91547182019-11-12 19:39:36 +0000405 }
406
407 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900408}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000409
Paul Duffin865171e2020-03-02 18:38:15 +0000410func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
411 for _, memberListProperty := range s.memberListProperties() {
412 names := memberListProperty.getter(dynamicMemberTypeListProperties)
413 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000414 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000415 }
416 }
417}
418
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000419type propertyTag struct {
420 name string
421}
422
Paul Duffin0cb37b92020-03-04 14:52:46 +0000423// A BpPropertyTag to add to a property that contains references to other sdk members.
424//
425// This will cause the references to be rewritten to a versioned reference in the version
426// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000427var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000428var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000429
Paul Duffin0cb37b92020-03-04 14:52:46 +0000430// A BpPropertyTag that indicates the property should only be present in the versioned
431// module.
432//
433// This will cause the property to be removed from the unversioned instance of a
434// snapshot module.
435var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
436
Paul Duffine6c0d842020-01-15 14:08:51 +0000437type unversionedToVersionedTransformation struct {
438 identityTransformation
439 builder *snapshotBuilder
440}
441
Paul Duffine6c0d842020-01-15 14:08:51 +0000442func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
443 // Use a versioned name for the module but remember the original name for the
444 // snapshot.
445 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000446 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000447 module.insertAfter("name", "sdk_member_name", name)
448 return module
449}
450
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000451func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000452 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
453 required := tag == requiredSdkMemberReferencePropertyTag
454 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000455 } else {
456 return value, tag
457 }
458}
459
Paul Duffin72910952020-01-20 18:16:30 +0000460type unversionedTransformation struct {
461 identityTransformation
462 builder *snapshotBuilder
463}
464
465func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
466 // If the module is an internal member then use a unique name for it.
467 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000468 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000469
470 // Set prefer: false - this is not strictly required as that is the default.
471 module.insertAfter("name", "prefer", false)
472
473 return module
474}
475
476func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000477 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
478 required := tag == requiredSdkMemberReferencePropertyTag
479 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000480 } else if tag == sdkVersionedOnlyPropertyTag {
481 // The property is not allowed in the unversioned module so remove it.
482 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000483 } else {
484 return value, tag
485 }
486}
487
Paul Duffina78f3a72020-02-21 16:29:35 +0000488type pruneEmptySetTransformer struct {
489 identityTransformation
490}
491
492var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
493
494func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
495 if len(propertySet.properties) == 0 {
496 return nil, nil
497 } else {
498 return propertySet, tag
499 }
500}
501
Paul Duffinb645ec82019-11-27 17:43:54 +0000502func generateBpContents(contents *generatedContents, bpFile *bpFile) {
503 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
504 for _, bpModule := range bpFile.order {
505 contents.Printfln("")
506 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000507 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000508 contents.Printfln("}")
509 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000510}
511
512func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
513 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000514
515 // Output the properties first, followed by the nested sets. This ensures a
516 // consistent output irrespective of whether property sets are created before
517 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000518 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000519 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000520
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000521 switch v := value.(type) {
522 case []string:
523 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000524 if length > 1 {
525 contents.Printfln("%s: [", name)
526 contents.Indent()
527 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000528 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000529 }
530 contents.Dedent()
531 contents.Printfln("],")
532 } else if length == 0 {
533 contents.Printfln("%s: [],", name)
534 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000535 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000536 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000537
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000538 case bool:
539 contents.Printfln("%s: %t,", name, v)
540
541 case *bpPropertySet:
542 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000543
544 default:
545 contents.Printfln("%s: %q,", name, value)
546 }
547 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000548
549 for _, name := range set.order {
550 value := set.getValue(name)
551
552 // Only write property sets in the sets phase.
553 switch v := value.(type) {
554 case *bpPropertySet:
555 contents.Printfln("%s: {", name)
556 outputPropertySet(contents, v)
557 contents.Printfln("},")
558 }
559 }
560
Paul Duffinb645ec82019-11-27 17:43:54 +0000561 contents.Dedent()
562}
563
Paul Duffinac37c502019-11-26 18:02:20 +0000564func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000565 contents := &generatedContents{}
566 generateBpContents(contents, s.builderForTests.bpFile)
567 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000568}
569
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000570type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000571 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000572 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000573 version string
574 snapshotDir android.OutputPath
575 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000576
577 // Map from destination to source of each copy - used to eliminate duplicates and
578 // detect conflicts.
579 copies map[string]string
580
Paul Duffinb645ec82019-11-27 17:43:54 +0000581 filesToZip android.Paths
582 zipsToMerge android.Paths
583
584 prebuiltModules map[string]*bpModule
585 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000586
587 // The set of all members by name.
588 allMembersByName map[string]struct{}
589
590 // The set of exported members by name.
591 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000592}
593
594func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000595 if existing, ok := s.copies[dest]; ok {
596 if existing != src.String() {
597 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
598 return
599 }
600 } else {
601 path := s.snapshotDir.Join(s.ctx, dest)
602 s.ctx.Build(pctx, android.BuildParams{
603 Rule: android.Cp,
604 Input: src,
605 Output: path,
606 })
607 s.filesToZip = append(s.filesToZip, path)
608
609 s.copies[dest] = src.String()
610 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000611}
612
Paul Duffin91547182019-11-12 19:39:36 +0000613func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
614 ctx := s.ctx
615
616 // Repackage the zip file so that the entries are in the destDir directory.
617 // This will allow the zip file to be merged into the snapshot.
618 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000619
620 ctx.Build(pctx, android.BuildParams{
621 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
622 Rule: repackageZip,
623 Input: zipPath,
624 Output: tmpZipPath,
625 Args: map[string]string{
626 "destdir": destDir,
627 },
628 })
Paul Duffin91547182019-11-12 19:39:36 +0000629
630 // Add the repackaged zip file to the files to merge.
631 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
632}
633
Paul Duffin9d8d6092019-12-05 18:19:29 +0000634func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
635 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000636 if s.prebuiltModules[name] != nil {
637 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
638 }
639
640 m := s.bpFile.newModule(moduleType)
641 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000642
Paul Duffinbefa4b92020-03-04 14:22:45 +0000643 variant := member.Variants()[0]
644
Paul Duffin13f02712020-03-06 12:30:43 +0000645 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000646 // An internal member is only referenced from the sdk snapshot which is in the
647 // same package so can be marked as private.
648 m.AddProperty("visibility", []string{"//visibility:private"})
649 } else {
650 // Extract visibility information from a member variant. All variants have the same
651 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000652 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000653 if len(visibility) != 0 {
654 m.AddProperty("visibility", visibility)
655 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000656 }
657
Paul Duffin865171e2020-03-02 18:38:15 +0000658 deviceSupported := false
659 hostSupported := false
660
661 for _, variant := range member.Variants() {
662 osClass := variant.Target().Os.Class
663 if osClass == android.Host || osClass == android.HostCross {
664 hostSupported = true
665 } else if osClass == android.Device {
666 deviceSupported = true
667 }
668 }
669
670 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000671
Paul Duffinbefa4b92020-03-04 14:22:45 +0000672 // Where available copy apex_available properties from the member.
673 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
674 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000675
676 // Add in any white listed apex available settings.
677 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
678
Paul Duffinbefa4b92020-03-04 14:22:45 +0000679 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000680 // Remove duplicates and sort.
681 apexAvailable = android.FirstUniqueStrings(apexAvailable)
682 sort.Strings(apexAvailable)
683
Paul Duffinbefa4b92020-03-04 14:22:45 +0000684 m.AddProperty("apex_available", apexAvailable)
685 }
686 }
687
Paul Duffin0cb37b92020-03-04 14:52:46 +0000688 // Disable installation in the versioned module of those modules that are ever installable.
689 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
690 if installable.EverInstallable() {
691 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
692 }
693 }
694
Paul Duffinb645ec82019-11-27 17:43:54 +0000695 s.prebuiltModules[name] = m
696 s.prebuiltOrder = append(s.prebuiltOrder, m)
697 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000698}
699
Paul Duffin865171e2020-03-02 18:38:15 +0000700func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
701 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000702 bpModule.AddProperty("device_supported", false)
703 }
Paul Duffin865171e2020-03-02 18:38:15 +0000704 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000705 bpModule.AddProperty("host_supported", true)
706 }
707}
708
Paul Duffin13f02712020-03-06 12:30:43 +0000709func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
710 if required {
711 return requiredSdkMemberReferencePropertyTag
712 } else {
713 return optionalSdkMemberReferencePropertyTag
714 }
715}
716
717func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
718 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000719}
720
Paul Duffinb645ec82019-11-27 17:43:54 +0000721// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000722func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
723 if _, ok := s.allMembersByName[unversionedName]; !ok {
724 if required {
725 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
726 }
727 return unversionedName
728 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000729 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
730}
Paul Duffinb645ec82019-11-27 17:43:54 +0000731
Paul Duffin13f02712020-03-06 12:30:43 +0000732func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000733 var references []string = nil
734 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000735 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000736 }
737 return references
738}
Paul Duffin13879572019-11-28 14:31:38 +0000739
Paul Duffin72910952020-01-20 18:16:30 +0000740// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000741func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
742 if _, ok := s.allMembersByName[unversionedName]; !ok {
743 if required {
744 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
745 }
746 return unversionedName
747 }
748
749 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000750 return s.ctx.ModuleName() + "_" + unversionedName
751 } else {
752 return unversionedName
753 }
754}
755
Paul Duffin13f02712020-03-06 12:30:43 +0000756func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000757 var references []string = nil
758 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000759 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000760 }
761 return references
762}
763
Paul Duffin13f02712020-03-06 12:30:43 +0000764func (s *snapshotBuilder) isInternalMember(memberName string) bool {
765 _, ok := s.exportedMembersByName[memberName]
766 return !ok
767}
768
Paul Duffin1356d8c2020-02-25 19:26:33 +0000769type sdkMemberRef struct {
770 memberType android.SdkMemberType
771 variant android.SdkAware
772}
773
Paul Duffin13879572019-11-28 14:31:38 +0000774var _ android.SdkMember = (*sdkMember)(nil)
775
776type sdkMember struct {
777 memberType android.SdkMemberType
778 name string
779 variants []android.SdkAware
780}
781
782func (m *sdkMember) Name() string {
783 return m.name
784}
785
786func (m *sdkMember) Variants() []android.SdkAware {
787 return m.variants
788}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000789
790type baseInfo struct {
791 Properties android.SdkMemberProperties
792}
793
794type osTypeSpecificInfo struct {
795 baseInfo
796
Paul Duffin00e46802020-03-12 20:40:35 +0000797 osType android.OsType
798
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000799 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000800 //
801 // Nil if there is one variant whose arch type is common
802 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000803}
804
Paul Duffinfc8dd232020-03-17 12:51:37 +0000805type variantPropertiesFactoryFunc func() android.SdkMemberProperties
806
Paul Duffin00e46802020-03-12 20:40:35 +0000807// Create a new osTypeSpecificInfo for the specified os type and its properties
808// structures populated with information from the variants.
809func newOsTypeSpecificInfo(osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.SdkAware) *osTypeSpecificInfo {
810 osInfo := &osTypeSpecificInfo{
811 osType: osType,
812 }
813
814 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
815 properties := variantPropertiesFactory()
816 properties.Base().Os = osType
817 return properties
818 }
819
820 // Create a structure into which properties common across the architectures in
821 // this os type will be stored.
822 osInfo.Properties = osSpecificVariantPropertiesFactory()
823
824 // Group the variants by arch type.
825 var variantsByArchName = make(map[string][]android.SdkAware)
826 var archTypes []android.ArchType
827 for _, variant := range osTypeVariants {
828 archType := variant.Target().Arch.ArchType
829 archTypeName := archType.Name
830 if _, ok := variantsByArchName[archTypeName]; !ok {
831 archTypes = append(archTypes, archType)
832 }
833
834 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
835 }
836
837 if commonVariants, ok := variantsByArchName["common"]; ok {
838 if len(osTypeVariants) != 1 {
839 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
840 }
841
842 // A common arch type only has one variant and its properties should be treated
843 // as common to the os type.
844 osInfo.Properties.PopulateFromVariant(commonVariants[0])
845 } else {
846 // Create an arch specific info for each supported architecture type.
847 for _, archType := range archTypes {
848 archTypeName := archType.Name
849
850 archVariants := variantsByArchName[archTypeName]
851 archInfo := newArchSpecificInfo(archType, osSpecificVariantPropertiesFactory, archVariants)
852
853 osInfo.archInfos = append(osInfo.archInfos, archInfo)
854 }
855 }
856
857 return osInfo
858}
859
860// Optimize the properties by extracting common properties from arch type specific
861// properties into os type specific properties.
862func (osInfo *osTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
863 // Nothing to do if there is only a single common architecture.
864 if len(osInfo.archInfos) == 0 {
865 return
866 }
867
868 var archPropertiesList []android.SdkMemberProperties
869 for _, archInfo := range osInfo.archInfos {
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000870 // Optimize the arch properties first.
871 archInfo.optimizeProperties(commonValueExtractor)
872
Paul Duffin00e46802020-03-12 20:40:35 +0000873 archPropertiesList = append(archPropertiesList, archInfo.Properties)
874 }
875
876 commonValueExtractor.extractCommonProperties(osInfo.Properties, archPropertiesList)
877
878 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
879 var multilib string
880 archVariantCount := len(osInfo.archInfos)
881 if archVariantCount == 2 {
882 multilib = "both"
883 } else if archVariantCount == 1 {
884 if strings.HasSuffix(osInfo.archInfos[0].archType.Name, "64") {
885 multilib = "64"
886 } else {
887 multilib = "32"
888 }
889 }
890
891 osInfo.Properties.Base().Compile_multilib = multilib
892}
893
894// Add the properties for an os to a property set.
895//
896// Maps the properties related to the os variants through to an appropriate
897// module structure that will produce equivalent set of variants when it is
898// processed in a build.
899func (osInfo *osTypeSpecificInfo) addToPropertySet(
900 builder *snapshotBuilder,
901 bpModule android.BpModule,
902 targetPropertySet android.BpPropertySet) {
903
904 var osPropertySet android.BpPropertySet
905 var archPropertySet android.BpPropertySet
906 var archOsPrefix string
907 if osInfo.Properties.Base().Os_count == 1 {
908 // There is only one os type present in the variants so don't bother
909 // with adding target specific properties.
910
911 // Create a structure that looks like:
912 // module_type {
913 // name: "...",
914 // ...
915 // <common properties>
916 // ...
917 // <single os type specific properties>
918 //
919 // arch: {
920 // <arch specific sections>
921 // }
922 //
923 osPropertySet = bpModule
924 archPropertySet = osPropertySet.AddPropertySet("arch")
925
926 // Arch specific properties need to be added to an arch specific section
927 // within arch.
928 archOsPrefix = ""
929 } else {
930 // Create a structure that looks like:
931 // module_type {
932 // name: "...",
933 // ...
934 // <common properties>
935 // ...
936 // target: {
937 // <arch independent os specific sections, e.g. android>
938 // ...
939 // <arch and os specific sections, e.g. android_x86>
940 // }
941 //
942 osType := osInfo.osType
943 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
944 archPropertySet = targetPropertySet
945
946 // Arch specific properties need to be added to an os and arch specific
947 // section prefixed with <os>_.
948 archOsPrefix = osType.Name + "_"
949 }
950
951 // Add the os specific but arch independent properties to the module.
952 osInfo.Properties.AddToPropertySet(builder.ctx, builder, osPropertySet)
953
954 // Add arch (and possibly os) specific sections for each set of arch (and possibly
955 // os) specific properties.
956 //
957 // The archInfos list will be empty if the os contains variants for the common
958 // architecture.
959 for _, archInfo := range osInfo.archInfos {
960 archInfo.addToPropertySet(builder, archPropertySet, archOsPrefix)
961 }
962}
963
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000964type archTypeSpecificInfo struct {
965 baseInfo
966
967 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000968
969 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000970}
971
Paul Duffinfc8dd232020-03-17 12:51:37 +0000972// Create a new archTypeSpecificInfo for the specified arch type and its properties
973// structures populated with information from the variants.
974func newArchSpecificInfo(archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.SdkAware) *archTypeSpecificInfo {
975
Paul Duffinfc8dd232020-03-17 12:51:37 +0000976 // Create an arch specific info into which the variant properties can be copied.
977 archInfo := &archTypeSpecificInfo{archType: archType}
978
979 // Create the properties into which the arch type specific properties will be
980 // added.
981 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000982
983 if len(archVariants) == 1 {
984 archInfo.Properties.PopulateFromVariant(archVariants[0])
985 } else {
986 // There is more than one variant for this arch type which must be differentiated
987 // by link type.
988 for _, linkVariant := range archVariants {
989 linkType := getLinkType(linkVariant)
990 if linkType == "" {
991 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
992 } else {
993 linkInfo := newLinkSpecificInfo(linkType, variantPropertiesFactory, linkVariant)
994
995 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
996 }
997 }
998 }
Paul Duffinfc8dd232020-03-17 12:51:37 +0000999
1000 return archInfo
1001}
1002
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001003// Get the link type of the variant
1004//
1005// If the variant is not differentiated by link type then it returns "",
1006// otherwise it returns one of "static" or "shared".
1007func getLinkType(variant android.Module) string {
1008 linkType := ""
1009 if linkable, ok := variant.(cc.LinkableInterface); ok {
1010 if linkable.Shared() && linkable.Static() {
1011 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1012 } else if linkable.Shared() {
1013 linkType = "shared"
1014 } else if linkable.Static() {
1015 linkType = "static"
1016 } else {
1017 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1018 }
1019 }
1020 return linkType
1021}
1022
1023// Optimize the properties by extracting common properties from link type specific
1024// properties into arch type specific properties.
1025func (archInfo *archTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
1026 if len(archInfo.linkInfos) == 0 {
1027 return
1028 }
1029
1030 var propertiesList []android.SdkMemberProperties
1031 for _, linkInfo := range archInfo.linkInfos {
1032 propertiesList = append(propertiesList, linkInfo.Properties)
1033 }
1034
1035 commonValueExtractor.extractCommonProperties(archInfo.Properties, propertiesList)
1036}
1037
Paul Duffinfc8dd232020-03-17 12:51:37 +00001038// Add the properties for an arch type to a property set.
1039func (archInfo *archTypeSpecificInfo) addToPropertySet(builder *snapshotBuilder, archPropertySet android.BpPropertySet, archOsPrefix string) {
1040 archTypeName := archInfo.archType.Name
1041 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
1042 archInfo.Properties.AddToPropertySet(builder.ctx, builder, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001043
1044 for _, linkInfo := range archInfo.linkInfos {
1045 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
1046 linkInfo.Properties.AddToPropertySet(builder.ctx, builder, linkPropertySet)
1047 }
1048}
1049
1050type linkTypeSpecificInfo struct {
1051 baseInfo
1052
1053 linkType string
1054}
1055
1056// Create a new linkTypeSpecificInfo for the specified link type and its properties
1057// structures populated with information from the variant.
1058func newLinkSpecificInfo(linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.SdkAware) *linkTypeSpecificInfo {
1059 linkInfo := &linkTypeSpecificInfo{
1060 baseInfo: baseInfo{
1061 // Create the properties into which the link type specific properties will be
1062 // added.
1063 Properties: variantPropertiesFactory(),
1064 },
1065 linkType: linkType,
1066 }
1067 linkInfo.Properties.PopulateFromVariant(linkVariant)
1068 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001069}
1070
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001071func (s *sdk) createMemberSnapshot(sdkModuleContext android.ModuleContext, builder *snapshotBuilder, member *sdkMember, bpModule android.BpModule) {
1072
1073 memberType := member.memberType
1074
Paul Duffina04c1072020-03-02 10:16:35 +00001075 // Group the variants by os type.
1076 variantsByOsType := make(map[android.OsType][]android.SdkAware)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001077 variants := member.Variants()
1078 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001079 osType := variant.Target().Os
1080 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001081 }
1082
Paul Duffina04c1072020-03-02 10:16:35 +00001083 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001084 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001085 properties := memberType.CreateVariantPropertiesStruct()
1086 base := properties.Base()
1087 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001088 return properties
1089 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001090
Paul Duffina04c1072020-03-02 10:16:35 +00001091 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001092
Paul Duffina04c1072020-03-02 10:16:35 +00001093 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001094 commonProperties := variantPropertiesFactory()
1095 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001096
Paul Duffinc097e362020-03-10 22:50:03 +00001097 // Create common value extractor that can be used to optimize the properties.
1098 commonValueExtractor := newCommonValueExtractor(commonProperties)
1099
Paul Duffina04c1072020-03-02 10:16:35 +00001100 // The list of property structures which are os type specific but common across
1101 // architectures within that os type.
1102 var osSpecificPropertiesList []android.SdkMemberProperties
1103
1104 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin00e46802020-03-12 20:40:35 +00001105 osInfo := newOsTypeSpecificInfo(osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001106 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001107 // Add the os specific properties to a list of os type specific yet architecture
1108 // independent properties structs.
Paul Duffina04c1072020-03-02 10:16:35 +00001109 osSpecificPropertiesList = append(osSpecificPropertiesList, osInfo.Properties)
1110
Paul Duffin00e46802020-03-12 20:40:35 +00001111 // Optimize the properties across all the variants for a specific os type.
1112 osInfo.optimizeProperties(commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001113 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001114
Paul Duffina04c1072020-03-02 10:16:35 +00001115 // Extract properties which are common across all architectures and os types.
Paul Duffinc097e362020-03-10 22:50:03 +00001116 commonValueExtractor.extractCommonProperties(commonProperties, osSpecificPropertiesList)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001117
Paul Duffina04c1072020-03-02 10:16:35 +00001118 // Add the common properties to the module.
1119 commonProperties.AddToPropertySet(sdkModuleContext, builder, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001120
Paul Duffina04c1072020-03-02 10:16:35 +00001121 // Create a target property set into which target specific properties can be
1122 // added.
1123 targetPropertySet := bpModule.AddPropertySet("target")
1124
1125 // Iterate over the os types in a fixed order.
1126 for _, osType := range s.getPossibleOsTypes() {
1127 osInfo := osTypeToInfo[osType]
1128 if osInfo == nil {
1129 continue
1130 }
1131
Paul Duffin00e46802020-03-12 20:40:35 +00001132 osInfo.addToPropertySet(builder, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001133 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001134}
1135
Paul Duffina04c1072020-03-02 10:16:35 +00001136// Compute the list of possible os types that this sdk could support.
1137func (s *sdk) getPossibleOsTypes() []android.OsType {
1138 var osTypes []android.OsType
1139 for _, osType := range android.OsTypeList {
1140 if s.DeviceSupported() {
1141 if osType.Class == android.Device && osType != android.Fuchsia {
1142 osTypes = append(osTypes, osType)
1143 }
1144 }
1145 if s.HostSupported() {
1146 if osType.Class == android.Host || osType.Class == android.HostCross {
1147 osTypes = append(osTypes, osType)
1148 }
1149 }
1150 }
1151 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1152 return osTypes
1153}
1154
Paul Duffinb07fa512020-03-10 22:17:04 +00001155// Given a struct value, access a field within that struct (or one of its embedded
1156// structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001157type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1158
1159// Supports extracting common values from a number of instances of a properties
1160// structure into a separate common set of properties.
1161type commonValueExtractor struct {
1162 // The getters for every field from which common values can be extracted.
1163 fieldGetters []fieldAccessorFunc
1164}
1165
1166// Create a new common value extractor for the structure type for the supplied
1167// properties struct.
1168//
1169// The returned extractor can be used on any properties structure of the same type
1170// as the supplied set of properties.
1171func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1172 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1173 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001174 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001175 return extractor
1176}
1177
1178// Gather the fields from the supplied structure type from which common values will
1179// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001180//
1181// This is recursive function. If it encounters an embedded field (no field name)
1182// that is a struct then it will recurse into that struct passing in the accessor
1183// for the field. That will then be used in the accessors for the fields in the
1184// embedded struct.
1185func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001186 for f := 0; f < structType.NumField(); f++ {
1187 field := structType.Field(f)
1188 if field.PkgPath != "" {
1189 // Ignore unexported fields.
1190 continue
1191 }
1192
Paul Duffinb07fa512020-03-10 22:17:04 +00001193 // Ignore fields whose value should be kept.
1194 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001195 continue
1196 }
1197
1198 // Save a copy of the field index for use in the function.
1199 fieldIndex := f
1200 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001201 if containingStructAccessor != nil {
1202 // This is an embedded structure so first access the field for the embedded
1203 // structure.
1204 value = containingStructAccessor(value)
1205 }
1206
Paul Duffinc097e362020-03-10 22:50:03 +00001207 // Skip through interface and pointer values to find the structure.
1208 value = getStructValue(value)
1209
1210 // Return the field.
1211 return value.Field(fieldIndex)
1212 }
1213
Paul Duffinb07fa512020-03-10 22:17:04 +00001214 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1215 // Gather fields from the embedded structure.
1216 e.gatherFields(field.Type, fieldGetter)
1217 } else {
1218 e.fieldGetters = append(e.fieldGetters, fieldGetter)
1219 }
Paul Duffinc097e362020-03-10 22:50:03 +00001220 }
1221}
1222
1223func getStructValue(value reflect.Value) reflect.Value {
1224foundStruct:
1225 for {
1226 kind := value.Kind()
1227 switch kind {
1228 case reflect.Interface, reflect.Ptr:
1229 value = value.Elem()
1230 case reflect.Struct:
1231 break foundStruct
1232 default:
1233 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1234 }
1235 }
1236 return value
1237}
1238
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001239// Extract common properties from a slice of property structures of the same type.
1240//
1241// All the property structures must be of the same type.
1242// commonProperties - must be a pointer to the structure into which common properties will be added.
1243// inputPropertiesSlice - must be a slice of input properties structures.
1244//
1245// Iterates over each exported field (capitalized name) and checks to see whether they
1246// have the same value (using DeepEquals) across all the input properties. If it does not then no
1247// change is made. Otherwise, the common value is stored in the field in the commonProperties
1248// and the field in each of the input properties structure is set to its default value.
Paul Duffinc097e362020-03-10 22:50:03 +00001249func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001250 commonPropertiesValue := reflect.ValueOf(commonProperties)
1251 commonStructValue := commonPropertiesValue.Elem()
1252 propertiesStructType := commonStructValue.Type()
1253
1254 // Create an empty structure from which default values for the field can be copied.
1255 emptyStructValue := reflect.New(propertiesStructType).Elem()
1256
Paul Duffinc097e362020-03-10 22:50:03 +00001257 for _, fieldGetter := range e.fieldGetters {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001258 // Check to see if all the structures have the same value for the field. The commonValue
1259 // is nil on entry to the loop and if it is nil on exit then there is no common value,
1260 // otherwise it points to the common value.
1261 var commonValue *reflect.Value
1262 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1263
1264 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001265 itemValue := sliceValue.Index(i)
1266 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001267
1268 if commonValue == nil {
1269 // Use the first value as the commonProperties value.
1270 commonValue = &fieldValue
1271 } else {
1272 // If the value does not match the current common value then there is
1273 // no value in common so break out.
1274 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1275 commonValue = nil
1276 break
1277 }
1278 }
1279 }
1280
1281 // If the fields all have a common value then store it in the common struct field
1282 // and set the input struct's field to the empty value.
1283 if commonValue != nil {
Paul Duffinc097e362020-03-10 22:50:03 +00001284 emptyValue := fieldGetter(emptyStructValue)
1285 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001286 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001287 itemValue := sliceValue.Index(i)
1288 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001289 fieldValue.Set(emptyValue)
1290 }
1291 }
1292 }
1293}