blob: 1baef2f29f3ca09ce667f46c16fb2f25be52ca71 [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").
Alice Wang38aed8d2024-11-27 08:18:59 +0000294 Without("name", "trusty-arm64-virt-test-debug.lk.elf.gen").
Inseob Kime8b1ac42024-10-24 09:27:44 +0000295 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 Kangecf76dd2024-11-12 05:24:46 +0000341 "prebuilt_tvconfig",
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000342 ).
343 DefinedInBpFile().
344 Because("module type not allowed to be defined in bp file")
345}
346
Steven Moreland65b3fd92017-12-06 14:18:35 -0800347func neverallowMutator(ctx BottomUpMutatorContext) {
348 m, ok := ctx.Module().(Module)
349 if !ok {
350 return
351 }
352
353 dir := ctx.ModuleDir() + "/"
354 properties := m.GetProperties()
355
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100356 osClass := ctx.Module().Target().Os.Class
357
Paul Duffin115445b2019-08-07 15:31:07 +0100358 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100359 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800360 if !n.appliesToPath(dir) {
361 continue
362 }
363
Colin Crossfd4f7432019-03-05 15:06:16 -0800364 if !n.appliesToModuleType(ctx.ModuleType()) {
365 continue
366 }
367
Cole Faust5b35cb92024-08-27 15:47:06 -0700368 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800369 continue
370 }
371
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100372 if !n.appliesToOsClass(osClass) {
373 continue
374 }
375
Paul Duffin35781882019-07-25 15:41:09 +0100376 if !n.appliesToDirectDeps(ctx) {
377 continue
378 }
379
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000380 if !n.appliesToBpDefinedModule(ctx) {
381 continue
382 }
383
Steven Moreland65b3fd92017-12-06 14:18:35 -0800384 ctx.ModuleErrorf("violates " + n.String())
385 }
386}
387
Paul Duffin73bf0542019-07-12 14:12:49 +0100388type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000389 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100390 String() string
391}
392
393type equalMatcher struct {
394 expected string
395}
396
Anton Hanssone1b18362021-12-23 15:05:38 +0000397func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100398 return m.expected == value
399}
400
401func (m *equalMatcher) String() string {
402 return "=" + m.expected
403}
404
405type anyMatcher struct {
406}
407
Anton Hanssone1b18362021-12-23 15:05:38 +0000408func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100409 return true
410}
411
412func (m *anyMatcher) String() string {
413 return "=*"
414}
415
416var anyMatcherInstance = &anyMatcher{}
417
Paul Duffinc8111702019-07-22 12:13:55 +0100418type startsWithMatcher struct {
419 prefix string
420}
421
Anton Hanssone1b18362021-12-23 15:05:38 +0000422func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100423 return strings.HasPrefix(value, m.prefix)
424}
425
426func (m *startsWithMatcher) String() string {
427 return ".starts-with(" + m.prefix + ")"
428}
429
Anton Hansson45376402020-04-09 14:18:21 +0100430type regexMatcher struct {
431 re *regexp.Regexp
432}
433
Anton Hanssone1b18362021-12-23 15:05:38 +0000434func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100435 return m.re.MatchString(value)
436}
437
438func (m *regexMatcher) String() string {
439 return ".regexp(" + m.re.String() + ")"
440}
441
Andrei Onea115e7e72020-06-05 21:14:03 +0100442type notInListMatcher struct {
443 allowed []string
444}
445
Anton Hanssone1b18362021-12-23 15:05:38 +0000446func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100447 return !InList(value, m.allowed)
448}
449
450func (m *notInListMatcher) String() string {
451 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
452}
453
Colin Crossc511bc52020-04-07 16:50:32 +0000454type isSetMatcher struct{}
455
Anton Hanssone1b18362021-12-23 15:05:38 +0000456func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000457 return value != ""
458}
459
460func (m *isSetMatcher) String() string {
461 return ".is-set"
462}
463
464var isSetMatcherInstance = &isSetMatcher{}
465
Steven Moreland65b3fd92017-12-06 14:18:35 -0800466type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100467 fields []string // e.x.: Vndk.Enabled
468 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800469}
470
Liz Kammera3d79152021-10-28 18:14:04 -0400471func (r *ruleProperty) String() string {
472 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
473}
474
475type ruleProperties []ruleProperty
476
477func (r ruleProperties) String() string {
478 var s []string
479 for _, r := range r {
480 s = append(s, r.String())
481 }
482 return strings.Join(s, " ")
483}
484
Paul Duffin730f2a52019-06-27 14:08:51 +0100485// A NeverAllow rule.
486type Rule interface {
487 In(path ...string) Rule
488
489 NotIn(path ...string) Rule
490
Paul Duffin35781882019-07-25 15:41:09 +0100491 InDirectDeps(deps ...string) Rule
492
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100493 WithOsClass(osClasses ...OsClass) Rule
494
Paul Duffin730f2a52019-06-27 14:08:51 +0100495 ModuleType(types ...string) Rule
496
497 NotModuleType(types ...string) Rule
498
499 With(properties, value string) Rule
500
Paul Duffinc8111702019-07-22 12:13:55 +0100501 WithMatcher(properties string, matcher ValueMatcher) Rule
502
Paul Duffin730f2a52019-06-27 14:08:51 +0100503 Without(properties, value string) Rule
504
Paul Duffinc8111702019-07-22 12:13:55 +0100505 WithoutMatcher(properties string, matcher ValueMatcher) Rule
506
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000507 DefinedInBpFile() Rule
508
Paul Duffin730f2a52019-06-27 14:08:51 +0100509 Because(reason string) Rule
510}
511
Steven Moreland65b3fd92017-12-06 14:18:35 -0800512type rule struct {
513 // User string for why this is a thing.
514 reason string
515
516 paths []string
517 unlessPaths []string
518
Paul Duffin35781882019-07-25 15:41:09 +0100519 directDeps map[string]bool
520
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100521 osClasses []OsClass
522
Colin Crossfd4f7432019-03-05 15:06:16 -0800523 moduleTypes []string
524 unlessModuleTypes []string
525
Liz Kammera3d79152021-10-28 18:14:04 -0400526 props ruleProperties
527 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100528
529 onlyBootclasspathJar bool
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000530
531 definedInBp bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532}
533
Paul Duffin730f2a52019-06-27 14:08:51 +0100534// Create a new NeverAllow rule.
535func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100536 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537}
Colin Crossfd4f7432019-03-05 15:06:16 -0800538
Liz Kammera3d79152021-10-28 18:14:04 -0400539// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100540func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800541 r.paths = append(r.paths, cleanPaths(path)...)
542 return r
543}
Colin Crossfd4f7432019-03-05 15:06:16 -0800544
Liz Kammera3d79152021-10-28 18:14:04 -0400545// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100546func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
548 return r
549}
Colin Crossfd4f7432019-03-05 15:06:16 -0800550
Liz Kammera3d79152021-10-28 18:14:04 -0400551// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100552func (r *rule) InDirectDeps(deps ...string) Rule {
553 for _, d := range deps {
554 r.directDeps[d] = true
555 }
556 return r
557}
558
Liz Kammera3d79152021-10-28 18:14:04 -0400559// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100560func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
561 r.osClasses = append(r.osClasses, osClasses...)
562 return r
563}
564
Liz Kammera3d79152021-10-28 18:14:04 -0400565// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100566func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800567 r.moduleTypes = append(r.moduleTypes, types...)
568 return r
569}
570
Liz Kammera3d79152021-10-28 18:14:04 -0400571// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100572func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800573 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
574 return r
575}
576
Liz Kammera3d79152021-10-28 18:14:04 -0400577// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100578func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100579 return r.WithMatcher(properties, selectMatcher(value))
580}
581
Liz Kammera3d79152021-10-28 18:14:04 -0400582// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100583func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800584 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100585 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100586 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800587 })
588 return r
589}
Colin Crossfd4f7432019-03-05 15:06:16 -0800590
Liz Kammera3d79152021-10-28 18:14:04 -0400591// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100592func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100593 return r.WithoutMatcher(properties, selectMatcher(value))
594}
595
Liz Kammera3d79152021-10-28 18:14:04 -0400596// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100597func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800598 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100599 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100600 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800601 })
602 return r
603}
Colin Crossfd4f7432019-03-05 15:06:16 -0800604
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000605// DefinedInBpFile specifies that this rule applies to modules that are defined
606// in bp files, and does not apply to modules that are auto generated by other modules.
607func (r *rule) DefinedInBpFile() Rule {
608 r.definedInBp = true
609 return r
610}
611
Paul Duffin73bf0542019-07-12 14:12:49 +0100612func selectMatcher(expected string) ValueMatcher {
613 if expected == "*" {
614 return anyMatcherInstance
615 }
616 return &equalMatcher{expected: expected}
617}
618
Liz Kammera3d79152021-10-28 18:14:04 -0400619// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100620func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800621 r.reason = reason
622 return r
623}
624
625func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400626 s := []string{"neverallow requirements. Not allowed:"}
627 if len(r.paths) > 0 {
628 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800629 }
Liz Kammera3d79152021-10-28 18:14:04 -0400630 if len(r.moduleTypes) > 0 {
631 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800632 }
Liz Kammera3d79152021-10-28 18:14:04 -0400633 if len(r.props) > 0 {
634 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800635 }
Liz Kammera3d79152021-10-28 18:14:04 -0400636 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800637 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800638 }
Liz Kammera3d79152021-10-28 18:14:04 -0400639 if len(r.osClasses) > 0 {
640 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100641 }
Liz Kammera3d79152021-10-28 18:14:04 -0400642 if len(r.unlessPaths) > 0 {
643 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
644 }
645 if len(r.unlessModuleTypes) > 0 {
646 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
647 }
648 if len(r.unlessProps) > 0 {
649 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100650 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800651 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400652 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800653 }
Liz Kammera3d79152021-10-28 18:14:04 -0400654 if len(s) == 1 {
655 s[0] = "neverallow requirements (empty)"
656 }
657 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800658}
659
660func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800661 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
662 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800663 return includePath && !excludePath
664}
665
Paul Duffin35781882019-07-25 15:41:09 +0100666func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
667 if len(r.directDeps) == 0 {
668 return true
669 }
670
671 matches := false
672 ctx.VisitDirectDeps(func(m Module) {
673 if !matches {
674 name := ctx.OtherModuleName(m)
675 matches = r.directDeps[name]
676 }
677 })
678
679 return matches
680}
681
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100682func (r *rule) appliesToOsClass(osClass OsClass) bool {
683 if len(r.osClasses) == 0 {
684 return true
685 }
686
687 for _, c := range r.osClasses {
688 if c == osClass {
689 return true
690 }
691 }
692
693 return false
694}
695
Colin Crossfd4f7432019-03-05 15:06:16 -0800696func (r *rule) appliesToModuleType(moduleType string) bool {
697 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
698}
699
Cole Faust5b35cb92024-08-27 15:47:06 -0700700func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
701 includeProps := hasAllProperties(ctx, properties, r.props)
702 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800703 return includeProps && !excludeProps
704}
705
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000706func (r *rule) appliesToBpDefinedModule(ctx BottomUpMutatorContext) bool {
707 if !r.definedInBp {
708 return true
709 }
710 return !ctx.OtherModuleIsAutoGenerated(ctx.Module()) == r.definedInBp
711}
712
Paul Duffinc8111702019-07-22 12:13:55 +0100713func StartsWith(prefix string) ValueMatcher {
714 return &startsWithMatcher{prefix}
715}
716
Anton Hansson45376402020-04-09 14:18:21 +0100717func Regexp(re string) ValueMatcher {
718 r, err := regexp.Compile(re)
719 if err != nil {
720 panic(err)
721 }
722 return &regexMatcher{r}
723}
724
Andrei Onea115e7e72020-06-05 21:14:03 +0100725func NotInList(allowed []string) ValueMatcher {
726 return &notInListMatcher{allowed}
727}
728
Steven Moreland65b3fd92017-12-06 14:18:35 -0800729// assorted utils
730
731func cleanPaths(paths []string) []string {
732 res := make([]string, len(paths))
733 for i, v := range paths {
734 res[i] = filepath.Clean(v) + "/"
735 }
736 return res
737}
738
739func fieldNamesForProperties(propertyNames string) []string {
740 names := strings.Split(propertyNames, ".")
741 for i, v := range names {
742 names[i] = proptools.FieldNameForProperty(v)
743 }
744 return names
745}
746
Cole Faust5b35cb92024-08-27 15:47:06 -0700747func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800748 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700749 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800750 return true
751 }
752 }
753 return false
754}
755
Cole Faust5b35cb92024-08-27 15:47:06 -0700756func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800757 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700758 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800759 return false
760 }
761 }
762 return true
763}
764
Cole Faust5b35cb92024-08-27 15:47:06 -0700765func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800766 for _, propertyStruct := range properties {
767 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
768 for _, v := range prop.fields {
769 if !propertiesValue.IsValid() {
770 break
771 }
772 propertiesValue = propertiesValue.FieldByName(v)
773 }
774 if !propertiesValue.IsValid() {
775 continue
776 }
777
Paul Duffin73bf0542019-07-12 14:12:49 +0100778 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000779 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800780 }
781
Cole Faust5b35cb92024-08-27 15:47:06 -0700782 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800783 return true
784 }
785 }
786 return false
787}
788
Cole Faust5b35cb92024-08-27 15:47:06 -0700789func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800790 if !value.IsValid() {
791 return false
792 }
793
794 if value.Kind() == reflect.Ptr {
795 if value.IsNil() {
796 return check("")
797 }
798 value = value.Elem()
799 }
800
Cole Faust5b35cb92024-08-27 15:47:06 -0700801 switch v := value.Interface().(type) {
802 case string:
803 return check(v)
804 case bool:
805 return check(strconv.FormatBool(v))
806 case int:
807 return check(strconv.FormatInt((int64)(v), 10))
808 case []string:
809 for _, v := range v {
810 if check(v) {
811 return true
812 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800813 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700814 return false
815 case proptools.Configurable[string]:
816 return check(v.GetOrDefault(ctx, ""))
817 case proptools.Configurable[bool]:
818 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
819 case proptools.Configurable[[]string]:
820 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800821 if check(v) {
822 return true
823 }
824 }
825 return false
826 }
827
828 panic("Can't handle type: " + value.Kind().String())
829}
Paul Duffin115445b2019-08-07 15:31:07 +0100830
831var neverallowRulesKey = NewOnceKey("neverallowRules")
832
833func neverallowRules(config Config) []Rule {
834 return config.Once(neverallowRulesKey, func() interface{} {
835 // No test rules were set by setTestNeverallowRules, use the global rules
836 return neverallows
837 }).([]Rule)
838}
839
840// Overrides the default neverallow rules for the supplied config.
841//
842// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100843func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100844 config.Once(neverallowRulesKey, func() interface{} { return testRules })
845}
Paul Duffin45338f02021-03-30 23:07:52 +0100846
847// Prepares for a test by setting neverallow rules and enabling the mutator.
848//
849// If the supplied rules are nil then the default rules are used.
850func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
851 return GroupFixturePreparers(
852 FixtureModifyConfig(func(config Config) {
853 if testRules != nil {
854 setTestNeverallowRules(config, testRules)
855 }
856 }),
857 FixtureRegisterWithContext(func(ctx RegistrationContext) {
858 ctx.PostDepsMutators(registerNeverallowMutator)
859 }),
860 )
861}