blob: 8b8e1accf17a0fb0785b2e0683a5531b1ea51ea2 [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "path/filepath"
19 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010020 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080021 "strconv"
22 "strings"
23
24 "github.com/google/blueprint/proptools"
25)
26
27// "neverallow" rules for the build system.
28//
29// This allows things which aren't related to the build system and are enforced
30// for sanity, in progress code refactors, or policy to be expressed in a
31// straightforward away disjoint from implementations and tests which should
32// work regardless of these restrictions.
33//
34// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010035// - it is in one of the "In" paths
36// - it is not in one of the "NotIn" paths
37// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080038// - - values are matched in their entirety
39// - - nil is interpreted as an empty string
40// - - nested properties are separated with a '.'
41// - - if the property is a list, any of the values in the list being matches
42// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010043// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080044
Artur Satayevc5570ac2020-04-09 16:06:36 +010045func RegisterNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080046 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
47}
48
Paul Duffin730f2a52019-06-27 14:08:51 +010049var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080050
Paul Duffin730f2a52019-06-27 14:08:51 +010051func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010052 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010053 AddNeverAllowRules(createTrebleRules()...)
54 AddNeverAllowRules(createLibcoreRules()...)
55 AddNeverAllowRules(createMediaRules()...)
56 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000057 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010058 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070059 AddNeverAllowRules(createMakefileGoalRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010060}
Steven Moreland65b3fd92017-12-06 14:18:35 -080061
Paul Duffin730f2a52019-06-27 14:08:51 +010062// Add a NeverAllow rule to the set of rules to apply.
63func AddNeverAllowRules(rules ...Rule) {
64 neverallows = append(neverallows, rules...)
65}
66
Paul Duffinc8111702019-07-22 12:13:55 +010067func createIncludeDirsRules() []Rule {
68 // The list of paths that cannot be referenced using include_dirs
69 paths := []string{
70 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000071 "art/libnativebridge",
72 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010073 "libcore",
74 "libnativehelper",
75 "external/apache-harmony",
76 "external/apache-xml",
77 "external/boringssl",
78 "external/bouncycastle",
79 "external/conscrypt",
80 "external/icu",
81 "external/okhttp",
82 "external/vixl",
83 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010084 }
85
86 // Create a composite matcher that will match if the value starts with any of the restricted
87 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
88 // XY.
89 rules := make([]Rule, 0, len(paths))
90 for _, path := range paths {
91 rule :=
92 NeverAllow().
93 WithMatcher("include_dirs", StartsWith(path+"/")).
94 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
95 " to use alternate mechanisms and so can no longer be used.")
96
97 rules = append(rules, rule)
98 }
99
100 return rules
101}
102
Paul Duffin730f2a52019-06-27 14:08:51 +0100103func createTrebleRules() []Rule {
104 return []Rule{
105 NeverAllow().
106 In("vendor", "device").
107 With("vndk.enabled", "true").
108 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900109 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100110 Because("the VNDK can never contain a library that is device dependent."),
111 NeverAllow().
112 With("vndk.enabled", "true").
113 Without("vendor", "true").
114 Without("owner", "").
115 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800116
Neil Fullerdf5f3562018-10-21 17:19:10 +0100117 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100118 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800119 Without("name", "libhidlbase-combined-impl").
120 Without("name", "libhidlbase").
121 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100122 With("product_variables.enforce_vintf_manifest.cflags", "*").
123 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100124
125 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100126 NeverAllow().
127 Without("name", "libc_bionic_ndk").
128 With("product_variables.treble_linker_namespaces.cflags", "*").
129 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100130
131 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100132 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100133 }
134}
135
Paul Duffin730f2a52019-06-27 14:08:51 +0100136func createLibcoreRules() []Rule {
Neil Fullerdf5f3562018-10-21 17:19:10 +0100137 var coreLibraryProjects = []string{
138 "libcore",
139 "external/apache-harmony",
140 "external/apache-xml",
141 "external/bouncycastle",
142 "external/conscrypt",
143 "external/icu",
144 "external/okhttp",
145 "external/wycheproof",
Paul Duffine5c3b852020-05-12 15:27:56 +0100146 "prebuilts",
Neil Fullerdf5f3562018-10-21 17:19:10 +0100147 }
148
Roland Levillainaca94492020-02-13 15:22:05 +0000149 // Additional whitelisted path only used for ART testing, which needs access to core library
150 // targets. This does not affect the contents of a device image (system, vendor, etc.).
151 var artTests = []string{
152 "art/test",
153 }
154
155 // Core library constraints. The sdk_version: "none" can only be used in core library projects and ART tests.
Paul Duffina3d09862019-06-11 13:40:47 +0100156 // Access to core library targets is restricted using visibility rules.
Paul Duffin730f2a52019-06-27 14:08:51 +0100157 rules := []Rule{
158 NeverAllow().
159 NotIn(coreLibraryProjects...).
Roland Levillainaca94492020-02-13 15:22:05 +0000160 NotIn(artTests...).
Anton Hansson45376402020-04-09 14:18:21 +0100161 With("sdk_version", "none").
162 WithoutMatcher("name", Regexp("^android_.*stubs_current$")),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100163 }
164
Neil Fullerdf5f3562018-10-21 17:19:10 +0100165 return rules
Steven Moreland65b3fd92017-12-06 14:18:35 -0800166}
167
Paul Duffin730f2a52019-06-27 14:08:51 +0100168func createMediaRules() []Rule {
169 return []Rule{
170 NeverAllow().
171 With("libs", "updatable-media").
172 Because("updatable-media includes private APIs. Use updatable_media_stubs instead."),
Dongwon Kang50a299f2019-02-04 09:00:51 -0800173 }
174}
175
Paul Duffin730f2a52019-06-27 14:08:51 +0100176func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700177 javaDeviceForHostProjectsAllowedList := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700178 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800179 "external/robolectric-shadows",
180 "framework/layoutlib",
181 }
182
Paul Duffin730f2a52019-06-27 14:08:51 +0100183 return []Rule{
184 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700185 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100186 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700187 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800188 }
189}
190
Colin Crossc511bc52020-04-07 16:50:32 +0000191func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700192 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000193 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
194 // This sometimes works because the APEX modules that contain derive_sdk and
195 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
196 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100197 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700198 // These are for apps and shouldn't be used by non-SDK variant modules.
199 "prebuilts/ndk",
200 "tools/test/graphicsbenchmark/apps/sample_app",
201 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700202 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Colin Crossc511bc52020-04-07 16:50:32 +0000203 }
204
Colin Cross440e0d02020-06-11 11:32:11 -0700205 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000206 // android_native_app_glue and libRSSupport use native_window.h but target old
207 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
208 // so they can't add libnativewindow to shared_libs to get the header directory
209 // for the platform variant. Allow them to use the platform variant
210 // property to set shared_libs.
211 "prebuilts/ndk",
212 "frameworks/rs",
213 }
214
215 return []Rule{
216 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700217 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000218 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700219 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000220 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700221 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000222 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700223 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000224 }
225}
226
David Srbeckye033cba2020-05-20 22:20:28 +0100227func createUncompressDexRules() []Rule {
228 return []Rule{
229 NeverAllow().
230 NotIn("art").
231 WithMatcher("uncompress_dex", isSetMatcherInstance).
232 Because("uncompress_dex is only allowed for certain jars for test in art."),
233 }
234}
235
Yifan Hong696ed4d2020-07-27 12:59:58 -0700236func createMakefileGoalRules() []Rule {
237 return []Rule{
238 NeverAllow().
239 ModuleType("makefile_goal").
240 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
241 Because("Only boot images may be imported as a makefile goal."),
242 }
243}
244
Steven Moreland65b3fd92017-12-06 14:18:35 -0800245func neverallowMutator(ctx BottomUpMutatorContext) {
246 m, ok := ctx.Module().(Module)
247 if !ok {
248 return
249 }
250
251 dir := ctx.ModuleDir() + "/"
252 properties := m.GetProperties()
253
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100254 osClass := ctx.Module().Target().Os.Class
255
Paul Duffin115445b2019-08-07 15:31:07 +0100256 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100257 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800258 if !n.appliesToPath(dir) {
259 continue
260 }
261
Colin Crossfd4f7432019-03-05 15:06:16 -0800262 if !n.appliesToModuleType(ctx.ModuleType()) {
263 continue
264 }
265
Steven Moreland65b3fd92017-12-06 14:18:35 -0800266 if !n.appliesToProperties(properties) {
267 continue
268 }
269
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100270 if !n.appliesToOsClass(osClass) {
271 continue
272 }
273
Paul Duffin35781882019-07-25 15:41:09 +0100274 if !n.appliesToDirectDeps(ctx) {
275 continue
276 }
277
Andrei Onea115e7e72020-06-05 21:14:03 +0100278 if !n.appliesToBootclasspathJar(ctx) {
279 continue
280 }
281
Steven Moreland65b3fd92017-12-06 14:18:35 -0800282 ctx.ModuleErrorf("violates " + n.String())
283 }
284}
285
Paul Duffin73bf0542019-07-12 14:12:49 +0100286type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100287 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100288 String() string
289}
290
291type equalMatcher struct {
292 expected string
293}
294
Artur Satayevc5570ac2020-04-09 16:06:36 +0100295func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100296 return m.expected == value
297}
298
299func (m *equalMatcher) String() string {
300 return "=" + m.expected
301}
302
303type anyMatcher struct {
304}
305
Artur Satayevc5570ac2020-04-09 16:06:36 +0100306func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100307 return true
308}
309
310func (m *anyMatcher) String() string {
311 return "=*"
312}
313
314var anyMatcherInstance = &anyMatcher{}
315
Paul Duffinc8111702019-07-22 12:13:55 +0100316type startsWithMatcher struct {
317 prefix string
318}
319
Artur Satayevc5570ac2020-04-09 16:06:36 +0100320func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100321 return strings.HasPrefix(value, m.prefix)
322}
323
324func (m *startsWithMatcher) String() string {
325 return ".starts-with(" + m.prefix + ")"
326}
327
Anton Hansson45376402020-04-09 14:18:21 +0100328type regexMatcher struct {
329 re *regexp.Regexp
330}
331
Artur Satayevc5570ac2020-04-09 16:06:36 +0100332func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100333 return m.re.MatchString(value)
334}
335
336func (m *regexMatcher) String() string {
337 return ".regexp(" + m.re.String() + ")"
338}
339
Andrei Onea115e7e72020-06-05 21:14:03 +0100340type notInListMatcher struct {
341 allowed []string
342}
343
344func (m *notInListMatcher) Test(value string) bool {
345 return !InList(value, m.allowed)
346}
347
348func (m *notInListMatcher) String() string {
349 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
350}
351
Colin Crossc511bc52020-04-07 16:50:32 +0000352type isSetMatcher struct{}
353
Artur Satayevc5570ac2020-04-09 16:06:36 +0100354func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000355 return value != ""
356}
357
358func (m *isSetMatcher) String() string {
359 return ".is-set"
360}
361
362var isSetMatcherInstance = &isSetMatcher{}
363
Steven Moreland65b3fd92017-12-06 14:18:35 -0800364type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100365 fields []string // e.x.: Vndk.Enabled
366 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800367}
368
Paul Duffin730f2a52019-06-27 14:08:51 +0100369// A NeverAllow rule.
370type Rule interface {
371 In(path ...string) Rule
372
373 NotIn(path ...string) Rule
374
Paul Duffin35781882019-07-25 15:41:09 +0100375 InDirectDeps(deps ...string) Rule
376
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100377 WithOsClass(osClasses ...OsClass) Rule
378
Paul Duffin730f2a52019-06-27 14:08:51 +0100379 ModuleType(types ...string) Rule
380
381 NotModuleType(types ...string) Rule
382
Andrei Onea115e7e72020-06-05 21:14:03 +0100383 BootclasspathJar() Rule
384
Paul Duffin730f2a52019-06-27 14:08:51 +0100385 With(properties, value string) Rule
386
Paul Duffinc8111702019-07-22 12:13:55 +0100387 WithMatcher(properties string, matcher ValueMatcher) Rule
388
Paul Duffin730f2a52019-06-27 14:08:51 +0100389 Without(properties, value string) Rule
390
Paul Duffinc8111702019-07-22 12:13:55 +0100391 WithoutMatcher(properties string, matcher ValueMatcher) Rule
392
Paul Duffin730f2a52019-06-27 14:08:51 +0100393 Because(reason string) Rule
394}
395
Steven Moreland65b3fd92017-12-06 14:18:35 -0800396type rule struct {
397 // User string for why this is a thing.
398 reason string
399
400 paths []string
401 unlessPaths []string
402
Paul Duffin35781882019-07-25 15:41:09 +0100403 directDeps map[string]bool
404
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100405 osClasses []OsClass
406
Colin Crossfd4f7432019-03-05 15:06:16 -0800407 moduleTypes []string
408 unlessModuleTypes []string
409
Steven Moreland65b3fd92017-12-06 14:18:35 -0800410 props []ruleProperty
411 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100412
413 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800414}
415
Paul Duffin730f2a52019-06-27 14:08:51 +0100416// Create a new NeverAllow rule.
417func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100418 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419}
Colin Crossfd4f7432019-03-05 15:06:16 -0800420
Paul Duffin730f2a52019-06-27 14:08:51 +0100421func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800422 r.paths = append(r.paths, cleanPaths(path)...)
423 return r
424}
Colin Crossfd4f7432019-03-05 15:06:16 -0800425
Paul Duffin730f2a52019-06-27 14:08:51 +0100426func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800427 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
428 return r
429}
Colin Crossfd4f7432019-03-05 15:06:16 -0800430
Paul Duffin35781882019-07-25 15:41:09 +0100431func (r *rule) InDirectDeps(deps ...string) Rule {
432 for _, d := range deps {
433 r.directDeps[d] = true
434 }
435 return r
436}
437
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100438func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
439 r.osClasses = append(r.osClasses, osClasses...)
440 return r
441}
442
Paul Duffin730f2a52019-06-27 14:08:51 +0100443func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800444 r.moduleTypes = append(r.moduleTypes, types...)
445 return r
446}
447
Paul Duffin730f2a52019-06-27 14:08:51 +0100448func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800449 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
450 return r
451}
452
Paul Duffin730f2a52019-06-27 14:08:51 +0100453func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100454 return r.WithMatcher(properties, selectMatcher(value))
455}
456
457func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800458 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100459 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100460 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800461 })
462 return r
463}
Colin Crossfd4f7432019-03-05 15:06:16 -0800464
Paul Duffin730f2a52019-06-27 14:08:51 +0100465func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100466 return r.WithoutMatcher(properties, selectMatcher(value))
467}
468
469func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800470 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100471 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100472 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800473 })
474 return r
475}
Colin Crossfd4f7432019-03-05 15:06:16 -0800476
Paul Duffin73bf0542019-07-12 14:12:49 +0100477func selectMatcher(expected string) ValueMatcher {
478 if expected == "*" {
479 return anyMatcherInstance
480 }
481 return &equalMatcher{expected: expected}
482}
483
Paul Duffin730f2a52019-06-27 14:08:51 +0100484func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800485 r.reason = reason
486 return r
487}
488
Andrei Onea115e7e72020-06-05 21:14:03 +0100489func (r *rule) BootclasspathJar() Rule {
490 r.onlyBootclasspathJar = true
491 return r
492}
493
Steven Moreland65b3fd92017-12-06 14:18:35 -0800494func (r *rule) String() string {
495 s := "neverallow"
496 for _, v := range r.paths {
497 s += " dir:" + v + "*"
498 }
499 for _, v := range r.unlessPaths {
500 s += " -dir:" + v + "*"
501 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800502 for _, v := range r.moduleTypes {
503 s += " type:" + v
504 }
505 for _, v := range r.unlessModuleTypes {
506 s += " -type:" + v
507 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800508 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100509 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800510 }
511 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100512 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 }
Paul Duffin35781882019-07-25 15:41:09 +0100514 for k := range r.directDeps {
515 s += " deps:" + k
516 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100517 for _, v := range r.osClasses {
518 s += " os:" + v.String()
519 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100520 if r.onlyBootclasspathJar {
521 s += " inBcp"
522 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800523 if len(r.reason) != 0 {
524 s += " which is restricted because " + r.reason
525 }
526 return s
527}
528
529func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800530 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
531 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532 return includePath && !excludePath
533}
534
Paul Duffin35781882019-07-25 15:41:09 +0100535func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
536 if len(r.directDeps) == 0 {
537 return true
538 }
539
540 matches := false
541 ctx.VisitDirectDeps(func(m Module) {
542 if !matches {
543 name := ctx.OtherModuleName(m)
544 matches = r.directDeps[name]
545 }
546 })
547
548 return matches
549}
550
Andrei Onea115e7e72020-06-05 21:14:03 +0100551func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
552 if !r.onlyBootclasspathJar {
553 return true
554 }
555
556 return InList(ctx.ModuleName(), ctx.Config().BootJars())
557}
558
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100559func (r *rule) appliesToOsClass(osClass OsClass) bool {
560 if len(r.osClasses) == 0 {
561 return true
562 }
563
564 for _, c := range r.osClasses {
565 if c == osClass {
566 return true
567 }
568 }
569
570 return false
571}
572
Colin Crossfd4f7432019-03-05 15:06:16 -0800573func (r *rule) appliesToModuleType(moduleType string) bool {
574 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
575}
576
Steven Moreland65b3fd92017-12-06 14:18:35 -0800577func (r *rule) appliesToProperties(properties []interface{}) bool {
578 includeProps := hasAllProperties(properties, r.props)
579 excludeProps := hasAnyProperty(properties, r.unlessProps)
580 return includeProps && !excludeProps
581}
582
Paul Duffinc8111702019-07-22 12:13:55 +0100583func StartsWith(prefix string) ValueMatcher {
584 return &startsWithMatcher{prefix}
585}
586
Anton Hansson45376402020-04-09 14:18:21 +0100587func Regexp(re string) ValueMatcher {
588 r, err := regexp.Compile(re)
589 if err != nil {
590 panic(err)
591 }
592 return &regexMatcher{r}
593}
594
Andrei Onea115e7e72020-06-05 21:14:03 +0100595func NotInList(allowed []string) ValueMatcher {
596 return &notInListMatcher{allowed}
597}
598
Steven Moreland65b3fd92017-12-06 14:18:35 -0800599// assorted utils
600
601func cleanPaths(paths []string) []string {
602 res := make([]string, len(paths))
603 for i, v := range paths {
604 res[i] = filepath.Clean(v) + "/"
605 }
606 return res
607}
608
609func fieldNamesForProperties(propertyNames string) []string {
610 names := strings.Split(propertyNames, ".")
611 for i, v := range names {
612 names[i] = proptools.FieldNameForProperty(v)
613 }
614 return names
615}
616
Steven Moreland65b3fd92017-12-06 14:18:35 -0800617func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
618 for _, v := range props {
619 if hasProperty(properties, v) {
620 return true
621 }
622 }
623 return false
624}
625
626func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
627 for _, v := range props {
628 if !hasProperty(properties, v) {
629 return false
630 }
631 }
632 return true
633}
634
635func hasProperty(properties []interface{}, prop ruleProperty) bool {
636 for _, propertyStruct := range properties {
637 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
638 for _, v := range prop.fields {
639 if !propertiesValue.IsValid() {
640 break
641 }
642 propertiesValue = propertiesValue.FieldByName(v)
643 }
644 if !propertiesValue.IsValid() {
645 continue
646 }
647
Paul Duffin73bf0542019-07-12 14:12:49 +0100648 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100649 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800650 }
651
652 if matchValue(propertiesValue, check) {
653 return true
654 }
655 }
656 return false
657}
658
659func matchValue(value reflect.Value, check func(string) bool) bool {
660 if !value.IsValid() {
661 return false
662 }
663
664 if value.Kind() == reflect.Ptr {
665 if value.IsNil() {
666 return check("")
667 }
668 value = value.Elem()
669 }
670
671 switch value.Kind() {
672 case reflect.String:
673 return check(value.String())
674 case reflect.Bool:
675 return check(strconv.FormatBool(value.Bool()))
676 case reflect.Int:
677 return check(strconv.FormatInt(value.Int(), 10))
678 case reflect.Slice:
679 slice, ok := value.Interface().([]string)
680 if !ok {
681 panic("Can only handle slice of string")
682 }
683 for _, v := range slice {
684 if check(v) {
685 return true
686 }
687 }
688 return false
689 }
690
691 panic("Can't handle type: " + value.Kind().String())
692}
Paul Duffin115445b2019-08-07 15:31:07 +0100693
694var neverallowRulesKey = NewOnceKey("neverallowRules")
695
696func neverallowRules(config Config) []Rule {
697 return config.Once(neverallowRulesKey, func() interface{} {
698 // No test rules were set by setTestNeverallowRules, use the global rules
699 return neverallows
700 }).([]Rule)
701}
702
703// Overrides the default neverallow rules for the supplied config.
704//
705// For testing only.
Artur Satayevc5570ac2020-04-09 16:06:36 +0100706func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100707 config.Once(neverallowRulesKey, func() interface{} { return testRules })
708}