blob: b36bf045a888d4779f635cd83699bbbb41ae7f1a [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
Joe Onoratob4638c12021-10-27 15:47:06 -070030// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080031// 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()...)
Inseob Kim800d1142021-06-14 12:03:51 +090058 AddNeverAllowRules(createInitFirstStageRules()...)
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 {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000067 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010068 "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 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000083 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000084 "frameworks/av/apex",
85 "frameworks/av/tools",
86 "frameworks/native/cmds",
87 "system/apex",
88 "system/bpf",
89 "system/gatekeeper",
90 "system/hwservicemanager",
91 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000092 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000093 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000094 }
Paul Duffinc8111702019-07-22 12:13:55 +010095
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
97
98 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +010099 rule :=
100 NeverAllow().
101 WithMatcher("include_dirs", StartsWith(path+"/")).
102 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
103 " to use alternate mechanisms and so can no longer be used.")
104
105 rules = append(rules, rule)
106 }
107
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000108 for _, path := range noUseIncludeDir {
109 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
110 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
111 " to use alternate mechanisms and so can no longer be used.")
112 rules = append(rules, rule)
113 }
114
Paul Duffinc8111702019-07-22 12:13:55 +0100115 return rules
116}
117
Paul Duffin730f2a52019-06-27 14:08:51 +0100118func createTrebleRules() []Rule {
119 return []Rule{
120 NeverAllow().
121 In("vendor", "device").
122 With("vndk.enabled", "true").
123 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900124 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100125 Because("the VNDK can never contain a library that is device dependent."),
126 NeverAllow().
127 With("vndk.enabled", "true").
128 Without("vendor", "true").
129 Without("owner", "").
130 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800131
Neil Fullerdf5f3562018-10-21 17:19:10 +0100132 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100133 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800134 Without("name", "libhidlbase-combined-impl").
135 Without("name", "libhidlbase").
136 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100137 With("product_variables.enforce_vintf_manifest.cflags", "*").
138 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100139
140 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100141 NeverAllow().
142 Without("name", "libc_bionic_ndk").
143 With("product_variables.treble_linker_namespaces.cflags", "*").
144 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145
146 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100148 }
149}
150
Paul Duffin730f2a52019-06-27 14:08:51 +0100151func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700152 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700153 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700154 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800155 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000156 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800157 }
158
Paul Duffin730f2a52019-06-27 14:08:51 +0100159 return []Rule{
160 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700161 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100162 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700163 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800164 }
165}
166
Colin Crossc511bc52020-04-07 16:50:32 +0000167func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700168 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000169 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
170 // This sometimes works because the APEX modules that contain derive_sdk and
171 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
172 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100173 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700174 // These are for apps and shouldn't be used by non-SDK variant modules.
175 "prebuilts/ndk",
176 "tools/test/graphicsbenchmark/apps/sample_app",
177 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700178 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000179 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000180 }
181
Colin Cross440e0d02020-06-11 11:32:11 -0700182 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000183 // android_native_app_glue and libRSSupport use native_window.h but target old
184 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
185 // so they can't add libnativewindow to shared_libs to get the header directory
186 // for the platform variant. Allow them to use the platform variant
187 // property to set shared_libs.
188 "prebuilts/ndk",
189 "frameworks/rs",
190 }
191
192 return []Rule{
193 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700194 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000195 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700196 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000197 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700198 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000199 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700200 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000201 }
202}
203
David Srbeckye033cba2020-05-20 22:20:28 +0100204func createUncompressDexRules() []Rule {
205 return []Rule{
206 NeverAllow().
207 NotIn("art").
208 WithMatcher("uncompress_dex", isSetMatcherInstance).
209 Because("uncompress_dex is only allowed for certain jars for test in art."),
210 }
211}
212
Yifan Hong696ed4d2020-07-27 12:59:58 -0700213func createMakefileGoalRules() []Rule {
214 return []Rule{
215 NeverAllow().
216 ModuleType("makefile_goal").
Yuntao Xufeb07562021-11-18 22:33:02 +0000217 // TODO(b/33691272): remove this after migrating seapp to Soong
218 Without("product_out_path", "obj/ETC/plat_seapp_contexts_intermediates/plat_seapp_contexts").
219 Without("product_out_path", "obj/ETC/plat_seapp_neverallows_intermediates/plat_seapp_neverallows").
Yifan Hong696ed4d2020-07-27 12:59:58 -0700220 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Yuntao Xufeb07562021-11-18 22:33:02 +0000221 Because("Only boot images and seapp contexts may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700222 }
223}
224
Inseob Kim800d1142021-06-14 12:03:51 +0900225func createInitFirstStageRules() []Rule {
226 return []Rule{
227 NeverAllow().
228 Without("name", "init_first_stage").
229 With("install_in_root", "true").
230 Because("install_in_root is only for init_first_stage."),
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
Andrei Onea115e7e72020-06-05 21:14:03 +0100267 if !n.appliesToBootclasspathJar(ctx) {
268 continue
269 }
270
Steven Moreland65b3fd92017-12-06 14:18:35 -0800271 ctx.ModuleErrorf("violates " + n.String())
272 }
273}
274
Paul Duffin73bf0542019-07-12 14:12:49 +0100275type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100276 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100277 String() string
278}
279
280type equalMatcher struct {
281 expected string
282}
283
Artur Satayevc5570ac2020-04-09 16:06:36 +0100284func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100285 return m.expected == value
286}
287
288func (m *equalMatcher) String() string {
289 return "=" + m.expected
290}
291
292type anyMatcher struct {
293}
294
Artur Satayevc5570ac2020-04-09 16:06:36 +0100295func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100296 return true
297}
298
299func (m *anyMatcher) String() string {
300 return "=*"
301}
302
303var anyMatcherInstance = &anyMatcher{}
304
Paul Duffinc8111702019-07-22 12:13:55 +0100305type startsWithMatcher struct {
306 prefix string
307}
308
Artur Satayevc5570ac2020-04-09 16:06:36 +0100309func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100310 return strings.HasPrefix(value, m.prefix)
311}
312
313func (m *startsWithMatcher) String() string {
314 return ".starts-with(" + m.prefix + ")"
315}
316
Anton Hansson45376402020-04-09 14:18:21 +0100317type regexMatcher struct {
318 re *regexp.Regexp
319}
320
Artur Satayevc5570ac2020-04-09 16:06:36 +0100321func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100322 return m.re.MatchString(value)
323}
324
325func (m *regexMatcher) String() string {
326 return ".regexp(" + m.re.String() + ")"
327}
328
Andrei Onea115e7e72020-06-05 21:14:03 +0100329type notInListMatcher struct {
330 allowed []string
331}
332
333func (m *notInListMatcher) Test(value string) bool {
334 return !InList(value, m.allowed)
335}
336
337func (m *notInListMatcher) String() string {
338 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
339}
340
Colin Crossc511bc52020-04-07 16:50:32 +0000341type isSetMatcher struct{}
342
Artur Satayevc5570ac2020-04-09 16:06:36 +0100343func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000344 return value != ""
345}
346
347func (m *isSetMatcher) String() string {
348 return ".is-set"
349}
350
351var isSetMatcherInstance = &isSetMatcher{}
352
Steven Moreland65b3fd92017-12-06 14:18:35 -0800353type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100354 fields []string // e.x.: Vndk.Enabled
355 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800356}
357
Paul Duffin730f2a52019-06-27 14:08:51 +0100358// A NeverAllow rule.
359type Rule interface {
360 In(path ...string) Rule
361
362 NotIn(path ...string) Rule
363
Paul Duffin35781882019-07-25 15:41:09 +0100364 InDirectDeps(deps ...string) Rule
365
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100366 WithOsClass(osClasses ...OsClass) Rule
367
Paul Duffin730f2a52019-06-27 14:08:51 +0100368 ModuleType(types ...string) Rule
369
370 NotModuleType(types ...string) Rule
371
Andrei Onea115e7e72020-06-05 21:14:03 +0100372 BootclasspathJar() Rule
373
Paul Duffin730f2a52019-06-27 14:08:51 +0100374 With(properties, value string) Rule
375
Paul Duffinc8111702019-07-22 12:13:55 +0100376 WithMatcher(properties string, matcher ValueMatcher) Rule
377
Paul Duffin730f2a52019-06-27 14:08:51 +0100378 Without(properties, value string) Rule
379
Paul Duffinc8111702019-07-22 12:13:55 +0100380 WithoutMatcher(properties string, matcher ValueMatcher) Rule
381
Paul Duffin730f2a52019-06-27 14:08:51 +0100382 Because(reason string) Rule
383}
384
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385type rule struct {
386 // User string for why this is a thing.
387 reason string
388
389 paths []string
390 unlessPaths []string
391
Paul Duffin35781882019-07-25 15:41:09 +0100392 directDeps map[string]bool
393
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100394 osClasses []OsClass
395
Colin Crossfd4f7432019-03-05 15:06:16 -0800396 moduleTypes []string
397 unlessModuleTypes []string
398
Steven Moreland65b3fd92017-12-06 14:18:35 -0800399 props []ruleProperty
400 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100401
402 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800403}
404
Paul Duffin730f2a52019-06-27 14:08:51 +0100405// Create a new NeverAllow rule.
406func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100407 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800408}
Colin Crossfd4f7432019-03-05 15:06:16 -0800409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800411 r.paths = append(r.paths, cleanPaths(path)...)
412 return r
413}
Colin Crossfd4f7432019-03-05 15:06:16 -0800414
Paul Duffin730f2a52019-06-27 14:08:51 +0100415func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800416 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
417 return r
418}
Colin Crossfd4f7432019-03-05 15:06:16 -0800419
Paul Duffin35781882019-07-25 15:41:09 +0100420func (r *rule) InDirectDeps(deps ...string) Rule {
421 for _, d := range deps {
422 r.directDeps[d] = true
423 }
424 return r
425}
426
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100427func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
428 r.osClasses = append(r.osClasses, osClasses...)
429 return r
430}
431
Paul Duffin730f2a52019-06-27 14:08:51 +0100432func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800433 r.moduleTypes = append(r.moduleTypes, types...)
434 return r
435}
436
Paul Duffin730f2a52019-06-27 14:08:51 +0100437func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800438 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
439 return r
440}
441
Paul Duffin730f2a52019-06-27 14:08:51 +0100442func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100443 return r.WithMatcher(properties, selectMatcher(value))
444}
445
446func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100448 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100449 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800450 })
451 return r
452}
Colin Crossfd4f7432019-03-05 15:06:16 -0800453
Paul Duffin730f2a52019-06-27 14:08:51 +0100454func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100455 return r.WithoutMatcher(properties, selectMatcher(value))
456}
457
458func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800459 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100460 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100461 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800462 })
463 return r
464}
Colin Crossfd4f7432019-03-05 15:06:16 -0800465
Paul Duffin73bf0542019-07-12 14:12:49 +0100466func selectMatcher(expected string) ValueMatcher {
467 if expected == "*" {
468 return anyMatcherInstance
469 }
470 return &equalMatcher{expected: expected}
471}
472
Paul Duffin730f2a52019-06-27 14:08:51 +0100473func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800474 r.reason = reason
475 return r
476}
477
Andrei Onea115e7e72020-06-05 21:14:03 +0100478func (r *rule) BootclasspathJar() Rule {
479 r.onlyBootclasspathJar = true
480 return r
481}
482
Steven Moreland65b3fd92017-12-06 14:18:35 -0800483func (r *rule) String() string {
484 s := "neverallow"
485 for _, v := range r.paths {
486 s += " dir:" + v + "*"
487 }
488 for _, v := range r.unlessPaths {
489 s += " -dir:" + v + "*"
490 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800491 for _, v := range r.moduleTypes {
492 s += " type:" + v
493 }
494 for _, v := range r.unlessModuleTypes {
495 s += " -type:" + v
496 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100498 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800499 }
500 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100501 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800502 }
Paul Duffin35781882019-07-25 15:41:09 +0100503 for k := range r.directDeps {
504 s += " deps:" + k
505 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100506 for _, v := range r.osClasses {
507 s += " os:" + v.String()
508 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100509 if r.onlyBootclasspathJar {
510 s += " inBcp"
511 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800512 if len(r.reason) != 0 {
513 s += " which is restricted because " + r.reason
514 }
515 return s
516}
517
518func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800519 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
520 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800521 return includePath && !excludePath
522}
523
Paul Duffin35781882019-07-25 15:41:09 +0100524func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
525 if len(r.directDeps) == 0 {
526 return true
527 }
528
529 matches := false
530 ctx.VisitDirectDeps(func(m Module) {
531 if !matches {
532 name := ctx.OtherModuleName(m)
533 matches = r.directDeps[name]
534 }
535 })
536
537 return matches
538}
539
Andrei Onea115e7e72020-06-05 21:14:03 +0100540func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
541 if !r.onlyBootclasspathJar {
542 return true
543 }
544
545 return InList(ctx.ModuleName(), ctx.Config().BootJars())
546}
547
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100548func (r *rule) appliesToOsClass(osClass OsClass) bool {
549 if len(r.osClasses) == 0 {
550 return true
551 }
552
553 for _, c := range r.osClasses {
554 if c == osClass {
555 return true
556 }
557 }
558
559 return false
560}
561
Colin Crossfd4f7432019-03-05 15:06:16 -0800562func (r *rule) appliesToModuleType(moduleType string) bool {
563 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
564}
565
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566func (r *rule) appliesToProperties(properties []interface{}) bool {
567 includeProps := hasAllProperties(properties, r.props)
568 excludeProps := hasAnyProperty(properties, r.unlessProps)
569 return includeProps && !excludeProps
570}
571
Paul Duffinc8111702019-07-22 12:13:55 +0100572func StartsWith(prefix string) ValueMatcher {
573 return &startsWithMatcher{prefix}
574}
575
Anton Hansson45376402020-04-09 14:18:21 +0100576func Regexp(re string) ValueMatcher {
577 r, err := regexp.Compile(re)
578 if err != nil {
579 panic(err)
580 }
581 return &regexMatcher{r}
582}
583
Andrei Onea115e7e72020-06-05 21:14:03 +0100584func NotInList(allowed []string) ValueMatcher {
585 return &notInListMatcher{allowed}
586}
587
Steven Moreland65b3fd92017-12-06 14:18:35 -0800588// assorted utils
589
590func cleanPaths(paths []string) []string {
591 res := make([]string, len(paths))
592 for i, v := range paths {
593 res[i] = filepath.Clean(v) + "/"
594 }
595 return res
596}
597
598func fieldNamesForProperties(propertyNames string) []string {
599 names := strings.Split(propertyNames, ".")
600 for i, v := range names {
601 names[i] = proptools.FieldNameForProperty(v)
602 }
603 return names
604}
605
Steven Moreland65b3fd92017-12-06 14:18:35 -0800606func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
607 for _, v := range props {
608 if hasProperty(properties, v) {
609 return true
610 }
611 }
612 return false
613}
614
615func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
616 for _, v := range props {
617 if !hasProperty(properties, v) {
618 return false
619 }
620 }
621 return true
622}
623
624func hasProperty(properties []interface{}, prop ruleProperty) bool {
625 for _, propertyStruct := range properties {
626 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
627 for _, v := range prop.fields {
628 if !propertiesValue.IsValid() {
629 break
630 }
631 propertiesValue = propertiesValue.FieldByName(v)
632 }
633 if !propertiesValue.IsValid() {
634 continue
635 }
636
Paul Duffin73bf0542019-07-12 14:12:49 +0100637 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100638 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800639 }
640
641 if matchValue(propertiesValue, check) {
642 return true
643 }
644 }
645 return false
646}
647
648func matchValue(value reflect.Value, check func(string) bool) bool {
649 if !value.IsValid() {
650 return false
651 }
652
653 if value.Kind() == reflect.Ptr {
654 if value.IsNil() {
655 return check("")
656 }
657 value = value.Elem()
658 }
659
660 switch value.Kind() {
661 case reflect.String:
662 return check(value.String())
663 case reflect.Bool:
664 return check(strconv.FormatBool(value.Bool()))
665 case reflect.Int:
666 return check(strconv.FormatInt(value.Int(), 10))
667 case reflect.Slice:
668 slice, ok := value.Interface().([]string)
669 if !ok {
670 panic("Can only handle slice of string")
671 }
672 for _, v := range slice {
673 if check(v) {
674 return true
675 }
676 }
677 return false
678 }
679
680 panic("Can't handle type: " + value.Kind().String())
681}
Paul Duffin115445b2019-08-07 15:31:07 +0100682
683var neverallowRulesKey = NewOnceKey("neverallowRules")
684
685func neverallowRules(config Config) []Rule {
686 return config.Once(neverallowRulesKey, func() interface{} {
687 // No test rules were set by setTestNeverallowRules, use the global rules
688 return neverallows
689 }).([]Rule)
690}
691
692// Overrides the default neverallow rules for the supplied config.
693//
694// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100695func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100696 config.Once(neverallowRulesKey, func() interface{} { return testRules })
697}
Paul Duffin45338f02021-03-30 23:07:52 +0100698
699// Prepares for a test by setting neverallow rules and enabling the mutator.
700//
701// If the supplied rules are nil then the default rules are used.
702func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
703 return GroupFixturePreparers(
704 FixtureModifyConfig(func(config Config) {
705 if testRules != nil {
706 setTestNeverallowRules(config, testRules)
707 }
708 }),
709 FixtureRegisterWithContext(func(ctx RegistrationContext) {
710 ctx.PostDepsMutators(registerNeverallowMutator)
711 }),
712 )
713}