blob: a8b053a3f253696e8c24b5b19d944efc0cbdb6fb [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
147func (m *aidlApi) makeApiDumpAsVersion(ctx android.ModuleContext, dump apiDump, version string) android.WritablePath {
148 timestampFile := android.PathForModuleOut(ctx, "updateapi_"+version+".timestamp")
149
150 modulePath := android.PathForModuleSrc(ctx).String()
151
152 targetDir := filepath.Join(modulePath, m.apiDir(), version)
153 rb := android.NewRuleBuilder(pctx, ctx)
154 // Wipe the target directory and then copy the API dump into the directory
155 rb.Command().Text("mkdir -p " + targetDir)
156 rb.Command().Text("rm -rf " + targetDir + "/*")
157 if version != currentVersion {
158 rb.Command().Text("cp -rf " + dump.dir.String() + "/. " + targetDir).Implicits(dump.files)
159 // If this is making a new frozen (i.e. non-current) version of the interface,
160 // modify Android.bp file to add the new version to the 'versions' property.
161 rb.Command().BuiltTool("bpmodify").
162 Text("-w -m " + m.properties.BaseName).
163 Text("-parameter versions -a " + version).
164 Text(android.PathForModuleSrc(ctx, "Android.bp").String())
165 } else {
166 // In this case (unfrozen interface), don't copy .hash
167 rb.Command().Text("cp -rf " + dump.dir.String() + "/* " + targetDir).Implicits(dump.files)
168 }
169 rb.Command().Text("touch").Output(timestampFile)
170
171 rb.Build("dump_aidl_api"+m.properties.BaseName+"_"+version,
172 "Making AIDL API of "+m.properties.BaseName+" as version "+version)
173 return timestampFile
174}
175
Jooyung Hanb8a97772021-01-19 01:27:38 +0900176func (m *aidlApi) checkApi(ctx android.ModuleContext, oldDump, newDump apiDump, checkApiLevel string, messageFile android.Path) android.WritablePath {
Jeongik Chada36d5a2021-01-20 00:43:34 +0900177 newVersion := newDump.dir.Base()
178 timestampFile := android.PathForModuleOut(ctx, "checkapi_"+newVersion+".timestamp")
Jeongik Chada36d5a2021-01-20 00:43:34 +0900179
180 var optionalFlags []string
181 if m.properties.Stability != nil {
182 optionalFlags = append(optionalFlags, "--stability", *m.properties.Stability)
183 }
184
185 var implicits android.Paths
186 implicits = append(implicits, oldDump.files...)
187 implicits = append(implicits, newDump.files...)
188 implicits = append(implicits, messageFile)
189 ctx.Build(pctx, android.BuildParams{
190 Rule: aidlCheckApiRule,
191 Implicits: implicits,
192 Output: timestampFile,
193 Args: map[string]string{
194 "optionalFlags": strings.Join(optionalFlags, " "),
195 "old": oldDump.dir.String(),
196 "new": newDump.dir.String(),
197 "messageFile": messageFile.String(),
Jooyung Hanb8a97772021-01-19 01:27:38 +0900198 "checkApiLevel": checkApiLevel,
Jeongik Chada36d5a2021-01-20 00:43:34 +0900199 },
200 })
201 return timestampFile
202}
203
Jooyung Hanb8a97772021-01-19 01:27:38 +0900204func (m *aidlApi) checkCompatibility(ctx android.ModuleContext, oldDump, newDump apiDump) android.WritablePath {
205 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_compatibility.txt")
206 return m.checkApi(ctx, oldDump, newDump, "compatible", messageFile)
207}
Jeongik Chada36d5a2021-01-20 00:43:34 +0900208
Jooyung Hanb8a97772021-01-19 01:27:38 +0900209func (m *aidlApi) checkEquality(ctx android.ModuleContext, oldDump apiDump, newDump apiDump) android.WritablePath {
Jeongik Chada36d5a2021-01-20 00:43:34 +0900210 // Use different messages depending on whether platform SDK is finalized or not.
211 // In case when it is finalized, we should never allow updating the already frozen API.
212 // If it's not finalized, we let users to update the current version by invoking
213 // `m <name>-update-api`.
214 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_equality.txt")
215 sdkIsFinal := !ctx.Config().DefaultAppTargetSdk(ctx).IsPreview()
216 if sdkIsFinal {
217 messageFile = android.PathForSource(ctx, "system/tools/aidl/build/message_check_equality_release.txt")
218 }
219 formattedMessageFile := android.PathForModuleOut(ctx, "message_check_equality.txt")
220 rb := android.NewRuleBuilder(pctx, ctx)
221 rb.Command().Text("sed").Flag(" s/%s/" + m.properties.BaseName + "/g ").Input(messageFile).Text(" > ").Output(formattedMessageFile)
222 rb.Build("format_message_"+m.properties.BaseName, "")
223
224 var implicits android.Paths
225 implicits = append(implicits, oldDump.files...)
226 implicits = append(implicits, newDump.files...)
227 implicits = append(implicits, formattedMessageFile)
Jooyung Hanb8a97772021-01-19 01:27:38 +0900228 return m.checkApi(ctx, oldDump, newDump, "equal", formattedMessageFile)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900229}
230
231func (m *aidlApi) checkIntegrity(ctx android.ModuleContext, dump apiDump) android.WritablePath {
232 version := dump.dir.Base()
233 timestampFile := android.PathForModuleOut(ctx, "checkhash_"+version+".timestamp")
234 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_integrity.txt")
235
Jeongik Chada36d5a2021-01-20 00:43:34 +0900236 var implicits android.Paths
237 implicits = append(implicits, dump.files...)
238 implicits = append(implicits, dump.hashFile.Path())
239 implicits = append(implicits, messageFile)
240 ctx.Build(pctx, android.BuildParams{
241 Rule: aidlVerifyHashRule,
242 Implicits: implicits,
243 Output: timestampFile,
244 Args: map[string]string{
245 "apiDir": dump.dir.String(),
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900246 "version": versionForHashGen(version),
Jeongik Chada36d5a2021-01-20 00:43:34 +0900247 "hashFile": dump.hashFile.Path().String(),
248 "messageFile": messageFile.String(),
249 },
250 })
251 return timestampFile
252}
253
254func (m *aidlApi) GenerateAndroidBuildActions(ctx android.ModuleContext) {
255 // An API dump is created from source and it is compared against the API dump of the
256 // 'current' (yet-to-be-finalized) version. By checking this we enforce that any change in
257 // the AIDL interface is gated by the AIDL API review even before the interface is frozen as
258 // a new version.
259 totApiDump := m.createApiDumpFromSource(ctx)
260 currentApiDir := android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), currentVersion)
261 var currentApiDump apiDump
262 if currentApiDir.Valid() {
263 currentApiDump = apiDump{
264 dir: currentApiDir.Path(),
265 files: ctx.Glob(filepath.Join(currentApiDir.Path().String(), "**/*.aidl"), nil),
266 hashFile: android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), currentVersion, ".hash"),
267 }
268 checked := m.checkEquality(ctx, currentApiDump, totApiDump)
269 m.checkApiTimestamps = append(m.checkApiTimestamps, checked)
270 } else {
271 // The "current" directory might not exist, in case when the interface is first created.
272 // Instruct user to create one by executing `m <name>-update-api`.
273 rb := android.NewRuleBuilder(pctx, ctx)
274 ifaceName := m.properties.BaseName
275 rb.Command().Text(fmt.Sprintf(`echo "API dump for the current version of AIDL interface %s does not exist."`, ifaceName))
276 rb.Command().Text(fmt.Sprintf(`echo Run "m %s-update-api", or add "unstable: true" to the build rule `+
277 `for the interface if it does not need to be versioned`, ifaceName))
278 // This file will never be created. Otherwise, the build will pass simply by running 'm; m'.
279 alwaysChecked := android.PathForModuleOut(ctx, "checkapi_current.timestamp")
280 rb.Command().Text("false").ImplicitOutput(alwaysChecked)
281 rb.Build("check_current_aidl_api", "")
282 m.checkApiTimestamps = append(m.checkApiTimestamps, alwaysChecked)
283 }
284
285 // Also check that version X is backwards compatible with version X-1.
286 // "current" is checked against the latest version.
287 var dumps []apiDump
288 for _, ver := range m.properties.Versions {
289 apiDir := filepath.Join(ctx.ModuleDir(), m.apiDir(), ver)
290 apiDirPath := android.ExistentPathForSource(ctx, apiDir)
291 if apiDirPath.Valid() {
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900292 hashFilePath := filepath.Join(apiDir, ".hash")
293 dump := apiDump{
Jeongik Chada36d5a2021-01-20 00:43:34 +0900294 dir: apiDirPath.Path(),
295 files: ctx.Glob(filepath.Join(apiDirPath.String(), "**/*.aidl"), nil),
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900296 hashFile: android.ExistentPathForSource(ctx, hashFilePath),
297 }
298 if !dump.hashFile.Valid() {
299 cmd := fmt.Sprintf(`(croot && aidl_hash_gen %s %s %s)`, apiDir, versionForHashGen(ver), hashFilePath)
300 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",
301 m.properties.BaseName, ver, cmd)
302 }
303 dumps = append(dumps, dump)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900304 } else if ctx.Config().AllowMissingDependencies() {
305 ctx.AddMissingDependencies([]string{apiDir})
306 } else {
307 ctx.ModuleErrorf("API version %s path %s does not exist", ver, apiDir)
308 }
309 }
310 if currentApiDir.Valid() {
311 dumps = append(dumps, currentApiDump)
312 }
313 for i, _ := range dumps {
314 if dumps[i].hashFile.Valid() {
315 checkHashTimestamp := m.checkIntegrity(ctx, dumps[i])
316 m.checkHashTimestamps = append(m.checkHashTimestamps, checkHashTimestamp)
317 }
318
319 if i == 0 {
320 continue
321 }
322 checked := m.checkCompatibility(ctx, dumps[i-1], dumps[i])
323 m.checkApiTimestamps = append(m.checkApiTimestamps, checked)
324 }
325
326 // API dump from source is updated to the 'current' version. Triggered by `m <name>-update-api`
327 m.updateApiTimestamp = m.makeApiDumpAsVersion(ctx, totApiDump, currentVersion)
328
329 // API dump from source is frozen as the next stable version. Triggered by `m <name>-freeze-api`
330 nextVersion := m.nextVersion()
331 m.freezeApiTimestamp = m.makeApiDumpAsVersion(ctx, totApiDump, nextVersion)
332}
333
334func (m *aidlApi) AndroidMk() android.AndroidMkData {
335 return android.AndroidMkData{
336 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
337 android.WriteAndroidMkData(w, data)
338 targetName := m.properties.BaseName + "-freeze-api"
339 fmt.Fprintln(w, ".PHONY:", targetName)
340 fmt.Fprintln(w, targetName+":", m.freezeApiTimestamp.String())
341
342 targetName = m.properties.BaseName + "-update-api"
343 fmt.Fprintln(w, ".PHONY:", targetName)
344 fmt.Fprintln(w, targetName+":", m.updateApiTimestamp.String())
345 },
346 }
347}
348
349func (m *aidlApi) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Chaa01447d2021-03-17 17:43:12 +0900350 ctx.AddDependency(ctx.Module(), nil, wrap("", m.properties.ImportsWithoutVersion, aidlInterfaceSuffix)...)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900351}
352
353func aidlApiFactory() android.Module {
354 m := &aidlApi{}
355 m.AddProperties(&m.properties)
356 android.InitAndroidModule(m)
357 return m
358}
359
360func addApiModule(mctx android.LoadHookContext, i *aidlInterface) string {
361 apiModule := i.ModuleBase.Name() + aidlApiSuffix
Jeongik Cha52e98022021-01-20 18:37:20 +0900362 srcs, aidlRoot := i.srcsForVersion(mctx, i.nextVersion())
Jeongik Chada36d5a2021-01-20 00:43:34 +0900363 mctx.CreateModule(aidlApiFactory, &nameProperties{
364 Name: proptools.StringPtr(apiModule),
365 }, &aidlApiProperties{
Jeongik Chaa01447d2021-03-17 17:43:12 +0900366 BaseName: i.ModuleBase.Name(),
367 Srcs: srcs,
368 AidlRoot: aidlRoot,
369 Stability: i.properties.Stability,
370 ImportsWithoutVersion: concat(i.properties.ImportsWithoutVersion, []string{i.ModuleBase.Name()}),
371 Versions: i.properties.Versions,
372 Dumpapi: i.properties.Dumpapi,
Jeongik Chada36d5a2021-01-20 00:43:34 +0900373 })
374 return apiModule
375}
Jeongik Cha6cc16f32021-05-18 11:23:55 +0900376
377func versionForHashGen(ver string) string {
378 // aidlHashGen uses the version before current version. If it has never been frozen, return 'latest-version'.
379 verInt, _ := strconv.Atoi(ver)
380 if verInt > 1 {
381 return strconv.Itoa(verInt - 1)
382 }
383 return "latest-version"
384}