blob: f7827f8ef93ede64136f0876dd1a8ef4a1d2e91b [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 (
18 "path/filepath"
19 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010020 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080021 "strconv"
22 "strings"
23
24 "github.com/google/blueprint/proptools"
25)
26
27// "neverallow" rules for the build system.
28//
29// This allows things which aren't related to the build system and are enforced
30// for sanity, in progress code refactors, or policy to be expressed in a
31// straightforward away disjoint from implementations and tests which should
32// work regardless of these restrictions.
33//
34// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010035// - it is in one of the "In" paths
36// - it is not in one of the "NotIn" paths
37// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080038// - - values are matched in their entirety
39// - - nil is interpreted as an empty string
40// - - nested properties are separated with a '.'
41// - - if the property is a list, any of the values in the list being matches
42// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010043// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080044
Paul Duffin45338f02021-03-30 23:07:52 +010045func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080046 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
47}
48
Paul Duffin730f2a52019-06-27 14:08:51 +010049var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080050
Paul Duffin730f2a52019-06-27 14:08:51 +010051func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010052 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010053 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000055 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010056 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070057 AddNeverAllowRules(createMakefileGoalRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010058}
Steven Moreland65b3fd92017-12-06 14:18:35 -080059
Paul Duffin730f2a52019-06-27 14:08:51 +010060// Add a NeverAllow rule to the set of rules to apply.
61func AddNeverAllowRules(rules ...Rule) {
62 neverallows = append(neverallows, rules...)
63}
64
Paul Duffinc8111702019-07-22 12:13:55 +010065func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000066 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010067 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000068 "art/libnativebridge",
69 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010070 "libcore",
71 "libnativehelper",
72 "external/apache-harmony",
73 "external/apache-xml",
74 "external/boringssl",
75 "external/bouncycastle",
76 "external/conscrypt",
77 "external/icu",
78 "external/okhttp",
79 "external/vixl",
80 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010081 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000082 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000083 "frameworks/av/apex",
84 "frameworks/av/tools",
85 "frameworks/native/cmds",
86 "system/apex",
87 "system/bpf",
88 "system/gatekeeper",
89 "system/hwservicemanager",
90 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000091 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000092 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000093 }
Paul Duffinc8111702019-07-22 12:13:55 +010094
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000095 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
96
97 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +010098 rule :=
99 NeverAllow().
100 WithMatcher("include_dirs", StartsWith(path+"/")).
101 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
102 " to use alternate mechanisms and so can no longer be used.")
103
104 rules = append(rules, rule)
105 }
106
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000107 for _, path := range noUseIncludeDir {
108 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
109 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
110 " to use alternate mechanisms and so can no longer be used.")
111 rules = append(rules, rule)
112 }
113
Paul Duffinc8111702019-07-22 12:13:55 +0100114 return rules
115}
116
Paul Duffin730f2a52019-06-27 14:08:51 +0100117func createTrebleRules() []Rule {
118 return []Rule{
119 NeverAllow().
120 In("vendor", "device").
121 With("vndk.enabled", "true").
122 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900123 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100124 Because("the VNDK can never contain a library that is device dependent."),
125 NeverAllow().
126 With("vndk.enabled", "true").
127 Without("vendor", "true").
128 Without("owner", "").
129 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800130
Neil Fullerdf5f3562018-10-21 17:19:10 +0100131 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100132 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800133 Without("name", "libhidlbase-combined-impl").
134 Without("name", "libhidlbase").
135 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100136 With("product_variables.enforce_vintf_manifest.cflags", "*").
137 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100138
139 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100140 NeverAllow().
141 Without("name", "libc_bionic_ndk").
142 With("product_variables.treble_linker_namespaces.cflags", "*").
143 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100144
145 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100147 }
148}
149
Paul Duffin730f2a52019-06-27 14:08:51 +0100150func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700151 javaDeviceForHostProjectsAllowedList := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700152 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800153 "external/robolectric-shadows",
154 "framework/layoutlib",
155 }
156
Paul Duffin730f2a52019-06-27 14:08:51 +0100157 return []Rule{
158 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700159 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100160 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700161 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800162 }
163}
164
Colin Crossc511bc52020-04-07 16:50:32 +0000165func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700166 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000167 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
168 // This sometimes works because the APEX modules that contain derive_sdk and
169 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
170 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100171 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700172 // These are for apps and shouldn't be used by non-SDK variant modules.
173 "prebuilts/ndk",
174 "tools/test/graphicsbenchmark/apps/sample_app",
175 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700176 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li9a7158b2021-06-18 14:04:50 +0000177 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000178 }
179
Colin Cross440e0d02020-06-11 11:32:11 -0700180 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000181 // android_native_app_glue and libRSSupport use native_window.h but target old
182 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
183 // so they can't add libnativewindow to shared_libs to get the header directory
184 // for the platform variant. Allow them to use the platform variant
185 // property to set shared_libs.
186 "prebuilts/ndk",
187 "frameworks/rs",
188 }
189
190 return []Rule{
191 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700192 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000193 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700194 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000195 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700196 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000197 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700198 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000199 }
200}
201
David Srbeckye033cba2020-05-20 22:20:28 +0100202func createUncompressDexRules() []Rule {
203 return []Rule{
204 NeverAllow().
205 NotIn("art").
206 WithMatcher("uncompress_dex", isSetMatcherInstance).
207 Because("uncompress_dex is only allowed for certain jars for test in art."),
208 }
209}
210
Yifan Hong696ed4d2020-07-27 12:59:58 -0700211func createMakefileGoalRules() []Rule {
212 return []Rule{
213 NeverAllow().
214 ModuleType("makefile_goal").
215 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
216 Because("Only boot images may be imported as a makefile goal."),
217 }
218}
219
Steven Moreland65b3fd92017-12-06 14:18:35 -0800220func neverallowMutator(ctx BottomUpMutatorContext) {
221 m, ok := ctx.Module().(Module)
222 if !ok {
223 return
224 }
225
226 dir := ctx.ModuleDir() + "/"
227 properties := m.GetProperties()
228
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100229 osClass := ctx.Module().Target().Os.Class
230
Paul Duffin115445b2019-08-07 15:31:07 +0100231 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100232 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800233 if !n.appliesToPath(dir) {
234 continue
235 }
236
Colin Crossfd4f7432019-03-05 15:06:16 -0800237 if !n.appliesToModuleType(ctx.ModuleType()) {
238 continue
239 }
240
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000241 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800242 continue
243 }
244
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100245 if !n.appliesToOsClass(osClass) {
246 continue
247 }
248
Paul Duffin35781882019-07-25 15:41:09 +0100249 if !n.appliesToDirectDeps(ctx) {
250 continue
251 }
252
Andrei Onea115e7e72020-06-05 21:14:03 +0100253 if !n.appliesToBootclasspathJar(ctx) {
254 continue
255 }
256
Steven Moreland65b3fd92017-12-06 14:18:35 -0800257 ctx.ModuleErrorf("violates " + n.String())
258 }
259}
260
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000261type ValueMatcherContext interface {
262 Config() Config
263}
264
Paul Duffin73bf0542019-07-12 14:12:49 +0100265type ValueMatcher interface {
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000266 Test(ValueMatcherContext, string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100267 String() string
268}
269
270type equalMatcher struct {
271 expected string
272}
273
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000274func (m *equalMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100275 return m.expected == value
276}
277
278func (m *equalMatcher) String() string {
279 return "=" + m.expected
280}
281
282type anyMatcher struct {
283}
284
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000285func (m *anyMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100286 return true
287}
288
289func (m *anyMatcher) String() string {
290 return "=*"
291}
292
293var anyMatcherInstance = &anyMatcher{}
294
Paul Duffinc8111702019-07-22 12:13:55 +0100295type startsWithMatcher struct {
296 prefix string
297}
298
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000299func (m *startsWithMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100300 return strings.HasPrefix(value, m.prefix)
301}
302
303func (m *startsWithMatcher) String() string {
304 return ".starts-with(" + m.prefix + ")"
305}
306
Anton Hansson45376402020-04-09 14:18:21 +0100307type regexMatcher struct {
308 re *regexp.Regexp
309}
310
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000311func (m *regexMatcher) Test(ctx ValueMatcherContext, value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100312 return m.re.MatchString(value)
313}
314
315func (m *regexMatcher) String() string {
316 return ".regexp(" + m.re.String() + ")"
317}
318
Andrei Onea115e7e72020-06-05 21:14:03 +0100319type notInListMatcher struct {
320 allowed []string
321}
322
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000323func (m *notInListMatcher) Test(ctx ValueMatcherContext, value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100324 return !InList(value, m.allowed)
325}
326
327func (m *notInListMatcher) String() string {
328 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
329}
330
Colin Crossc511bc52020-04-07 16:50:32 +0000331type isSetMatcher struct{}
332
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000333func (m *isSetMatcher) Test(ctx ValueMatcherContext, value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000334 return value != ""
335}
336
337func (m *isSetMatcher) String() string {
338 return ".is-set"
339}
340
341var isSetMatcherInstance = &isSetMatcher{}
342
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000343type sdkVersionMatcher struct {
344 condition func(ctx ValueMatcherContext, spec SdkSpec) bool
345 description string
346}
347
348func (m *sdkVersionMatcher) Test(ctx ValueMatcherContext, value string) bool {
349 return m.condition(ctx, SdkSpecFromWithConfig(ctx.Config(), value))
350}
351
352func (m *sdkVersionMatcher) String() string {
353 return ".sdk-version(" + m.description + ")"
354}
355
Steven Moreland65b3fd92017-12-06 14:18:35 -0800356type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100357 fields []string // e.x.: Vndk.Enabled
358 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800359}
360
Paul Duffin730f2a52019-06-27 14:08:51 +0100361// A NeverAllow rule.
362type Rule interface {
363 In(path ...string) Rule
364
365 NotIn(path ...string) Rule
366
Paul Duffin35781882019-07-25 15:41:09 +0100367 InDirectDeps(deps ...string) Rule
368
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100369 WithOsClass(osClasses ...OsClass) Rule
370
Paul Duffin730f2a52019-06-27 14:08:51 +0100371 ModuleType(types ...string) Rule
372
373 NotModuleType(types ...string) Rule
374
Andrei Onea115e7e72020-06-05 21:14:03 +0100375 BootclasspathJar() Rule
376
Paul Duffin730f2a52019-06-27 14:08:51 +0100377 With(properties, value string) Rule
378
Paul Duffinc8111702019-07-22 12:13:55 +0100379 WithMatcher(properties string, matcher ValueMatcher) Rule
380
Paul Duffin730f2a52019-06-27 14:08:51 +0100381 Without(properties, value string) Rule
382
Paul Duffinc8111702019-07-22 12:13:55 +0100383 WithoutMatcher(properties string, matcher ValueMatcher) Rule
384
Paul Duffin730f2a52019-06-27 14:08:51 +0100385 Because(reason string) Rule
386}
387
Steven Moreland65b3fd92017-12-06 14:18:35 -0800388type rule struct {
389 // User string for why this is a thing.
390 reason string
391
392 paths []string
393 unlessPaths []string
394
Paul Duffin35781882019-07-25 15:41:09 +0100395 directDeps map[string]bool
396
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100397 osClasses []OsClass
398
Colin Crossfd4f7432019-03-05 15:06:16 -0800399 moduleTypes []string
400 unlessModuleTypes []string
401
Steven Moreland65b3fd92017-12-06 14:18:35 -0800402 props []ruleProperty
403 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100404
405 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800406}
407
Paul Duffin730f2a52019-06-27 14:08:51 +0100408// Create a new NeverAllow rule.
409func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100410 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800411}
Colin Crossfd4f7432019-03-05 15:06:16 -0800412
Paul Duffin730f2a52019-06-27 14:08:51 +0100413func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800414 r.paths = append(r.paths, cleanPaths(path)...)
415 return r
416}
Colin Crossfd4f7432019-03-05 15:06:16 -0800417
Paul Duffin730f2a52019-06-27 14:08:51 +0100418func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
420 return r
421}
Colin Crossfd4f7432019-03-05 15:06:16 -0800422
Paul Duffin35781882019-07-25 15:41:09 +0100423func (r *rule) InDirectDeps(deps ...string) Rule {
424 for _, d := range deps {
425 r.directDeps[d] = true
426 }
427 return r
428}
429
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100430func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
431 r.osClasses = append(r.osClasses, osClasses...)
432 return r
433}
434
Paul Duffin730f2a52019-06-27 14:08:51 +0100435func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800436 r.moduleTypes = append(r.moduleTypes, types...)
437 return r
438}
439
Paul Duffin730f2a52019-06-27 14:08:51 +0100440func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800441 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
442 return r
443}
444
Paul Duffin730f2a52019-06-27 14:08:51 +0100445func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100446 return r.WithMatcher(properties, selectMatcher(value))
447}
448
449func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800450 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100451 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100452 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800453 })
454 return r
455}
Colin Crossfd4f7432019-03-05 15:06:16 -0800456
Paul Duffin730f2a52019-06-27 14:08:51 +0100457func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100458 return r.WithoutMatcher(properties, selectMatcher(value))
459}
460
461func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800462 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100463 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100464 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800465 })
466 return r
467}
Colin Crossfd4f7432019-03-05 15:06:16 -0800468
Paul Duffin73bf0542019-07-12 14:12:49 +0100469func selectMatcher(expected string) ValueMatcher {
470 if expected == "*" {
471 return anyMatcherInstance
472 }
473 return &equalMatcher{expected: expected}
474}
475
Paul Duffin730f2a52019-06-27 14:08:51 +0100476func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800477 r.reason = reason
478 return r
479}
480
Andrei Onea115e7e72020-06-05 21:14:03 +0100481func (r *rule) BootclasspathJar() Rule {
482 r.onlyBootclasspathJar = true
483 return r
484}
485
Steven Moreland65b3fd92017-12-06 14:18:35 -0800486func (r *rule) String() string {
487 s := "neverallow"
488 for _, v := range r.paths {
489 s += " dir:" + v + "*"
490 }
491 for _, v := range r.unlessPaths {
492 s += " -dir:" + v + "*"
493 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800494 for _, v := range r.moduleTypes {
495 s += " type:" + v
496 }
497 for _, v := range r.unlessModuleTypes {
498 s += " -type:" + v
499 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100501 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800502 }
503 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100504 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800505 }
Paul Duffin35781882019-07-25 15:41:09 +0100506 for k := range r.directDeps {
507 s += " deps:" + k
508 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100509 for _, v := range r.osClasses {
510 s += " os:" + v.String()
511 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100512 if r.onlyBootclasspathJar {
513 s += " inBcp"
514 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800515 if len(r.reason) != 0 {
516 s += " which is restricted because " + r.reason
517 }
518 return s
519}
520
521func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800522 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
523 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800524 return includePath && !excludePath
525}
526
Paul Duffin35781882019-07-25 15:41:09 +0100527func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
528 if len(r.directDeps) == 0 {
529 return true
530 }
531
532 matches := false
533 ctx.VisitDirectDeps(func(m Module) {
534 if !matches {
535 name := ctx.OtherModuleName(m)
536 matches = r.directDeps[name]
537 }
538 })
539
540 return matches
541}
542
Andrei Onea115e7e72020-06-05 21:14:03 +0100543func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
544 if !r.onlyBootclasspathJar {
545 return true
546 }
547
548 return InList(ctx.ModuleName(), ctx.Config().BootJars())
549}
550
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100551func (r *rule) appliesToOsClass(osClass OsClass) bool {
552 if len(r.osClasses) == 0 {
553 return true
554 }
555
556 for _, c := range r.osClasses {
557 if c == osClass {
558 return true
559 }
560 }
561
562 return false
563}
564
Colin Crossfd4f7432019-03-05 15:06:16 -0800565func (r *rule) appliesToModuleType(moduleType string) bool {
566 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
567}
568
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000569func (r *rule) appliesToProperties(ctx ValueMatcherContext,
570 properties []interface{}) bool {
571 includeProps := hasAllProperties(ctx, properties, r.props)
572 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800573 return includeProps && !excludeProps
574}
575
Paul Duffinc8111702019-07-22 12:13:55 +0100576func StartsWith(prefix string) ValueMatcher {
577 return &startsWithMatcher{prefix}
578}
579
Anton Hansson45376402020-04-09 14:18:21 +0100580func Regexp(re string) ValueMatcher {
581 r, err := regexp.Compile(re)
582 if err != nil {
583 panic(err)
584 }
585 return &regexMatcher{r}
586}
587
Andrei Onea115e7e72020-06-05 21:14:03 +0100588func NotInList(allowed []string) ValueMatcher {
589 return &notInListMatcher{allowed}
590}
591
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000592func LessThanSdkVersion(sdk string) ValueMatcher {
593 return &sdkVersionMatcher{
594 condition: func(ctx ValueMatcherContext, spec SdkSpec) bool {
595 return spec.ApiLevel.LessThan(
596 SdkSpecFromWithConfig(ctx.Config(), sdk).ApiLevel)
597 },
598 description: "lessThan=" + sdk,
599 }
600}
601
Steven Moreland65b3fd92017-12-06 14:18:35 -0800602// assorted utils
603
604func cleanPaths(paths []string) []string {
605 res := make([]string, len(paths))
606 for i, v := range paths {
607 res[i] = filepath.Clean(v) + "/"
608 }
609 return res
610}
611
612func fieldNamesForProperties(propertyNames string) []string {
613 names := strings.Split(propertyNames, ".")
614 for i, v := range names {
615 names[i] = proptools.FieldNameForProperty(v)
616 }
617 return names
618}
619
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000620func hasAnyProperty(ctx ValueMatcherContext, properties []interface{},
621 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800622 for _, v := range props {
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000623 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800624 return true
625 }
626 }
627 return false
628}
629
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000630func hasAllProperties(ctx ValueMatcherContext, properties []interface{},
631 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800632 for _, v := range props {
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000633 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800634 return false
635 }
636 }
637 return true
638}
639
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000640func hasProperty(ctx ValueMatcherContext, properties []interface{},
641 prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800642 for _, propertyStruct := range properties {
643 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
644 for _, v := range prop.fields {
645 if !propertiesValue.IsValid() {
646 break
647 }
648 propertiesValue = propertiesValue.FieldByName(v)
649 }
650 if !propertiesValue.IsValid() {
651 continue
652 }
653
Paul Duffin73bf0542019-07-12 14:12:49 +0100654 check := func(value string) bool {
Remi NGUYEN VANefb49af2021-12-10 00:17:57 +0000655 return prop.matcher.Test(ctx, value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800656 }
657
658 if matchValue(propertiesValue, check) {
659 return true
660 }
661 }
662 return false
663}
664
665func matchValue(value reflect.Value, check func(string) bool) bool {
666 if !value.IsValid() {
667 return false
668 }
669
670 if value.Kind() == reflect.Ptr {
671 if value.IsNil() {
672 return check("")
673 }
674 value = value.Elem()
675 }
676
677 switch value.Kind() {
678 case reflect.String:
679 return check(value.String())
680 case reflect.Bool:
681 return check(strconv.FormatBool(value.Bool()))
682 case reflect.Int:
683 return check(strconv.FormatInt(value.Int(), 10))
684 case reflect.Slice:
685 slice, ok := value.Interface().([]string)
686 if !ok {
687 panic("Can only handle slice of string")
688 }
689 for _, v := range slice {
690 if check(v) {
691 return true
692 }
693 }
694 return false
695 }
696
697 panic("Can't handle type: " + value.Kind().String())
698}
Paul Duffin115445b2019-08-07 15:31:07 +0100699
700var neverallowRulesKey = NewOnceKey("neverallowRules")
701
702func neverallowRules(config Config) []Rule {
703 return config.Once(neverallowRulesKey, func() interface{} {
704 // No test rules were set by setTestNeverallowRules, use the global rules
705 return neverallows
706 }).([]Rule)
707}
708
709// Overrides the default neverallow rules for the supplied config.
710//
711// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100712func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100713 config.Once(neverallowRulesKey, func() interface{} { return testRules })
714}
Paul Duffin45338f02021-03-30 23:07:52 +0100715
716// Prepares for a test by setting neverallow rules and enabling the mutator.
717//
718// If the supplied rules are nil then the default rules are used.
719func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
720 return GroupFixturePreparers(
721 FixtureModifyConfig(func(config Config) {
722 if testRules != nil {
723 setTestNeverallowRules(config, testRules)
724 }
725 }),
726 FixtureRegisterWithContext(func(ctx RegistrationContext) {
727 ctx.PostDepsMutators(registerNeverallowMutator)
728 }),
729 )
730}