blob: 7fb22bf1312a71b7a0ece801d822e124283a12b1 [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()...)
Inseob Kim800d1142021-06-14 12:03:51 +090058 AddNeverAllowRules(createInitFirstStageRules()...)
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
Inseob Kim800d1142021-06-14 12:03:51 +0900238func createInitFirstStageRules() []Rule {
239 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").
Inseob Kim800d1142021-06-14 12:03:51 +0900244 With("install_in_root", "true").
Inseob Kimbe6a66d2024-07-11 15:43:44 +0900245 NotModuleType("prebuilt_root").
Inseob Kim800d1142021-06-14 12:03:51 +0900246 Because("install_in_root is only for init_first_stage."),
247 }
248}
249
Jiyong Park3c306f32022-04-05 15:29:53 +0900250func createProhibitFrameworkAccessRules() []Rule {
251 return []Rule{
252 NeverAllow().
253 With("libs", "framework").
254 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
255 Because("framework can't be used when building against SDK"),
256 }
257}
258
Mark Whitea15790a2023-08-22 21:28:11 +0000259func createProhibitHeaderOnlyRule() Rule {
260 return NeverAllow().
261 Without("name", "framework-minus-apex-headers").
262 With("headers_only", "true").
263 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
264}
265
Steven Moreland0db999c2024-09-03 22:06:24 +0000266func createLimitNdkExportRule() []Rule {
267 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."
268 // DO NOT ADD HERE - please consult danalbert@
269 // b/357711733
270 return []Rule{
271 NeverAllow().
272 NotIn("frameworks/native/libs/binder/ndk").
273 ModuleType("ndk_library").
274 WithMatcher("export_header_libs", isSetMatcherInstance).Because(reason),
275 NeverAllow().ModuleType("ndk_library").WithMatcher("export_generated_headers", isSetMatcherInstance).Because(reason),
276 NeverAllow().ModuleType("ndk_library").WithMatcher("export_include_dirs", isSetMatcherInstance).Because(reason),
277 NeverAllow().ModuleType("ndk_library").WithMatcher("export_shared_lib_headers", isSetMatcherInstance).Because(reason),
278 NeverAllow().ModuleType("ndk_library").WithMatcher("export_static_lib_headers", isSetMatcherInstance).Because(reason),
279 }
280}
281
Inseob Kim76e19852024-10-10 17:57:22 +0900282func createLimitDirgroupRule() []Rule {
283 reason := "dirgroup module and dir_srcs property of genrule is allowed only to Trusty build rule."
284 return []Rule{
285 NeverAllow().
286 ModuleType("dirgroup").
287 WithMatcher("visibility", NotInList([]string{"//trusty/vendor/google/aosp/scripts"})).Because(reason),
288 NeverAllow().
289 ModuleType("dirgroup").
290 Without("visibility", "//trusty/vendor/google/aosp/scripts").Because(reason),
291 NeverAllow().
292 ModuleType("genrule").
Inseob Kime8b1ac42024-10-24 09:27:44 +0000293 Without("name", "trusty-arm64.lk.elf.gen").
294 Without("name", "trusty-arm64-test.lk.elf.gen").
295 Without("name", "trusty-x86_64.lk.elf.gen").
296 Without("name", "trusty-x86_64-test.lk.elf.gen").
Inseob Kim76e19852024-10-10 17:57:22 +0900297 WithMatcher("dir_srcs", isSetMatcherInstance).Because(reason),
298 }
299}
300
Jihoon Kang0d545b82024-10-11 00:21:57 +0000301func createFilesystemIsAutoGeneratedRule() Rule {
302 return NeverAllow().
303 NotIn("build/soong/fsgen").
304 ModuleType("filesystem", "android_system_image").
305 WithMatcher("is_auto_generated", isSetMatcherInstance).
306 Because("is_auto_generated property is only allowed for filesystem modules in build/soong/fsgen directory")
307}
308
Luca Stefani50098f72024-10-12 17:55:31 +0200309func createKotlinPluginRule() []Rule {
310 kotlinPluginProjectsAllowedList := []string{
311 // TODO: Migrate compose plugin to the bundled compiler plugin
312 // Actual path prebuilts/sdk/current/androidx/m2repository/androidx/compose/compiler/compiler-hosted
313 "prebuilts/sdk/current/androidx",
314 "external/kotlinc",
315 }
316
317 return []Rule{
318 NeverAllow().
319 NotIn(kotlinPluginProjectsAllowedList...).
320 ModuleType("kotlin_plugin").
321 Because("kotlin_plugin can only be used in allowed projects"),
322 }
323}
324
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000325// These module types are introduced to convert PRODUCT_COPY_FILES to Soong,
326// and is only intended to be used by filesystem_creator.
327func createPrebuiltEtcBpDefineRule() Rule {
328 return NeverAllow().
329 ModuleType(
330 "prebuilt_usr_srec",
331 "prebuilt_priv_app",
332 "prebuilt_rfs",
333 "prebuilt_framework",
334 "prebuilt_res",
335 "prebuilt_wlc_upt",
336 "prebuilt_odm",
337 ).
338 DefinedInBpFile().
339 Because("module type not allowed to be defined in bp file")
340}
341
Steven Moreland65b3fd92017-12-06 14:18:35 -0800342func neverallowMutator(ctx BottomUpMutatorContext) {
343 m, ok := ctx.Module().(Module)
344 if !ok {
345 return
346 }
347
348 dir := ctx.ModuleDir() + "/"
349 properties := m.GetProperties()
350
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100351 osClass := ctx.Module().Target().Os.Class
352
Paul Duffin115445b2019-08-07 15:31:07 +0100353 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100354 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800355 if !n.appliesToPath(dir) {
356 continue
357 }
358
Colin Crossfd4f7432019-03-05 15:06:16 -0800359 if !n.appliesToModuleType(ctx.ModuleType()) {
360 continue
361 }
362
Cole Faust5b35cb92024-08-27 15:47:06 -0700363 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800364 continue
365 }
366
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100367 if !n.appliesToOsClass(osClass) {
368 continue
369 }
370
Paul Duffin35781882019-07-25 15:41:09 +0100371 if !n.appliesToDirectDeps(ctx) {
372 continue
373 }
374
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000375 if !n.appliesToBpDefinedModule(ctx) {
376 continue
377 }
378
Steven Moreland65b3fd92017-12-06 14:18:35 -0800379 ctx.ModuleErrorf("violates " + n.String())
380 }
381}
382
Paul Duffin73bf0542019-07-12 14:12:49 +0100383type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000384 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100385 String() string
386}
387
388type equalMatcher struct {
389 expected string
390}
391
Anton Hanssone1b18362021-12-23 15:05:38 +0000392func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100393 return m.expected == value
394}
395
396func (m *equalMatcher) String() string {
397 return "=" + m.expected
398}
399
400type anyMatcher struct {
401}
402
Anton Hanssone1b18362021-12-23 15:05:38 +0000403func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100404 return true
405}
406
407func (m *anyMatcher) String() string {
408 return "=*"
409}
410
411var anyMatcherInstance = &anyMatcher{}
412
Paul Duffinc8111702019-07-22 12:13:55 +0100413type startsWithMatcher struct {
414 prefix string
415}
416
Anton Hanssone1b18362021-12-23 15:05:38 +0000417func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100418 return strings.HasPrefix(value, m.prefix)
419}
420
421func (m *startsWithMatcher) String() string {
422 return ".starts-with(" + m.prefix + ")"
423}
424
Anton Hansson45376402020-04-09 14:18:21 +0100425type regexMatcher struct {
426 re *regexp.Regexp
427}
428
Anton Hanssone1b18362021-12-23 15:05:38 +0000429func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100430 return m.re.MatchString(value)
431}
432
433func (m *regexMatcher) String() string {
434 return ".regexp(" + m.re.String() + ")"
435}
436
Andrei Onea115e7e72020-06-05 21:14:03 +0100437type notInListMatcher struct {
438 allowed []string
439}
440
Anton Hanssone1b18362021-12-23 15:05:38 +0000441func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100442 return !InList(value, m.allowed)
443}
444
445func (m *notInListMatcher) String() string {
446 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
447}
448
Colin Crossc511bc52020-04-07 16:50:32 +0000449type isSetMatcher struct{}
450
Anton Hanssone1b18362021-12-23 15:05:38 +0000451func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000452 return value != ""
453}
454
455func (m *isSetMatcher) String() string {
456 return ".is-set"
457}
458
459var isSetMatcherInstance = &isSetMatcher{}
460
Steven Moreland65b3fd92017-12-06 14:18:35 -0800461type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100462 fields []string // e.x.: Vndk.Enabled
463 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800464}
465
Liz Kammera3d79152021-10-28 18:14:04 -0400466func (r *ruleProperty) String() string {
467 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
468}
469
470type ruleProperties []ruleProperty
471
472func (r ruleProperties) String() string {
473 var s []string
474 for _, r := range r {
475 s = append(s, r.String())
476 }
477 return strings.Join(s, " ")
478}
479
Paul Duffin730f2a52019-06-27 14:08:51 +0100480// A NeverAllow rule.
481type Rule interface {
482 In(path ...string) Rule
483
484 NotIn(path ...string) Rule
485
Paul Duffin35781882019-07-25 15:41:09 +0100486 InDirectDeps(deps ...string) Rule
487
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100488 WithOsClass(osClasses ...OsClass) Rule
489
Paul Duffin730f2a52019-06-27 14:08:51 +0100490 ModuleType(types ...string) Rule
491
492 NotModuleType(types ...string) Rule
493
494 With(properties, value string) Rule
495
Paul Duffinc8111702019-07-22 12:13:55 +0100496 WithMatcher(properties string, matcher ValueMatcher) Rule
497
Paul Duffin730f2a52019-06-27 14:08:51 +0100498 Without(properties, value string) Rule
499
Paul Duffinc8111702019-07-22 12:13:55 +0100500 WithoutMatcher(properties string, matcher ValueMatcher) Rule
501
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000502 DefinedInBpFile() Rule
503
Paul Duffin730f2a52019-06-27 14:08:51 +0100504 Because(reason string) Rule
505}
506
Steven Moreland65b3fd92017-12-06 14:18:35 -0800507type rule struct {
508 // User string for why this is a thing.
509 reason string
510
511 paths []string
512 unlessPaths []string
513
Paul Duffin35781882019-07-25 15:41:09 +0100514 directDeps map[string]bool
515
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100516 osClasses []OsClass
517
Colin Crossfd4f7432019-03-05 15:06:16 -0800518 moduleTypes []string
519 unlessModuleTypes []string
520
Liz Kammera3d79152021-10-28 18:14:04 -0400521 props ruleProperties
522 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100523
524 onlyBootclasspathJar bool
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000525
526 definedInBp bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800527}
528
Paul Duffin730f2a52019-06-27 14:08:51 +0100529// Create a new NeverAllow rule.
530func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100531 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532}
Colin Crossfd4f7432019-03-05 15:06:16 -0800533
Liz Kammera3d79152021-10-28 18:14:04 -0400534// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100535func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800536 r.paths = append(r.paths, cleanPaths(path)...)
537 return r
538}
Colin Crossfd4f7432019-03-05 15:06:16 -0800539
Liz Kammera3d79152021-10-28 18:14:04 -0400540// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100541func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
543 return r
544}
Colin Crossfd4f7432019-03-05 15:06:16 -0800545
Liz Kammera3d79152021-10-28 18:14:04 -0400546// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100547func (r *rule) InDirectDeps(deps ...string) Rule {
548 for _, d := range deps {
549 r.directDeps[d] = true
550 }
551 return r
552}
553
Liz Kammera3d79152021-10-28 18:14:04 -0400554// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100555func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
556 r.osClasses = append(r.osClasses, osClasses...)
557 return r
558}
559
Liz Kammera3d79152021-10-28 18:14:04 -0400560// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100561func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800562 r.moduleTypes = append(r.moduleTypes, types...)
563 return r
564}
565
Liz Kammera3d79152021-10-28 18:14:04 -0400566// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100567func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800568 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
569 return r
570}
571
Liz Kammera3d79152021-10-28 18:14:04 -0400572// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100573func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100574 return r.WithMatcher(properties, selectMatcher(value))
575}
576
Liz Kammera3d79152021-10-28 18:14:04 -0400577// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100578func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800579 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100580 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100581 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800582 })
583 return r
584}
Colin Crossfd4f7432019-03-05 15:06:16 -0800585
Liz Kammera3d79152021-10-28 18:14:04 -0400586// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100587func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100588 return r.WithoutMatcher(properties, selectMatcher(value))
589}
590
Liz Kammera3d79152021-10-28 18:14:04 -0400591// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100592func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800593 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100594 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100595 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800596 })
597 return r
598}
Colin Crossfd4f7432019-03-05 15:06:16 -0800599
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000600// DefinedInBpFile specifies that this rule applies to modules that are defined
601// in bp files, and does not apply to modules that are auto generated by other modules.
602func (r *rule) DefinedInBpFile() Rule {
603 r.definedInBp = true
604 return r
605}
606
Paul Duffin73bf0542019-07-12 14:12:49 +0100607func selectMatcher(expected string) ValueMatcher {
608 if expected == "*" {
609 return anyMatcherInstance
610 }
611 return &equalMatcher{expected: expected}
612}
613
Liz Kammera3d79152021-10-28 18:14:04 -0400614// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100615func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800616 r.reason = reason
617 return r
618}
619
620func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400621 s := []string{"neverallow requirements. Not allowed:"}
622 if len(r.paths) > 0 {
623 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800624 }
Liz Kammera3d79152021-10-28 18:14:04 -0400625 if len(r.moduleTypes) > 0 {
626 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800627 }
Liz Kammera3d79152021-10-28 18:14:04 -0400628 if len(r.props) > 0 {
629 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800630 }
Liz Kammera3d79152021-10-28 18:14:04 -0400631 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800632 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800633 }
Liz Kammera3d79152021-10-28 18:14:04 -0400634 if len(r.osClasses) > 0 {
635 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100636 }
Liz Kammera3d79152021-10-28 18:14:04 -0400637 if len(r.unlessPaths) > 0 {
638 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
639 }
640 if len(r.unlessModuleTypes) > 0 {
641 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
642 }
643 if len(r.unlessProps) > 0 {
644 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100645 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400647 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800648 }
Liz Kammera3d79152021-10-28 18:14:04 -0400649 if len(s) == 1 {
650 s[0] = "neverallow requirements (empty)"
651 }
652 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800653}
654
655func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800656 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
657 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800658 return includePath && !excludePath
659}
660
Paul Duffin35781882019-07-25 15:41:09 +0100661func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
662 if len(r.directDeps) == 0 {
663 return true
664 }
665
666 matches := false
667 ctx.VisitDirectDeps(func(m Module) {
668 if !matches {
669 name := ctx.OtherModuleName(m)
670 matches = r.directDeps[name]
671 }
672 })
673
674 return matches
675}
676
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100677func (r *rule) appliesToOsClass(osClass OsClass) bool {
678 if len(r.osClasses) == 0 {
679 return true
680 }
681
682 for _, c := range r.osClasses {
683 if c == osClass {
684 return true
685 }
686 }
687
688 return false
689}
690
Colin Crossfd4f7432019-03-05 15:06:16 -0800691func (r *rule) appliesToModuleType(moduleType string) bool {
692 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
693}
694
Cole Faust5b35cb92024-08-27 15:47:06 -0700695func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
696 includeProps := hasAllProperties(ctx, properties, r.props)
697 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800698 return includeProps && !excludeProps
699}
700
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000701func (r *rule) appliesToBpDefinedModule(ctx BottomUpMutatorContext) bool {
702 if !r.definedInBp {
703 return true
704 }
705 return !ctx.OtherModuleIsAutoGenerated(ctx.Module()) == r.definedInBp
706}
707
Paul Duffinc8111702019-07-22 12:13:55 +0100708func StartsWith(prefix string) ValueMatcher {
709 return &startsWithMatcher{prefix}
710}
711
Anton Hansson45376402020-04-09 14:18:21 +0100712func Regexp(re string) ValueMatcher {
713 r, err := regexp.Compile(re)
714 if err != nil {
715 panic(err)
716 }
717 return &regexMatcher{r}
718}
719
Andrei Onea115e7e72020-06-05 21:14:03 +0100720func NotInList(allowed []string) ValueMatcher {
721 return &notInListMatcher{allowed}
722}
723
Steven Moreland65b3fd92017-12-06 14:18:35 -0800724// assorted utils
725
726func cleanPaths(paths []string) []string {
727 res := make([]string, len(paths))
728 for i, v := range paths {
729 res[i] = filepath.Clean(v) + "/"
730 }
731 return res
732}
733
734func fieldNamesForProperties(propertyNames string) []string {
735 names := strings.Split(propertyNames, ".")
736 for i, v := range names {
737 names[i] = proptools.FieldNameForProperty(v)
738 }
739 return names
740}
741
Cole Faust5b35cb92024-08-27 15:47:06 -0700742func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800743 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700744 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800745 return true
746 }
747 }
748 return false
749}
750
Cole Faust5b35cb92024-08-27 15:47:06 -0700751func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800752 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700753 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800754 return false
755 }
756 }
757 return true
758}
759
Cole Faust5b35cb92024-08-27 15:47:06 -0700760func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800761 for _, propertyStruct := range properties {
762 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
763 for _, v := range prop.fields {
764 if !propertiesValue.IsValid() {
765 break
766 }
767 propertiesValue = propertiesValue.FieldByName(v)
768 }
769 if !propertiesValue.IsValid() {
770 continue
771 }
772
Paul Duffin73bf0542019-07-12 14:12:49 +0100773 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000774 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800775 }
776
Cole Faust5b35cb92024-08-27 15:47:06 -0700777 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800778 return true
779 }
780 }
781 return false
782}
783
Cole Faust5b35cb92024-08-27 15:47:06 -0700784func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800785 if !value.IsValid() {
786 return false
787 }
788
789 if value.Kind() == reflect.Ptr {
790 if value.IsNil() {
791 return check("")
792 }
793 value = value.Elem()
794 }
795
Cole Faust5b35cb92024-08-27 15:47:06 -0700796 switch v := value.Interface().(type) {
797 case string:
798 return check(v)
799 case bool:
800 return check(strconv.FormatBool(v))
801 case int:
802 return check(strconv.FormatInt((int64)(v), 10))
803 case []string:
804 for _, v := range v {
805 if check(v) {
806 return true
807 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800808 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700809 return false
810 case proptools.Configurable[string]:
811 return check(v.GetOrDefault(ctx, ""))
812 case proptools.Configurable[bool]:
813 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
814 case proptools.Configurable[[]string]:
815 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800816 if check(v) {
817 return true
818 }
819 }
820 return false
821 }
822
823 panic("Can't handle type: " + value.Kind().String())
824}
Paul Duffin115445b2019-08-07 15:31:07 +0100825
826var neverallowRulesKey = NewOnceKey("neverallowRules")
827
828func neverallowRules(config Config) []Rule {
829 return config.Once(neverallowRulesKey, func() interface{} {
830 // No test rules were set by setTestNeverallowRules, use the global rules
831 return neverallows
832 }).([]Rule)
833}
834
835// Overrides the default neverallow rules for the supplied config.
836//
837// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100838func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100839 config.Once(neverallowRulesKey, func() interface{} { return testRules })
840}
Paul Duffin45338f02021-03-30 23:07:52 +0100841
842// Prepares for a test by setting neverallow rules and enabling the mutator.
843//
844// If the supplied rules are nil then the default rules are used.
845func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
846 return GroupFixturePreparers(
847 FixtureModifyConfig(func(config Config) {
848 if testRules != nil {
849 setTestNeverallowRules(config, testRules)
850 }
851 }),
852 FixtureRegisterWithContext(func(ctx RegistrationContext) {
853 ctx.PostDepsMutators(registerNeverallowMutator)
854 }),
855 )
856}