blob: b8517a986f994653e94f3361e89f7b861211c990 [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",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000155 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800156 }
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",
Chang Li66d3cb72021-06-18 14:04:50 +0000178 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000179 }
180
Colin Cross440e0d02020-06-11 11:32:11 -0700181 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000182 // android_native_app_glue and libRSSupport use native_window.h but target old
183 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
184 // so they can't add libnativewindow to shared_libs to get the header directory
185 // for the platform variant. Allow them to use the platform variant
186 // property to set shared_libs.
187 "prebuilts/ndk",
188 "frameworks/rs",
189 }
190
191 return []Rule{
192 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700193 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000194 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700195 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000196 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700197 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000198 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700199 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000200 }
201}
202
David Srbeckye033cba2020-05-20 22:20:28 +0100203func createUncompressDexRules() []Rule {
204 return []Rule{
205 NeverAllow().
206 NotIn("art").
207 WithMatcher("uncompress_dex", isSetMatcherInstance).
208 Because("uncompress_dex is only allowed for certain jars for test in art."),
209 }
210}
211
Yifan Hong696ed4d2020-07-27 12:59:58 -0700212func createMakefileGoalRules() []Rule {
213 return []Rule{
214 NeverAllow().
215 ModuleType("makefile_goal").
216 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
217 Because("Only boot images may be imported as a makefile goal."),
218 }
219}
220
Inseob Kim800d1142021-06-14 12:03:51 +0900221func createInitFirstStageRules() []Rule {
222 return []Rule{
223 NeverAllow().
224 Without("name", "init_first_stage").
225 With("install_in_root", "true").
226 Because("install_in_root is only for init_first_stage."),
227 }
228}
229
Steven Moreland65b3fd92017-12-06 14:18:35 -0800230func neverallowMutator(ctx BottomUpMutatorContext) {
231 m, ok := ctx.Module().(Module)
232 if !ok {
233 return
234 }
235
236 dir := ctx.ModuleDir() + "/"
237 properties := m.GetProperties()
238
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100239 osClass := ctx.Module().Target().Os.Class
240
Paul Duffin115445b2019-08-07 15:31:07 +0100241 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100242 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800243 if !n.appliesToPath(dir) {
244 continue
245 }
246
Colin Crossfd4f7432019-03-05 15:06:16 -0800247 if !n.appliesToModuleType(ctx.ModuleType()) {
248 continue
249 }
250
Steven Moreland65b3fd92017-12-06 14:18:35 -0800251 if !n.appliesToProperties(properties) {
252 continue
253 }
254
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100255 if !n.appliesToOsClass(osClass) {
256 continue
257 }
258
Paul Duffin35781882019-07-25 15:41:09 +0100259 if !n.appliesToDirectDeps(ctx) {
260 continue
261 }
262
Andrei Onea115e7e72020-06-05 21:14:03 +0100263 if !n.appliesToBootclasspathJar(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
Andrei Onea115e7e72020-06-05 21:14:03 +0100325type notInListMatcher struct {
326 allowed []string
327}
328
329func (m *notInListMatcher) Test(value string) bool {
330 return !InList(value, m.allowed)
331}
332
333func (m *notInListMatcher) String() string {
334 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
335}
336
Colin Crossc511bc52020-04-07 16:50:32 +0000337type isSetMatcher struct{}
338
Artur Satayevc5570ac2020-04-09 16:06:36 +0100339func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000340 return value != ""
341}
342
343func (m *isSetMatcher) String() string {
344 return ".is-set"
345}
346
347var isSetMatcherInstance = &isSetMatcher{}
348
Steven Moreland65b3fd92017-12-06 14:18:35 -0800349type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100350 fields []string // e.x.: Vndk.Enabled
351 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800352}
353
Paul Duffin730f2a52019-06-27 14:08:51 +0100354// A NeverAllow rule.
355type Rule interface {
356 In(path ...string) Rule
357
358 NotIn(path ...string) Rule
359
Paul Duffin35781882019-07-25 15:41:09 +0100360 InDirectDeps(deps ...string) Rule
361
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100362 WithOsClass(osClasses ...OsClass) Rule
363
Paul Duffin730f2a52019-06-27 14:08:51 +0100364 ModuleType(types ...string) Rule
365
366 NotModuleType(types ...string) Rule
367
Andrei Onea115e7e72020-06-05 21:14:03 +0100368 BootclasspathJar() Rule
369
Paul Duffin730f2a52019-06-27 14:08:51 +0100370 With(properties, value string) Rule
371
Paul Duffinc8111702019-07-22 12:13:55 +0100372 WithMatcher(properties string, matcher ValueMatcher) Rule
373
Paul Duffin730f2a52019-06-27 14:08:51 +0100374 Without(properties, value string) Rule
375
Paul Duffinc8111702019-07-22 12:13:55 +0100376 WithoutMatcher(properties string, matcher ValueMatcher) Rule
377
Paul Duffin730f2a52019-06-27 14:08:51 +0100378 Because(reason string) Rule
379}
380
Steven Moreland65b3fd92017-12-06 14:18:35 -0800381type rule struct {
382 // User string for why this is a thing.
383 reason string
384
385 paths []string
386 unlessPaths []string
387
Paul Duffin35781882019-07-25 15:41:09 +0100388 directDeps map[string]bool
389
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100390 osClasses []OsClass
391
Colin Crossfd4f7432019-03-05 15:06:16 -0800392 moduleTypes []string
393 unlessModuleTypes []string
394
Steven Moreland65b3fd92017-12-06 14:18:35 -0800395 props []ruleProperty
396 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100397
398 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800399}
400
Paul Duffin730f2a52019-06-27 14:08:51 +0100401// Create a new NeverAllow rule.
402func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100403 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800404}
Colin Crossfd4f7432019-03-05 15:06:16 -0800405
Paul Duffin730f2a52019-06-27 14:08:51 +0100406func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800407 r.paths = append(r.paths, cleanPaths(path)...)
408 return r
409}
Colin Crossfd4f7432019-03-05 15:06:16 -0800410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800412 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
413 return r
414}
Colin Crossfd4f7432019-03-05 15:06:16 -0800415
Paul Duffin35781882019-07-25 15:41:09 +0100416func (r *rule) InDirectDeps(deps ...string) Rule {
417 for _, d := range deps {
418 r.directDeps[d] = true
419 }
420 return r
421}
422
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100423func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
424 r.osClasses = append(r.osClasses, osClasses...)
425 return r
426}
427
Paul Duffin730f2a52019-06-27 14:08:51 +0100428func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800429 r.moduleTypes = append(r.moduleTypes, types...)
430 return r
431}
432
Paul Duffin730f2a52019-06-27 14:08:51 +0100433func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800434 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
435 return r
436}
437
Paul Duffin730f2a52019-06-27 14:08:51 +0100438func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100439 return r.WithMatcher(properties, selectMatcher(value))
440}
441
442func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800443 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100444 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100445 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800446 })
447 return r
448}
Colin Crossfd4f7432019-03-05 15:06:16 -0800449
Paul Duffin730f2a52019-06-27 14:08:51 +0100450func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100451 return r.WithoutMatcher(properties, selectMatcher(value))
452}
453
454func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800455 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100456 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100457 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800458 })
459 return r
460}
Colin Crossfd4f7432019-03-05 15:06:16 -0800461
Paul Duffin73bf0542019-07-12 14:12:49 +0100462func selectMatcher(expected string) ValueMatcher {
463 if expected == "*" {
464 return anyMatcherInstance
465 }
466 return &equalMatcher{expected: expected}
467}
468
Paul Duffin730f2a52019-06-27 14:08:51 +0100469func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800470 r.reason = reason
471 return r
472}
473
Andrei Onea115e7e72020-06-05 21:14:03 +0100474func (r *rule) BootclasspathJar() Rule {
475 r.onlyBootclasspathJar = true
476 return r
477}
478
Steven Moreland65b3fd92017-12-06 14:18:35 -0800479func (r *rule) String() string {
480 s := "neverallow"
481 for _, v := range r.paths {
482 s += " dir:" + v + "*"
483 }
484 for _, v := range r.unlessPaths {
485 s += " -dir:" + v + "*"
486 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800487 for _, v := range r.moduleTypes {
488 s += " type:" + v
489 }
490 for _, v := range r.unlessModuleTypes {
491 s += " -type:" + v
492 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800493 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100494 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800495 }
496 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100497 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800498 }
Paul Duffin35781882019-07-25 15:41:09 +0100499 for k := range r.directDeps {
500 s += " deps:" + k
501 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100502 for _, v := range r.osClasses {
503 s += " os:" + v.String()
504 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100505 if r.onlyBootclasspathJar {
506 s += " inBcp"
507 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800508 if len(r.reason) != 0 {
509 s += " which is restricted because " + r.reason
510 }
511 return s
512}
513
514func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800515 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
516 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800517 return includePath && !excludePath
518}
519
Paul Duffin35781882019-07-25 15:41:09 +0100520func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
521 if len(r.directDeps) == 0 {
522 return true
523 }
524
525 matches := false
526 ctx.VisitDirectDeps(func(m Module) {
527 if !matches {
528 name := ctx.OtherModuleName(m)
529 matches = r.directDeps[name]
530 }
531 })
532
533 return matches
534}
535
Andrei Onea115e7e72020-06-05 21:14:03 +0100536func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
537 if !r.onlyBootclasspathJar {
538 return true
539 }
540
541 return InList(ctx.ModuleName(), ctx.Config().BootJars())
542}
543
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100544func (r *rule) appliesToOsClass(osClass OsClass) bool {
545 if len(r.osClasses) == 0 {
546 return true
547 }
548
549 for _, c := range r.osClasses {
550 if c == osClass {
551 return true
552 }
553 }
554
555 return false
556}
557
Colin Crossfd4f7432019-03-05 15:06:16 -0800558func (r *rule) appliesToModuleType(moduleType string) bool {
559 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
560}
561
Steven Moreland65b3fd92017-12-06 14:18:35 -0800562func (r *rule) appliesToProperties(properties []interface{}) bool {
563 includeProps := hasAllProperties(properties, r.props)
564 excludeProps := hasAnyProperty(properties, r.unlessProps)
565 return includeProps && !excludeProps
566}
567
Paul Duffinc8111702019-07-22 12:13:55 +0100568func StartsWith(prefix string) ValueMatcher {
569 return &startsWithMatcher{prefix}
570}
571
Anton Hansson45376402020-04-09 14:18:21 +0100572func Regexp(re string) ValueMatcher {
573 r, err := regexp.Compile(re)
574 if err != nil {
575 panic(err)
576 }
577 return &regexMatcher{r}
578}
579
Andrei Onea115e7e72020-06-05 21:14:03 +0100580func NotInList(allowed []string) ValueMatcher {
581 return &notInListMatcher{allowed}
582}
583
Steven Moreland65b3fd92017-12-06 14:18:35 -0800584// assorted utils
585
586func cleanPaths(paths []string) []string {
587 res := make([]string, len(paths))
588 for i, v := range paths {
589 res[i] = filepath.Clean(v) + "/"
590 }
591 return res
592}
593
594func fieldNamesForProperties(propertyNames string) []string {
595 names := strings.Split(propertyNames, ".")
596 for i, v := range names {
597 names[i] = proptools.FieldNameForProperty(v)
598 }
599 return names
600}
601
Steven Moreland65b3fd92017-12-06 14:18:35 -0800602func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
603 for _, v := range props {
604 if hasProperty(properties, v) {
605 return true
606 }
607 }
608 return false
609}
610
611func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
612 for _, v := range props {
613 if !hasProperty(properties, v) {
614 return false
615 }
616 }
617 return true
618}
619
620func hasProperty(properties []interface{}, prop ruleProperty) bool {
621 for _, propertyStruct := range properties {
622 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
623 for _, v := range prop.fields {
624 if !propertiesValue.IsValid() {
625 break
626 }
627 propertiesValue = propertiesValue.FieldByName(v)
628 }
629 if !propertiesValue.IsValid() {
630 continue
631 }
632
Paul Duffin73bf0542019-07-12 14:12:49 +0100633 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100634 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800635 }
636
637 if matchValue(propertiesValue, check) {
638 return true
639 }
640 }
641 return false
642}
643
644func matchValue(value reflect.Value, check func(string) bool) bool {
645 if !value.IsValid() {
646 return false
647 }
648
649 if value.Kind() == reflect.Ptr {
650 if value.IsNil() {
651 return check("")
652 }
653 value = value.Elem()
654 }
655
656 switch value.Kind() {
657 case reflect.String:
658 return check(value.String())
659 case reflect.Bool:
660 return check(strconv.FormatBool(value.Bool()))
661 case reflect.Int:
662 return check(strconv.FormatInt(value.Int(), 10))
663 case reflect.Slice:
664 slice, ok := value.Interface().([]string)
665 if !ok {
666 panic("Can only handle slice of string")
667 }
668 for _, v := range slice {
669 if check(v) {
670 return true
671 }
672 }
673 return false
674 }
675
676 panic("Can't handle type: " + value.Kind().String())
677}
Paul Duffin115445b2019-08-07 15:31:07 +0100678
679var neverallowRulesKey = NewOnceKey("neverallowRules")
680
681func neverallowRules(config Config) []Rule {
682 return config.Once(neverallowRulesKey, func() interface{} {
683 // No test rules were set by setTestNeverallowRules, use the global rules
684 return neverallows
685 }).([]Rule)
686}
687
688// Overrides the default neverallow rules for the supplied config.
689//
690// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100691func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100692 config.Once(neverallowRulesKey, func() interface{} { return testRules })
693}
Paul Duffin45338f02021-03-30 23:07:52 +0100694
695// Prepares for a test by setting neverallow rules and enabling the mutator.
696//
697// If the supplied rules are nil then the default rules are used.
698func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
699 return GroupFixturePreparers(
700 FixtureModifyConfig(func(config Config) {
701 if testRules != nil {
702 setTestNeverallowRules(config, testRules)
703 }
704 }),
705 FixtureRegisterWithContext(func(ctx RegistrationContext) {
706 ctx.PostDepsMutators(registerNeverallowMutator)
707 }),
708 )
709}