blob: 6251e2b0d3f5060fc54d65849e1b22eb683ee60d [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 Kang2a7bf752024-11-01 21:21:25 +0000339 ).
340 DefinedInBpFile().
341 Because("module type not allowed to be defined in bp file")
342}
343
Steven Moreland65b3fd92017-12-06 14:18:35 -0800344func neverallowMutator(ctx BottomUpMutatorContext) {
345 m, ok := ctx.Module().(Module)
346 if !ok {
347 return
348 }
349
350 dir := ctx.ModuleDir() + "/"
351 properties := m.GetProperties()
352
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100353 osClass := ctx.Module().Target().Os.Class
354
Paul Duffin115445b2019-08-07 15:31:07 +0100355 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100356 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800357 if !n.appliesToPath(dir) {
358 continue
359 }
360
Colin Crossfd4f7432019-03-05 15:06:16 -0800361 if !n.appliesToModuleType(ctx.ModuleType()) {
362 continue
363 }
364
Cole Faust5b35cb92024-08-27 15:47:06 -0700365 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800366 continue
367 }
368
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100369 if !n.appliesToOsClass(osClass) {
370 continue
371 }
372
Paul Duffin35781882019-07-25 15:41:09 +0100373 if !n.appliesToDirectDeps(ctx) {
374 continue
375 }
376
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000377 if !n.appliesToBpDefinedModule(ctx) {
378 continue
379 }
380
Steven Moreland65b3fd92017-12-06 14:18:35 -0800381 ctx.ModuleErrorf("violates " + n.String())
382 }
383}
384
Paul Duffin73bf0542019-07-12 14:12:49 +0100385type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000386 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100387 String() string
388}
389
390type equalMatcher struct {
391 expected string
392}
393
Anton Hanssone1b18362021-12-23 15:05:38 +0000394func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100395 return m.expected == value
396}
397
398func (m *equalMatcher) String() string {
399 return "=" + m.expected
400}
401
402type anyMatcher struct {
403}
404
Anton Hanssone1b18362021-12-23 15:05:38 +0000405func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100406 return true
407}
408
409func (m *anyMatcher) String() string {
410 return "=*"
411}
412
413var anyMatcherInstance = &anyMatcher{}
414
Paul Duffinc8111702019-07-22 12:13:55 +0100415type startsWithMatcher struct {
416 prefix string
417}
418
Anton Hanssone1b18362021-12-23 15:05:38 +0000419func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100420 return strings.HasPrefix(value, m.prefix)
421}
422
423func (m *startsWithMatcher) String() string {
424 return ".starts-with(" + m.prefix + ")"
425}
426
Anton Hansson45376402020-04-09 14:18:21 +0100427type regexMatcher struct {
428 re *regexp.Regexp
429}
430
Anton Hanssone1b18362021-12-23 15:05:38 +0000431func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100432 return m.re.MatchString(value)
433}
434
435func (m *regexMatcher) String() string {
436 return ".regexp(" + m.re.String() + ")"
437}
438
Andrei Onea115e7e72020-06-05 21:14:03 +0100439type notInListMatcher struct {
440 allowed []string
441}
442
Anton Hanssone1b18362021-12-23 15:05:38 +0000443func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100444 return !InList(value, m.allowed)
445}
446
447func (m *notInListMatcher) String() string {
448 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
449}
450
Colin Crossc511bc52020-04-07 16:50:32 +0000451type isSetMatcher struct{}
452
Anton Hanssone1b18362021-12-23 15:05:38 +0000453func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000454 return value != ""
455}
456
457func (m *isSetMatcher) String() string {
458 return ".is-set"
459}
460
461var isSetMatcherInstance = &isSetMatcher{}
462
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100464 fields []string // e.x.: Vndk.Enabled
465 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800466}
467
Liz Kammera3d79152021-10-28 18:14:04 -0400468func (r *ruleProperty) String() string {
469 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
470}
471
472type ruleProperties []ruleProperty
473
474func (r ruleProperties) String() string {
475 var s []string
476 for _, r := range r {
477 s = append(s, r.String())
478 }
479 return strings.Join(s, " ")
480}
481
Paul Duffin730f2a52019-06-27 14:08:51 +0100482// A NeverAllow rule.
483type Rule interface {
484 In(path ...string) Rule
485
486 NotIn(path ...string) Rule
487
Paul Duffin35781882019-07-25 15:41:09 +0100488 InDirectDeps(deps ...string) Rule
489
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100490 WithOsClass(osClasses ...OsClass) Rule
491
Paul Duffin730f2a52019-06-27 14:08:51 +0100492 ModuleType(types ...string) Rule
493
494 NotModuleType(types ...string) Rule
495
496 With(properties, value string) Rule
497
Paul Duffinc8111702019-07-22 12:13:55 +0100498 WithMatcher(properties string, matcher ValueMatcher) Rule
499
Paul Duffin730f2a52019-06-27 14:08:51 +0100500 Without(properties, value string) Rule
501
Paul Duffinc8111702019-07-22 12:13:55 +0100502 WithoutMatcher(properties string, matcher ValueMatcher) Rule
503
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000504 DefinedInBpFile() Rule
505
Paul Duffin730f2a52019-06-27 14:08:51 +0100506 Because(reason string) Rule
507}
508
Steven Moreland65b3fd92017-12-06 14:18:35 -0800509type rule struct {
510 // User string for why this is a thing.
511 reason string
512
513 paths []string
514 unlessPaths []string
515
Paul Duffin35781882019-07-25 15:41:09 +0100516 directDeps map[string]bool
517
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100518 osClasses []OsClass
519
Colin Crossfd4f7432019-03-05 15:06:16 -0800520 moduleTypes []string
521 unlessModuleTypes []string
522
Liz Kammera3d79152021-10-28 18:14:04 -0400523 props ruleProperties
524 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100525
526 onlyBootclasspathJar bool
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000527
528 definedInBp bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800529}
530
Paul Duffin730f2a52019-06-27 14:08:51 +0100531// Create a new NeverAllow rule.
532func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100533 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800534}
Colin Crossfd4f7432019-03-05 15:06:16 -0800535
Liz Kammera3d79152021-10-28 18:14:04 -0400536// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100537func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800538 r.paths = append(r.paths, cleanPaths(path)...)
539 return r
540}
Colin Crossfd4f7432019-03-05 15:06:16 -0800541
Liz Kammera3d79152021-10-28 18:14:04 -0400542// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100543func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800544 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
545 return r
546}
Colin Crossfd4f7432019-03-05 15:06:16 -0800547
Liz Kammera3d79152021-10-28 18:14:04 -0400548// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100549func (r *rule) InDirectDeps(deps ...string) Rule {
550 for _, d := range deps {
551 r.directDeps[d] = true
552 }
553 return r
554}
555
Liz Kammera3d79152021-10-28 18:14:04 -0400556// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100557func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
558 r.osClasses = append(r.osClasses, osClasses...)
559 return r
560}
561
Liz Kammera3d79152021-10-28 18:14:04 -0400562// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100563func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800564 r.moduleTypes = append(r.moduleTypes, types...)
565 return r
566}
567
Liz Kammera3d79152021-10-28 18:14:04 -0400568// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100569func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800570 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
571 return r
572}
573
Liz Kammera3d79152021-10-28 18:14:04 -0400574// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100575func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100576 return r.WithMatcher(properties, selectMatcher(value))
577}
578
Liz Kammera3d79152021-10-28 18:14:04 -0400579// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100580func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800581 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100582 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100583 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800584 })
585 return r
586}
Colin Crossfd4f7432019-03-05 15:06:16 -0800587
Liz Kammera3d79152021-10-28 18:14:04 -0400588// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100589func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100590 return r.WithoutMatcher(properties, selectMatcher(value))
591}
592
Liz Kammera3d79152021-10-28 18:14:04 -0400593// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100594func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800595 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100596 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100597 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800598 })
599 return r
600}
Colin Crossfd4f7432019-03-05 15:06:16 -0800601
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000602// DefinedInBpFile specifies that this rule applies to modules that are defined
603// in bp files, and does not apply to modules that are auto generated by other modules.
604func (r *rule) DefinedInBpFile() Rule {
605 r.definedInBp = true
606 return r
607}
608
Paul Duffin73bf0542019-07-12 14:12:49 +0100609func selectMatcher(expected string) ValueMatcher {
610 if expected == "*" {
611 return anyMatcherInstance
612 }
613 return &equalMatcher{expected: expected}
614}
615
Liz Kammera3d79152021-10-28 18:14:04 -0400616// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100617func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800618 r.reason = reason
619 return r
620}
621
622func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400623 s := []string{"neverallow requirements. Not allowed:"}
624 if len(r.paths) > 0 {
625 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800626 }
Liz Kammera3d79152021-10-28 18:14:04 -0400627 if len(r.moduleTypes) > 0 {
628 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800629 }
Liz Kammera3d79152021-10-28 18:14:04 -0400630 if len(r.props) > 0 {
631 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800632 }
Liz Kammera3d79152021-10-28 18:14:04 -0400633 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800634 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800635 }
Liz Kammera3d79152021-10-28 18:14:04 -0400636 if len(r.osClasses) > 0 {
637 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100638 }
Liz Kammera3d79152021-10-28 18:14:04 -0400639 if len(r.unlessPaths) > 0 {
640 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
641 }
642 if len(r.unlessModuleTypes) > 0 {
643 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
644 }
645 if len(r.unlessProps) > 0 {
646 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100647 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800648 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400649 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800650 }
Liz Kammera3d79152021-10-28 18:14:04 -0400651 if len(s) == 1 {
652 s[0] = "neverallow requirements (empty)"
653 }
654 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800655}
656
657func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800658 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
659 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800660 return includePath && !excludePath
661}
662
Paul Duffin35781882019-07-25 15:41:09 +0100663func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
664 if len(r.directDeps) == 0 {
665 return true
666 }
667
668 matches := false
669 ctx.VisitDirectDeps(func(m Module) {
670 if !matches {
671 name := ctx.OtherModuleName(m)
672 matches = r.directDeps[name]
673 }
674 })
675
676 return matches
677}
678
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100679func (r *rule) appliesToOsClass(osClass OsClass) bool {
680 if len(r.osClasses) == 0 {
681 return true
682 }
683
684 for _, c := range r.osClasses {
685 if c == osClass {
686 return true
687 }
688 }
689
690 return false
691}
692
Colin Crossfd4f7432019-03-05 15:06:16 -0800693func (r *rule) appliesToModuleType(moduleType string) bool {
694 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
695}
696
Cole Faust5b35cb92024-08-27 15:47:06 -0700697func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
698 includeProps := hasAllProperties(ctx, properties, r.props)
699 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800700 return includeProps && !excludeProps
701}
702
Jihoon Kang2a7bf752024-11-01 21:21:25 +0000703func (r *rule) appliesToBpDefinedModule(ctx BottomUpMutatorContext) bool {
704 if !r.definedInBp {
705 return true
706 }
707 return !ctx.OtherModuleIsAutoGenerated(ctx.Module()) == r.definedInBp
708}
709
Paul Duffinc8111702019-07-22 12:13:55 +0100710func StartsWith(prefix string) ValueMatcher {
711 return &startsWithMatcher{prefix}
712}
713
Anton Hansson45376402020-04-09 14:18:21 +0100714func Regexp(re string) ValueMatcher {
715 r, err := regexp.Compile(re)
716 if err != nil {
717 panic(err)
718 }
719 return &regexMatcher{r}
720}
721
Andrei Onea115e7e72020-06-05 21:14:03 +0100722func NotInList(allowed []string) ValueMatcher {
723 return &notInListMatcher{allowed}
724}
725
Steven Moreland65b3fd92017-12-06 14:18:35 -0800726// assorted utils
727
728func cleanPaths(paths []string) []string {
729 res := make([]string, len(paths))
730 for i, v := range paths {
731 res[i] = filepath.Clean(v) + "/"
732 }
733 return res
734}
735
736func fieldNamesForProperties(propertyNames string) []string {
737 names := strings.Split(propertyNames, ".")
738 for i, v := range names {
739 names[i] = proptools.FieldNameForProperty(v)
740 }
741 return names
742}
743
Cole Faust5b35cb92024-08-27 15:47:06 -0700744func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800745 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700746 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800747 return true
748 }
749 }
750 return false
751}
752
Cole Faust5b35cb92024-08-27 15:47:06 -0700753func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800754 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700755 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800756 return false
757 }
758 }
759 return true
760}
761
Cole Faust5b35cb92024-08-27 15:47:06 -0700762func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800763 for _, propertyStruct := range properties {
764 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
765 for _, v := range prop.fields {
766 if !propertiesValue.IsValid() {
767 break
768 }
769 propertiesValue = propertiesValue.FieldByName(v)
770 }
771 if !propertiesValue.IsValid() {
772 continue
773 }
774
Paul Duffin73bf0542019-07-12 14:12:49 +0100775 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000776 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800777 }
778
Cole Faust5b35cb92024-08-27 15:47:06 -0700779 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800780 return true
781 }
782 }
783 return false
784}
785
Cole Faust5b35cb92024-08-27 15:47:06 -0700786func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800787 if !value.IsValid() {
788 return false
789 }
790
791 if value.Kind() == reflect.Ptr {
792 if value.IsNil() {
793 return check("")
794 }
795 value = value.Elem()
796 }
797
Cole Faust5b35cb92024-08-27 15:47:06 -0700798 switch v := value.Interface().(type) {
799 case string:
800 return check(v)
801 case bool:
802 return check(strconv.FormatBool(v))
803 case int:
804 return check(strconv.FormatInt((int64)(v), 10))
805 case []string:
806 for _, v := range v {
807 if check(v) {
808 return true
809 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800810 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700811 return false
812 case proptools.Configurable[string]:
813 return check(v.GetOrDefault(ctx, ""))
814 case proptools.Configurable[bool]:
815 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
816 case proptools.Configurable[[]string]:
817 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800818 if check(v) {
819 return true
820 }
821 }
822 return false
823 }
824
825 panic("Can't handle type: " + value.Kind().String())
826}
Paul Duffin115445b2019-08-07 15:31:07 +0100827
828var neverallowRulesKey = NewOnceKey("neverallowRules")
829
830func neverallowRules(config Config) []Rule {
831 return config.Once(neverallowRulesKey, func() interface{} {
832 // No test rules were set by setTestNeverallowRules, use the global rules
833 return neverallows
834 }).([]Rule)
835}
836
837// Overrides the default neverallow rules for the supplied config.
838//
839// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100840func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100841 config.Once(neverallowRulesKey, func() interface{} { return testRules })
842}
Paul Duffin45338f02021-03-30 23:07:52 +0100843
844// Prepares for a test by setting neverallow rules and enabling the mutator.
845//
846// If the supplied rules are nil then the default rules are used.
847func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
848 return GroupFixturePreparers(
849 FixtureModifyConfig(func(config Config) {
850 if testRules != nil {
851 setTestNeverallowRules(config, testRules)
852 }
853 }),
854 FixtureRegisterWithContext(func(ctx RegistrationContext) {
855 ctx.PostDepsMutators(registerNeverallowMutator)
856 }),
857 )
858}