blob: 22155043bfa172d1753039addb6cc3515a7701b8 [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 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 android
16
17import (
Liz Kammera3d79152021-10-28 18:14:04 -040018 "fmt"
Steven Moreland65b3fd92017-12-06 14:18:35 -080019 "path/filepath"
20 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010021 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080022 "strconv"
23 "strings"
24
25 "github.com/google/blueprint/proptools"
26)
27
28// "neverallow" rules for the build system.
29//
30// This allows things which aren't related to the build system and are enforced
Joe Onoratob4638c12021-10-27 15:47:06 -070031// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080032// straightforward away disjoint from implementations and tests which should
33// work regardless of these restrictions.
34//
35// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010036// - it is in one of the "In" paths
37// - it is not in one of the "NotIn" paths
38// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080039// - - values are matched in their entirety
40// - - nil is interpreted as an empty string
41// - - nested properties are separated with a '.'
42// - - if the property is a list, any of the values in the list being matches
43// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010044// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080045
Paul Duffin45338f02021-03-30 23:07:52 +010046func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Colin Cross8a962802024-10-09 15:29:27 -070047 ctx.BottomUp("neverallow", neverallowMutator)
Steven Moreland65b3fd92017-12-06 14:18:35 -080048}
49
Paul Duffin730f2a52019-06-27 14:08:51 +010050var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080051
Paul Duffin730f2a52019-06-27 14:08:51 +010052func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010053 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010055 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000056 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010057 AddNeverAllowRules(createUncompressDexRules()...)
Nelson Li43808202024-11-20 09:05:53 +000058 AddNeverAllowRules(createInstallInRootAllowingRules()...)
Jiyong Park3c306f32022-04-05 15:29:53 +090059 AddNeverAllowRules(createProhibitFrameworkAccessRules()...)
Alan Stokes73feba32022-11-14 12:21:24 +000060 AddNeverAllowRules(createCcStubsRule())
Mark Whitea15790a2023-08-22 21:28:11 +000061 AddNeverAllowRules(createProhibitHeaderOnlyRule())
Steven Moreland0db999c2024-09-03 22:06:24 +000062 AddNeverAllowRules(createLimitNdkExportRule()...)
Inseob Kim76e19852024-10-10 17:57:22 +090063 AddNeverAllowRules(createLimitDirgroupRule()...)
Jihoon Kang0d545b82024-10-11 00:21:57 +000064 AddNeverAllowRules(createFilesystemIsAutoGeneratedRule())
Luca Stefani50098f72024-10-12 17:55:31 +020065 AddNeverAllowRules(createKotlinPluginRule()...)
Jihoon Kang2a7bf752024-11-01 21:21:25 +000066 AddNeverAllowRules(createPrebuiltEtcBpDefineRule())
Neil Fullerdf5f3562018-10-21 17:19:10 +010067}
Steven Moreland65b3fd92017-12-06 14:18:35 -080068
Paul Duffin730f2a52019-06-27 14:08:51 +010069// Add a NeverAllow rule to the set of rules to apply.
70func AddNeverAllowRules(rules ...Rule) {
71 neverallows = append(neverallows, rules...)
72}
73
Sam Delmerico46d08b42022-11-15 15:51:04 -050074var (
75 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010076 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000077 "art/libnativebridge",
78 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010079 "libcore",
80 "libnativehelper",
81 "external/apache-harmony",
82 "external/apache-xml",
83 "external/boringssl",
84 "external/bouncycastle",
85 "external/conscrypt",
86 "external/icu",
87 "external/okhttp",
88 "external/vixl",
89 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010090 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050091 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000092 "frameworks/av/apex",
93 "frameworks/av/tools",
94 "frameworks/native/cmds",
95 "system/apex",
96 "system/bpf",
97 "system/gatekeeper",
98 "system/hwservicemanager",
99 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000100 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000101 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000102 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500103)
Paul Duffinc8111702019-07-22 12:13:55 +0100104
Sam Delmerico46d08b42022-11-15 15:51:04 -0500105func createIncludeDirsRules() []Rule {
106 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000107
Sam Delmerico46d08b42022-11-15 15:51:04 -0500108 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100109 rule :=
110 NeverAllow().
111 WithMatcher("include_dirs", StartsWith(path+"/")).
112 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
113 " to use alternate mechanisms and so can no longer be used.")
114
115 rules = append(rules, rule)
116 }
117
Sam Delmerico46d08b42022-11-15 15:51:04 -0500118 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000119 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
120 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
121 " to use alternate mechanisms and so can no longer be used.")
122 rules = append(rules, rule)
123 }
124
Paul Duffinc8111702019-07-22 12:13:55 +0100125 return rules
126}
127
Paul Duffin730f2a52019-06-27 14:08:51 +0100128func createTrebleRules() []Rule {
129 return []Rule{
130 NeverAllow().
131 In("vendor", "device").
132 With("vndk.enabled", "true").
133 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900134 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100135 Because("the VNDK can never contain a library that is device dependent."),
136 NeverAllow().
137 With("vndk.enabled", "true").
138 Without("vendor", "true").
139 Without("owner", "").
140 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800141
Neil Fullerdf5f3562018-10-21 17:19:10 +0100142 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100143 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800144 Without("name", "libhidlbase-combined-impl").
145 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 With("product_variables.enforce_vintf_manifest.cflags", "*").
147 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100148
149 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100150 NeverAllow().
151 Without("name", "libc_bionic_ndk").
152 With("product_variables.treble_linker_namespaces.cflags", "*").
153 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100154
155 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100156 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100157 }
158}
159
Paul Duffin730f2a52019-06-27 14:08:51 +0100160func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700161 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700162 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700163 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400164 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800165 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000166 "external/robolectric",
Makoto Onukib66bba32023-11-11 00:06:09 +0000167 "frameworks/base/ravenwood",
168 "frameworks/base/tools/hoststubgen",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000169 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800170 }
171
Paul Duffin730f2a52019-06-27 14:08:51 +0100172 return []Rule{
173 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700174 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100175 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700176 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800177 }
178}
179
Colin Crossc511bc52020-04-07 16:50:32 +0000180func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700181 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000182 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
183 // This sometimes works because the APEX modules that contain derive_sdk and
184 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
185 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100186 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700187 // These are for apps and shouldn't be used by non-SDK variant modules.
188 "prebuilts/ndk",
Jiyong Parka574d532024-08-28 18:06:43 +0900189 "frameworks/native/libs/binder/ndk",
Dan Alberte2054a92020-04-20 14:46:47 -0700190 "tools/test/graphicsbenchmark/apps/sample_app",
191 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700192 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000193 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000194 }
195
Colin Cross440e0d02020-06-11 11:32:11 -0700196 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000197 // android_native_app_glue and libRSSupport use native_window.h but target old
198 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
199 // so they can't add libnativewindow to shared_libs to get the header directory
200 // for the platform variant. Allow them to use the platform variant
201 // property to set shared_libs.
202 "prebuilts/ndk",
203 "frameworks/rs",
204 }
205
206 return []Rule{
207 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700208 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000209 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700210 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000211 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700212 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000213 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700214 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000215 }
216}
217
Alan Stokes73feba32022-11-14 12:21:24 +0000218func createCcStubsRule() Rule {
219 ccStubsImplementationInstallableProjectsAllowedList := []string{
Jiyong Parkf6736c72024-07-22 11:22:35 +0900220 "packages/modules/Virtualization/libs/libvm_payload",
Alan Stokes73feba32022-11-14 12:21:24 +0000221 }
222
223 return NeverAllow().
224 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
225 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
226 Because("implementation_installable can only be used in allowed projects.")
227}
228
David Srbeckye033cba2020-05-20 22:20:28 +0100229func createUncompressDexRules() []Rule {
230 return []Rule{
231 NeverAllow().
232 NotIn("art").
233 WithMatcher("uncompress_dex", isSetMatcherInstance).
234 Because("uncompress_dex is only allowed for certain jars for test in art."),
235 }
236}
237
Nelson Li43808202024-11-20 09:05:53 +0000238func createInstallInRootAllowingRules() []Rule {
Inseob Kim800d1142021-06-14 12:03:51 +0900239 return []Rule{
240 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100241 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900242 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100243 Without("name", "init_first_stage.microdroid").
Nelson Li43808202024-11-20 09:05:53 +0000244 Without("name", "librecovery_ui_ext").
Inseob Kim800d1142021-06-14 12:03:51 +0900245 With("install_in_root", "true").
Inseob Kimbe6a66d2024-07-11 15:43:44 +0900246 NotModuleType("prebuilt_root").
Nelson Li43808202024-11-20 09:05:53 +0000247 Because("install_in_root is only for init_first_stage or librecovery_ui_ext."),
Inseob Kim800d1142021-06-14 12:03:51 +0900248 }
249}
250
Jiyong Park3c306f32022-04-05 15:29:53 +0900251func createProhibitFrameworkAccessRules() []Rule {
252 return []Rule{
253 NeverAllow().
254 With("libs", "framework").
255 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
256 Because("framework can't be used when building against SDK"),
257 }
258}
259
Mark Whitea15790a2023-08-22 21:28:11 +0000260func createProhibitHeaderOnlyRule() Rule {
261 return NeverAllow().
262 Without("name", "framework-minus-apex-headers").
263 With("headers_only", "true").
264 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
265}
266
Steven Moreland0db999c2024-09-03 22:06:24 +0000267func createLimitNdkExportRule() []Rule {
268 reason := "If the headers you're trying to export are meant to be a part of the NDK, they should be exposed by an ndk_headers module. If the headers shouldn't be a part of the NDK, the headers should instead be exposed from a separate `cc_library_headers` which consumers depend on."
269 // DO NOT ADD HERE - please consult danalbert@
270 // b/357711733
271 return []Rule{
272 NeverAllow().
273 NotIn("frameworks/native/libs/binder/ndk").
274 ModuleType("ndk_library").
275 WithMatcher("export_header_libs", isSetMatcherInstance).Because(reason),
276 NeverAllow().ModuleType("ndk_library").WithMatcher("export_generated_headers", isSetMatcherInstance).Because(reason),
277 NeverAllow().ModuleType("ndk_library").WithMatcher("export_include_dirs", isSetMatcherInstance).Because(reason),
278 NeverAllow().ModuleType("ndk_library").WithMatcher("export_shared_lib_headers", isSetMatcherInstance).Because(reason),
279 NeverAllow().ModuleType("ndk_library").WithMatcher("export_static_lib_headers", isSetMatcherInstance).Because(reason),
280 }
281}
282
Inseob Kim76e19852024-10-10 17:57:22 +0900283func createLimitDirgroupRule() []Rule {
284 reason := "dirgroup module and dir_srcs property of genrule is allowed only to Trusty build rule."
285 return []Rule{
286 NeverAllow().
287 ModuleType("dirgroup").
288 WithMatcher("visibility", NotInList([]string{"//trusty/vendor/google/aosp/scripts"})).Because(reason),
289 NeverAllow().
290 ModuleType("dirgroup").
291 Without("visibility", "//trusty/vendor/google/aosp/scripts").Because(reason),
292 NeverAllow().
293 ModuleType("genrule").
Inseob Kime8b1ac42024-10-24 09:27:44 +0000294 Without("name", "trusty-arm64.lk.elf.gen").
295 Without("name", "trusty-arm64-test.lk.elf.gen").
296 Without("name", "trusty-x86_64.lk.elf.gen").
297 Without("name", "trusty-x86_64-test.lk.elf.gen").
Inseob Kim76e19852024-10-10 17:57:22 +0900298 WithMatcher("dir_srcs", isSetMatcherInstance).Because(reason),
299 }
300}
301
Jihoon Kang0d545b82024-10-11 00:21:57 +0000302func createFilesystemIsAutoGeneratedRule() Rule {
303 return NeverAllow().
304 NotIn("build/soong/fsgen").
305 ModuleType("filesystem", "android_system_image").
306 WithMatcher("is_auto_generated", isSetMatcherInstance).
307 Because("is_auto_generated property is only allowed for filesystem modules in build/soong/fsgen directory")
308}
309
Luca Stefani50098f72024-10-12 17:55:31 +0200310func createKotlinPluginRule() []Rule {
311 kotlinPluginProjectsAllowedList := []string{
312 // TODO: Migrate compose plugin to the bundled compiler plugin
313 // Actual path prebuilts/sdk/current/androidx/m2repository/androidx/compose/compiler/compiler-hosted
314 "prebuilts/sdk/current/androidx",
315 "external/kotlinc",
316 }
317
318 return []Rule{
319 NeverAllow().
320 NotIn(kotlinPluginProjectsAllowedList...).
321 ModuleType("kotlin_plugin").
322 Because("kotlin_plugin can only be used in allowed projects"),
323 }
324}
325
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000326// These module types are introduced to convert PRODUCT_COPY_FILES to Soong,
327// and is only intended to be used by filesystem_creator.
328func createPrebuiltEtcBpDefineRule() Rule {
329 return NeverAllow().
330 ModuleType(
331 "prebuilt_usr_srec",
332 "prebuilt_priv_app",
333 "prebuilt_rfs",
334 "prebuilt_framework",
335 "prebuilt_res",
336 "prebuilt_wlc_upt",
337 "prebuilt_odm",
Jihoon Kang2e2b7442024-11-05 00:26:20 +0000338 "prebuilt_vendor_dlkm",
339 "prebuilt_bt_firmware",
Jihoon Kangdca2f2b2024-11-06 18:43:19 +0000340 "prebuilt_tvservice",
341 "prebuilt_optee",
Jihoon Kangecf76dd2024-11-12 05:24:46 +0000342 "prebuilt_tvconfig",
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000343 ).
344 DefinedInBpFile().
345 Because("module type not allowed to be defined in bp file")
346}
347
Steven Moreland65b3fd92017-12-06 14:18:35 -0800348func neverallowMutator(ctx BottomUpMutatorContext) {
349 m, ok := ctx.Module().(Module)
350 if !ok {
351 return
352 }
353
354 dir := ctx.ModuleDir() + "/"
355 properties := m.GetProperties()
356
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100357 osClass := ctx.Module().Target().Os.Class
358
Paul Duffin115445b2019-08-07 15:31:07 +0100359 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100360 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800361 if !n.appliesToPath(dir) {
362 continue
363 }
364
Colin Crossfd4f7432019-03-05 15:06:16 -0800365 if !n.appliesToModuleType(ctx.ModuleType()) {
366 continue
367 }
368
Cole Faust5b35cb92024-08-27 15:47:06 -0700369 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370 continue
371 }
372
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100373 if !n.appliesToOsClass(osClass) {
374 continue
375 }
376
Paul Duffin35781882019-07-25 15:41:09 +0100377 if !n.appliesToDirectDeps(ctx) {
378 continue
379 }
380
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000381 if !n.appliesToBpDefinedModule(ctx) {
382 continue
383 }
384
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385 ctx.ModuleErrorf("violates " + n.String())
386 }
387}
388
Paul Duffin73bf0542019-07-12 14:12:49 +0100389type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000390 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100391 String() string
392}
393
394type equalMatcher struct {
395 expected string
396}
397
Anton Hanssone1b18362021-12-23 15:05:38 +0000398func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100399 return m.expected == value
400}
401
402func (m *equalMatcher) String() string {
403 return "=" + m.expected
404}
405
406type anyMatcher struct {
407}
408
Anton Hanssone1b18362021-12-23 15:05:38 +0000409func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100410 return true
411}
412
413func (m *anyMatcher) String() string {
414 return "=*"
415}
416
417var anyMatcherInstance = &anyMatcher{}
418
Paul Duffinc8111702019-07-22 12:13:55 +0100419type startsWithMatcher struct {
420 prefix string
421}
422
Anton Hanssone1b18362021-12-23 15:05:38 +0000423func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100424 return strings.HasPrefix(value, m.prefix)
425}
426
427func (m *startsWithMatcher) String() string {
428 return ".starts-with(" + m.prefix + ")"
429}
430
Anton Hansson45376402020-04-09 14:18:21 +0100431type regexMatcher struct {
432 re *regexp.Regexp
433}
434
Anton Hanssone1b18362021-12-23 15:05:38 +0000435func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100436 return m.re.MatchString(value)
437}
438
439func (m *regexMatcher) String() string {
440 return ".regexp(" + m.re.String() + ")"
441}
442
Andrei Onea115e7e72020-06-05 21:14:03 +0100443type notInListMatcher struct {
444 allowed []string
445}
446
Anton Hanssone1b18362021-12-23 15:05:38 +0000447func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100448 return !InList(value, m.allowed)
449}
450
451func (m *notInListMatcher) String() string {
452 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
453}
454
Colin Crossc511bc52020-04-07 16:50:32 +0000455type isSetMatcher struct{}
456
Anton Hanssone1b18362021-12-23 15:05:38 +0000457func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000458 return value != ""
459}
460
461func (m *isSetMatcher) String() string {
462 return ".is-set"
463}
464
465var isSetMatcherInstance = &isSetMatcher{}
466
Steven Moreland65b3fd92017-12-06 14:18:35 -0800467type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100468 fields []string // e.x.: Vndk.Enabled
469 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800470}
471
Liz Kammera3d79152021-10-28 18:14:04 -0400472func (r *ruleProperty) String() string {
473 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
474}
475
476type ruleProperties []ruleProperty
477
478func (r ruleProperties) String() string {
479 var s []string
480 for _, r := range r {
481 s = append(s, r.String())
482 }
483 return strings.Join(s, " ")
484}
485
Paul Duffin730f2a52019-06-27 14:08:51 +0100486// A NeverAllow rule.
487type Rule interface {
488 In(path ...string) Rule
489
490 NotIn(path ...string) Rule
491
Paul Duffin35781882019-07-25 15:41:09 +0100492 InDirectDeps(deps ...string) Rule
493
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100494 WithOsClass(osClasses ...OsClass) Rule
495
Paul Duffin730f2a52019-06-27 14:08:51 +0100496 ModuleType(types ...string) Rule
497
498 NotModuleType(types ...string) Rule
499
500 With(properties, value string) Rule
501
Paul Duffinc8111702019-07-22 12:13:55 +0100502 WithMatcher(properties string, matcher ValueMatcher) Rule
503
Paul Duffin730f2a52019-06-27 14:08:51 +0100504 Without(properties, value string) Rule
505
Paul Duffinc8111702019-07-22 12:13:55 +0100506 WithoutMatcher(properties string, matcher ValueMatcher) Rule
507
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000508 DefinedInBpFile() Rule
509
Paul Duffin730f2a52019-06-27 14:08:51 +0100510 Because(reason string) Rule
511}
512
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513type rule struct {
514 // User string for why this is a thing.
515 reason string
516
517 paths []string
518 unlessPaths []string
519
Paul Duffin35781882019-07-25 15:41:09 +0100520 directDeps map[string]bool
521
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100522 osClasses []OsClass
523
Colin Crossfd4f7432019-03-05 15:06:16 -0800524 moduleTypes []string
525 unlessModuleTypes []string
526
Liz Kammera3d79152021-10-28 18:14:04 -0400527 props ruleProperties
528 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100529
530 onlyBootclasspathJar bool
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000531
532 definedInBp bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800533}
534
Paul Duffin730f2a52019-06-27 14:08:51 +0100535// Create a new NeverAllow rule.
536func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100537 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800538}
Colin Crossfd4f7432019-03-05 15:06:16 -0800539
Liz Kammera3d79152021-10-28 18:14:04 -0400540// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100541func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542 r.paths = append(r.paths, cleanPaths(path)...)
543 return r
544}
Colin Crossfd4f7432019-03-05 15:06:16 -0800545
Liz Kammera3d79152021-10-28 18:14:04 -0400546// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100547func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800548 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
549 return r
550}
Colin Crossfd4f7432019-03-05 15:06:16 -0800551
Liz Kammera3d79152021-10-28 18:14:04 -0400552// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100553func (r *rule) InDirectDeps(deps ...string) Rule {
554 for _, d := range deps {
555 r.directDeps[d] = true
556 }
557 return r
558}
559
Liz Kammera3d79152021-10-28 18:14:04 -0400560// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100561func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
562 r.osClasses = append(r.osClasses, osClasses...)
563 return r
564}
565
Liz Kammera3d79152021-10-28 18:14:04 -0400566// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100567func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800568 r.moduleTypes = append(r.moduleTypes, types...)
569 return r
570}
571
Liz Kammera3d79152021-10-28 18:14:04 -0400572// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100573func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800574 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
575 return r
576}
577
Liz Kammera3d79152021-10-28 18:14:04 -0400578// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100579func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100580 return r.WithMatcher(properties, selectMatcher(value))
581}
582
Liz Kammera3d79152021-10-28 18:14:04 -0400583// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100584func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800585 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100586 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100587 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800588 })
589 return r
590}
Colin Crossfd4f7432019-03-05 15:06:16 -0800591
Liz Kammera3d79152021-10-28 18:14:04 -0400592// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100593func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100594 return r.WithoutMatcher(properties, selectMatcher(value))
595}
596
Liz Kammera3d79152021-10-28 18:14:04 -0400597// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100598func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800599 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100600 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100601 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800602 })
603 return r
604}
Colin Crossfd4f7432019-03-05 15:06:16 -0800605
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000606// DefinedInBpFile specifies that this rule applies to modules that are defined
607// in bp files, and does not apply to modules that are auto generated by other modules.
608func (r *rule) DefinedInBpFile() Rule {
609 r.definedInBp = true
610 return r
611}
612
Paul Duffin73bf0542019-07-12 14:12:49 +0100613func selectMatcher(expected string) ValueMatcher {
614 if expected == "*" {
615 return anyMatcherInstance
616 }
617 return &equalMatcher{expected: expected}
618}
619
Liz Kammera3d79152021-10-28 18:14:04 -0400620// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100621func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800622 r.reason = reason
623 return r
624}
625
626func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400627 s := []string{"neverallow requirements. Not allowed:"}
628 if len(r.paths) > 0 {
629 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800630 }
Liz Kammera3d79152021-10-28 18:14:04 -0400631 if len(r.moduleTypes) > 0 {
632 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800633 }
Liz Kammera3d79152021-10-28 18:14:04 -0400634 if len(r.props) > 0 {
635 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800636 }
Liz Kammera3d79152021-10-28 18:14:04 -0400637 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800638 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800639 }
Liz Kammera3d79152021-10-28 18:14:04 -0400640 if len(r.osClasses) > 0 {
641 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100642 }
Liz Kammera3d79152021-10-28 18:14:04 -0400643 if len(r.unlessPaths) > 0 {
644 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
645 }
646 if len(r.unlessModuleTypes) > 0 {
647 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
648 }
649 if len(r.unlessProps) > 0 {
650 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100651 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800652 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400653 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800654 }
Liz Kammera3d79152021-10-28 18:14:04 -0400655 if len(s) == 1 {
656 s[0] = "neverallow requirements (empty)"
657 }
658 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800659}
660
661func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800662 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
663 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800664 return includePath && !excludePath
665}
666
Paul Duffin35781882019-07-25 15:41:09 +0100667func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
668 if len(r.directDeps) == 0 {
669 return true
670 }
671
672 matches := false
673 ctx.VisitDirectDeps(func(m Module) {
674 if !matches {
675 name := ctx.OtherModuleName(m)
676 matches = r.directDeps[name]
677 }
678 })
679
680 return matches
681}
682
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100683func (r *rule) appliesToOsClass(osClass OsClass) bool {
684 if len(r.osClasses) == 0 {
685 return true
686 }
687
688 for _, c := range r.osClasses {
689 if c == osClass {
690 return true
691 }
692 }
693
694 return false
695}
696
Colin Crossfd4f7432019-03-05 15:06:16 -0800697func (r *rule) appliesToModuleType(moduleType string) bool {
698 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
699}
700
Cole Faust5b35cb92024-08-27 15:47:06 -0700701func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
702 includeProps := hasAllProperties(ctx, properties, r.props)
703 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800704 return includeProps && !excludeProps
705}
706
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000707func (r *rule) appliesToBpDefinedModule(ctx BottomUpMutatorContext) bool {
708 if !r.definedInBp {
709 return true
710 }
711 return !ctx.OtherModuleIsAutoGenerated(ctx.Module()) == r.definedInBp
712}
713
Paul Duffinc8111702019-07-22 12:13:55 +0100714func StartsWith(prefix string) ValueMatcher {
715 return &startsWithMatcher{prefix}
716}
717
Anton Hansson45376402020-04-09 14:18:21 +0100718func Regexp(re string) ValueMatcher {
719 r, err := regexp.Compile(re)
720 if err != nil {
721 panic(err)
722 }
723 return &regexMatcher{r}
724}
725
Andrei Onea115e7e72020-06-05 21:14:03 +0100726func NotInList(allowed []string) ValueMatcher {
727 return &notInListMatcher{allowed}
728}
729
Steven Moreland65b3fd92017-12-06 14:18:35 -0800730// assorted utils
731
732func cleanPaths(paths []string) []string {
733 res := make([]string, len(paths))
734 for i, v := range paths {
735 res[i] = filepath.Clean(v) + "/"
736 }
737 return res
738}
739
740func fieldNamesForProperties(propertyNames string) []string {
741 names := strings.Split(propertyNames, ".")
742 for i, v := range names {
743 names[i] = proptools.FieldNameForProperty(v)
744 }
745 return names
746}
747
Cole Faust5b35cb92024-08-27 15:47:06 -0700748func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800749 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700750 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800751 return true
752 }
753 }
754 return false
755}
756
Cole Faust5b35cb92024-08-27 15:47:06 -0700757func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800758 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700759 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800760 return false
761 }
762 }
763 return true
764}
765
Cole Faust5b35cb92024-08-27 15:47:06 -0700766func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800767 for _, propertyStruct := range properties {
768 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
769 for _, v := range prop.fields {
770 if !propertiesValue.IsValid() {
771 break
772 }
773 propertiesValue = propertiesValue.FieldByName(v)
774 }
775 if !propertiesValue.IsValid() {
776 continue
777 }
778
Paul Duffin73bf0542019-07-12 14:12:49 +0100779 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000780 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800781 }
782
Cole Faust5b35cb92024-08-27 15:47:06 -0700783 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800784 return true
785 }
786 }
787 return false
788}
789
Cole Faust5b35cb92024-08-27 15:47:06 -0700790func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800791 if !value.IsValid() {
792 return false
793 }
794
795 if value.Kind() == reflect.Ptr {
796 if value.IsNil() {
797 return check("")
798 }
799 value = value.Elem()
800 }
801
Cole Faust5b35cb92024-08-27 15:47:06 -0700802 switch v := value.Interface().(type) {
803 case string:
804 return check(v)
805 case bool:
806 return check(strconv.FormatBool(v))
807 case int:
808 return check(strconv.FormatInt((int64)(v), 10))
809 case []string:
810 for _, v := range v {
811 if check(v) {
812 return true
813 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800814 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700815 return false
816 case proptools.Configurable[string]:
817 return check(v.GetOrDefault(ctx, ""))
818 case proptools.Configurable[bool]:
819 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
820 case proptools.Configurable[[]string]:
821 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800822 if check(v) {
823 return true
824 }
825 }
826 return false
827 }
828
829 panic("Can't handle type: " + value.Kind().String())
830}
Paul Duffin115445b2019-08-07 15:31:07 +0100831
832var neverallowRulesKey = NewOnceKey("neverallowRules")
833
834func neverallowRules(config Config) []Rule {
835 return config.Once(neverallowRulesKey, func() interface{} {
836 // No test rules were set by setTestNeverallowRules, use the global rules
837 return neverallows
838 }).([]Rule)
839}
840
841// Overrides the default neverallow rules for the supplied config.
842//
843// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100844func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100845 config.Once(neverallowRulesKey, func() interface{} { return testRules })
846}
Paul Duffin45338f02021-03-30 23:07:52 +0100847
848// Prepares for a test by setting neverallow rules and enabling the mutator.
849//
850// If the supplied rules are nil then the default rules are used.
851func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
852 return GroupFixturePreparers(
853 FixtureModifyConfig(func(config Config) {
854 if testRules != nil {
855 setTestNeverallowRules(config, testRules)
856 }
857 }),
858 FixtureRegisterWithContext(func(ctx RegistrationContext) {
859 ctx.PostDepsMutators(registerNeverallowMutator)
860 }),
861 )
862}