blob: 496e2a5bbd89aa4b3eb48ced5104c5a7b9fee236 [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} && ` +
34 `(cd ${outDir} && find ./ -name "*.aidl" -print0 | LC_ALL=C sort -z | xargs -0 sha1sum && echo ${latestVersion}) | sha1sum | cut -d " " -f 1 > ${hashFile} `,
35 CommandDeps: []string{"${aidlCmd}"},
36 }, "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 {
53 BaseName string
54 Srcs []string `android:"path"`
55 AidlRoot string // base directory for the input aidl file
56 Stability *string
57 Imports []string
58 Versions []string
59}
60
61type aidlApi struct {
62 android.ModuleBase
63
64 properties aidlApiProperties
65
66 // for triggering api check for version X against version X-1
67 checkApiTimestamps android.WritablePaths
68
69 // for triggering updating current API
70 updateApiTimestamp android.WritablePath
71
72 // for triggering check that files have not been modified
73 checkHashTimestamps android.WritablePaths
74
75 // for triggering freezing API as the new version
76 freezeApiTimestamp android.WritablePath
77}
78
79func (m *aidlApi) apiDir() string {
80 return filepath.Join(aidlApiDir, m.properties.BaseName)
81}
82
83// `m <iface>-freeze-api` will freeze ToT as this version
84func (m *aidlApi) nextVersion() string {
85 if len(m.properties.Versions) == 0 {
86 return "1"
87 } else {
88 latestVersion := m.properties.Versions[len(m.properties.Versions)-1]
89
90 i, err := strconv.Atoi(latestVersion)
91 if err != nil {
92 panic(err)
93 }
94
95 return strconv.Itoa(i + 1)
96 }
97}
98
99type apiDump struct {
100 dir android.Path
101 files android.Paths
102 hashFile android.OptionalPath
103}
104
105func (m *aidlApi) createApiDumpFromSource(ctx android.ModuleContext) apiDump {
106 srcs, imports := getPaths(ctx, m.properties.Srcs)
107
108 if ctx.Failed() {
109 return apiDump{}
110 }
111
112 var importPaths []string
113 importPaths = append(importPaths, imports...)
114 ctx.VisitDirectDeps(func(dep android.Module) {
115 if importedAidl, ok := dep.(*aidlInterface); ok {
116 importPaths = append(importPaths, importedAidl.properties.Full_import_paths...)
117 }
118 })
119
120 var apiDir android.WritablePath
121 var apiFiles android.WritablePaths
122 var hashFile android.WritablePath
123
124 apiDir = android.PathForModuleOut(ctx, "dump")
125 aidlRoot := android.PathForModuleSrc(ctx, m.properties.AidlRoot)
126 for _, src := range srcs {
127 baseDir := getBaseDir(ctx, src, aidlRoot)
128 relPath, _ := filepath.Rel(baseDir, src.String())
129 outFile := android.PathForModuleOut(ctx, "dump", relPath)
130 apiFiles = append(apiFiles, outFile)
131 }
132 hashFile = android.PathForModuleOut(ctx, "dump", ".hash")
133 latestVersion := "latest-version"
134 if len(m.properties.Versions) >= 1 {
135 latestVersion = m.properties.Versions[len(m.properties.Versions)-1]
136 }
137
138 var optionalFlags []string
139 if m.properties.Stability != nil {
140 optionalFlags = append(optionalFlags, "--stability", *m.properties.Stability)
141 }
142
143 ctx.Build(pctx, android.BuildParams{
144 Rule: aidlDumpApiRule,
145 Outputs: append(apiFiles, hashFile),
146 Inputs: srcs,
147 Args: map[string]string{
148 "optionalFlags": strings.Join(optionalFlags, " "),
149 "imports": strings.Join(wrap("-I", importPaths, ""), " "),
150 "outDir": apiDir.String(),
151 "hashFile": hashFile.String(),
152 "latestVersion": latestVersion,
153 },
154 })
155 return apiDump{apiDir, apiFiles.Paths(), android.OptionalPathForPath(hashFile)}
156}
157
158func (m *aidlApi) makeApiDumpAsVersion(ctx android.ModuleContext, dump apiDump, version string) android.WritablePath {
159 timestampFile := android.PathForModuleOut(ctx, "updateapi_"+version+".timestamp")
160
161 modulePath := android.PathForModuleSrc(ctx).String()
162
163 targetDir := filepath.Join(modulePath, m.apiDir(), version)
164 rb := android.NewRuleBuilder(pctx, ctx)
165 // Wipe the target directory and then copy the API dump into the directory
166 rb.Command().Text("mkdir -p " + targetDir)
167 rb.Command().Text("rm -rf " + targetDir + "/*")
168 if version != currentVersion {
169 rb.Command().Text("cp -rf " + dump.dir.String() + "/. " + targetDir).Implicits(dump.files)
170 // If this is making a new frozen (i.e. non-current) version of the interface,
171 // modify Android.bp file to add the new version to the 'versions' property.
172 rb.Command().BuiltTool("bpmodify").
173 Text("-w -m " + m.properties.BaseName).
174 Text("-parameter versions -a " + version).
175 Text(android.PathForModuleSrc(ctx, "Android.bp").String())
176 } else {
177 // In this case (unfrozen interface), don't copy .hash
178 rb.Command().Text("cp -rf " + dump.dir.String() + "/* " + targetDir).Implicits(dump.files)
179 }
180 rb.Command().Text("touch").Output(timestampFile)
181
182 rb.Build("dump_aidl_api"+m.properties.BaseName+"_"+version,
183 "Making AIDL API of "+m.properties.BaseName+" as version "+version)
184 return timestampFile
185}
186
Jooyung Hanb8a97772021-01-19 01:27:38 +0900187func (m *aidlApi) checkApi(ctx android.ModuleContext, oldDump, newDump apiDump, checkApiLevel string, messageFile android.Path) android.WritablePath {
Jeongik Chada36d5a2021-01-20 00:43:34 +0900188 newVersion := newDump.dir.Base()
189 timestampFile := android.PathForModuleOut(ctx, "checkapi_"+newVersion+".timestamp")
Jeongik Chada36d5a2021-01-20 00:43:34 +0900190
191 var optionalFlags []string
192 if m.properties.Stability != nil {
193 optionalFlags = append(optionalFlags, "--stability", *m.properties.Stability)
194 }
195
196 var implicits android.Paths
197 implicits = append(implicits, oldDump.files...)
198 implicits = append(implicits, newDump.files...)
199 implicits = append(implicits, messageFile)
200 ctx.Build(pctx, android.BuildParams{
201 Rule: aidlCheckApiRule,
202 Implicits: implicits,
203 Output: timestampFile,
204 Args: map[string]string{
205 "optionalFlags": strings.Join(optionalFlags, " "),
206 "old": oldDump.dir.String(),
207 "new": newDump.dir.String(),
208 "messageFile": messageFile.String(),
Jooyung Hanb8a97772021-01-19 01:27:38 +0900209 "checkApiLevel": checkApiLevel,
Jeongik Chada36d5a2021-01-20 00:43:34 +0900210 },
211 })
212 return timestampFile
213}
214
Jooyung Hanb8a97772021-01-19 01:27:38 +0900215func (m *aidlApi) checkCompatibility(ctx android.ModuleContext, oldDump, newDump apiDump) android.WritablePath {
216 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_compatibility.txt")
217 return m.checkApi(ctx, oldDump, newDump, "compatible", messageFile)
218}
Jeongik Chada36d5a2021-01-20 00:43:34 +0900219
Jooyung Hanb8a97772021-01-19 01:27:38 +0900220func (m *aidlApi) checkEquality(ctx android.ModuleContext, oldDump apiDump, newDump apiDump) android.WritablePath {
Jeongik Chada36d5a2021-01-20 00:43:34 +0900221 // Use different messages depending on whether platform SDK is finalized or not.
222 // In case when it is finalized, we should never allow updating the already frozen API.
223 // If it's not finalized, we let users to update the current version by invoking
224 // `m <name>-update-api`.
225 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_equality.txt")
226 sdkIsFinal := !ctx.Config().DefaultAppTargetSdk(ctx).IsPreview()
227 if sdkIsFinal {
228 messageFile = android.PathForSource(ctx, "system/tools/aidl/build/message_check_equality_release.txt")
229 }
230 formattedMessageFile := android.PathForModuleOut(ctx, "message_check_equality.txt")
231 rb := android.NewRuleBuilder(pctx, ctx)
232 rb.Command().Text("sed").Flag(" s/%s/" + m.properties.BaseName + "/g ").Input(messageFile).Text(" > ").Output(formattedMessageFile)
233 rb.Build("format_message_"+m.properties.BaseName, "")
234
235 var implicits android.Paths
236 implicits = append(implicits, oldDump.files...)
237 implicits = append(implicits, newDump.files...)
238 implicits = append(implicits, formattedMessageFile)
Jooyung Hanb8a97772021-01-19 01:27:38 +0900239 return m.checkApi(ctx, oldDump, newDump, "equal", formattedMessageFile)
Jeongik Chada36d5a2021-01-20 00:43:34 +0900240}
241
242func (m *aidlApi) checkIntegrity(ctx android.ModuleContext, dump apiDump) android.WritablePath {
243 version := dump.dir.Base()
244 timestampFile := android.PathForModuleOut(ctx, "checkhash_"+version+".timestamp")
245 messageFile := android.PathForSource(ctx, "system/tools/aidl/build/message_check_integrity.txt")
246
247 i, _ := strconv.Atoi(version)
248 if i == 1 {
249 version = "latest-version"
250 } else {
251 version = strconv.Itoa(i - 1)
252 }
253
254 var implicits android.Paths
255 implicits = append(implicits, dump.files...)
256 implicits = append(implicits, dump.hashFile.Path())
257 implicits = append(implicits, messageFile)
258 ctx.Build(pctx, android.BuildParams{
259 Rule: aidlVerifyHashRule,
260 Implicits: implicits,
261 Output: timestampFile,
262 Args: map[string]string{
263 "apiDir": dump.dir.String(),
264 "version": version,
265 "hashFile": dump.hashFile.Path().String(),
266 "messageFile": messageFile.String(),
267 },
268 })
269 return timestampFile
270}
271
272func (m *aidlApi) GenerateAndroidBuildActions(ctx android.ModuleContext) {
273 // An API dump is created from source and it is compared against the API dump of the
274 // 'current' (yet-to-be-finalized) version. By checking this we enforce that any change in
275 // the AIDL interface is gated by the AIDL API review even before the interface is frozen as
276 // a new version.
277 totApiDump := m.createApiDumpFromSource(ctx)
278 currentApiDir := android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), currentVersion)
279 var currentApiDump apiDump
280 if currentApiDir.Valid() {
281 currentApiDump = apiDump{
282 dir: currentApiDir.Path(),
283 files: ctx.Glob(filepath.Join(currentApiDir.Path().String(), "**/*.aidl"), nil),
284 hashFile: android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), currentVersion, ".hash"),
285 }
286 checked := m.checkEquality(ctx, currentApiDump, totApiDump)
287 m.checkApiTimestamps = append(m.checkApiTimestamps, checked)
288 } else {
289 // The "current" directory might not exist, in case when the interface is first created.
290 // Instruct user to create one by executing `m <name>-update-api`.
291 rb := android.NewRuleBuilder(pctx, ctx)
292 ifaceName := m.properties.BaseName
293 rb.Command().Text(fmt.Sprintf(`echo "API dump for the current version of AIDL interface %s does not exist."`, ifaceName))
294 rb.Command().Text(fmt.Sprintf(`echo Run "m %s-update-api", or add "unstable: true" to the build rule `+
295 `for the interface if it does not need to be versioned`, ifaceName))
296 // This file will never be created. Otherwise, the build will pass simply by running 'm; m'.
297 alwaysChecked := android.PathForModuleOut(ctx, "checkapi_current.timestamp")
298 rb.Command().Text("false").ImplicitOutput(alwaysChecked)
299 rb.Build("check_current_aidl_api", "")
300 m.checkApiTimestamps = append(m.checkApiTimestamps, alwaysChecked)
301 }
302
303 // Also check that version X is backwards compatible with version X-1.
304 // "current" is checked against the latest version.
305 var dumps []apiDump
306 for _, ver := range m.properties.Versions {
307 apiDir := filepath.Join(ctx.ModuleDir(), m.apiDir(), ver)
308 apiDirPath := android.ExistentPathForSource(ctx, apiDir)
309 if apiDirPath.Valid() {
310 dumps = append(dumps, apiDump{
311 dir: apiDirPath.Path(),
312 files: ctx.Glob(filepath.Join(apiDirPath.String(), "**/*.aidl"), nil),
313 hashFile: android.ExistentPathForSource(ctx, ctx.ModuleDir(), m.apiDir(), ver, ".hash"),
314 })
315 } else if ctx.Config().AllowMissingDependencies() {
316 ctx.AddMissingDependencies([]string{apiDir})
317 } else {
318 ctx.ModuleErrorf("API version %s path %s does not exist", ver, apiDir)
319 }
320 }
321 if currentApiDir.Valid() {
322 dumps = append(dumps, currentApiDump)
323 }
324 for i, _ := range dumps {
325 if dumps[i].hashFile.Valid() {
326 checkHashTimestamp := m.checkIntegrity(ctx, dumps[i])
327 m.checkHashTimestamps = append(m.checkHashTimestamps, checkHashTimestamp)
328 }
329
330 if i == 0 {
331 continue
332 }
333 checked := m.checkCompatibility(ctx, dumps[i-1], dumps[i])
334 m.checkApiTimestamps = append(m.checkApiTimestamps, checked)
335 }
336
337 // API dump from source is updated to the 'current' version. Triggered by `m <name>-update-api`
338 m.updateApiTimestamp = m.makeApiDumpAsVersion(ctx, totApiDump, currentVersion)
339
340 // API dump from source is frozen as the next stable version. Triggered by `m <name>-freeze-api`
341 nextVersion := m.nextVersion()
342 m.freezeApiTimestamp = m.makeApiDumpAsVersion(ctx, totApiDump, nextVersion)
343}
344
345func (m *aidlApi) AndroidMk() android.AndroidMkData {
346 return android.AndroidMkData{
347 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
348 android.WriteAndroidMkData(w, data)
349 targetName := m.properties.BaseName + "-freeze-api"
350 fmt.Fprintln(w, ".PHONY:", targetName)
351 fmt.Fprintln(w, targetName+":", m.freezeApiTimestamp.String())
352
353 targetName = m.properties.BaseName + "-update-api"
354 fmt.Fprintln(w, ".PHONY:", targetName)
355 fmt.Fprintln(w, targetName+":", m.updateApiTimestamp.String())
356 },
357 }
358}
359
360func (m *aidlApi) DepsMutator(ctx android.BottomUpMutatorContext) {
361 ctx.AddDependency(ctx.Module(), nil, wrap("", m.properties.Imports, aidlInterfaceSuffix)...)
362}
363
364func aidlApiFactory() android.Module {
365 m := &aidlApi{}
366 m.AddProperties(&m.properties)
367 android.InitAndroidModule(m)
368 return m
369}
370
371func addApiModule(mctx android.LoadHookContext, i *aidlInterface) string {
372 apiModule := i.ModuleBase.Name() + aidlApiSuffix
373 srcs, aidlRoot := i.srcsForVersion(mctx, i.currentVersion())
374 mctx.CreateModule(aidlApiFactory, &nameProperties{
375 Name: proptools.StringPtr(apiModule),
376 }, &aidlApiProperties{
377 BaseName: i.ModuleBase.Name(),
378 Srcs: srcs,
379 AidlRoot: aidlRoot,
380 Stability: i.properties.Stability,
381 Imports: concat(i.properties.Imports, []string{i.ModuleBase.Name()}),
382 Versions: i.properties.Versions,
383 })
384 return apiModule
385}