blob: 8f17fe8895fb85d07890d0c576f163e379e34170 [file] [log] [blame]
Jeongik Chada36d5a2021-01-20 00:43:34 +09001// Copyright (C) 2021 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 aidl
16
17import (
18 "android/soong/android"
19
20 "fmt"
21 "io"
22 "path/filepath"
23 "strconv"
24 "strings"
25
26 "github.com/google/blueprint"
27 "github.com/google/blueprint/proptools"
28)
29
30var (
31 aidlDumpApiRule = pctx.StaticRule("aidlDumpApiRule", blueprint.RuleParams{
32 Command: `rm -rf "${outDir}" && mkdir -p "${outDir}" && ` +
33 `${aidlCmd} --dumpapi --structured ${imports} ${optionalFlags} --out ${outDir} ${in} && ` +
Jeongik Cha6cc16f32021-05-18 11:23:55 +090034 `${aidlHashGen} ${outDir} ${latestVersion} ${hashFile}`,
35 CommandDeps: []string{"${aidlCmd}", "${aidlHashGen}"},
Jeongik Chada36d5a2021-01-20 00:43:34 +090036 }, "optionalFlags", "imports", "outDir", "hashFile", "latestVersion")
37
38 aidlCheckApiRule = pctx.StaticRule("aidlCheckApiRule", blueprint.RuleParams{
Jooyung Hanb8a97772021-01-19 01:27:38 +090039 Command: `(${aidlCmd} ${optionalFlags} --checkapi=${checkApiLevel} ${old} ${new} && touch ${out}) || ` +
Jeongik Chada36d5a2021-01-20 00:43:34 +090040 `(cat ${messageFile} && exit 1)`,
41 CommandDeps: []string{"${aidlCmd}"},
42 Description: "AIDL CHECK API: ${new} against ${old}",
Jooyung Hanb8a97772021-01-19 01:27:38 +090043 }, "optionalFlags", "old", "new", "messageFile", "checkApiLevel")
Jeongik Chada36d5a2021-01-20 00:43:34 +090044
45 aidlVerifyHashRule = pctx.StaticRule("aidlVerifyHashRule", blueprint.RuleParams{
46 Command: `if [ $$(cd '${apiDir}' && { find ./ -name "*.aidl" -print0 | LC_ALL=C sort -z | xargs -0 sha1sum && echo ${version}; } | sha1sum | cut -d " " -f 1) = $$(read -r <'${hashFile}' hash extra; printf %s $$hash) ]; then ` +
47 `touch ${out}; else cat '${messageFile}' && exit 1; fi`,
48 Description: "Verify ${apiDir} files have not been modified",
49 }, "apiDir", "version", "messageFile", "hashFile")
50)
51
52type aidlApiProperties struct {
Jeongik Chaa01447d2021-03-17 17:43:12 +090053 BaseName string
54 Srcs []string `android:"path"`
55 AidlRoot string // base directory for the input aidl file
56 Stability *string
57 ImportsWithoutVersion []string
58 Versions []string
59 Dumpapi DumpApiProperties
Jeongik Chada36d5a2021-01-20 00:43:34 +090060}
61
62type aidlApi struct {
63 android.ModuleBase
64
65 properties aidlApiProperties
66
67 // for triggering api check for version X against version X-1
68 checkApiTimestamps android.WritablePaths
69
70 // for triggering updating current API
71 updateApiTimestamp android.WritablePath
72
73 // for triggering check that files have not been modified
74 checkHashTimestamps android.WritablePaths
75
76 // for triggering freezing API as the new version
77 freezeApiTimestamp android.WritablePath
78}
79
80func (m *aidlApi) apiDir() string {
81 return filepath.Join(aidlApiDir, m.properties.BaseName)
82}
83
84// `m <iface>-freeze-api` will freeze ToT as this version
85func (m *aidlApi) nextVersion() string {
Jeongik Cha52e98022021-01-20 18:37:20 +090086 return nextVersion(m.properties.Versions)
Jeongik Chada36d5a2021-01-20 00:43:34 +090087}
88
89type apiDump struct {
90 dir android.Path
91 files android.Paths
92 hashFile android.OptionalPath
93}
94
95func (m *aidlApi) createApiDumpFromSource(ctx android.ModuleContext) apiDump {
96 srcs, imports := getPaths(ctx, m.properties.Srcs)
97
98 if ctx.Failed() {
99 return apiDump{}
100 }
101
102 var importPaths []string
103 importPaths = append(importPaths, imports...)
104 ctx.VisitDirectDeps(func(dep android.Module) {
105 if importedAidl, ok := dep.(*aidlInterface); ok {
106 importPaths = append(importPaths, importedAidl.properties.Full_import_paths...)
107 }
108 })
109
110 var apiDir android.WritablePath
111 var apiFiles android.WritablePaths
112 var hashFile android.WritablePath
113
114 apiDir = android.PathForModuleOut(ctx, "dump")
115 aidlRoot := android.PathForModuleSrc(ctx, m.properties.AidlRoot)
116 for _, src := range srcs {
117 baseDir := getBaseDir(ctx, src, aidlRoot)
118 relPath, _ := filepath.Rel(baseDir, src.String())
119 outFile := android.PathForModuleOut(ctx, "dump", relPath)
120 apiFiles = append(apiFiles, outFile)
121 }
122 hashFile = android.PathForModuleOut(ctx, "dump", ".hash")
Jeongik Chada36d5a2021-01-20 00:43:34 +0900123
124 var optionalFlags []string
125 if m.properties.Stability != nil {
126 optionalFlags = append(optionalFlags, "--stability", *m.properties.Stability)
127 }
Jooyung Han252657e2021-02-27 02:51:39 +0900128 if proptools.Bool(m.properties.Dumpapi.No_license) {
129 optionalFlags = append(optionalFlags, "--no_license")
130 }
Jeongik Chada36d5a2021-01-20 00:43:34 +0900131
132 ctx.Build(pctx, android.BuildParams{
133 Rule: aidlDumpApiRule,
134 Outputs: append(apiFiles, hashFile),
135 Inputs: srcs,
136 Args: map[string]string{
137 "optionalFlags": strings.Join(optionalFlags, " "),
138 "imports": strings.Join(wrap("-I", importPaths, ""), " "),
139 "outDir": apiDir.String(),
140 "hashFile": hashFile.String(),
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900141 "latestVersion": versionForHashGen(nextVersion(m.properties.Versions)),
Jeongik Chada36d5a2021-01-20 00:43:34 +0900142 },
143 })
144 return apiDump{apiDir, apiFiles.Paths(), android.OptionalPathForPath(hashFile)}
145}
146
Jiyong Park72e08932021-05-21 00:18:20 +0900147func (m *aidlApi) makeApiDumpAsVersion(ctx android.ModuleContext, dump apiDump, version string, latestVersionDump *apiDump) android.WritablePath {
148 creatingNewVersion := version != currentVersion
149 moduleDir := android.PathForModuleSrc(ctx).String()
150 targetDir := filepath.Join(moduleDir, m.apiDir(), version)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900151 rb := android.NewRuleBuilder(pctx, ctx)
Jiyong Park72e08932021-05-21 00:18:20 +0900152
153 if creatingNewVersion {
154 // We are asked to create a new version. But before doing that, check if the given
155 // dump is the same as the latest version. If so, don't create a new version,
156 // otherwise we will be unnecessarily creating many versions. `newVersionNeededFile`
157 // is created when the equality check fails.
158 newVersionNeededFile := android.PathForModuleOut(ctx, "updateapi_"+version+".needed")
159 rb.Command().Text("rm -f " + newVersionNeededFile.String())
160
161 if latestVersionDump != nil {
162 equalityCheckCommand := rb.Command()
163 equalityCheckCommand.BuiltTool("aidl").
164 FlagWithArg("--checkapi=", "equal")
165 if m.properties.Stability != nil {
166 equalityCheckCommand.FlagWithArg("--stability ", *m.properties.Stability)
167 }
168 equalityCheckCommand.
169 Text(latestVersionDump.dir.String()).Implicits(latestVersionDump.files).
170 Text(dump.dir.String()).Implicits(dump.files).
171 Text("&> /dev/null")
172 equalityCheckCommand.
173 Text("|| touch").
174 Text(newVersionNeededFile.String())
175 } else {
176 // If there is no latest version (i.e. we are creating the initial version)
177 // create the new version unconditionally
178 rb.Command().Text("touch").Text(newVersionNeededFile.String())
179 }
180
181 // Copy the given dump to the target directory only when the equality check failed
182 // (i.e. `newVersionNeededFile` exists).
183 rb.Command().
184 Text("if [ -f " + newVersionNeededFile.String() + " ]; then").
185 Text("cp -rf " + dump.dir.String() + "/. " + targetDir).Implicits(dump.files).
186 Text("; fi")
187
188 // Also modify Android.bp file to add the new version to the 'versions' property.
189 rb.Command().
190 Text("if [ -f " + newVersionNeededFile.String() + " ]; then").
191 BuiltTool("bpmodify").
Jeongik Chada36d5a2021-01-20 00:43:34 +0900192 Text("-w -m " + m.properties.BaseName).
193 Text("-parameter versions -a " + version).
Jiyong Park72e08932021-05-21 00:18:20 +0900194 Text(android.PathForModuleSrc(ctx, "Android.bp").String()).
195 Text("; fi")
196
Jeongik Chada36d5a2021-01-20 00:43:34 +0900197 } else {
Jiyong Park72e08932021-05-21 00:18:20 +0900198 // We are updating the current version. Don't copy .hash to the current dump
199 rb.Command().Text("mkdir -p " + targetDir)
200 rb.Command().Text("rm -rf " + targetDir + "/*")
Jeongik Chada36d5a2021-01-20 00:43:34 +0900201 rb.Command().Text("cp -rf " + dump.dir.String() + "/* " + targetDir).Implicits(dump.files)
202 }
Jiyong Park72e08932021-05-21 00:18:20 +0900203
204 timestampFile := android.PathForModuleOut(ctx, "updateapi_"+version+".timestamp")
Jeongik Chada36d5a2021-01-20 00:43:34 +0900205 rb.Command().Text("touch").Output(timestampFile)
206
207 rb.Build("dump_aidl_api"+m.properties.BaseName+"_"+version,
208 "Making AIDL API of "+m.properties.BaseName+" as version "+version)
209 return timestampFile
210}
211
Jooyung Hanb8a97772021-01-19 01:27:38 +0900212func (m *aidlApi) checkApi(ctx android.ModuleContext, oldDump, newDump apiDump, checkApiLevel string, messageFile android.Path) android.WritablePath {
Jeongik Chada36d5a2021-01-20 00:43:34 +0900213 newVersion := newDump.dir.Base()
214 timestampFile := android.PathForModuleOut(ctx, "checkapi_"+newVersion+".timestamp")
Jeongik Chada36d5a2021-01-20 00:43:34 +0900215
216 var optionalFlags []string
217 if m.properties.Stability != nil {
218 optionalFlags = append(optionalFlags, "--stability", *m.properties.Stability)
219 }
220
221 var implicits android.Paths
222 implicits = append(implicits, oldDump.files...)
223 implicits = append(implicits, newDump.files...)
224 implicits = append(implicits, messageFile)
225 ctx.Build(pctx, android.BuildParams{
226 Rule: aidlCheckApiRule,
227 Implicits: implicits,
228 Output: timestampFile,
229 Args: map[string]string{
230 "optionalFlags": strings.Join(optionalFlags, " "),
231 "old": oldDump.dir.String(),
232 "new": newDump.dir.String(),
233 "messageFile": messageFile.String(),
Jooyung Hanb8a97772021-01-19 01:27:38 +0900234 "checkApiLevel": checkApiLevel,
Jeongik Chada36d5a2021-01-20 00:43:34 +0900235 },
236 })
237 return timestampFile
238}
239
Jooyung Hanb8a97772021-01-19 01:27:38 +0900240func (m *aidlApi) checkCompatibility(ctx android.ModuleContext, oldDump, newDump apiDump) android.WritablePath {
241 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_compatibility.txt")
242 return m.checkApi(ctx, oldDump, newDump, "compatible", messageFile)
243}
Jeongik Chada36d5a2021-01-20 00:43:34 +0900244
Jooyung Hanb8a97772021-01-19 01:27:38 +0900245func (m *aidlApi) checkEquality(ctx android.ModuleContext, oldDump apiDump, newDump apiDump) android.WritablePath {
Jeongik Chada36d5a2021-01-20 00:43:34 +0900246 // Use different messages depending on whether platform SDK is finalized or not.
247 // In case when it is finalized, we should never allow updating the already frozen API.
248 // If it's not finalized, we let users to update the current version by invoking
249 // `m <name>-update-api`.
250 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_equality.txt")
251 sdkIsFinal := !ctx.Config().DefaultAppTargetSdk(ctx).IsPreview()
252 if sdkIsFinal {
253 messageFile = android.PathForSource(ctx, "system/tools/aidl/build/message_check_equality_release.txt")
254 }
255 formattedMessageFile := android.PathForModuleOut(ctx, "message_check_equality.txt")
256 rb := android.NewRuleBuilder(pctx, ctx)
257 rb.Command().Text("sed").Flag(" s/%s/" + m.properties.BaseName + "/g ").Input(messageFile).Text(" > ").Output(formattedMessageFile)
258 rb.Build("format_message_"+m.properties.BaseName, "")
259
260 var implicits android.Paths
261 implicits = append(implicits, oldDump.files...)
262 implicits = append(implicits, newDump.files...)
263 implicits = append(implicits, formattedMessageFile)
Jooyung Hanb8a97772021-01-19 01:27:38 +0900264 return m.checkApi(ctx, oldDump, newDump, "equal", formattedMessageFile)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900265}
266
267func (m *aidlApi) checkIntegrity(ctx android.ModuleContext, dump apiDump) android.WritablePath {
268 version := dump.dir.Base()
269 timestampFile := android.PathForModuleOut(ctx, "checkhash_"+version+".timestamp")
270 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_integrity.txt")
271
Jeongik Chada36d5a2021-01-20 00:43:34 +0900272 var implicits android.Paths
273 implicits = append(implicits, dump.files...)
274 implicits = append(implicits, dump.hashFile.Path())
275 implicits = append(implicits, messageFile)
276 ctx.Build(pctx, android.BuildParams{
277 Rule: aidlVerifyHashRule,
278 Implicits: implicits,
279 Output: timestampFile,
280 Args: map[string]string{
281 "apiDir": dump.dir.String(),
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900282 "version": versionForHashGen(version),
Jeongik Chada36d5a2021-01-20 00:43:34 +0900283 "hashFile": dump.hashFile.Path().String(),
284 "messageFile": messageFile.String(),
285 },
286 })
287 return timestampFile
288}
289
290func (m *aidlApi) GenerateAndroidBuildActions(ctx android.ModuleContext) {
291 // An API dump is created from source and it is compared against the API dump of the
292 // 'current' (yet-to-be-finalized) version. By checking this we enforce that any change in
293 // the AIDL interface is gated by the AIDL API review even before the interface is frozen as
294 // a new version.
295 totApiDump := m.createApiDumpFromSource(ctx)
296 currentApiDir := android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), currentVersion)
297 var currentApiDump apiDump
298 if currentApiDir.Valid() {
299 currentApiDump = apiDump{
300 dir: currentApiDir.Path(),
301 files: ctx.Glob(filepath.Join(currentApiDir.Path().String(), "**/*.aidl"), nil),
302 hashFile: android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), currentVersion, ".hash"),
303 }
304 checked := m.checkEquality(ctx, currentApiDump, totApiDump)
305 m.checkApiTimestamps = append(m.checkApiTimestamps, checked)
306 } else {
307 // The "current" directory might not exist, in case when the interface is first created.
308 // Instruct user to create one by executing `m <name>-update-api`.
309 rb := android.NewRuleBuilder(pctx, ctx)
310 ifaceName := m.properties.BaseName
311 rb.Command().Text(fmt.Sprintf(`echo "API dump for the current version of AIDL interface %s does not exist."`, ifaceName))
312 rb.Command().Text(fmt.Sprintf(`echo Run "m %s-update-api", or add "unstable: true" to the build rule `+
313 `for the interface if it does not need to be versioned`, ifaceName))
314 // This file will never be created. Otherwise, the build will pass simply by running 'm; m'.
315 alwaysChecked := android.PathForModuleOut(ctx, "checkapi_current.timestamp")
316 rb.Command().Text("false").ImplicitOutput(alwaysChecked)
317 rb.Build("check_current_aidl_api", "")
318 m.checkApiTimestamps = append(m.checkApiTimestamps, alwaysChecked)
319 }
320
321 // Also check that version X is backwards compatible with version X-1.
322 // "current" is checked against the latest version.
323 var dumps []apiDump
324 for _, ver := range m.properties.Versions {
325 apiDir := filepath.Join(ctx.ModuleDir(), m.apiDir(), ver)
326 apiDirPath := android.ExistentPathForSource(ctx, apiDir)
327 if apiDirPath.Valid() {
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900328 hashFilePath := filepath.Join(apiDir, ".hash")
329 dump := apiDump{
Jeongik Chada36d5a2021-01-20 00:43:34 +0900330 dir: apiDirPath.Path(),
331 files: ctx.Glob(filepath.Join(apiDirPath.String(), "**/*.aidl"), nil),
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900332 hashFile: android.ExistentPathForSource(ctx, hashFilePath),
333 }
334 if !dump.hashFile.Valid() {
335 cmd := fmt.Sprintf(`(croot && aidl_hash_gen %s %s %s)`, apiDir, versionForHashGen(ver), hashFilePath)
336 ctx.ModuleErrorf("A frozen aidl_interface must have '.hash' file, but %s-V%s doesn't have it. Use the command below to generate hash.\n%s\n",
337 m.properties.BaseName, ver, cmd)
338 }
339 dumps = append(dumps, dump)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900340 } else if ctx.Config().AllowMissingDependencies() {
341 ctx.AddMissingDependencies([]string{apiDir})
342 } else {
343 ctx.ModuleErrorf("API version %s path %s does not exist", ver, apiDir)
344 }
345 }
Jiyong Park72e08932021-05-21 00:18:20 +0900346 var latestVersionDump *apiDump
347 if len(dumps) >= 1 {
348 latestVersionDump = &dumps[len(dumps)-1]
349 }
Jeongik Chada36d5a2021-01-20 00:43:34 +0900350 if currentApiDir.Valid() {
351 dumps = append(dumps, currentApiDump)
352 }
353 for i, _ := range dumps {
354 if dumps[i].hashFile.Valid() {
355 checkHashTimestamp := m.checkIntegrity(ctx, dumps[i])
356 m.checkHashTimestamps = append(m.checkHashTimestamps, checkHashTimestamp)
357 }
358
359 if i == 0 {
360 continue
361 }
362 checked := m.checkCompatibility(ctx, dumps[i-1], dumps[i])
363 m.checkApiTimestamps = append(m.checkApiTimestamps, checked)
364 }
365
366 // API dump from source is updated to the 'current' version. Triggered by `m <name>-update-api`
Jiyong Park72e08932021-05-21 00:18:20 +0900367 m.updateApiTimestamp = m.makeApiDumpAsVersion(ctx, totApiDump, currentVersion, nil)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900368
369 // API dump from source is frozen as the next stable version. Triggered by `m <name>-freeze-api`
370 nextVersion := m.nextVersion()
Jiyong Park72e08932021-05-21 00:18:20 +0900371 m.freezeApiTimestamp = m.makeApiDumpAsVersion(ctx, totApiDump, nextVersion, latestVersionDump)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900372}
373
374func (m *aidlApi) AndroidMk() android.AndroidMkData {
375 return android.AndroidMkData{
376 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
377 android.WriteAndroidMkData(w, data)
378 targetName := m.properties.BaseName + "-freeze-api"
379 fmt.Fprintln(w, ".PHONY:", targetName)
380 fmt.Fprintln(w, targetName+":", m.freezeApiTimestamp.String())
381
382 targetName = m.properties.BaseName + "-update-api"
383 fmt.Fprintln(w, ".PHONY:", targetName)
384 fmt.Fprintln(w, targetName+":", m.updateApiTimestamp.String())
385 },
386 }
387}
388
389func (m *aidlApi) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Chaa01447d2021-03-17 17:43:12 +0900390 ctx.AddDependency(ctx.Module(), nil, wrap("", m.properties.ImportsWithoutVersion, aidlInterfaceSuffix)...)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900391}
392
393func aidlApiFactory() android.Module {
394 m := &aidlApi{}
395 m.AddProperties(&m.properties)
396 android.InitAndroidModule(m)
397 return m
398}
399
400func addApiModule(mctx android.LoadHookContext, i *aidlInterface) string {
401 apiModule := i.ModuleBase.Name() + aidlApiSuffix
Jeongik Cha52e98022021-01-20 18:37:20 +0900402 srcs, aidlRoot := i.srcsForVersion(mctx, i.nextVersion())
Jeongik Chada36d5a2021-01-20 00:43:34 +0900403 mctx.CreateModule(aidlApiFactory, &nameProperties{
404 Name: proptools.StringPtr(apiModule),
405 }, &aidlApiProperties{
Jeongik Chaa01447d2021-03-17 17:43:12 +0900406 BaseName: i.ModuleBase.Name(),
407 Srcs: srcs,
408 AidlRoot: aidlRoot,
409 Stability: i.properties.Stability,
410 ImportsWithoutVersion: concat(i.properties.ImportsWithoutVersion, []string{i.ModuleBase.Name()}),
411 Versions: i.properties.Versions,
412 Dumpapi: i.properties.Dumpapi,
Jeongik Chada36d5a2021-01-20 00:43:34 +0900413 })
414 return apiModule
415}
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900416
417func versionForHashGen(ver string) string {
418 // aidlHashGen uses the version before current version. If it has never been frozen, return 'latest-version'.
419 verInt, _ := strconv.Atoi(ver)
420 if verInt > 1 {
421 return strconv.Itoa(verInt - 1)
422 }
423 return "latest-version"
424}
Jiyong Parke38dab42021-05-20 14:25:34 +0900425
426func init() {
427 android.RegisterSingletonType("aidl-freeze-api", freezeApiSingletonFactory)
428}
429
430func freezeApiSingletonFactory() android.Singleton {
431 return &freezeApiSingleton{}
432}
433
434type freezeApiSingleton struct{}
435
436func (f *freezeApiSingleton) GenerateBuildActions(ctx android.SingletonContext) {
437 var files android.Paths
438 ctx.VisitAllModules(func(module android.Module) {
439 if !module.Enabled() {
440 return
441 }
442 if m, ok := module.(*aidlApi); ok {
443 files = append(files, m.freezeApiTimestamp)
444 }
445 })
446 ctx.Phony("aidl-freeze-api", files...)
447}