blob: 6176a996a1c1fb10adbc0ba561126ddfacf193e1 [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",
Jihoon Kang2e2b7442024-11-05 00:26:20 +0000337 "prebuilt_vendor_dlkm",
338 "prebuilt_bt_firmware",
Jihoon Kangdca2f2b2024-11-06 18:43:19 +0000339 "prebuilt_tvservice",
340 "prebuilt_optee",
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000341 ).
342 DefinedInBpFile().
343 Because("module type not allowed to be defined in bp file")
344}
345
Steven Moreland65b3fd92017-12-06 14:18:35 -0800346func neverallowMutator(ctx BottomUpMutatorContext) {
347 m, ok := ctx.Module().(Module)
348 if !ok {
349 return
350 }
351
352 dir := ctx.ModuleDir() + "/"
353 properties := m.GetProperties()
354
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100355 osClass := ctx.Module().Target().Os.Class
356
Paul Duffin115445b2019-08-07 15:31:07 +0100357 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100358 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800359 if !n.appliesToPath(dir) {
360 continue
361 }
362
Colin Crossfd4f7432019-03-05 15:06:16 -0800363 if !n.appliesToModuleType(ctx.ModuleType()) {
364 continue
365 }
366
Cole Faust5b35cb92024-08-27 15:47:06 -0700367 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800368 continue
369 }
370
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100371 if !n.appliesToOsClass(osClass) {
372 continue
373 }
374
Paul Duffin35781882019-07-25 15:41:09 +0100375 if !n.appliesToDirectDeps(ctx) {
376 continue
377 }
378
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000379 if !n.appliesToBpDefinedModule(ctx) {
380 continue
381 }
382
Steven Moreland65b3fd92017-12-06 14:18:35 -0800383 ctx.ModuleErrorf("violates " + n.String())
384 }
385}
386
Paul Duffin73bf0542019-07-12 14:12:49 +0100387type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000388 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100389 String() string
390}
391
392type equalMatcher struct {
393 expected string
394}
395
Anton Hanssone1b18362021-12-23 15:05:38 +0000396func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100397 return m.expected == value
398}
399
400func (m *equalMatcher) String() string {
401 return "=" + m.expected
402}
403
404type anyMatcher struct {
405}
406
Anton Hanssone1b18362021-12-23 15:05:38 +0000407func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100408 return true
409}
410
411func (m *anyMatcher) String() string {
412 return "=*"
413}
414
415var anyMatcherInstance = &anyMatcher{}
416
Paul Duffinc8111702019-07-22 12:13:55 +0100417type startsWithMatcher struct {
418 prefix string
419}
420
Anton Hanssone1b18362021-12-23 15:05:38 +0000421func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100422 return strings.HasPrefix(value, m.prefix)
423}
424
425func (m *startsWithMatcher) String() string {
426 return ".starts-with(" + m.prefix + ")"
427}
428
Anton Hansson45376402020-04-09 14:18:21 +0100429type regexMatcher struct {
430 re *regexp.Regexp
431}
432
Anton Hanssone1b18362021-12-23 15:05:38 +0000433func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100434 return m.re.MatchString(value)
435}
436
437func (m *regexMatcher) String() string {
438 return ".regexp(" + m.re.String() + ")"
439}
440
Andrei Onea115e7e72020-06-05 21:14:03 +0100441type notInListMatcher struct {
442 allowed []string
443}
444
Anton Hanssone1b18362021-12-23 15:05:38 +0000445func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100446 return !InList(value, m.allowed)
447}
448
449func (m *notInListMatcher) String() string {
450 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
451}
452
Colin Crossc511bc52020-04-07 16:50:32 +0000453type isSetMatcher struct{}
454
Anton Hanssone1b18362021-12-23 15:05:38 +0000455func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000456 return value != ""
457}
458
459func (m *isSetMatcher) String() string {
460 return ".is-set"
461}
462
463var isSetMatcherInstance = &isSetMatcher{}
464
Steven Moreland65b3fd92017-12-06 14:18:35 -0800465type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100466 fields []string // e.x.: Vndk.Enabled
467 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800468}
469
Liz Kammera3d79152021-10-28 18:14:04 -0400470func (r *ruleProperty) String() string {
471 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
472}
473
474type ruleProperties []ruleProperty
475
476func (r ruleProperties) String() string {
477 var s []string
478 for _, r := range r {
479 s = append(s, r.String())
480 }
481 return strings.Join(s, " ")
482}
483
Paul Duffin730f2a52019-06-27 14:08:51 +0100484// A NeverAllow rule.
485type Rule interface {
486 In(path ...string) Rule
487
488 NotIn(path ...string) Rule
489
Paul Duffin35781882019-07-25 15:41:09 +0100490 InDirectDeps(deps ...string) Rule
491
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100492 WithOsClass(osClasses ...OsClass) Rule
493
Paul Duffin730f2a52019-06-27 14:08:51 +0100494 ModuleType(types ...string) Rule
495
496 NotModuleType(types ...string) Rule
497
498 With(properties, value string) Rule
499
Paul Duffinc8111702019-07-22 12:13:55 +0100500 WithMatcher(properties string, matcher ValueMatcher) Rule
501
Paul Duffin730f2a52019-06-27 14:08:51 +0100502 Without(properties, value string) Rule
503
Paul Duffinc8111702019-07-22 12:13:55 +0100504 WithoutMatcher(properties string, matcher ValueMatcher) Rule
505
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000506 DefinedInBpFile() Rule
507
Paul Duffin730f2a52019-06-27 14:08:51 +0100508 Because(reason string) Rule
509}
510
Steven Moreland65b3fd92017-12-06 14:18:35 -0800511type rule struct {
512 // User string for why this is a thing.
513 reason string
514
515 paths []string
516 unlessPaths []string
517
Paul Duffin35781882019-07-25 15:41:09 +0100518 directDeps map[string]bool
519
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100520 osClasses []OsClass
521
Colin Crossfd4f7432019-03-05 15:06:16 -0800522 moduleTypes []string
523 unlessModuleTypes []string
524
Liz Kammera3d79152021-10-28 18:14:04 -0400525 props ruleProperties
526 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100527
528 onlyBootclasspathJar bool
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000529
530 definedInBp bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800531}
532
Paul Duffin730f2a52019-06-27 14:08:51 +0100533// Create a new NeverAllow rule.
534func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100535 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800536}
Colin Crossfd4f7432019-03-05 15:06:16 -0800537
Liz Kammera3d79152021-10-28 18:14:04 -0400538// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100539func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800540 r.paths = append(r.paths, cleanPaths(path)...)
541 return r
542}
Colin Crossfd4f7432019-03-05 15:06:16 -0800543
Liz Kammera3d79152021-10-28 18:14:04 -0400544// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100545func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800546 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
547 return r
548}
Colin Crossfd4f7432019-03-05 15:06:16 -0800549
Liz Kammera3d79152021-10-28 18:14:04 -0400550// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100551func (r *rule) InDirectDeps(deps ...string) Rule {
552 for _, d := range deps {
553 r.directDeps[d] = true
554 }
555 return r
556}
557
Liz Kammera3d79152021-10-28 18:14:04 -0400558// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100559func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
560 r.osClasses = append(r.osClasses, osClasses...)
561 return r
562}
563
Liz Kammera3d79152021-10-28 18:14:04 -0400564// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100565func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800566 r.moduleTypes = append(r.moduleTypes, types...)
567 return r
568}
569
Liz Kammera3d79152021-10-28 18:14:04 -0400570// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100571func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800572 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
573 return r
574}
575
Liz Kammera3d79152021-10-28 18:14:04 -0400576// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100577func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100578 return r.WithMatcher(properties, selectMatcher(value))
579}
580
Liz Kammera3d79152021-10-28 18:14:04 -0400581// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100582func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800583 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100584 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100585 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800586 })
587 return r
588}
Colin Crossfd4f7432019-03-05 15:06:16 -0800589
Liz Kammera3d79152021-10-28 18:14:04 -0400590// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100591func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100592 return r.WithoutMatcher(properties, selectMatcher(value))
593}
594
Liz Kammera3d79152021-10-28 18:14:04 -0400595// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100596func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800597 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100598 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100599 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800600 })
601 return r
602}
Colin Crossfd4f7432019-03-05 15:06:16 -0800603
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000604// DefinedInBpFile specifies that this rule applies to modules that are defined
605// in bp files, and does not apply to modules that are auto generated by other modules.
606func (r *rule) DefinedInBpFile() Rule {
607 r.definedInBp = true
608 return r
609}
610
Paul Duffin73bf0542019-07-12 14:12:49 +0100611func selectMatcher(expected string) ValueMatcher {
612 if expected == "*" {
613 return anyMatcherInstance
614 }
615 return &equalMatcher{expected: expected}
616}
617
Liz Kammera3d79152021-10-28 18:14:04 -0400618// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100619func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800620 r.reason = reason
621 return r
622}
623
624func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400625 s := []string{"neverallow requirements. Not allowed:"}
626 if len(r.paths) > 0 {
627 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800628 }
Liz Kammera3d79152021-10-28 18:14:04 -0400629 if len(r.moduleTypes) > 0 {
630 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800631 }
Liz Kammera3d79152021-10-28 18:14:04 -0400632 if len(r.props) > 0 {
633 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800634 }
Liz Kammera3d79152021-10-28 18:14:04 -0400635 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800636 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800637 }
Liz Kammera3d79152021-10-28 18:14:04 -0400638 if len(r.osClasses) > 0 {
639 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100640 }
Liz Kammera3d79152021-10-28 18:14:04 -0400641 if len(r.unlessPaths) > 0 {
642 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
643 }
644 if len(r.unlessModuleTypes) > 0 {
645 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
646 }
647 if len(r.unlessProps) > 0 {
648 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100649 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800650 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400651 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800652 }
Liz Kammera3d79152021-10-28 18:14:04 -0400653 if len(s) == 1 {
654 s[0] = "neverallow requirements (empty)"
655 }
656 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800657}
658
659func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800660 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
661 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800662 return includePath && !excludePath
663}
664
Paul Duffin35781882019-07-25 15:41:09 +0100665func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
666 if len(r.directDeps) == 0 {
667 return true
668 }
669
670 matches := false
671 ctx.VisitDirectDeps(func(m Module) {
672 if !matches {
673 name := ctx.OtherModuleName(m)
674 matches = r.directDeps[name]
675 }
676 })
677
678 return matches
679}
680
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100681func (r *rule) appliesToOsClass(osClass OsClass) bool {
682 if len(r.osClasses) == 0 {
683 return true
684 }
685
686 for _, c := range r.osClasses {
687 if c == osClass {
688 return true
689 }
690 }
691
692 return false
693}
694
Colin Crossfd4f7432019-03-05 15:06:16 -0800695func (r *rule) appliesToModuleType(moduleType string) bool {
696 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
697}
698
Cole Faust5b35cb92024-08-27 15:47:06 -0700699func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
700 includeProps := hasAllProperties(ctx, properties, r.props)
701 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800702 return includeProps && !excludeProps
703}
704
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000705func (r *rule) appliesToBpDefinedModule(ctx BottomUpMutatorContext) bool {
706 if !r.definedInBp {
707 return true
708 }
709 return !ctx.OtherModuleIsAutoGenerated(ctx.Module()) == r.definedInBp
710}
711
Paul Duffinc8111702019-07-22 12:13:55 +0100712func StartsWith(prefix string) ValueMatcher {
713 return &startsWithMatcher{prefix}
714}
715
Anton Hansson45376402020-04-09 14:18:21 +0100716func Regexp(re string) ValueMatcher {
717 r, err := regexp.Compile(re)
718 if err != nil {
719 panic(err)
720 }
721 return &regexMatcher{r}
722}
723
Andrei Onea115e7e72020-06-05 21:14:03 +0100724func NotInList(allowed []string) ValueMatcher {
725 return &notInListMatcher{allowed}
726}
727
Steven Moreland65b3fd92017-12-06 14:18:35 -0800728// assorted utils
729
730func cleanPaths(paths []string) []string {
731 res := make([]string, len(paths))
732 for i, v := range paths {
733 res[i] = filepath.Clean(v) + "/"
734 }
735 return res
736}
737
738func fieldNamesForProperties(propertyNames string) []string {
739 names := strings.Split(propertyNames, ".")
740 for i, v := range names {
741 names[i] = proptools.FieldNameForProperty(v)
742 }
743 return names
744}
745
Cole Faust5b35cb92024-08-27 15:47:06 -0700746func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800747 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700748 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800749 return true
750 }
751 }
752 return false
753}
754
Cole Faust5b35cb92024-08-27 15:47:06 -0700755func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800756 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700757 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800758 return false
759 }
760 }
761 return true
762}
763
Cole Faust5b35cb92024-08-27 15:47:06 -0700764func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800765 for _, propertyStruct := range properties {
766 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
767 for _, v := range prop.fields {
768 if !propertiesValue.IsValid() {
769 break
770 }
771 propertiesValue = propertiesValue.FieldByName(v)
772 }
773 if !propertiesValue.IsValid() {
774 continue
775 }
776
Paul Duffin73bf0542019-07-12 14:12:49 +0100777 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000778 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800779 }
780
Cole Faust5b35cb92024-08-27 15:47:06 -0700781 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800782 return true
783 }
784 }
785 return false
786}
787
Cole Faust5b35cb92024-08-27 15:47:06 -0700788func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800789 if !value.IsValid() {
790 return false
791 }
792
793 if value.Kind() == reflect.Ptr {
794 if value.IsNil() {
795 return check("")
796 }
797 value = value.Elem()
798 }
799
Cole Faust5b35cb92024-08-27 15:47:06 -0700800 switch v := value.Interface().(type) {
801 case string:
802 return check(v)
803 case bool:
804 return check(strconv.FormatBool(v))
805 case int:
806 return check(strconv.FormatInt((int64)(v), 10))
807 case []string:
808 for _, v := range v {
809 if check(v) {
810 return true
811 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800812 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700813 return false
814 case proptools.Configurable[string]:
815 return check(v.GetOrDefault(ctx, ""))
816 case proptools.Configurable[bool]:
817 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
818 case proptools.Configurable[[]string]:
819 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800820 if check(v) {
821 return true
822 }
823 }
824 return false
825 }
826
827 panic("Can't handle type: " + value.Kind().String())
828}
Paul Duffin115445b2019-08-07 15:31:07 +0100829
830var neverallowRulesKey = NewOnceKey("neverallowRules")
831
832func neverallowRules(config Config) []Rule {
833 return config.Once(neverallowRulesKey, func() interface{} {
834 // No test rules were set by setTestNeverallowRules, use the global rules
835 return neverallows
836 }).([]Rule)
837}
838
839// Overrides the default neverallow rules for the supplied config.
840//
841// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100842func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100843 config.Once(neverallowRulesKey, func() interface{} { return testRules })
844}
Paul Duffin45338f02021-03-30 23:07:52 +0100845
846// Prepares for a test by setting neverallow rules and enabling the mutator.
847//
848// If the supplied rules are nil then the default rules are used.
849func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
850 return GroupFixturePreparers(
851 FixtureModifyConfig(func(config Config) {
852 if testRules != nil {
853 setTestNeverallowRules(config, testRules)
854 }
855 }),
856 FixtureRegisterWithContext(func(ctx RegistrationContext) {
857 ctx.PostDepsMutators(registerNeverallowMutator)
858 }),
859 )
860}