blob: e291bdbdf19c7e4388329d20fe2f5ed35a48666c [file] [log] [blame]
Paul Duffin82d90432019-11-30 09:24:33 +00001// Copyright 2019 Google Inc. All rights reserved.
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 (
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000018 "fmt"
Paul Duffin82d90432019-11-30 09:24:33 +000019 "io/ioutil"
20 "os"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +000021 "path/filepath"
Paul Duffin82d90432019-11-30 09:24:33 +000022 "strings"
23 "testing"
24
25 "android/soong/android"
26 "android/soong/apex"
27 "android/soong/cc"
Paul Duffind6ceb862021-03-04 23:02:31 +000028 "android/soong/genrule"
Paul Duffin82d90432019-11-30 09:24:33 +000029 "android/soong/java"
30)
31
Martin Stjernholm7feceb22020-07-11 04:33:29 +010032func testSdkContext(bp string, fs map[string][]byte, extraOsTypes []android.OsType) (*android.TestContext, android.Config) {
33 extraOsTypes = append(extraOsTypes, android.Android, android.Windows)
34
Colin Cross98be1bb2019-12-13 20:41:13 -080035 bp = bp + `
36 apex_key {
37 name: "myapex.key",
38 public_key: "myapex.avbpubkey",
39 private_key: "myapex.pem",
40 }
41
42 android_app_certificate {
43 name: "myapex.cert",
44 certificate: "myapex",
45 }
Martin Stjernholm7feceb22020-07-11 04:33:29 +010046 ` + cc.GatherRequiredDepsForTest(extraOsTypes...)
Colin Cross98be1bb2019-12-13 20:41:13 -080047
48 mockFS := map[string][]byte{
Martin Stjernholmcc776012020-07-07 03:22:21 +010049 "build/make/target/product/security": nil,
50 "apex_manifest.json": nil,
51 "system/sepolicy/apex/myapex-file_contexts": nil,
52 "system/sepolicy/apex/myapex2-file_contexts": nil,
53 "system/sepolicy/apex/mysdkapex-file_contexts": nil,
54 "myapex.avbpubkey": nil,
55 "myapex.pem": nil,
56 "myapex.x509.pem": nil,
57 "myapex.pk8": nil,
Colin Cross98be1bb2019-12-13 20:41:13 -080058 }
59
Colin Crossf28329d2020-02-15 11:00:10 -080060 cc.GatherRequiredFilesForTest(mockFS)
61
Colin Cross98be1bb2019-12-13 20:41:13 -080062 for k, v := range fs {
63 mockFS[k] = v
64 }
65
66 config := android.TestArchConfig(buildDir, nil, bp, mockFS)
67
Paul Duffin08798aa2020-02-27 13:12:46 +000068 // Add windows as a default disable OS to test behavior when some OS variants
69 // are disabled.
70 config.Targets[android.Windows] = []android.Target{
Jiyong Park1613e552020-09-14 19:43:17 +090071 {android.Windows, android.Arch{ArchType: android.X86_64}, android.NativeBridgeDisabled, "", "", true},
Paul Duffin08798aa2020-02-27 13:12:46 +000072 }
73
Martin Stjernholm7feceb22020-07-11 04:33:29 +010074 for _, extraOsType := range extraOsTypes {
75 switch extraOsType {
76 case android.LinuxBionic:
77 config.Targets[android.LinuxBionic] = []android.Target{
Jiyong Park1613e552020-09-14 19:43:17 +090078 {android.LinuxBionic, android.Arch{ArchType: android.X86_64}, android.NativeBridgeDisabled, "", "", false},
Martin Stjernholm7feceb22020-07-11 04:33:29 +010079 }
80 }
81 }
82
Colin Crossae8600b2020-10-29 17:09:13 -070083 ctx := android.NewTestArchContext(config)
Paul Duffin82d90432019-11-30 09:24:33 +000084
Paul Duffin8c3fec42020-03-04 20:15:08 +000085 // Enable androidmk support.
86 // * Register the singleton
87 // * Configure that we are inside make
88 // * Add CommonOS to ensure that androidmk processing works.
89 android.RegisterAndroidMkBuildComponents(ctx)
Jingwen Chencda22c92020-11-23 00:22:30 -050090 android.SetKatiEnabledForTests(config)
Paul Duffin8c3fec42020-03-04 20:15:08 +000091 config.Targets[android.CommonOS] = []android.Target{
Jiyong Park1613e552020-09-14 19:43:17 +090092 {android.CommonOS, android.Arch{ArchType: android.Common}, android.NativeBridgeDisabled, "", "", true},
Paul Duffin8c3fec42020-03-04 20:15:08 +000093 }
94
Paul Duffin82d90432019-11-30 09:24:33 +000095 // from android package
Paul Duffinc1327422020-01-14 12:15:29 +000096 android.RegisterPackageBuildComponents(ctx)
Paul Duffina2ae7e02020-09-11 11:55:00 +010097 ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
Paul Duffin593b3c92019-12-05 14:31:48 +000098 ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
Paul Duffin82d90432019-11-30 09:24:33 +000099 ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
Paul Duffin44f1d842020-06-26 20:17:02 +0100100 ctx.PreArchMutators(android.RegisterComponentsMutator)
Paul Duffin021f4e52020-07-30 16:04:17 +0100101
102 android.RegisterPrebuiltMutators(ctx)
103
104 // Register these after the prebuilt mutators have been registered to match what
105 // happens at runtime.
Paul Duffin593b3c92019-12-05 14:31:48 +0000106 ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
107 ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
108
Paul Duffin82d90432019-11-30 09:24:33 +0000109 // from java package
Paul Duffinc059c8c2021-01-20 17:13:52 +0000110 java.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +0000111
Paul Duffind6ceb862021-03-04 23:02:31 +0000112 // from genrule package
113 genrule.RegisterGenruleBuildComponents(ctx)
114
Paul Duffin82d90432019-11-30 09:24:33 +0000115 // from cc package
Paul Duffin77980a82019-12-19 16:01:36 +0000116 cc.RegisterRequiredBuildComponentsForTest(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +0000117
118 // from apex package
119 ctx.RegisterModuleType("apex", apex.BundleFactory)
120 ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
121 ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
122
123 // from this package
Paul Duffin6d9108f02021-03-09 22:59:28 +0000124 registerModuleExportsBuildComponents(ctx)
125 registerSdkBuildComponents(ctx)
Paul Duffin82d90432019-11-30 09:24:33 +0000126
Colin Crossae8600b2020-10-29 17:09:13 -0700127 ctx.Register()
Paul Duffin82d90432019-11-30 09:24:33 +0000128
129 return ctx, config
130}
131
Martin Stjernholm7feceb22020-07-11 04:33:29 +0100132func runTests(t *testing.T, ctx *android.TestContext, config android.Config) *testSdkResult {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000133 t.Helper()
Paul Duffin593b3c92019-12-05 14:31:48 +0000134 _, errs := ctx.ParseBlueprintsFiles(".")
Paul Duffin82d90432019-11-30 09:24:33 +0000135 android.FailIfErrored(t, errs)
136 _, errs = ctx.PrepareBuildActions(config)
137 android.FailIfErrored(t, errs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000138 return &testSdkResult{
Paul Duffina3cb2b32021-03-10 09:15:22 +0000139 TestHelper: android.TestHelper{T: t},
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000140 ctx: ctx,
141 config: config,
142 }
Paul Duffin82d90432019-11-30 09:24:33 +0000143}
144
Martin Stjernholm7feceb22020-07-11 04:33:29 +0100145func testSdkWithFs(t *testing.T, bp string, fs map[string][]byte) *testSdkResult {
146 t.Helper()
147 ctx, config := testSdkContext(bp, fs, nil)
148 return runTests(t, ctx, config)
149}
150
Paul Duffin82d90432019-11-30 09:24:33 +0000151func testSdkError(t *testing.T, pattern, bp string) {
152 t.Helper()
Martin Stjernholm7feceb22020-07-11 04:33:29 +0100153 ctx, config := testSdkContext(bp, nil, nil)
Paul Duffin82d90432019-11-30 09:24:33 +0000154 _, errs := ctx.ParseFileList(".", []string{"Android.bp"})
155 if len(errs) > 0 {
156 android.FailIfNoMatchingErrors(t, pattern, errs)
157 return
158 }
159 _, errs = ctx.PrepareBuildActions(config)
160 if len(errs) > 0 {
161 android.FailIfNoMatchingErrors(t, pattern, errs)
162 return
163 }
164
165 t.Fatalf("missing expected error %q (0 errors are returned)", pattern)
166}
167
168func ensureListContains(t *testing.T, result []string, expected string) {
169 t.Helper()
170 if !android.InList(expected, result) {
171 t.Errorf("%q is not found in %v", expected, result)
172 }
173}
174
175func pathsToStrings(paths android.Paths) []string {
176 var ret []string
177 for _, p := range paths {
178 ret = append(ret, p.String())
179 }
180 return ret
181}
182
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000183// Encapsulates result of processing an SDK definition. Provides support for
184// checking the state of the build structures.
185type testSdkResult struct {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000186 android.TestHelper
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000187 ctx *android.TestContext
188 config android.Config
189}
190
191// Analyse the sdk build rules to extract information about what it is doing.
192
193// e.g. find the src/dest pairs from each cp command, the various zip files
194// generated, etc.
195func (r *testSdkResult) getSdkSnapshotBuildInfo(sdk *sdk) *snapshotBuildInfo {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000196 info := &snapshotBuildInfo{
Paul Duffind0759072021-02-17 11:23:00 +0000197 r: r,
198 androidBpContents: sdk.GetAndroidBpContentsForTests(),
199 androidUnversionedBpContents: sdk.GetUnversionedAndroidBpContentsForTests(),
200 androidVersionedBpContents: sdk.GetVersionedAndroidBpContentsForTests(),
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000201 }
202
203 buildParams := sdk.BuildParamsForTests()
204 copyRules := &strings.Builder{}
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000205 otherCopyRules := &strings.Builder{}
Paul Duffine1ddcc92020-03-03 16:01:26 +0000206 snapshotDirPrefix := sdk.builderForTests.snapshotDir.String() + "/"
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000207 for _, bp := range buildParams {
208 switch bp.Rule.String() {
209 case android.Cp.String():
Paul Duffine1ddcc92020-03-03 16:01:26 +0000210 output := bp.Output
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000211 // Get destination relative to the snapshot root
212 dest := output.Rel()
213 src := android.NormalizePathForTesting(bp.Input)
214 // We differentiate between copy rules for the snapshot, and copy rules for the install file.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000215 if strings.HasPrefix(output.String(), snapshotDirPrefix) {
216 // Get source relative to build directory.
Paul Duffine1ddcc92020-03-03 16:01:26 +0000217 _, _ = fmt.Fprintf(copyRules, "%s -> %s\n", src, dest)
218 info.snapshotContents = append(info.snapshotContents, dest)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000219 } else {
220 _, _ = fmt.Fprintf(otherCopyRules, "%s -> %s\n", src, dest)
Paul Duffine1ddcc92020-03-03 16:01:26 +0000221 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000222
223 case repackageZip.String():
224 // Add the destdir to the snapshot contents as that is effectively where
225 // the content of the repackaged zip is copied.
226 dest := bp.Args["destdir"]
227 info.snapshotContents = append(info.snapshotContents, dest)
228
229 case zipFiles.String():
230 // This could be an intermediate zip file and not the actual output zip.
231 // In that case this will be overridden when the rule to merge the zips
232 // is processed.
Paul Duffin9b478b02019-12-10 13:41:51 +0000233 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000234
235 case mergeZips.String():
236 // Copy the current outputZip to the intermediateZip.
237 info.intermediateZip = info.outputZip
Paul Duffin9b478b02019-12-10 13:41:51 +0000238 mergeInput := android.NormalizePathForTesting(bp.Input)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000239 if info.intermediateZip != mergeInput {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000240 r.Errorf("Expected intermediate zip %s to be an input to merge zips but found %s instead",
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000241 info.intermediateZip, mergeInput)
242 }
243
244 // Override output zip (which was actually the intermediate zip file) with the actual
245 // output zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000246 info.outputZip = android.NormalizePathForTesting(bp.Output)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000247
248 // Save the zips to be merged into the intermediate zip.
Paul Duffin9b478b02019-12-10 13:41:51 +0000249 info.mergeZips = android.NormalizePathsForTesting(bp.Inputs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000250 }
251 }
252
253 info.copyRules = copyRules.String()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000254 info.otherCopyRules = otherCopyRules.String()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000255
256 return info
257}
258
259func (r *testSdkResult) Module(name string, variant string) android.Module {
260 return r.ctx.ModuleForTests(name, variant).Module()
261}
262
263func (r *testSdkResult) ModuleForTests(name string, variant string) android.TestingModule {
264 return r.ctx.ModuleForTests(name, variant)
265}
266
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000267// Check the snapshot build rules.
268//
269// Takes a list of functions which check different facets of the snapshot build rules.
270// Allows each test to customize what is checked without duplicating lots of code
271// or proliferating check methods of different flavors.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000272func (r *testSdkResult) CheckSnapshot(name string, dir string, checkers ...snapshotBuildInfoChecker) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000273 r.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000274
Paul Duffin1356d8c2020-02-25 19:26:33 +0000275 // The sdk CommonOS variant is always responsible for generating the snapshot.
276 variant := android.CommonOS.Name
277
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000278 sdk := r.Module(name, variant).(*sdk)
279
280 snapshotBuildInfo := r.getSdkSnapshotBuildInfo(sdk)
281
282 // Check state of the snapshot build.
283 for _, checker := range checkers {
284 checker(snapshotBuildInfo)
285 }
286
287 // Make sure that the generated zip file is in the correct place.
288 actual := snapshotBuildInfo.outputZip
Paul Duffin593b3c92019-12-05 14:31:48 +0000289 if dir != "" {
290 dir = filepath.Clean(dir) + "/"
291 }
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000292 r.AssertStringEquals("Snapshot zip file in wrong place",
Paul Duffin593b3c92019-12-05 14:31:48 +0000293 fmt.Sprintf(".intermediates/%s%s/%s/%s-current.zip", dir, name, variant, name), actual)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000294
295 // Populate a mock filesystem with the files that would have been copied by
296 // the rules.
297 fs := make(map[string][]byte)
298 for _, dest := range snapshotBuildInfo.snapshotContents {
299 fs[dest] = nil
300 }
301
302 // Process the generated bp file to make sure it is valid.
Paul Duffina3cb2b32021-03-10 09:15:22 +0000303 testSdkWithFs(r.T, snapshotBuildInfo.androidBpContents, fs)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000304}
305
306type snapshotBuildInfoChecker func(info *snapshotBuildInfo)
307
308// Check that the snapshot's generated Android.bp is correct.
309//
310// Both the expected and actual string are both trimmed before comparing.
311func checkAndroidBpContents(expected string) snapshotBuildInfoChecker {
312 return func(info *snapshotBuildInfo) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000313 info.r.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000314 info.r.AssertTrimmedStringEquals("Android.bp contents do not match", expected, info.androidBpContents)
315 }
316}
317
Paul Duffind0759072021-02-17 11:23:00 +0000318// Check that the snapshot's unversioned generated Android.bp is correct.
319//
320// This func should be used to check the general snapshot generation code.
321//
322// Both the expected and actual string are both trimmed before comparing.
323func checkUnversionedAndroidBpContents(expected string) snapshotBuildInfoChecker {
324 return func(info *snapshotBuildInfo) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000325 info.r.Helper()
Paul Duffind0759072021-02-17 11:23:00 +0000326 info.r.AssertTrimmedStringEquals("unversioned Android.bp contents do not match", expected, info.androidUnversionedBpContents)
327 }
328}
329
330// Check that the snapshot's versioned generated Android.bp is correct.
331//
332// This func should only be used to check the version specific snapshot generation code,
333// i.e. the encoding of version into module names and the generation of the _snapshot module. The
334// general snapshot generation code should be checked using the checkUnversionedAndroidBpContents()
335// func.
336//
337// Both the expected and actual string are both trimmed before comparing.
338func checkVersionedAndroidBpContents(expected string) snapshotBuildInfoChecker {
339 return func(info *snapshotBuildInfo) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000340 info.r.Helper()
Paul Duffind0759072021-02-17 11:23:00 +0000341 info.r.AssertTrimmedStringEquals("versioned Android.bp contents do not match", expected, info.androidVersionedBpContents)
342 }
343}
344
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000345// Check that the snapshot's copy rules are correct.
346//
347// The copy rules are formatted as <src> -> <dest>, one per line and then compared
348// to the supplied expected string. Both the expected and actual string are trimmed
349// before comparing.
350func checkAllCopyRules(expected string) snapshotBuildInfoChecker {
351 return func(info *snapshotBuildInfo) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000352 info.r.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000353 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.copyRules)
354 }
355}
356
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000357func checkAllOtherCopyRules(expected string) snapshotBuildInfoChecker {
358 return func(info *snapshotBuildInfo) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000359 info.r.Helper()
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000360 info.r.AssertTrimmedStringEquals("Incorrect copy rules", expected, info.otherCopyRules)
361 }
362}
363
Paul Duffin3d1248c2020-04-09 00:10:17 +0100364// Check that the specified paths match the list of zips to merge with the intermediate zip.
365func checkMergeZips(expected ...string) snapshotBuildInfoChecker {
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000366 return func(info *snapshotBuildInfo) {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000367 info.r.Helper()
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000368 if info.intermediateZip == "" {
Paul Duffina3cb2b32021-03-10 09:15:22 +0000369 info.r.Errorf("No intermediate zip file was created")
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000370 }
Paul Duffin3d1248c2020-04-09 00:10:17 +0100371
372 info.r.AssertDeepEquals("mismatching merge zip files", expected, info.mergeZips)
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000373 }
374}
375
376// Encapsulates information about the snapshot build structure in order to insulate tests from
377// knowing too much about internal structures.
378//
379// All source/input paths are relative either the build directory. All dest/output paths are
380// relative to the snapshot root directory.
381type snapshotBuildInfo struct {
382 r *testSdkResult
383
384 // The contents of the generated Android.bp file
385 androidBpContents string
386
Paul Duffind0759072021-02-17 11:23:00 +0000387 // The contents of the unversioned Android.bp file
388 androidUnversionedBpContents string
389
390 // The contents of the versioned Android.bp file
391 androidVersionedBpContents string
392
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000393 // The paths, relative to the snapshot root, of all files and directories copied into the
394 // snapshot.
395 snapshotContents []string
396
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000397 // A formatted representation of the src/dest pairs for a snapshot, one pair per line,
398 // of the format src -> dest
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000399 copyRules string
400
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +0000401 // A formatted representation of the src/dest pairs for files not in a snapshot, one pair
402 // per line, of the format src -> dest
403 otherCopyRules string
404
Paul Duffinc3c5d5e2019-11-29 20:45:22 +0000405 // The path to the intermediate zip, which is a zip created from the source files copied
406 // into the snapshot directory and which will be merged with other zips to form the final output.
407 // Is am empty string if there is no intermediate zip because there are no zips to merge in.
408 intermediateZip string
409
410 // The paths to the zips to merge into the output zip, does not include the intermediate
411 // zip.
412 mergeZips []string
413
414 // The final output zip.
415 outputZip string
416}
417
Paul Duffin82d90432019-11-30 09:24:33 +0000418var buildDir string
419
420func setUp() {
421 var err error
422 buildDir, err = ioutil.TempDir("", "soong_sdk_test")
423 if err != nil {
424 panic(err)
425 }
426}
427
428func tearDown() {
429 _ = os.RemoveAll(buildDir)
430}
431
432func runTestWithBuildDir(m *testing.M) {
433 run := func() int {
434 setUp()
435 defer tearDown()
436
437 return m.Run()
438 }
439
440 os.Exit(run())
441}