blob: d4a1ff1603e34d92113689b5bf490bfec0408949 [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{
83 "system/libfmq",
84 }
Paul Duffinc8111702019-07-22 12:13:55 +010085
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000086 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
87
88 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +010089 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
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000098 for _, path := range noUseIncludeDir {
99 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
100 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
101 " to use alternate mechanisms and so can no longer be used.")
102 rules = append(rules, rule)
103 }
104
Paul Duffinc8111702019-07-22 12:13:55 +0100105 return rules
106}
107
Paul Duffin730f2a52019-06-27 14:08:51 +0100108func createTrebleRules() []Rule {
109 return []Rule{
110 NeverAllow().
111 In("vendor", "device").
112 With("vndk.enabled", "true").
113 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900114 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100115 Because("the VNDK can never contain a library that is device dependent."),
116 NeverAllow().
117 With("vndk.enabled", "true").
118 Without("vendor", "true").
119 Without("owner", "").
120 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800121
Neil Fullerdf5f3562018-10-21 17:19:10 +0100122 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100123 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800124 Without("name", "libhidlbase-combined-impl").
125 Without("name", "libhidlbase").
126 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100127 With("product_variables.enforce_vintf_manifest.cflags", "*").
128 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100129
130 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100131 NeverAllow().
132 Without("name", "libc_bionic_ndk").
133 With("product_variables.treble_linker_namespaces.cflags", "*").
134 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100135
136 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100137 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100138 }
139}
140
Paul Duffin730f2a52019-06-27 14:08:51 +0100141func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700142 javaDeviceForHostProjectsAllowedList := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700143 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800144 "external/robolectric-shadows",
145 "framework/layoutlib",
146 }
147
Paul Duffin730f2a52019-06-27 14:08:51 +0100148 return []Rule{
149 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700150 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100151 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700152 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800153 }
154}
155
Colin Crossc511bc52020-04-07 16:50:32 +0000156func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700157 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000158 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
159 // This sometimes works because the APEX modules that contain derive_sdk and
160 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
161 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100162 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700163 // These are for apps and shouldn't be used by non-SDK variant modules.
164 "prebuilts/ndk",
165 "tools/test/graphicsbenchmark/apps/sample_app",
166 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700167 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Colin Crossc511bc52020-04-07 16:50:32 +0000168 }
169
Colin Cross440e0d02020-06-11 11:32:11 -0700170 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000171 // android_native_app_glue and libRSSupport use native_window.h but target old
172 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
173 // so they can't add libnativewindow to shared_libs to get the header directory
174 // for the platform variant. Allow them to use the platform variant
175 // property to set shared_libs.
176 "prebuilts/ndk",
177 "frameworks/rs",
178 }
179
180 return []Rule{
181 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700182 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000183 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700184 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000185 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700186 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000187 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700188 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000189 }
190}
191
David Srbeckye033cba2020-05-20 22:20:28 +0100192func createUncompressDexRules() []Rule {
193 return []Rule{
194 NeverAllow().
195 NotIn("art").
196 WithMatcher("uncompress_dex", isSetMatcherInstance).
197 Because("uncompress_dex is only allowed for certain jars for test in art."),
198 }
199}
200
Yifan Hong696ed4d2020-07-27 12:59:58 -0700201func createMakefileGoalRules() []Rule {
202 return []Rule{
203 NeverAllow().
204 ModuleType("makefile_goal").
205 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
206 Because("Only boot images may be imported as a makefile goal."),
207 }
208}
209
Steven Moreland65b3fd92017-12-06 14:18:35 -0800210func neverallowMutator(ctx BottomUpMutatorContext) {
211 m, ok := ctx.Module().(Module)
212 if !ok {
213 return
214 }
215
216 dir := ctx.ModuleDir() + "/"
217 properties := m.GetProperties()
218
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100219 osClass := ctx.Module().Target().Os.Class
220
Paul Duffin115445b2019-08-07 15:31:07 +0100221 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100222 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800223 if !n.appliesToPath(dir) {
224 continue
225 }
226
Colin Crossfd4f7432019-03-05 15:06:16 -0800227 if !n.appliesToModuleType(ctx.ModuleType()) {
228 continue
229 }
230
Steven Moreland65b3fd92017-12-06 14:18:35 -0800231 if !n.appliesToProperties(properties) {
232 continue
233 }
234
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100235 if !n.appliesToOsClass(osClass) {
236 continue
237 }
238
Paul Duffin35781882019-07-25 15:41:09 +0100239 if !n.appliesToDirectDeps(ctx) {
240 continue
241 }
242
Andrei Onea115e7e72020-06-05 21:14:03 +0100243 if !n.appliesToBootclasspathJar(ctx) {
244 continue
245 }
246
Steven Moreland65b3fd92017-12-06 14:18:35 -0800247 ctx.ModuleErrorf("violates " + n.String())
248 }
249}
250
Paul Duffin73bf0542019-07-12 14:12:49 +0100251type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100252 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100253 String() string
254}
255
256type equalMatcher struct {
257 expected string
258}
259
Artur Satayevc5570ac2020-04-09 16:06:36 +0100260func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100261 return m.expected == value
262}
263
264func (m *equalMatcher) String() string {
265 return "=" + m.expected
266}
267
268type anyMatcher struct {
269}
270
Artur Satayevc5570ac2020-04-09 16:06:36 +0100271func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100272 return true
273}
274
275func (m *anyMatcher) String() string {
276 return "=*"
277}
278
279var anyMatcherInstance = &anyMatcher{}
280
Paul Duffinc8111702019-07-22 12:13:55 +0100281type startsWithMatcher struct {
282 prefix string
283}
284
Artur Satayevc5570ac2020-04-09 16:06:36 +0100285func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100286 return strings.HasPrefix(value, m.prefix)
287}
288
289func (m *startsWithMatcher) String() string {
290 return ".starts-with(" + m.prefix + ")"
291}
292
Anton Hansson45376402020-04-09 14:18:21 +0100293type regexMatcher struct {
294 re *regexp.Regexp
295}
296
Artur Satayevc5570ac2020-04-09 16:06:36 +0100297func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100298 return m.re.MatchString(value)
299}
300
301func (m *regexMatcher) String() string {
302 return ".regexp(" + m.re.String() + ")"
303}
304
Andrei Onea115e7e72020-06-05 21:14:03 +0100305type notInListMatcher struct {
306 allowed []string
307}
308
309func (m *notInListMatcher) Test(value string) bool {
310 return !InList(value, m.allowed)
311}
312
313func (m *notInListMatcher) String() string {
314 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
315}
316
Colin Crossc511bc52020-04-07 16:50:32 +0000317type isSetMatcher struct{}
318
Artur Satayevc5570ac2020-04-09 16:06:36 +0100319func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000320 return value != ""
321}
322
323func (m *isSetMatcher) String() string {
324 return ".is-set"
325}
326
327var isSetMatcherInstance = &isSetMatcher{}
328
Steven Moreland65b3fd92017-12-06 14:18:35 -0800329type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100330 fields []string // e.x.: Vndk.Enabled
331 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800332}
333
Paul Duffin730f2a52019-06-27 14:08:51 +0100334// A NeverAllow rule.
335type Rule interface {
336 In(path ...string) Rule
337
338 NotIn(path ...string) Rule
339
Paul Duffin35781882019-07-25 15:41:09 +0100340 InDirectDeps(deps ...string) Rule
341
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100342 WithOsClass(osClasses ...OsClass) Rule
343
Paul Duffin730f2a52019-06-27 14:08:51 +0100344 ModuleType(types ...string) Rule
345
346 NotModuleType(types ...string) Rule
347
Andrei Onea115e7e72020-06-05 21:14:03 +0100348 BootclasspathJar() Rule
349
Paul Duffin730f2a52019-06-27 14:08:51 +0100350 With(properties, value string) Rule
351
Paul Duffinc8111702019-07-22 12:13:55 +0100352 WithMatcher(properties string, matcher ValueMatcher) Rule
353
Paul Duffin730f2a52019-06-27 14:08:51 +0100354 Without(properties, value string) Rule
355
Paul Duffinc8111702019-07-22 12:13:55 +0100356 WithoutMatcher(properties string, matcher ValueMatcher) Rule
357
Paul Duffin730f2a52019-06-27 14:08:51 +0100358 Because(reason string) Rule
359}
360
Steven Moreland65b3fd92017-12-06 14:18:35 -0800361type rule struct {
362 // User string for why this is a thing.
363 reason string
364
365 paths []string
366 unlessPaths []string
367
Paul Duffin35781882019-07-25 15:41:09 +0100368 directDeps map[string]bool
369
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100370 osClasses []OsClass
371
Colin Crossfd4f7432019-03-05 15:06:16 -0800372 moduleTypes []string
373 unlessModuleTypes []string
374
Steven Moreland65b3fd92017-12-06 14:18:35 -0800375 props []ruleProperty
376 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100377
378 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800379}
380
Paul Duffin730f2a52019-06-27 14:08:51 +0100381// Create a new NeverAllow rule.
382func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100383 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800384}
Colin Crossfd4f7432019-03-05 15:06:16 -0800385
Paul Duffin730f2a52019-06-27 14:08:51 +0100386func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800387 r.paths = append(r.paths, cleanPaths(path)...)
388 return r
389}
Colin Crossfd4f7432019-03-05 15:06:16 -0800390
Paul Duffin730f2a52019-06-27 14:08:51 +0100391func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800392 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
393 return r
394}
Colin Crossfd4f7432019-03-05 15:06:16 -0800395
Paul Duffin35781882019-07-25 15:41:09 +0100396func (r *rule) InDirectDeps(deps ...string) Rule {
397 for _, d := range deps {
398 r.directDeps[d] = true
399 }
400 return r
401}
402
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100403func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
404 r.osClasses = append(r.osClasses, osClasses...)
405 return r
406}
407
Paul Duffin730f2a52019-06-27 14:08:51 +0100408func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800409 r.moduleTypes = append(r.moduleTypes, types...)
410 return r
411}
412
Paul Duffin730f2a52019-06-27 14:08:51 +0100413func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800414 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
415 return r
416}
417
Paul Duffin730f2a52019-06-27 14:08:51 +0100418func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100419 return r.WithMatcher(properties, selectMatcher(value))
420}
421
422func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100424 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100425 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800426 })
427 return r
428}
Colin Crossfd4f7432019-03-05 15:06:16 -0800429
Paul Duffin730f2a52019-06-27 14:08:51 +0100430func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100431 return r.WithoutMatcher(properties, selectMatcher(value))
432}
433
434func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800435 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100436 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100437 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800438 })
439 return r
440}
Colin Crossfd4f7432019-03-05 15:06:16 -0800441
Paul Duffin73bf0542019-07-12 14:12:49 +0100442func selectMatcher(expected string) ValueMatcher {
443 if expected == "*" {
444 return anyMatcherInstance
445 }
446 return &equalMatcher{expected: expected}
447}
448
Paul Duffin730f2a52019-06-27 14:08:51 +0100449func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800450 r.reason = reason
451 return r
452}
453
Andrei Onea115e7e72020-06-05 21:14:03 +0100454func (r *rule) BootclasspathJar() Rule {
455 r.onlyBootclasspathJar = true
456 return r
457}
458
Steven Moreland65b3fd92017-12-06 14:18:35 -0800459func (r *rule) String() string {
460 s := "neverallow"
461 for _, v := range r.paths {
462 s += " dir:" + v + "*"
463 }
464 for _, v := range r.unlessPaths {
465 s += " -dir:" + v + "*"
466 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800467 for _, v := range r.moduleTypes {
468 s += " type:" + v
469 }
470 for _, v := range r.unlessModuleTypes {
471 s += " -type:" + v
472 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800473 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100474 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800475 }
476 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100477 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800478 }
Paul Duffin35781882019-07-25 15:41:09 +0100479 for k := range r.directDeps {
480 s += " deps:" + k
481 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100482 for _, v := range r.osClasses {
483 s += " os:" + v.String()
484 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100485 if r.onlyBootclasspathJar {
486 s += " inBcp"
487 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800488 if len(r.reason) != 0 {
489 s += " which is restricted because " + r.reason
490 }
491 return s
492}
493
494func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800495 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
496 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 return includePath && !excludePath
498}
499
Paul Duffin35781882019-07-25 15:41:09 +0100500func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
501 if len(r.directDeps) == 0 {
502 return true
503 }
504
505 matches := false
506 ctx.VisitDirectDeps(func(m Module) {
507 if !matches {
508 name := ctx.OtherModuleName(m)
509 matches = r.directDeps[name]
510 }
511 })
512
513 return matches
514}
515
Andrei Onea115e7e72020-06-05 21:14:03 +0100516func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
517 if !r.onlyBootclasspathJar {
518 return true
519 }
520
521 return InList(ctx.ModuleName(), ctx.Config().BootJars())
522}
523
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100524func (r *rule) appliesToOsClass(osClass OsClass) bool {
525 if len(r.osClasses) == 0 {
526 return true
527 }
528
529 for _, c := range r.osClasses {
530 if c == osClass {
531 return true
532 }
533 }
534
535 return false
536}
537
Colin Crossfd4f7432019-03-05 15:06:16 -0800538func (r *rule) appliesToModuleType(moduleType string) bool {
539 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
540}
541
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542func (r *rule) appliesToProperties(properties []interface{}) bool {
543 includeProps := hasAllProperties(properties, r.props)
544 excludeProps := hasAnyProperty(properties, r.unlessProps)
545 return includeProps && !excludeProps
546}
547
Paul Duffinc8111702019-07-22 12:13:55 +0100548func StartsWith(prefix string) ValueMatcher {
549 return &startsWithMatcher{prefix}
550}
551
Anton Hansson45376402020-04-09 14:18:21 +0100552func Regexp(re string) ValueMatcher {
553 r, err := regexp.Compile(re)
554 if err != nil {
555 panic(err)
556 }
557 return &regexMatcher{r}
558}
559
Andrei Onea115e7e72020-06-05 21:14:03 +0100560func NotInList(allowed []string) ValueMatcher {
561 return &notInListMatcher{allowed}
562}
563
Steven Moreland65b3fd92017-12-06 14:18:35 -0800564// assorted utils
565
566func cleanPaths(paths []string) []string {
567 res := make([]string, len(paths))
568 for i, v := range paths {
569 res[i] = filepath.Clean(v) + "/"
570 }
571 return res
572}
573
574func fieldNamesForProperties(propertyNames string) []string {
575 names := strings.Split(propertyNames, ".")
576 for i, v := range names {
577 names[i] = proptools.FieldNameForProperty(v)
578 }
579 return names
580}
581
Steven Moreland65b3fd92017-12-06 14:18:35 -0800582func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
583 for _, v := range props {
584 if hasProperty(properties, v) {
585 return true
586 }
587 }
588 return false
589}
590
591func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
592 for _, v := range props {
593 if !hasProperty(properties, v) {
594 return false
595 }
596 }
597 return true
598}
599
600func hasProperty(properties []interface{}, prop ruleProperty) bool {
601 for _, propertyStruct := range properties {
602 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
603 for _, v := range prop.fields {
604 if !propertiesValue.IsValid() {
605 break
606 }
607 propertiesValue = propertiesValue.FieldByName(v)
608 }
609 if !propertiesValue.IsValid() {
610 continue
611 }
612
Paul Duffin73bf0542019-07-12 14:12:49 +0100613 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100614 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800615 }
616
617 if matchValue(propertiesValue, check) {
618 return true
619 }
620 }
621 return false
622}
623
624func matchValue(value reflect.Value, check func(string) bool) bool {
625 if !value.IsValid() {
626 return false
627 }
628
629 if value.Kind() == reflect.Ptr {
630 if value.IsNil() {
631 return check("")
632 }
633 value = value.Elem()
634 }
635
636 switch value.Kind() {
637 case reflect.String:
638 return check(value.String())
639 case reflect.Bool:
640 return check(strconv.FormatBool(value.Bool()))
641 case reflect.Int:
642 return check(strconv.FormatInt(value.Int(), 10))
643 case reflect.Slice:
644 slice, ok := value.Interface().([]string)
645 if !ok {
646 panic("Can only handle slice of string")
647 }
648 for _, v := range slice {
649 if check(v) {
650 return true
651 }
652 }
653 return false
654 }
655
656 panic("Can't handle type: " + value.Kind().String())
657}
Paul Duffin115445b2019-08-07 15:31:07 +0100658
659var neverallowRulesKey = NewOnceKey("neverallowRules")
660
661func neverallowRules(config Config) []Rule {
662 return config.Once(neverallowRulesKey, func() interface{} {
663 // No test rules were set by setTestNeverallowRules, use the global rules
664 return neverallows
665 }).([]Rule)
666}
667
668// Overrides the default neverallow rules for the supplied config.
669//
670// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100671func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100672 config.Once(neverallowRulesKey, func() interface{} { return testRules })
673}
Paul Duffin45338f02021-03-30 23:07:52 +0100674
675// Prepares for a test by setting neverallow rules and enabling the mutator.
676//
677// If the supplied rules are nil then the default rules are used.
678func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
679 return GroupFixturePreparers(
680 FixtureModifyConfig(func(config Config) {
681 if testRules != nil {
682 setTestNeverallowRules(config, testRules)
683 }
684 }),
685 FixtureRegisterWithContext(func(ctx RegistrationContext) {
686 ctx.PostDepsMutators(registerNeverallowMutator)
687 }),
688 )
689}