blob: 19b58a77504f920d8a0a9066732c7bcf5c1ffc1c [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()...)
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{
Colin Crossb5191a52019-04-11 14:07:38 -0700153 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800154 "external/robolectric-shadows",
155 "framework/layoutlib",
156 }
157
Paul Duffin730f2a52019-06-27 14:08:51 +0100158 return []Rule{
159 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700160 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100161 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700162 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800163 }
164}
165
Colin Crossc511bc52020-04-07 16:50:32 +0000166func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700167 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000168 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
169 // This sometimes works because the APEX modules that contain derive_sdk and
170 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
171 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100172 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700173 // These are for apps and shouldn't be used by non-SDK variant modules.
174 "prebuilts/ndk",
175 "tools/test/graphicsbenchmark/apps/sample_app",
176 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700177 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Colin Crossc511bc52020-04-07 16:50:32 +0000178 }
179
Colin Cross440e0d02020-06-11 11:32:11 -0700180 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000181 // android_native_app_glue and libRSSupport use native_window.h but target old
182 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
183 // so they can't add libnativewindow to shared_libs to get the header directory
184 // for the platform variant. Allow them to use the platform variant
185 // property to set shared_libs.
186 "prebuilts/ndk",
187 "frameworks/rs",
188 }
189
190 return []Rule{
191 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700192 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000193 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700194 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000195 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700196 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000197 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700198 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000199 }
200}
201
David Srbeckye033cba2020-05-20 22:20:28 +0100202func createUncompressDexRules() []Rule {
203 return []Rule{
204 NeverAllow().
205 NotIn("art").
206 WithMatcher("uncompress_dex", isSetMatcherInstance).
207 Because("uncompress_dex is only allowed for certain jars for test in art."),
208 }
209}
210
Yifan Hong696ed4d2020-07-27 12:59:58 -0700211func createMakefileGoalRules() []Rule {
212 return []Rule{
213 NeverAllow().
214 ModuleType("makefile_goal").
215 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
216 Because("Only boot images may be imported as a makefile goal."),
217 }
218}
219
Inseob Kim800d1142021-06-14 12:03:51 +0900220func createInitFirstStageRules() []Rule {
221 return []Rule{
222 NeverAllow().
223 Without("name", "init_first_stage").
224 With("install_in_root", "true").
225 Because("install_in_root is only for init_first_stage."),
226 }
227}
228
Steven Moreland65b3fd92017-12-06 14:18:35 -0800229func neverallowMutator(ctx BottomUpMutatorContext) {
230 m, ok := ctx.Module().(Module)
231 if !ok {
232 return
233 }
234
235 dir := ctx.ModuleDir() + "/"
236 properties := m.GetProperties()
237
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100238 osClass := ctx.Module().Target().Os.Class
239
Paul Duffin115445b2019-08-07 15:31:07 +0100240 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100241 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800242 if !n.appliesToPath(dir) {
243 continue
244 }
245
Colin Crossfd4f7432019-03-05 15:06:16 -0800246 if !n.appliesToModuleType(ctx.ModuleType()) {
247 continue
248 }
249
Steven Moreland65b3fd92017-12-06 14:18:35 -0800250 if !n.appliesToProperties(properties) {
251 continue
252 }
253
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100254 if !n.appliesToOsClass(osClass) {
255 continue
256 }
257
Paul Duffin35781882019-07-25 15:41:09 +0100258 if !n.appliesToDirectDeps(ctx) {
259 continue
260 }
261
Andrei Onea115e7e72020-06-05 21:14:03 +0100262 if !n.appliesToBootclasspathJar(ctx) {
263 continue
264 }
265
Steven Moreland65b3fd92017-12-06 14:18:35 -0800266 ctx.ModuleErrorf("violates " + n.String())
267 }
268}
269
Paul Duffin73bf0542019-07-12 14:12:49 +0100270type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100271 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100272 String() string
273}
274
275type equalMatcher struct {
276 expected string
277}
278
Artur Satayevc5570ac2020-04-09 16:06:36 +0100279func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100280 return m.expected == value
281}
282
283func (m *equalMatcher) String() string {
284 return "=" + m.expected
285}
286
287type anyMatcher struct {
288}
289
Artur Satayevc5570ac2020-04-09 16:06:36 +0100290func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100291 return true
292}
293
294func (m *anyMatcher) String() string {
295 return "=*"
296}
297
298var anyMatcherInstance = &anyMatcher{}
299
Paul Duffinc8111702019-07-22 12:13:55 +0100300type startsWithMatcher struct {
301 prefix string
302}
303
Artur Satayevc5570ac2020-04-09 16:06:36 +0100304func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100305 return strings.HasPrefix(value, m.prefix)
306}
307
308func (m *startsWithMatcher) String() string {
309 return ".starts-with(" + m.prefix + ")"
310}
311
Anton Hansson45376402020-04-09 14:18:21 +0100312type regexMatcher struct {
313 re *regexp.Regexp
314}
315
Artur Satayevc5570ac2020-04-09 16:06:36 +0100316func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100317 return m.re.MatchString(value)
318}
319
320func (m *regexMatcher) String() string {
321 return ".regexp(" + m.re.String() + ")"
322}
323
Andrei Onea115e7e72020-06-05 21:14:03 +0100324type notInListMatcher struct {
325 allowed []string
326}
327
328func (m *notInListMatcher) Test(value string) bool {
329 return !InList(value, m.allowed)
330}
331
332func (m *notInListMatcher) String() string {
333 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
334}
335
Colin Crossc511bc52020-04-07 16:50:32 +0000336type isSetMatcher struct{}
337
Artur Satayevc5570ac2020-04-09 16:06:36 +0100338func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000339 return value != ""
340}
341
342func (m *isSetMatcher) String() string {
343 return ".is-set"
344}
345
346var isSetMatcherInstance = &isSetMatcher{}
347
Steven Moreland65b3fd92017-12-06 14:18:35 -0800348type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100349 fields []string // e.x.: Vndk.Enabled
350 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800351}
352
Paul Duffin730f2a52019-06-27 14:08:51 +0100353// A NeverAllow rule.
354type Rule interface {
355 In(path ...string) Rule
356
357 NotIn(path ...string) Rule
358
Paul Duffin35781882019-07-25 15:41:09 +0100359 InDirectDeps(deps ...string) Rule
360
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100361 WithOsClass(osClasses ...OsClass) Rule
362
Paul Duffin730f2a52019-06-27 14:08:51 +0100363 ModuleType(types ...string) Rule
364
365 NotModuleType(types ...string) Rule
366
Andrei Onea115e7e72020-06-05 21:14:03 +0100367 BootclasspathJar() Rule
368
Paul Duffin730f2a52019-06-27 14:08:51 +0100369 With(properties, value string) Rule
370
Paul Duffinc8111702019-07-22 12:13:55 +0100371 WithMatcher(properties string, matcher ValueMatcher) Rule
372
Paul Duffin730f2a52019-06-27 14:08:51 +0100373 Without(properties, value string) Rule
374
Paul Duffinc8111702019-07-22 12:13:55 +0100375 WithoutMatcher(properties string, matcher ValueMatcher) Rule
376
Paul Duffin730f2a52019-06-27 14:08:51 +0100377 Because(reason string) Rule
378}
379
Steven Moreland65b3fd92017-12-06 14:18:35 -0800380type rule struct {
381 // User string for why this is a thing.
382 reason string
383
384 paths []string
385 unlessPaths []string
386
Paul Duffin35781882019-07-25 15:41:09 +0100387 directDeps map[string]bool
388
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100389 osClasses []OsClass
390
Colin Crossfd4f7432019-03-05 15:06:16 -0800391 moduleTypes []string
392 unlessModuleTypes []string
393
Steven Moreland65b3fd92017-12-06 14:18:35 -0800394 props []ruleProperty
395 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100396
397 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800398}
399
Paul Duffin730f2a52019-06-27 14:08:51 +0100400// Create a new NeverAllow rule.
401func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100402 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800403}
Colin Crossfd4f7432019-03-05 15:06:16 -0800404
Paul Duffin730f2a52019-06-27 14:08:51 +0100405func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800406 r.paths = append(r.paths, cleanPaths(path)...)
407 return r
408}
Colin Crossfd4f7432019-03-05 15:06:16 -0800409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800411 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
412 return r
413}
Colin Crossfd4f7432019-03-05 15:06:16 -0800414
Paul Duffin35781882019-07-25 15:41:09 +0100415func (r *rule) InDirectDeps(deps ...string) Rule {
416 for _, d := range deps {
417 r.directDeps[d] = true
418 }
419 return r
420}
421
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100422func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
423 r.osClasses = append(r.osClasses, osClasses...)
424 return r
425}
426
Paul Duffin730f2a52019-06-27 14:08:51 +0100427func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800428 r.moduleTypes = append(r.moduleTypes, types...)
429 return r
430}
431
Paul Duffin730f2a52019-06-27 14:08:51 +0100432func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800433 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
434 return r
435}
436
Paul Duffin730f2a52019-06-27 14:08:51 +0100437func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100438 return r.WithMatcher(properties, selectMatcher(value))
439}
440
441func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800442 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100443 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100444 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800445 })
446 return r
447}
Colin Crossfd4f7432019-03-05 15:06:16 -0800448
Paul Duffin730f2a52019-06-27 14:08:51 +0100449func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100450 return r.WithoutMatcher(properties, selectMatcher(value))
451}
452
453func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800454 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100455 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100456 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457 })
458 return r
459}
Colin Crossfd4f7432019-03-05 15:06:16 -0800460
Paul Duffin73bf0542019-07-12 14:12:49 +0100461func selectMatcher(expected string) ValueMatcher {
462 if expected == "*" {
463 return anyMatcherInstance
464 }
465 return &equalMatcher{expected: expected}
466}
467
Paul Duffin730f2a52019-06-27 14:08:51 +0100468func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800469 r.reason = reason
470 return r
471}
472
Andrei Onea115e7e72020-06-05 21:14:03 +0100473func (r *rule) BootclasspathJar() Rule {
474 r.onlyBootclasspathJar = true
475 return r
476}
477
Steven Moreland65b3fd92017-12-06 14:18:35 -0800478func (r *rule) String() string {
479 s := "neverallow"
480 for _, v := range r.paths {
481 s += " dir:" + v + "*"
482 }
483 for _, v := range r.unlessPaths {
484 s += " -dir:" + v + "*"
485 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800486 for _, v := range r.moduleTypes {
487 s += " type:" + v
488 }
489 for _, v := range r.unlessModuleTypes {
490 s += " -type:" + v
491 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800492 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100493 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800494 }
495 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100496 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 }
Paul Duffin35781882019-07-25 15:41:09 +0100498 for k := range r.directDeps {
499 s += " deps:" + k
500 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100501 for _, v := range r.osClasses {
502 s += " os:" + v.String()
503 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100504 if r.onlyBootclasspathJar {
505 s += " inBcp"
506 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800507 if len(r.reason) != 0 {
508 s += " which is restricted because " + r.reason
509 }
510 return s
511}
512
513func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800514 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
515 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800516 return includePath && !excludePath
517}
518
Paul Duffin35781882019-07-25 15:41:09 +0100519func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
520 if len(r.directDeps) == 0 {
521 return true
522 }
523
524 matches := false
525 ctx.VisitDirectDeps(func(m Module) {
526 if !matches {
527 name := ctx.OtherModuleName(m)
528 matches = r.directDeps[name]
529 }
530 })
531
532 return matches
533}
534
Andrei Onea115e7e72020-06-05 21:14:03 +0100535func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
536 if !r.onlyBootclasspathJar {
537 return true
538 }
539
540 return InList(ctx.ModuleName(), ctx.Config().BootJars())
541}
542
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100543func (r *rule) appliesToOsClass(osClass OsClass) bool {
544 if len(r.osClasses) == 0 {
545 return true
546 }
547
548 for _, c := range r.osClasses {
549 if c == osClass {
550 return true
551 }
552 }
553
554 return false
555}
556
Colin Crossfd4f7432019-03-05 15:06:16 -0800557func (r *rule) appliesToModuleType(moduleType string) bool {
558 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
559}
560
Steven Moreland65b3fd92017-12-06 14:18:35 -0800561func (r *rule) appliesToProperties(properties []interface{}) bool {
562 includeProps := hasAllProperties(properties, r.props)
563 excludeProps := hasAnyProperty(properties, r.unlessProps)
564 return includeProps && !excludeProps
565}
566
Paul Duffinc8111702019-07-22 12:13:55 +0100567func StartsWith(prefix string) ValueMatcher {
568 return &startsWithMatcher{prefix}
569}
570
Anton Hansson45376402020-04-09 14:18:21 +0100571func Regexp(re string) ValueMatcher {
572 r, err := regexp.Compile(re)
573 if err != nil {
574 panic(err)
575 }
576 return &regexMatcher{r}
577}
578
Andrei Onea115e7e72020-06-05 21:14:03 +0100579func NotInList(allowed []string) ValueMatcher {
580 return &notInListMatcher{allowed}
581}
582
Steven Moreland65b3fd92017-12-06 14:18:35 -0800583// assorted utils
584
585func cleanPaths(paths []string) []string {
586 res := make([]string, len(paths))
587 for i, v := range paths {
588 res[i] = filepath.Clean(v) + "/"
589 }
590 return res
591}
592
593func fieldNamesForProperties(propertyNames string) []string {
594 names := strings.Split(propertyNames, ".")
595 for i, v := range names {
596 names[i] = proptools.FieldNameForProperty(v)
597 }
598 return names
599}
600
Steven Moreland65b3fd92017-12-06 14:18:35 -0800601func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
602 for _, v := range props {
603 if hasProperty(properties, v) {
604 return true
605 }
606 }
607 return false
608}
609
610func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
611 for _, v := range props {
612 if !hasProperty(properties, v) {
613 return false
614 }
615 }
616 return true
617}
618
619func hasProperty(properties []interface{}, prop ruleProperty) bool {
620 for _, propertyStruct := range properties {
621 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
622 for _, v := range prop.fields {
623 if !propertiesValue.IsValid() {
624 break
625 }
626 propertiesValue = propertiesValue.FieldByName(v)
627 }
628 if !propertiesValue.IsValid() {
629 continue
630 }
631
Paul Duffin73bf0542019-07-12 14:12:49 +0100632 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100633 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800634 }
635
636 if matchValue(propertiesValue, check) {
637 return true
638 }
639 }
640 return false
641}
642
643func matchValue(value reflect.Value, check func(string) bool) bool {
644 if !value.IsValid() {
645 return false
646 }
647
648 if value.Kind() == reflect.Ptr {
649 if value.IsNil() {
650 return check("")
651 }
652 value = value.Elem()
653 }
654
655 switch value.Kind() {
656 case reflect.String:
657 return check(value.String())
658 case reflect.Bool:
659 return check(strconv.FormatBool(value.Bool()))
660 case reflect.Int:
661 return check(strconv.FormatInt(value.Int(), 10))
662 case reflect.Slice:
663 slice, ok := value.Interface().([]string)
664 if !ok {
665 panic("Can only handle slice of string")
666 }
667 for _, v := range slice {
668 if check(v) {
669 return true
670 }
671 }
672 return false
673 }
674
675 panic("Can't handle type: " + value.Kind().String())
676}
Paul Duffin115445b2019-08-07 15:31:07 +0100677
678var neverallowRulesKey = NewOnceKey("neverallowRules")
679
680func neverallowRules(config Config) []Rule {
681 return config.Once(neverallowRulesKey, func() interface{} {
682 // No test rules were set by setTestNeverallowRules, use the global rules
683 return neverallows
684 }).([]Rule)
685}
686
687// Overrides the default neverallow rules for the supplied config.
688//
689// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100690func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100691 config.Once(neverallowRulesKey, func() interface{} { return testRules })
692}
Paul Duffin45338f02021-03-30 23:07:52 +0100693
694// Prepares for a test by setting neverallow rules and enabling the mutator.
695//
696// If the supplied rules are nil then the default rules are used.
697func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
698 return GroupFixturePreparers(
699 FixtureModifyConfig(func(config Config) {
700 if testRules != nil {
701 setTestNeverallowRules(config, testRules)
702 }
703 }),
704 FixtureRegisterWithContext(func(ctx RegistrationContext) {
705 ctx.PostDepsMutators(registerNeverallowMutator)
706 }),
707 )
708}