blob: a385bbc0cd80ea4cbe446e3b20d40d7e11ccc641 [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 {
66 // The list of paths that cannot be referenced using include_dirs
67 paths := []string{
68 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000069 "art/libnativebridge",
70 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010071 "libcore",
72 "libnativehelper",
73 "external/apache-harmony",
74 "external/apache-xml",
75 "external/boringssl",
76 "external/bouncycastle",
77 "external/conscrypt",
78 "external/icu",
79 "external/okhttp",
80 "external/vixl",
81 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010082 }
83
84 // Create a composite matcher that will match if the value starts with any of the restricted
85 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
86 // XY.
87 rules := make([]Rule, 0, len(paths))
88 for _, path := range paths {
89 rule :=
90 NeverAllow().
91 WithMatcher("include_dirs", StartsWith(path+"/")).
92 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
93 " to use alternate mechanisms and so can no longer be used.")
94
95 rules = append(rules, rule)
96 }
97
98 return rules
99}
100
Paul Duffin730f2a52019-06-27 14:08:51 +0100101func createTrebleRules() []Rule {
102 return []Rule{
103 NeverAllow().
104 In("vendor", "device").
105 With("vndk.enabled", "true").
106 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900107 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100108 Because("the VNDK can never contain a library that is device dependent."),
109 NeverAllow().
110 With("vndk.enabled", "true").
111 Without("vendor", "true").
112 Without("owner", "").
113 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800114
Neil Fullerdf5f3562018-10-21 17:19:10 +0100115 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100116 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800117 Without("name", "libhidlbase-combined-impl").
118 Without("name", "libhidlbase").
119 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100120 With("product_variables.enforce_vintf_manifest.cflags", "*").
121 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100122
123 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100124 NeverAllow().
125 Without("name", "libc_bionic_ndk").
126 With("product_variables.treble_linker_namespaces.cflags", "*").
127 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100128
129 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100130 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100131 }
132}
133
Paul Duffin730f2a52019-06-27 14:08:51 +0100134func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700135 javaDeviceForHostProjectsAllowedList := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700136 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800137 "external/robolectric-shadows",
138 "framework/layoutlib",
139 }
140
Paul Duffin730f2a52019-06-27 14:08:51 +0100141 return []Rule{
142 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700143 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100144 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700145 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800146 }
147}
148
Colin Crossc511bc52020-04-07 16:50:32 +0000149func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700150 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000151 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
152 // This sometimes works because the APEX modules that contain derive_sdk and
153 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
154 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100155 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700156 // These are for apps and shouldn't be used by non-SDK variant modules.
157 "prebuilts/ndk",
158 "tools/test/graphicsbenchmark/apps/sample_app",
159 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700160 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Colin Crossc511bc52020-04-07 16:50:32 +0000161 }
162
Colin Cross440e0d02020-06-11 11:32:11 -0700163 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000164 // android_native_app_glue and libRSSupport use native_window.h but target old
165 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
166 // so they can't add libnativewindow to shared_libs to get the header directory
167 // for the platform variant. Allow them to use the platform variant
168 // property to set shared_libs.
169 "prebuilts/ndk",
170 "frameworks/rs",
171 }
172
173 return []Rule{
174 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700175 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000176 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700177 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000178 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700179 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000180 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700181 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000182 }
183}
184
David Srbeckye033cba2020-05-20 22:20:28 +0100185func createUncompressDexRules() []Rule {
186 return []Rule{
187 NeverAllow().
188 NotIn("art").
189 WithMatcher("uncompress_dex", isSetMatcherInstance).
190 Because("uncompress_dex is only allowed for certain jars for test in art."),
191 }
192}
193
Yifan Hong696ed4d2020-07-27 12:59:58 -0700194func createMakefileGoalRules() []Rule {
195 return []Rule{
196 NeverAllow().
197 ModuleType("makefile_goal").
198 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
199 Because("Only boot images may be imported as a makefile goal."),
200 }
201}
202
Steven Moreland65b3fd92017-12-06 14:18:35 -0800203func neverallowMutator(ctx BottomUpMutatorContext) {
204 m, ok := ctx.Module().(Module)
205 if !ok {
206 return
207 }
208
209 dir := ctx.ModuleDir() + "/"
210 properties := m.GetProperties()
211
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100212 osClass := ctx.Module().Target().Os.Class
213
Paul Duffin115445b2019-08-07 15:31:07 +0100214 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100215 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800216 if !n.appliesToPath(dir) {
217 continue
218 }
219
Colin Crossfd4f7432019-03-05 15:06:16 -0800220 if !n.appliesToModuleType(ctx.ModuleType()) {
221 continue
222 }
223
Steven Moreland65b3fd92017-12-06 14:18:35 -0800224 if !n.appliesToProperties(properties) {
225 continue
226 }
227
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100228 if !n.appliesToOsClass(osClass) {
229 continue
230 }
231
Paul Duffin35781882019-07-25 15:41:09 +0100232 if !n.appliesToDirectDeps(ctx) {
233 continue
234 }
235
Andrei Onea115e7e72020-06-05 21:14:03 +0100236 if !n.appliesToBootclasspathJar(ctx) {
237 continue
238 }
239
Steven Moreland65b3fd92017-12-06 14:18:35 -0800240 ctx.ModuleErrorf("violates " + n.String())
241 }
242}
243
Paul Duffin73bf0542019-07-12 14:12:49 +0100244type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100245 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100246 String() string
247}
248
249type equalMatcher struct {
250 expected string
251}
252
Artur Satayevc5570ac2020-04-09 16:06:36 +0100253func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100254 return m.expected == value
255}
256
257func (m *equalMatcher) String() string {
258 return "=" + m.expected
259}
260
261type anyMatcher struct {
262}
263
Artur Satayevc5570ac2020-04-09 16:06:36 +0100264func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100265 return true
266}
267
268func (m *anyMatcher) String() string {
269 return "=*"
270}
271
272var anyMatcherInstance = &anyMatcher{}
273
Paul Duffinc8111702019-07-22 12:13:55 +0100274type startsWithMatcher struct {
275 prefix string
276}
277
Artur Satayevc5570ac2020-04-09 16:06:36 +0100278func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100279 return strings.HasPrefix(value, m.prefix)
280}
281
282func (m *startsWithMatcher) String() string {
283 return ".starts-with(" + m.prefix + ")"
284}
285
Anton Hansson45376402020-04-09 14:18:21 +0100286type regexMatcher struct {
287 re *regexp.Regexp
288}
289
Artur Satayevc5570ac2020-04-09 16:06:36 +0100290func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100291 return m.re.MatchString(value)
292}
293
294func (m *regexMatcher) String() string {
295 return ".regexp(" + m.re.String() + ")"
296}
297
Andrei Onea115e7e72020-06-05 21:14:03 +0100298type notInListMatcher struct {
299 allowed []string
300}
301
302func (m *notInListMatcher) Test(value string) bool {
303 return !InList(value, m.allowed)
304}
305
306func (m *notInListMatcher) String() string {
307 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
308}
309
Colin Crossc511bc52020-04-07 16:50:32 +0000310type isSetMatcher struct{}
311
Artur Satayevc5570ac2020-04-09 16:06:36 +0100312func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000313 return value != ""
314}
315
316func (m *isSetMatcher) String() string {
317 return ".is-set"
318}
319
320var isSetMatcherInstance = &isSetMatcher{}
321
Steven Moreland65b3fd92017-12-06 14:18:35 -0800322type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100323 fields []string // e.x.: Vndk.Enabled
324 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800325}
326
Paul Duffin730f2a52019-06-27 14:08:51 +0100327// A NeverAllow rule.
328type Rule interface {
329 In(path ...string) Rule
330
331 NotIn(path ...string) Rule
332
Paul Duffin35781882019-07-25 15:41:09 +0100333 InDirectDeps(deps ...string) Rule
334
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100335 WithOsClass(osClasses ...OsClass) Rule
336
Paul Duffin730f2a52019-06-27 14:08:51 +0100337 ModuleType(types ...string) Rule
338
339 NotModuleType(types ...string) Rule
340
Andrei Onea115e7e72020-06-05 21:14:03 +0100341 BootclasspathJar() Rule
342
Paul Duffin730f2a52019-06-27 14:08:51 +0100343 With(properties, value string) Rule
344
Paul Duffinc8111702019-07-22 12:13:55 +0100345 WithMatcher(properties string, matcher ValueMatcher) Rule
346
Paul Duffin730f2a52019-06-27 14:08:51 +0100347 Without(properties, value string) Rule
348
Paul Duffinc8111702019-07-22 12:13:55 +0100349 WithoutMatcher(properties string, matcher ValueMatcher) Rule
350
Paul Duffin730f2a52019-06-27 14:08:51 +0100351 Because(reason string) Rule
352}
353
Steven Moreland65b3fd92017-12-06 14:18:35 -0800354type rule struct {
355 // User string for why this is a thing.
356 reason string
357
358 paths []string
359 unlessPaths []string
360
Paul Duffin35781882019-07-25 15:41:09 +0100361 directDeps map[string]bool
362
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100363 osClasses []OsClass
364
Colin Crossfd4f7432019-03-05 15:06:16 -0800365 moduleTypes []string
366 unlessModuleTypes []string
367
Steven Moreland65b3fd92017-12-06 14:18:35 -0800368 props []ruleProperty
369 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100370
371 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800372}
373
Paul Duffin730f2a52019-06-27 14:08:51 +0100374// Create a new NeverAllow rule.
375func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100376 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800377}
Colin Crossfd4f7432019-03-05 15:06:16 -0800378
Paul Duffin730f2a52019-06-27 14:08:51 +0100379func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800380 r.paths = append(r.paths, cleanPaths(path)...)
381 return r
382}
Colin Crossfd4f7432019-03-05 15:06:16 -0800383
Paul Duffin730f2a52019-06-27 14:08:51 +0100384func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
386 return r
387}
Colin Crossfd4f7432019-03-05 15:06:16 -0800388
Paul Duffin35781882019-07-25 15:41:09 +0100389func (r *rule) InDirectDeps(deps ...string) Rule {
390 for _, d := range deps {
391 r.directDeps[d] = true
392 }
393 return r
394}
395
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100396func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
397 r.osClasses = append(r.osClasses, osClasses...)
398 return r
399}
400
Paul Duffin730f2a52019-06-27 14:08:51 +0100401func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800402 r.moduleTypes = append(r.moduleTypes, types...)
403 return r
404}
405
Paul Duffin730f2a52019-06-27 14:08:51 +0100406func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800407 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
408 return r
409}
410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100412 return r.WithMatcher(properties, selectMatcher(value))
413}
414
415func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800416 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100417 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100418 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419 })
420 return r
421}
Colin Crossfd4f7432019-03-05 15:06:16 -0800422
Paul Duffin730f2a52019-06-27 14:08:51 +0100423func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100424 return r.WithoutMatcher(properties, selectMatcher(value))
425}
426
427func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800428 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100429 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100430 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800431 })
432 return r
433}
Colin Crossfd4f7432019-03-05 15:06:16 -0800434
Paul Duffin73bf0542019-07-12 14:12:49 +0100435func selectMatcher(expected string) ValueMatcher {
436 if expected == "*" {
437 return anyMatcherInstance
438 }
439 return &equalMatcher{expected: expected}
440}
441
Paul Duffin730f2a52019-06-27 14:08:51 +0100442func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800443 r.reason = reason
444 return r
445}
446
Andrei Onea115e7e72020-06-05 21:14:03 +0100447func (r *rule) BootclasspathJar() Rule {
448 r.onlyBootclasspathJar = true
449 return r
450}
451
Steven Moreland65b3fd92017-12-06 14:18:35 -0800452func (r *rule) String() string {
453 s := "neverallow"
454 for _, v := range r.paths {
455 s += " dir:" + v + "*"
456 }
457 for _, v := range r.unlessPaths {
458 s += " -dir:" + v + "*"
459 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800460 for _, v := range r.moduleTypes {
461 s += " type:" + v
462 }
463 for _, v := range r.unlessModuleTypes {
464 s += " -type:" + v
465 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800466 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100467 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800468 }
469 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100470 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800471 }
Paul Duffin35781882019-07-25 15:41:09 +0100472 for k := range r.directDeps {
473 s += " deps:" + k
474 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100475 for _, v := range r.osClasses {
476 s += " os:" + v.String()
477 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100478 if r.onlyBootclasspathJar {
479 s += " inBcp"
480 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800481 if len(r.reason) != 0 {
482 s += " which is restricted because " + r.reason
483 }
484 return s
485}
486
487func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800488 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
489 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800490 return includePath && !excludePath
491}
492
Paul Duffin35781882019-07-25 15:41:09 +0100493func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
494 if len(r.directDeps) == 0 {
495 return true
496 }
497
498 matches := false
499 ctx.VisitDirectDeps(func(m Module) {
500 if !matches {
501 name := ctx.OtherModuleName(m)
502 matches = r.directDeps[name]
503 }
504 })
505
506 return matches
507}
508
Andrei Onea115e7e72020-06-05 21:14:03 +0100509func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
510 if !r.onlyBootclasspathJar {
511 return true
512 }
513
514 return InList(ctx.ModuleName(), ctx.Config().BootJars())
515}
516
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100517func (r *rule) appliesToOsClass(osClass OsClass) bool {
518 if len(r.osClasses) == 0 {
519 return true
520 }
521
522 for _, c := range r.osClasses {
523 if c == osClass {
524 return true
525 }
526 }
527
528 return false
529}
530
Colin Crossfd4f7432019-03-05 15:06:16 -0800531func (r *rule) appliesToModuleType(moduleType string) bool {
532 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
533}
534
Steven Moreland65b3fd92017-12-06 14:18:35 -0800535func (r *rule) appliesToProperties(properties []interface{}) bool {
536 includeProps := hasAllProperties(properties, r.props)
537 excludeProps := hasAnyProperty(properties, r.unlessProps)
538 return includeProps && !excludeProps
539}
540
Paul Duffinc8111702019-07-22 12:13:55 +0100541func StartsWith(prefix string) ValueMatcher {
542 return &startsWithMatcher{prefix}
543}
544
Anton Hansson45376402020-04-09 14:18:21 +0100545func Regexp(re string) ValueMatcher {
546 r, err := regexp.Compile(re)
547 if err != nil {
548 panic(err)
549 }
550 return &regexMatcher{r}
551}
552
Andrei Onea115e7e72020-06-05 21:14:03 +0100553func NotInList(allowed []string) ValueMatcher {
554 return &notInListMatcher{allowed}
555}
556
Steven Moreland65b3fd92017-12-06 14:18:35 -0800557// assorted utils
558
559func cleanPaths(paths []string) []string {
560 res := make([]string, len(paths))
561 for i, v := range paths {
562 res[i] = filepath.Clean(v) + "/"
563 }
564 return res
565}
566
567func fieldNamesForProperties(propertyNames string) []string {
568 names := strings.Split(propertyNames, ".")
569 for i, v := range names {
570 names[i] = proptools.FieldNameForProperty(v)
571 }
572 return names
573}
574
Steven Moreland65b3fd92017-12-06 14:18:35 -0800575func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
576 for _, v := range props {
577 if hasProperty(properties, v) {
578 return true
579 }
580 }
581 return false
582}
583
584func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
585 for _, v := range props {
586 if !hasProperty(properties, v) {
587 return false
588 }
589 }
590 return true
591}
592
593func hasProperty(properties []interface{}, prop ruleProperty) bool {
594 for _, propertyStruct := range properties {
595 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
596 for _, v := range prop.fields {
597 if !propertiesValue.IsValid() {
598 break
599 }
600 propertiesValue = propertiesValue.FieldByName(v)
601 }
602 if !propertiesValue.IsValid() {
603 continue
604 }
605
Paul Duffin73bf0542019-07-12 14:12:49 +0100606 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100607 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800608 }
609
610 if matchValue(propertiesValue, check) {
611 return true
612 }
613 }
614 return false
615}
616
617func matchValue(value reflect.Value, check func(string) bool) bool {
618 if !value.IsValid() {
619 return false
620 }
621
622 if value.Kind() == reflect.Ptr {
623 if value.IsNil() {
624 return check("")
625 }
626 value = value.Elem()
627 }
628
629 switch value.Kind() {
630 case reflect.String:
631 return check(value.String())
632 case reflect.Bool:
633 return check(strconv.FormatBool(value.Bool()))
634 case reflect.Int:
635 return check(strconv.FormatInt(value.Int(), 10))
636 case reflect.Slice:
637 slice, ok := value.Interface().([]string)
638 if !ok {
639 panic("Can only handle slice of string")
640 }
641 for _, v := range slice {
642 if check(v) {
643 return true
644 }
645 }
646 return false
647 }
648
649 panic("Can't handle type: " + value.Kind().String())
650}
Paul Duffin115445b2019-08-07 15:31:07 +0100651
652var neverallowRulesKey = NewOnceKey("neverallowRules")
653
654func neverallowRules(config Config) []Rule {
655 return config.Once(neverallowRulesKey, func() interface{} {
656 // No test rules were set by setTestNeverallowRules, use the global rules
657 return neverallows
658 }).([]Rule)
659}
660
661// Overrides the default neverallow rules for the supplied config.
662//
663// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100664func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100665 config.Once(neverallowRulesKey, func() interface{} { return testRules })
666}
Paul Duffin45338f02021-03-30 23:07:52 +0100667
668// Prepares for a test by setting neverallow rules and enabling the mutator.
669//
670// If the supplied rules are nil then the default rules are used.
671func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
672 return GroupFixturePreparers(
673 FixtureModifyConfig(func(config Config) {
674 if testRules != nil {
675 setTestNeverallowRules(config, testRules)
676 }
677 }),
678 FixtureRegisterWithContext(func(ctx RegistrationContext) {
679 ctx.PostDepsMutators(registerNeverallowMutator)
680 }),
681 )
682}