blob: 526d39949affa18063504b9777717de5683784f5 [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
Artur Satayevc5570ac2020-04-09 16:06:36 +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()...)
54 AddNeverAllowRules(createLibcoreRules()...)
55 AddNeverAllowRules(createMediaRules()...)
56 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000057 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010058 AddNeverAllowRules(createUncompressDexRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010059}
Steven Moreland65b3fd92017-12-06 14:18:35 -080060
Paul Duffin730f2a52019-06-27 14:08:51 +010061// Add a NeverAllow rule to the set of rules to apply.
62func AddNeverAllowRules(rules ...Rule) {
63 neverallows = append(neverallows, rules...)
64}
65
Paul Duffinc8111702019-07-22 12:13:55 +010066func createIncludeDirsRules() []Rule {
67 // The list of paths that cannot be referenced using include_dirs
68 paths := []string{
69 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000070 "art/libnativebridge",
71 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010072 "libcore",
73 "libnativehelper",
74 "external/apache-harmony",
75 "external/apache-xml",
76 "external/boringssl",
77 "external/bouncycastle",
78 "external/conscrypt",
79 "external/icu",
80 "external/okhttp",
81 "external/vixl",
82 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010083 }
84
85 // Create a composite matcher that will match if the value starts with any of the restricted
86 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
87 // XY.
88 rules := make([]Rule, 0, len(paths))
89 for _, path := range paths {
90 rule :=
91 NeverAllow().
92 WithMatcher("include_dirs", StartsWith(path+"/")).
93 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
94 " to use alternate mechanisms and so can no longer be used.")
95
96 rules = append(rules, rule)
97 }
98
99 return rules
100}
101
Paul Duffin730f2a52019-06-27 14:08:51 +0100102func createTrebleRules() []Rule {
103 return []Rule{
104 NeverAllow().
105 In("vendor", "device").
106 With("vndk.enabled", "true").
107 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900108 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100109 Because("the VNDK can never contain a library that is device dependent."),
110 NeverAllow().
111 With("vndk.enabled", "true").
112 Without("vendor", "true").
113 Without("owner", "").
114 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800115
Neil Fullerdf5f3562018-10-21 17:19:10 +0100116 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100117 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800118 Without("name", "libhidlbase-combined-impl").
119 Without("name", "libhidlbase").
120 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100121 With("product_variables.enforce_vintf_manifest.cflags", "*").
122 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100123
124 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100125 NeverAllow().
126 Without("name", "libc_bionic_ndk").
127 With("product_variables.treble_linker_namespaces.cflags", "*").
128 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100129
130 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100131 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100132 }
133}
134
Paul Duffin730f2a52019-06-27 14:08:51 +0100135func createLibcoreRules() []Rule {
Neil Fullerdf5f3562018-10-21 17:19:10 +0100136 var coreLibraryProjects = []string{
137 "libcore",
138 "external/apache-harmony",
139 "external/apache-xml",
140 "external/bouncycastle",
141 "external/conscrypt",
142 "external/icu",
143 "external/okhttp",
144 "external/wycheproof",
Paul Duffine5c3b852020-05-12 15:27:56 +0100145 "prebuilts",
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146 }
147
Roland Levillainaca94492020-02-13 15:22:05 +0000148 // Additional whitelisted path only used for ART testing, which needs access to core library
149 // targets. This does not affect the contents of a device image (system, vendor, etc.).
150 var artTests = []string{
151 "art/test",
152 }
153
154 // Core library constraints. The sdk_version: "none" can only be used in core library projects and ART tests.
Paul Duffina3d09862019-06-11 13:40:47 +0100155 // Access to core library targets is restricted using visibility rules.
Paul Duffin730f2a52019-06-27 14:08:51 +0100156 rules := []Rule{
157 NeverAllow().
158 NotIn(coreLibraryProjects...).
Roland Levillainaca94492020-02-13 15:22:05 +0000159 NotIn(artTests...).
Anton Hansson45376402020-04-09 14:18:21 +0100160 With("sdk_version", "none").
161 WithoutMatcher("name", Regexp("^android_.*stubs_current$")),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100162 }
163
Neil Fullerdf5f3562018-10-21 17:19:10 +0100164 return rules
Steven Moreland65b3fd92017-12-06 14:18:35 -0800165}
166
Paul Duffin730f2a52019-06-27 14:08:51 +0100167func createMediaRules() []Rule {
168 return []Rule{
169 NeverAllow().
170 With("libs", "updatable-media").
171 Because("updatable-media includes private APIs. Use updatable_media_stubs instead."),
Dongwon Kang50a299f2019-02-04 09:00:51 -0800172 }
173}
174
Paul Duffin730f2a52019-06-27 14:08:51 +0100175func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700176 javaDeviceForHostProjectsAllowedList := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700177 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800178 "external/robolectric-shadows",
179 "framework/layoutlib",
180 }
181
Paul Duffin730f2a52019-06-27 14:08:51 +0100182 return []Rule{
183 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700184 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100185 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700186 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800187 }
188}
189
Colin Crossc511bc52020-04-07 16:50:32 +0000190func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700191 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000192 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
193 // This sometimes works because the APEX modules that contain derive_sdk and
194 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
195 // the APEX modules contain the SDK variant and the platform variant still exists.
196 "frameworks/base/apex/sdkextensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700197 // These are for apps and shouldn't be used by non-SDK variant modules.
198 "prebuilts/ndk",
199 "tools/test/graphicsbenchmark/apps/sample_app",
200 "tools/test/graphicsbenchmark/functional_tests/java",
Colin Crossc511bc52020-04-07 16:50:32 +0000201 }
202
Colin Cross440e0d02020-06-11 11:32:11 -0700203 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000204 // android_native_app_glue and libRSSupport use native_window.h but target old
205 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
206 // so they can't add libnativewindow to shared_libs to get the header directory
207 // for the platform variant. Allow them to use the platform variant
208 // property to set shared_libs.
209 "prebuilts/ndk",
210 "frameworks/rs",
211 }
212
213 return []Rule{
214 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700215 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000216 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700217 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000218 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700219 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000220 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700221 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000222 }
223}
224
David Srbeckye033cba2020-05-20 22:20:28 +0100225func createUncompressDexRules() []Rule {
226 return []Rule{
227 NeverAllow().
228 NotIn("art").
229 WithMatcher("uncompress_dex", isSetMatcherInstance).
230 Because("uncompress_dex is only allowed for certain jars for test in art."),
231 }
232}
233
Steven Moreland65b3fd92017-12-06 14:18:35 -0800234func neverallowMutator(ctx BottomUpMutatorContext) {
235 m, ok := ctx.Module().(Module)
236 if !ok {
237 return
238 }
239
240 dir := ctx.ModuleDir() + "/"
241 properties := m.GetProperties()
242
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100243 osClass := ctx.Module().Target().Os.Class
244
Paul Duffin115445b2019-08-07 15:31:07 +0100245 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100246 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800247 if !n.appliesToPath(dir) {
248 continue
249 }
250
Colin Crossfd4f7432019-03-05 15:06:16 -0800251 if !n.appliesToModuleType(ctx.ModuleType()) {
252 continue
253 }
254
Steven Moreland65b3fd92017-12-06 14:18:35 -0800255 if !n.appliesToProperties(properties) {
256 continue
257 }
258
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100259 if !n.appliesToOsClass(osClass) {
260 continue
261 }
262
Paul Duffin35781882019-07-25 15:41:09 +0100263 if !n.appliesToDirectDeps(ctx) {
264 continue
265 }
266
Steven Moreland65b3fd92017-12-06 14:18:35 -0800267 ctx.ModuleErrorf("violates " + n.String())
268 }
269}
270
Paul Duffin73bf0542019-07-12 14:12:49 +0100271type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100272 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100273 String() string
274}
275
276type equalMatcher struct {
277 expected string
278}
279
Artur Satayevc5570ac2020-04-09 16:06:36 +0100280func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100281 return m.expected == value
282}
283
284func (m *equalMatcher) String() string {
285 return "=" + m.expected
286}
287
288type anyMatcher struct {
289}
290
Artur Satayevc5570ac2020-04-09 16:06:36 +0100291func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100292 return true
293}
294
295func (m *anyMatcher) String() string {
296 return "=*"
297}
298
299var anyMatcherInstance = &anyMatcher{}
300
Paul Duffinc8111702019-07-22 12:13:55 +0100301type startsWithMatcher struct {
302 prefix string
303}
304
Artur Satayevc5570ac2020-04-09 16:06:36 +0100305func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100306 return strings.HasPrefix(value, m.prefix)
307}
308
309func (m *startsWithMatcher) String() string {
310 return ".starts-with(" + m.prefix + ")"
311}
312
Anton Hansson45376402020-04-09 14:18:21 +0100313type regexMatcher struct {
314 re *regexp.Regexp
315}
316
Artur Satayevc5570ac2020-04-09 16:06:36 +0100317func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100318 return m.re.MatchString(value)
319}
320
321func (m *regexMatcher) String() string {
322 return ".regexp(" + m.re.String() + ")"
323}
324
Colin Crossc511bc52020-04-07 16:50:32 +0000325type isSetMatcher struct{}
326
Artur Satayevc5570ac2020-04-09 16:06:36 +0100327func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000328 return value != ""
329}
330
331func (m *isSetMatcher) String() string {
332 return ".is-set"
333}
334
335var isSetMatcherInstance = &isSetMatcher{}
336
Steven Moreland65b3fd92017-12-06 14:18:35 -0800337type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100338 fields []string // e.x.: Vndk.Enabled
339 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800340}
341
Paul Duffin730f2a52019-06-27 14:08:51 +0100342// A NeverAllow rule.
343type Rule interface {
344 In(path ...string) Rule
345
346 NotIn(path ...string) Rule
347
Paul Duffin35781882019-07-25 15:41:09 +0100348 InDirectDeps(deps ...string) Rule
349
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100350 WithOsClass(osClasses ...OsClass) Rule
351
Paul Duffin730f2a52019-06-27 14:08:51 +0100352 ModuleType(types ...string) Rule
353
354 NotModuleType(types ...string) Rule
355
356 With(properties, value string) Rule
357
Paul Duffinc8111702019-07-22 12:13:55 +0100358 WithMatcher(properties string, matcher ValueMatcher) Rule
359
Paul Duffin730f2a52019-06-27 14:08:51 +0100360 Without(properties, value string) Rule
361
Paul Duffinc8111702019-07-22 12:13:55 +0100362 WithoutMatcher(properties string, matcher ValueMatcher) Rule
363
Paul Duffin730f2a52019-06-27 14:08:51 +0100364 Because(reason string) Rule
365}
366
Steven Moreland65b3fd92017-12-06 14:18:35 -0800367type rule struct {
368 // User string for why this is a thing.
369 reason string
370
371 paths []string
372 unlessPaths []string
373
Paul Duffin35781882019-07-25 15:41:09 +0100374 directDeps map[string]bool
375
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100376 osClasses []OsClass
377
Colin Crossfd4f7432019-03-05 15:06:16 -0800378 moduleTypes []string
379 unlessModuleTypes []string
380
Steven Moreland65b3fd92017-12-06 14:18:35 -0800381 props []ruleProperty
382 unlessProps []ruleProperty
383}
384
Paul Duffin730f2a52019-06-27 14:08:51 +0100385// Create a new NeverAllow rule.
386func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100387 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800388}
Colin Crossfd4f7432019-03-05 15:06:16 -0800389
Paul Duffin730f2a52019-06-27 14:08:51 +0100390func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800391 r.paths = append(r.paths, cleanPaths(path)...)
392 return r
393}
Colin Crossfd4f7432019-03-05 15:06:16 -0800394
Paul Duffin730f2a52019-06-27 14:08:51 +0100395func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800396 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
397 return r
398}
Colin Crossfd4f7432019-03-05 15:06:16 -0800399
Paul Duffin35781882019-07-25 15:41:09 +0100400func (r *rule) InDirectDeps(deps ...string) Rule {
401 for _, d := range deps {
402 r.directDeps[d] = true
403 }
404 return r
405}
406
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100407func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
408 r.osClasses = append(r.osClasses, osClasses...)
409 return r
410}
411
Paul Duffin730f2a52019-06-27 14:08:51 +0100412func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800413 r.moduleTypes = append(r.moduleTypes, types...)
414 return r
415}
416
Paul Duffin730f2a52019-06-27 14:08:51 +0100417func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800418 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
419 return r
420}
421
Paul Duffin730f2a52019-06-27 14:08:51 +0100422func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100423 return r.WithMatcher(properties, selectMatcher(value))
424}
425
426func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800427 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100428 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100429 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800430 })
431 return r
432}
Colin Crossfd4f7432019-03-05 15:06:16 -0800433
Paul Duffin730f2a52019-06-27 14:08:51 +0100434func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100435 return r.WithoutMatcher(properties, selectMatcher(value))
436}
437
438func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800439 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100440 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100441 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800442 })
443 return r
444}
Colin Crossfd4f7432019-03-05 15:06:16 -0800445
Paul Duffin73bf0542019-07-12 14:12:49 +0100446func selectMatcher(expected string) ValueMatcher {
447 if expected == "*" {
448 return anyMatcherInstance
449 }
450 return &equalMatcher{expected: expected}
451}
452
Paul Duffin730f2a52019-06-27 14:08:51 +0100453func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800454 r.reason = reason
455 return r
456}
457
458func (r *rule) String() string {
459 s := "neverallow"
460 for _, v := range r.paths {
461 s += " dir:" + v + "*"
462 }
463 for _, v := range r.unlessPaths {
464 s += " -dir:" + v + "*"
465 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800466 for _, v := range r.moduleTypes {
467 s += " type:" + v
468 }
469 for _, v := range r.unlessModuleTypes {
470 s += " -type:" + v
471 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800472 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100473 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800474 }
475 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100476 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800477 }
Paul Duffin35781882019-07-25 15:41:09 +0100478 for k := range r.directDeps {
479 s += " deps:" + k
480 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100481 for _, v := range r.osClasses {
482 s += " os:" + v.String()
483 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800484 if len(r.reason) != 0 {
485 s += " which is restricted because " + r.reason
486 }
487 return s
488}
489
490func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800491 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
492 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800493 return includePath && !excludePath
494}
495
Paul Duffin35781882019-07-25 15:41:09 +0100496func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
497 if len(r.directDeps) == 0 {
498 return true
499 }
500
501 matches := false
502 ctx.VisitDirectDeps(func(m Module) {
503 if !matches {
504 name := ctx.OtherModuleName(m)
505 matches = r.directDeps[name]
506 }
507 })
508
509 return matches
510}
511
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100512func (r *rule) appliesToOsClass(osClass OsClass) bool {
513 if len(r.osClasses) == 0 {
514 return true
515 }
516
517 for _, c := range r.osClasses {
518 if c == osClass {
519 return true
520 }
521 }
522
523 return false
524}
525
Colin Crossfd4f7432019-03-05 15:06:16 -0800526func (r *rule) appliesToModuleType(moduleType string) bool {
527 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
528}
529
Steven Moreland65b3fd92017-12-06 14:18:35 -0800530func (r *rule) appliesToProperties(properties []interface{}) bool {
531 includeProps := hasAllProperties(properties, r.props)
532 excludeProps := hasAnyProperty(properties, r.unlessProps)
533 return includeProps && !excludeProps
534}
535
Paul Duffinc8111702019-07-22 12:13:55 +0100536func StartsWith(prefix string) ValueMatcher {
537 return &startsWithMatcher{prefix}
538}
539
Anton Hansson45376402020-04-09 14:18:21 +0100540func Regexp(re string) ValueMatcher {
541 r, err := regexp.Compile(re)
542 if err != nil {
543 panic(err)
544 }
545 return &regexMatcher{r}
546}
547
Steven Moreland65b3fd92017-12-06 14:18:35 -0800548// assorted utils
549
550func cleanPaths(paths []string) []string {
551 res := make([]string, len(paths))
552 for i, v := range paths {
553 res[i] = filepath.Clean(v) + "/"
554 }
555 return res
556}
557
558func fieldNamesForProperties(propertyNames string) []string {
559 names := strings.Split(propertyNames, ".")
560 for i, v := range names {
561 names[i] = proptools.FieldNameForProperty(v)
562 }
563 return names
564}
565
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
567 for _, v := range props {
568 if hasProperty(properties, v) {
569 return true
570 }
571 }
572 return false
573}
574
575func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
576 for _, v := range props {
577 if !hasProperty(properties, v) {
578 return false
579 }
580 }
581 return true
582}
583
584func hasProperty(properties []interface{}, prop ruleProperty) bool {
585 for _, propertyStruct := range properties {
586 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
587 for _, v := range prop.fields {
588 if !propertiesValue.IsValid() {
589 break
590 }
591 propertiesValue = propertiesValue.FieldByName(v)
592 }
593 if !propertiesValue.IsValid() {
594 continue
595 }
596
Paul Duffin73bf0542019-07-12 14:12:49 +0100597 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100598 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800599 }
600
601 if matchValue(propertiesValue, check) {
602 return true
603 }
604 }
605 return false
606}
607
608func matchValue(value reflect.Value, check func(string) bool) bool {
609 if !value.IsValid() {
610 return false
611 }
612
613 if value.Kind() == reflect.Ptr {
614 if value.IsNil() {
615 return check("")
616 }
617 value = value.Elem()
618 }
619
620 switch value.Kind() {
621 case reflect.String:
622 return check(value.String())
623 case reflect.Bool:
624 return check(strconv.FormatBool(value.Bool()))
625 case reflect.Int:
626 return check(strconv.FormatInt(value.Int(), 10))
627 case reflect.Slice:
628 slice, ok := value.Interface().([]string)
629 if !ok {
630 panic("Can only handle slice of string")
631 }
632 for _, v := range slice {
633 if check(v) {
634 return true
635 }
636 }
637 return false
638 }
639
640 panic("Can't handle type: " + value.Kind().String())
641}
Paul Duffin115445b2019-08-07 15:31:07 +0100642
643var neverallowRulesKey = NewOnceKey("neverallowRules")
644
645func neverallowRules(config Config) []Rule {
646 return config.Once(neverallowRulesKey, func() interface{} {
647 // No test rules were set by setTestNeverallowRules, use the global rules
648 return neverallows
649 }).([]Rule)
650}
651
652// Overrides the default neverallow rules for the supplied config.
653//
654// For testing only.
Artur Satayevc5570ac2020-04-09 16:06:36 +0100655func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100656 config.Once(neverallowRulesKey, func() interface{} { return testRules })
657}