blob: a43a14b854c7dccc43d3fdf4710558deba79b923 [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 Duffin375058f2019-11-29 20:17:53 +000023 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090024 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027)
28
29var pctx = android.NewPackageContext("android/soong/sdk")
30
Paul Duffin375058f2019-11-29 20:17:53 +000031var (
32 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
33 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000034 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000035 CommandDeps: []string{
36 "${config.Zip2ZipCmd}",
37 },
38 },
39 "destdir")
40
41 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
42 blueprint.RuleParams{
43 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
44 CommandDeps: []string{
45 "${config.SoongZipCmd}",
46 },
47 Rspfile: "$out.rsp",
48 RspfileContent: "$in",
49 },
50 "basedir")
51
52 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
53 blueprint.RuleParams{
54 Command: `${config.MergeZipsCmd} $out $in`,
55 CommandDeps: []string{
56 "${config.MergeZipsCmd}",
57 },
58 })
59)
60
Paul Duffinb645ec82019-11-27 17:43:54 +000061type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090062 content strings.Builder
63 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090064}
65
Paul Duffinb645ec82019-11-27 17:43:54 +000066// generatedFile abstracts operations for writing contents into a file and emit a build rule
67// for the file.
68type generatedFile struct {
69 generatedContents
70 path android.OutputPath
71}
72
Jiyong Park232e7852019-11-04 12:23:40 +090073func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090074 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000075 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090076 }
77}
78
Paul Duffinb645ec82019-11-27 17:43:54 +000079func (gc *generatedContents) Indent() {
80 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090081}
82
Paul Duffinb645ec82019-11-27 17:43:54 +000083func (gc *generatedContents) Dedent() {
84 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090085}
86
Paul Duffinb645ec82019-11-27 17:43:54 +000087func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Jiyong Park9b409bc2019-10-11 14:59:13 +090088 // ninja consumes newline characters in rspfile_content. Prevent it by
Paul Duffin0e0cf1d2019-11-12 19:39:25 +000089 // escaping the backslash in the newline character. The extra backslash
Jiyong Park9b409bc2019-10-11 14:59:13 +090090 // is removed when the rspfile is written to the actual script file
Paul Duffinb645ec82019-11-27 17:43:54 +000091 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090092}
93
94func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
95 rb := android.NewRuleBuilder()
96 // convert \\n to \n
97 rb.Command().
98 Implicits(implicits).
99 Text("echo").Text(proptools.ShellEscape(gf.content.String())).
100 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
101 rb.Command().
102 Text("chmod a+x").Output(gf.path)
103 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
104}
105
Paul Duffin13879572019-11-28 14:31:38 +0000106// Collect all the members.
107//
Paul Duffin1356d8c2020-02-25 19:26:33 +0000108// Returns a list containing type (extracted from the dependency tag) and the variant.
109func (s *sdk) collectMembers(ctx android.ModuleContext) []sdkMemberRef {
110 var memberRefs []sdkMemberRef
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000111 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
112 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000113 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
114 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900115
Paul Duffin13879572019-11-28 14:31:38 +0000116 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000117 if !memberType.IsInstance(child) {
118 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900119 }
Paul Duffin13879572019-11-28 14:31:38 +0000120
Paul Duffin1356d8c2020-02-25 19:26:33 +0000121 memberRefs = append(memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000122
123 // If the member type supports transitive sdk members then recurse down into
124 // its dependencies, otherwise exit traversal.
125 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900126 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000127
128 return false
Paul Duffin13879572019-11-28 14:31:38 +0000129 })
130
Paul Duffin1356d8c2020-02-25 19:26:33 +0000131 return memberRefs
132}
133
134// Organize the members.
135//
136// The members are first grouped by type and then grouped by name. The order of
137// the types is the order they are referenced in android.SdkMemberTypesRegistry.
138// The names are in the order in which the dependencies were added.
139//
140// Returns the members as well as the multilib setting to use.
141func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) ([]*sdkMember, string) {
142 byType := make(map[android.SdkMemberType][]*sdkMember)
143 byName := make(map[string]*sdkMember)
144
145 lib32 := false // True if any of the members have 32 bit version.
146 lib64 := false // True if any of the members have 64 bit version.
147
148 for _, memberRef := range memberRefs {
149 memberType := memberRef.memberType
150 variant := memberRef.variant
151
152 name := ctx.OtherModuleName(variant)
153 member := byName[name]
154 if member == nil {
155 member = &sdkMember{memberType: memberType, name: name}
156 byName[name] = member
157 byType[memberType] = append(byType[memberType], member)
158 }
159
160 multilib := variant.Target().Arch.ArchType.Multilib
161 if multilib == "lib32" {
162 lib32 = true
163 } else if multilib == "lib64" {
164 lib64 = true
165 }
166
167 // Only append new variants to the list. This is needed because a member can be both
168 // exported by the sdk and also be a transitive sdk member.
169 member.variants = appendUniqueVariants(member.variants, variant)
170 }
171
Paul Duffin13879572019-11-28 14:31:38 +0000172 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000173 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000174 membersOfType := byType[memberListProperty.memberType]
175 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900176 }
177
Paul Duffin13ad94f2020-02-19 16:19:27 +0000178 // Compute the setting of multilib.
179 var multilib string
180 if lib32 && lib64 {
181 multilib = "both"
182 } else if lib32 {
183 multilib = "32"
184 } else if lib64 {
185 multilib = "64"
186 }
187
188 return members, multilib
Jiyong Park73c54ee2019-10-22 20:31:18 +0900189}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900190
Paul Duffin72910952020-01-20 18:16:30 +0000191func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
192 for _, v := range variants {
193 if v == newVariant {
194 return variants
195 }
196 }
197 return append(variants, newVariant)
198}
199
Jiyong Park73c54ee2019-10-22 20:31:18 +0900200// SDK directory structure
201// <sdk_root>/
202// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
203// <api_ver>/ : below this directory are all auto-generated
204// Android.bp : definition of 'sdk_snapshot' module is here
205// aidl/
206// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
207// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900208// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900209// include/
210// bionic/libc/include/stdlib.h : an exported header file
211// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900212// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900213// <arch>/include/ : arch-specific exported headers
214// <arch>/include_gen/ : arch-specific generated headers
215// <arch>/lib/
216// libFoo.so : a stub library
217
Jiyong Park232e7852019-11-04 12:23:40 +0900218// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900219// This isn't visible to users, so could be changed in future.
220func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
221 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
222}
223
Jiyong Park232e7852019-11-04 12:23:40 +0900224// buildSnapshot is the main function in this source file. It creates rules to copy
225// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000226func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
227
Paul Duffin865171e2020-03-02 18:38:15 +0000228 exportedMembers := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000229 var memberRefs []sdkMemberRef
230 for _, sdkVariant := range sdkVariants {
231 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000232
233 // Merge the exported member sets from all sdk variants.
234 for key, _ := range sdkVariant.getExportedMembers() {
235 exportedMembers[key] = struct{}{}
236 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000237 }
Paul Duffin865171e2020-03-02 18:38:15 +0000238 s.exportedMembers = exportedMembers
Paul Duffin1356d8c2020-02-25 19:26:33 +0000239
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000240 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900241
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000242 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000243
244 bpFile := &bpFile{
245 modules: make(map[string]*bpModule),
246 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000247
248 builder := &snapshotBuilder{
Paul Duffinb645ec82019-11-27 17:43:54 +0000249 ctx: ctx,
Paul Duffine44358f2019-11-26 18:04:12 +0000250 sdk: s,
Paul Duffinb645ec82019-11-27 17:43:54 +0000251 version: "current",
252 snapshotDir: snapshotDir.OutputPath,
Paul Duffinc62a5102019-12-11 18:34:15 +0000253 copies: make(map[string]string),
Paul Duffinb645ec82019-11-27 17:43:54 +0000254 filesToZip: []android.Path{bp.path},
255 bpFile: bpFile,
256 prebuiltModules: make(map[string]*bpModule),
Jiyong Park73c54ee2019-10-22 20:31:18 +0900257 }
Paul Duffinac37c502019-11-26 18:02:20 +0000258 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900259
Paul Duffin1356d8c2020-02-25 19:26:33 +0000260 members, multilib := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000261 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000262 memberType := member.memberType
263 prebuiltModule := memberType.AddPrebuiltModule(ctx, builder, member)
264 if prebuiltModule == nil {
265 // Fall back to legacy method of building a snapshot
266 memberType.BuildSnapshot(ctx, builder, member)
267 } else {
268 s.createMemberSnapshot(ctx, builder, member, prebuiltModule)
269 }
Jiyong Park73c54ee2019-10-22 20:31:18 +0900270 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900271
Paul Duffine6c0d842020-01-15 14:08:51 +0000272 // Create a transformer that will transform an unversioned module into a versioned module.
273 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
274
Paul Duffin72910952020-01-20 18:16:30 +0000275 // Create a transformer that will transform an unversioned module by replacing any references
276 // to internal members with a unique module name and setting prefer: false.
277 unversionedTransformer := unversionedTransformation{builder: builder}
278
Paul Duffinb645ec82019-11-27 17:43:54 +0000279 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000280 // Prune any empty property sets.
281 unversioned = unversioned.transform(pruneEmptySetTransformer{})
282
Paul Duffinb645ec82019-11-27 17:43:54 +0000283 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000284 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000285
286 // Transform the unversioned module into a versioned one.
287 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000288 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000289
Paul Duffin72910952020-01-20 18:16:30 +0000290 // Transform the unversioned module to make it suitable for use in the snapshot.
291 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000292 bpFile.AddModule(unversioned)
293 }
294
295 // Create the snapshot module.
296 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000297 var snapshotModuleType string
298 if s.properties.Module_exports {
299 snapshotModuleType = "module_exports_snapshot"
300 } else {
301 snapshotModuleType = "sdk_snapshot"
302 }
303 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000304 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000305
306 // Make sure that the snapshot has the same visibility as the sdk.
307 visibility := android.EffectiveVisibilityRules(ctx, s)
308 if len(visibility) != 0 {
309 snapshotModule.AddProperty("visibility", visibility)
310 }
311
Paul Duffin865171e2020-03-02 18:38:15 +0000312 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000313
314 // Compile_multilib defaults to both and must always be set to both on the
315 // device and so only needs to be set when targeted at the host and is neither
316 // unspecified or both.
Paul Duffin865171e2020-03-02 18:38:15 +0000317 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000318 if s.HostSupported() && multilib != "" && multilib != "both" {
Paul Duffin865171e2020-03-02 18:38:15 +0000319 hostSet := targetPropertySet.AddPropertySet("host")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000320 hostSet.AddProperty("compile_multilib", multilib)
321 }
322
Paul Duffin865171e2020-03-02 18:38:15 +0000323 var dynamicMemberPropertiesList []interface{}
324 osTypeToMemberProperties := make(map[android.OsType]*sdk)
325 for _, sdkVariant := range sdkVariants {
326 properties := sdkVariant.dynamicMemberTypeListProperties
327 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
328 dynamicMemberPropertiesList = append(dynamicMemberPropertiesList, properties)
329 }
330
331 // Extract the common lists of members into a separate struct.
332 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
333 extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesList)
334
335 // Add properties common to all os types.
336 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
337
338 // Iterate over the os types in a fixed order.
339 for _, osType := range s.getPossibleOsTypes() {
340 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
341 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
342 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000343 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000344 }
Paul Duffin865171e2020-03-02 18:38:15 +0000345
346 // Prune any empty property sets.
347 snapshotModule.transform(pruneEmptySetTransformer{})
348
Paul Duffinb645ec82019-11-27 17:43:54 +0000349 bpFile.AddModule(snapshotModule)
350
351 // generate Android.bp
352 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
353 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000354
355 bp.build(pctx, ctx, nil)
356
357 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900358
Jiyong Park232e7852019-11-04 12:23:40 +0900359 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000360 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000361 outputDesc := "Building snapshot for " + ctx.ModuleName()
362
363 // If there are no zips to merge then generate the output zip directly.
364 // Otherwise, generate an intermediate zip file into which other zips can be
365 // merged.
366 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000367 var desc string
368 if len(builder.zipsToMerge) == 0 {
369 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000370 desc = outputDesc
371 } else {
372 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000373 desc = "Building intermediate snapshot for " + ctx.ModuleName()
374 }
375
Paul Duffin375058f2019-11-29 20:17:53 +0000376 ctx.Build(pctx, android.BuildParams{
377 Description: desc,
378 Rule: zipFiles,
379 Inputs: filesToZip,
380 Output: zipFile,
381 Args: map[string]string{
382 "basedir": builder.snapshotDir.String(),
383 },
384 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900385
Paul Duffin91547182019-11-12 19:39:36 +0000386 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000387 ctx.Build(pctx, android.BuildParams{
388 Description: outputDesc,
389 Rule: mergeZips,
390 Input: zipFile,
391 Inputs: builder.zipsToMerge,
392 Output: outputZipFile,
393 })
Paul Duffin91547182019-11-12 19:39:36 +0000394 }
395
396 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900397}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000398
Paul Duffin865171e2020-03-02 18:38:15 +0000399func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
400 for _, memberListProperty := range s.memberListProperties() {
401 names := memberListProperty.getter(dynamicMemberTypeListProperties)
402 if len(names) > 0 {
403 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names))
404 }
405 }
406}
407
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000408type propertyTag struct {
409 name string
410}
411
412var sdkMemberReferencePropertyTag = propertyTag{"sdkMemberReferencePropertyTag"}
413
Paul Duffine6c0d842020-01-15 14:08:51 +0000414type unversionedToVersionedTransformation struct {
415 identityTransformation
416 builder *snapshotBuilder
417}
418
Paul Duffine6c0d842020-01-15 14:08:51 +0000419func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
420 // Use a versioned name for the module but remember the original name for the
421 // snapshot.
422 name := module.getValue("name").(string)
423 module.setProperty("name", t.builder.versionedSdkMemberName(name))
424 module.insertAfter("name", "sdk_member_name", name)
425 return module
426}
427
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000428func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
429 if tag == sdkMemberReferencePropertyTag {
430 return t.builder.versionedSdkMemberNames(value.([]string)), tag
431 } else {
432 return value, tag
433 }
434}
435
Paul Duffin72910952020-01-20 18:16:30 +0000436type unversionedTransformation struct {
437 identityTransformation
438 builder *snapshotBuilder
439}
440
441func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
442 // If the module is an internal member then use a unique name for it.
443 name := module.getValue("name").(string)
444 module.setProperty("name", t.builder.unversionedSdkMemberName(name))
445
446 // Set prefer: false - this is not strictly required as that is the default.
447 module.insertAfter("name", "prefer", false)
448
449 return module
450}
451
452func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
453 if tag == sdkMemberReferencePropertyTag {
454 return t.builder.unversionedSdkMemberNames(value.([]string)), tag
455 } else {
456 return value, tag
457 }
458}
459
Paul Duffina78f3a72020-02-21 16:29:35 +0000460type pruneEmptySetTransformer struct {
461 identityTransformation
462}
463
464var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
465
466func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
467 if len(propertySet.properties) == 0 {
468 return nil, nil
469 } else {
470 return propertySet, tag
471 }
472}
473
Paul Duffinb645ec82019-11-27 17:43:54 +0000474func generateBpContents(contents *generatedContents, bpFile *bpFile) {
475 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
476 for _, bpModule := range bpFile.order {
477 contents.Printfln("")
478 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000479 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000480 contents.Printfln("}")
481 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000482}
483
484func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
485 contents.Indent()
486 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000487 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000488
489 reflectedValue := reflect.ValueOf(value)
490 t := reflectedValue.Type()
491
492 kind := t.Kind()
493 switch kind {
494 case reflect.Slice:
495 length := reflectedValue.Len()
496 if length > 1 {
497 contents.Printfln("%s: [", name)
498 contents.Indent()
499 for i := 0; i < length; i = i + 1 {
500 contents.Printfln("%q,", reflectedValue.Index(i).Interface())
501 }
502 contents.Dedent()
503 contents.Printfln("],")
504 } else if length == 0 {
505 contents.Printfln("%s: [],", name)
506 } else {
507 contents.Printfln("%s: [%q],", name, reflectedValue.Index(0).Interface())
508 }
509 case reflect.Bool:
510 contents.Printfln("%s: %t,", name, reflectedValue.Bool())
511
512 case reflect.Ptr:
513 contents.Printfln("%s: {", name)
514 outputPropertySet(contents, reflectedValue.Interface().(*bpPropertySet))
515 contents.Printfln("},")
516
517 default:
518 contents.Printfln("%s: %q,", name, value)
519 }
520 }
521 contents.Dedent()
522}
523
Paul Duffinac37c502019-11-26 18:02:20 +0000524func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000525 contents := &generatedContents{}
526 generateBpContents(contents, s.builderForTests.bpFile)
527 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000528}
529
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000530type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000531 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000532 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000533 version string
534 snapshotDir android.OutputPath
535 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000536
537 // Map from destination to source of each copy - used to eliminate duplicates and
538 // detect conflicts.
539 copies map[string]string
540
Paul Duffinb645ec82019-11-27 17:43:54 +0000541 filesToZip android.Paths
542 zipsToMerge android.Paths
543
544 prebuiltModules map[string]*bpModule
545 prebuiltOrder []*bpModule
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000546}
547
548func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000549 if existing, ok := s.copies[dest]; ok {
550 if existing != src.String() {
551 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
552 return
553 }
554 } else {
555 path := s.snapshotDir.Join(s.ctx, dest)
556 s.ctx.Build(pctx, android.BuildParams{
557 Rule: android.Cp,
558 Input: src,
559 Output: path,
560 })
561 s.filesToZip = append(s.filesToZip, path)
562
563 s.copies[dest] = src.String()
564 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000565}
566
Paul Duffin91547182019-11-12 19:39:36 +0000567func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
568 ctx := s.ctx
569
570 // Repackage the zip file so that the entries are in the destDir directory.
571 // This will allow the zip file to be merged into the snapshot.
572 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000573
574 ctx.Build(pctx, android.BuildParams{
575 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
576 Rule: repackageZip,
577 Input: zipPath,
578 Output: tmpZipPath,
579 Args: map[string]string{
580 "destdir": destDir,
581 },
582 })
Paul Duffin91547182019-11-12 19:39:36 +0000583
584 // Add the repackaged zip file to the files to merge.
585 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
586}
587
Paul Duffin9d8d6092019-12-05 18:19:29 +0000588func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
589 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000590 if s.prebuiltModules[name] != nil {
591 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
592 }
593
594 m := s.bpFile.newModule(moduleType)
595 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000596
Paul Duffinbefa4b92020-03-04 14:22:45 +0000597 variant := member.Variants()[0]
598
Paul Duffin72910952020-01-20 18:16:30 +0000599 if s.sdk.isInternalMember(name) {
600 // An internal member is only referenced from the sdk snapshot which is in the
601 // same package so can be marked as private.
602 m.AddProperty("visibility", []string{"//visibility:private"})
603 } else {
604 // Extract visibility information from a member variant. All variants have the same
605 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000606 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000607 if len(visibility) != 0 {
608 m.AddProperty("visibility", visibility)
609 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000610 }
611
Paul Duffin865171e2020-03-02 18:38:15 +0000612 deviceSupported := false
613 hostSupported := false
614
615 for _, variant := range member.Variants() {
616 osClass := variant.Target().Os.Class
617 if osClass == android.Host || osClass == android.HostCross {
618 hostSupported = true
619 } else if osClass == android.Device {
620 deviceSupported = true
621 }
622 }
623
624 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000625
Paul Duffinbefa4b92020-03-04 14:22:45 +0000626 // Where available copy apex_available properties from the member.
627 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
628 apexAvailable := apexAware.ApexAvailable()
629 if len(apexAvailable) > 0 {
630 m.AddProperty("apex_available", apexAvailable)
631 }
632 }
633
Paul Duffinb645ec82019-11-27 17:43:54 +0000634 s.prebuiltModules[name] = m
635 s.prebuiltOrder = append(s.prebuiltOrder, m)
636 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000637}
638
Paul Duffin865171e2020-03-02 18:38:15 +0000639func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
640 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000641 bpModule.AddProperty("device_supported", false)
642 }
Paul Duffin865171e2020-03-02 18:38:15 +0000643 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000644 bpModule.AddProperty("host_supported", true)
645 }
646}
647
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000648func (s *snapshotBuilder) SdkMemberReferencePropertyTag() android.BpPropertyTag {
649 return sdkMemberReferencePropertyTag
650}
651
Paul Duffinb645ec82019-11-27 17:43:54 +0000652// Get a versioned name appropriate for the SDK snapshot version being taken.
653func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string) string {
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000654 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
655}
Paul Duffinb645ec82019-11-27 17:43:54 +0000656
657func (s *snapshotBuilder) versionedSdkMemberNames(members []string) []string {
658 var references []string = nil
659 for _, m := range members {
660 references = append(references, s.versionedSdkMemberName(m))
661 }
662 return references
663}
Paul Duffin13879572019-11-28 14:31:38 +0000664
Paul Duffin72910952020-01-20 18:16:30 +0000665// Get an internal name unique to the sdk.
666func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string) string {
667 if s.sdk.isInternalMember(unversionedName) {
668 return s.ctx.ModuleName() + "_" + unversionedName
669 } else {
670 return unversionedName
671 }
672}
673
674func (s *snapshotBuilder) unversionedSdkMemberNames(members []string) []string {
675 var references []string = nil
676 for _, m := range members {
677 references = append(references, s.unversionedSdkMemberName(m))
678 }
679 return references
680}
681
Paul Duffin1356d8c2020-02-25 19:26:33 +0000682type sdkMemberRef struct {
683 memberType android.SdkMemberType
684 variant android.SdkAware
685}
686
Paul Duffin13879572019-11-28 14:31:38 +0000687var _ android.SdkMember = (*sdkMember)(nil)
688
689type sdkMember struct {
690 memberType android.SdkMemberType
691 name string
692 variants []android.SdkAware
693}
694
695func (m *sdkMember) Name() string {
696 return m.name
697}
698
699func (m *sdkMember) Variants() []android.SdkAware {
700 return m.variants
701}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000702
703type baseInfo struct {
704 Properties android.SdkMemberProperties
705}
706
707type osTypeSpecificInfo struct {
708 baseInfo
709
710 // The list of arch type specific info for this os type.
711 archTypes []*archTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +0000712
713 // True if the member has common arch variants for this os type.
714 commonArch bool
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000715}
716
717type archTypeSpecificInfo struct {
718 baseInfo
719
720 archType android.ArchType
721}
722
723func (s *sdk) createMemberSnapshot(sdkModuleContext android.ModuleContext, builder *snapshotBuilder, member *sdkMember, bpModule android.BpModule) {
724
725 memberType := member.memberType
726
Paul Duffina04c1072020-03-02 10:16:35 +0000727 // Group the variants by os type.
728 variantsByOsType := make(map[android.OsType][]android.SdkAware)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000729 variants := member.Variants()
730 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +0000731 osType := variant.Target().Os
732 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000733 }
734
Paul Duffina04c1072020-03-02 10:16:35 +0000735 osCount := len(variantsByOsType)
736 createVariantPropertiesStruct := func(os android.OsType) android.SdkMemberProperties {
737 properties := memberType.CreateVariantPropertiesStruct()
738 base := properties.Base()
739 base.Os_count = osCount
740 base.Os = os
741 return properties
742 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000743
Paul Duffina04c1072020-03-02 10:16:35 +0000744 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +0000745
Paul Duffina04c1072020-03-02 10:16:35 +0000746 // The set of properties that are common across all architectures and os types.
747 commonProperties := createVariantPropertiesStruct(android.CommonOS)
748
749 // The list of property structures which are os type specific but common across
750 // architectures within that os type.
751 var osSpecificPropertiesList []android.SdkMemberProperties
752
753 for osType, osTypeVariants := range variantsByOsType {
754 // Group the properties for each variant by arch type within the os.
755 osInfo := &osTypeSpecificInfo{}
756 osTypeToInfo[osType] = osInfo
757
758 // Create a structure into which properties common across the architectures in
759 // this os type will be stored. Add it to the list of os type specific yet
760 // architecture independent properties structs.
761 osInfo.Properties = createVariantPropertiesStruct(osType)
762 osSpecificPropertiesList = append(osSpecificPropertiesList, osInfo.Properties)
763
764 commonArch := false
765 for _, variant := range osTypeVariants {
766 var properties android.SdkMemberProperties
767
768 // Get the info associated with the arch type inside the os info.
769 archType := variant.Target().Arch.ArchType
770
771 if archType.Name == "common" {
772 // The arch type is common so populate the common properties directly.
773 properties = osInfo.Properties
774
775 commonArch = true
Paul Duffin14eb4672020-03-02 11:33:02 +0000776 } else {
Paul Duffina04c1072020-03-02 10:16:35 +0000777 archInfo := &archTypeSpecificInfo{archType: archType}
778 properties = createVariantPropertiesStruct(osType)
779 archInfo.Properties = properties
780
781 osInfo.archTypes = append(osInfo.archTypes, archInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +0000782 }
Paul Duffina04c1072020-03-02 10:16:35 +0000783
784 properties.PopulateFromVariant(variant)
Paul Duffin14eb4672020-03-02 11:33:02 +0000785 }
786
Paul Duffina04c1072020-03-02 10:16:35 +0000787 if commonArch {
788 if len(osTypeVariants) != 1 {
789 panic("Expected to only have 1 variant when arch type is common but found " + string(len(variants)))
790 }
791 } else {
792 var archPropertiesList []android.SdkMemberProperties
793 for _, archInfo := range osInfo.archTypes {
794 archPropertiesList = append(archPropertiesList, archInfo.Properties)
795 }
796
797 extractCommonProperties(osInfo.Properties, archPropertiesList)
798
799 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
800 var multilib string
801 archVariantCount := len(osInfo.archTypes)
802 if archVariantCount == 2 {
803 multilib = "both"
804 } else if archVariantCount == 1 {
805 if strings.HasSuffix(osInfo.archTypes[0].archType.Name, "64") {
806 multilib = "64"
807 } else {
808 multilib = "32"
809 }
810 }
811
812 osInfo.commonArch = commonArch
813 osInfo.Properties.Base().Compile_multilib = multilib
814 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000815 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000816
Paul Duffina04c1072020-03-02 10:16:35 +0000817 // Extract properties which are common across all architectures and os types.
818 extractCommonProperties(commonProperties, osSpecificPropertiesList)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000819
Paul Duffina04c1072020-03-02 10:16:35 +0000820 // Add the common properties to the module.
821 commonProperties.AddToPropertySet(sdkModuleContext, builder, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000822
Paul Duffina04c1072020-03-02 10:16:35 +0000823 // Create a target property set into which target specific properties can be
824 // added.
825 targetPropertySet := bpModule.AddPropertySet("target")
826
827 // Iterate over the os types in a fixed order.
828 for _, osType := range s.getPossibleOsTypes() {
829 osInfo := osTypeToInfo[osType]
830 if osInfo == nil {
831 continue
832 }
833
834 var osPropertySet android.BpPropertySet
835 var archOsPrefix string
836 if len(osTypeToInfo) == 1 {
837 // There is only one os type present in the variants sp don't bother
838 // with adding target specific properties.
839
840 // Create a structure that looks like:
841 // module_type {
842 // name: "...",
843 // ...
844 // <common properties>
845 // ...
846 // <single os type specific properties>
847 //
848 // arch: {
849 // <arch specific sections>
850 // }
851 //
852 osPropertySet = bpModule
853
854 // Arch specific properties need to be added to an arch specific section
855 // within arch.
856 archOsPrefix = ""
857 } else {
858 // Create a structure that looks like:
859 // module_type {
860 // name: "...",
861 // ...
862 // <common properties>
863 // ...
864 // target: {
865 // <arch independent os specific sections, e.g. android>
866 // ...
867 // <arch and os specific sections, e.g. android_x86>
868 // }
869 //
870 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
871
872 // Arch specific properties need to be added to an os and arch specific
873 // section prefixed with <os>_.
874 archOsPrefix = osType.Name + "_"
875 }
876
877 osInfo.Properties.AddToPropertySet(sdkModuleContext, builder, osPropertySet)
878 if !osInfo.commonArch {
879 // Either add the arch specific sections into the target or arch sections
880 // depending on whether they will also be os specific.
881 var archPropertySet android.BpPropertySet
882 if archOsPrefix == "" {
883 archPropertySet = osPropertySet.AddPropertySet("arch")
884 } else {
885 archPropertySet = targetPropertySet
886 }
887
888 // Add arch (and possibly os) specific sections for each set of
889 // arch (and possibly os) specific properties.
890 for _, av := range osInfo.archTypes {
891 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + av.archType.Name)
892
893 av.Properties.AddToPropertySet(sdkModuleContext, builder, archTypePropertySet)
894 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000895 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000896 }
897
898 memberType.FinalizeModule(sdkModuleContext, builder, member, bpModule)
899}
900
Paul Duffina04c1072020-03-02 10:16:35 +0000901// Compute the list of possible os types that this sdk could support.
902func (s *sdk) getPossibleOsTypes() []android.OsType {
903 var osTypes []android.OsType
904 for _, osType := range android.OsTypeList {
905 if s.DeviceSupported() {
906 if osType.Class == android.Device && osType != android.Fuchsia {
907 osTypes = append(osTypes, osType)
908 }
909 }
910 if s.HostSupported() {
911 if osType.Class == android.Host || osType.Class == android.HostCross {
912 osTypes = append(osTypes, osType)
913 }
914 }
915 }
916 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
917 return osTypes
918}
919
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000920// Extract common properties from a slice of property structures of the same type.
921//
922// All the property structures must be of the same type.
923// commonProperties - must be a pointer to the structure into which common properties will be added.
924// inputPropertiesSlice - must be a slice of input properties structures.
925//
926// Iterates over each exported field (capitalized name) and checks to see whether they
927// have the same value (using DeepEquals) across all the input properties. If it does not then no
928// change is made. Otherwise, the common value is stored in the field in the commonProperties
929// and the field in each of the input properties structure is set to its default value.
930func extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
931 commonPropertiesValue := reflect.ValueOf(commonProperties)
932 commonStructValue := commonPropertiesValue.Elem()
933 propertiesStructType := commonStructValue.Type()
934
935 // Create an empty structure from which default values for the field can be copied.
936 emptyStructValue := reflect.New(propertiesStructType).Elem()
937
938 for f := 0; f < propertiesStructType.NumField(); f++ {
939 // Check to see if all the structures have the same value for the field. The commonValue
940 // is nil on entry to the loop and if it is nil on exit then there is no common value,
941 // otherwise it points to the common value.
942 var commonValue *reflect.Value
943 sliceValue := reflect.ValueOf(inputPropertiesSlice)
944
Paul Duffina04c1072020-03-02 10:16:35 +0000945 field := propertiesStructType.Field(f)
946 if field.Name == "SdkMemberPropertiesBase" {
947 continue
948 }
949
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000950 for i := 0; i < sliceValue.Len(); i++ {
951 structValue := sliceValue.Index(i).Elem().Elem()
952 fieldValue := structValue.Field(f)
953 if !fieldValue.CanInterface() {
954 // The field is not exported so ignore it.
955 continue
956 }
957
958 if commonValue == nil {
959 // Use the first value as the commonProperties value.
960 commonValue = &fieldValue
961 } else {
962 // If the value does not match the current common value then there is
963 // no value in common so break out.
964 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
965 commonValue = nil
966 break
967 }
968 }
969 }
970
971 // If the fields all have a common value then store it in the common struct field
972 // and set the input struct's field to the empty value.
973 if commonValue != nil {
974 emptyValue := emptyStructValue.Field(f)
975 commonStructValue.Field(f).Set(*commonValue)
976 for i := 0; i < sliceValue.Len(); i++ {
977 structValue := sliceValue.Index(i).Elem().Elem()
978 fieldValue := structValue.Field(f)
979 fieldValue.Set(emptyValue)
980 }
981 }
982 }
983}