blob: 41b399a70ac569acff11a4af5bdefc52e426f7da [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "path/filepath"
19 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010020 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080021 "strconv"
22 "strings"
23
24 "github.com/google/blueprint/proptools"
25)
26
27// "neverallow" rules for the build system.
28//
29// This allows things which aren't related to the build system and are enforced
30// for sanity, in progress code refactors, or policy to be expressed in a
31// straightforward away disjoint from implementations and tests which should
32// work regardless of these restrictions.
33//
34// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010035// - it is in one of the "In" paths
36// - it is not in one of the "NotIn" paths
37// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080038// - - values are matched in their entirety
39// - - nil is interpreted as an empty string
40// - - nested properties are separated with a '.'
41// - - if the property is a list, any of the values in the list being matches
42// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010043// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080044
Paul Duffin45338f02021-03-30 23:07:52 +010045func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080046 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
47}
48
Paul Duffin730f2a52019-06-27 14:08:51 +010049var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080050
Paul Duffin730f2a52019-06-27 14:08:51 +010051func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010052 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010053 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000055 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010056 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070057 AddNeverAllowRules(createMakefileGoalRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010058}
Steven Moreland65b3fd92017-12-06 14:18:35 -080059
Paul Duffin730f2a52019-06-27 14:08:51 +010060// Add a NeverAllow rule to the set of rules to apply.
61func AddNeverAllowRules(rules ...Rule) {
62 neverallows = append(neverallows, rules...)
63}
64
Paul Duffinc8111702019-07-22 12:13:55 +010065func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000066 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010067 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000068 "art/libnativebridge",
69 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010070 "libcore",
71 "libnativehelper",
72 "external/apache-harmony",
73 "external/apache-xml",
74 "external/boringssl",
75 "external/bouncycastle",
76 "external/conscrypt",
77 "external/icu",
78 "external/okhttp",
79 "external/vixl",
80 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010081 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000082 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000083 "frameworks/av/apex",
84 "frameworks/av/tools",
85 "frameworks/native/cmds",
86 "system/apex",
87 "system/bpf",
88 "system/gatekeeper",
89 "system/hwservicemanager",
90 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000091 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000092 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000093 }
Paul Duffinc8111702019-07-22 12:13:55 +010094
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000095 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
96
97 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +010098 rule :=
99 NeverAllow().
100 WithMatcher("include_dirs", StartsWith(path+"/")).
101 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
102 " to use alternate mechanisms and so can no longer be used.")
103
104 rules = append(rules, rule)
105 }
106
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000107 for _, path := range noUseIncludeDir {
108 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
109 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
110 " to use alternate mechanisms and so can no longer be used.")
111 rules = append(rules, rule)
112 }
113
Paul Duffinc8111702019-07-22 12:13:55 +0100114 return rules
115}
116
Paul Duffin730f2a52019-06-27 14:08:51 +0100117func createTrebleRules() []Rule {
118 return []Rule{
119 NeverAllow().
120 In("vendor", "device").
121 With("vndk.enabled", "true").
122 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900123 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100124 Because("the VNDK can never contain a library that is device dependent."),
125 NeverAllow().
126 With("vndk.enabled", "true").
127 Without("vendor", "true").
128 Without("owner", "").
129 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800130
Neil Fullerdf5f3562018-10-21 17:19:10 +0100131 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100132 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800133 Without("name", "libhidlbase-combined-impl").
134 Without("name", "libhidlbase").
135 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100136 With("product_variables.enforce_vintf_manifest.cflags", "*").
137 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100138
139 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100140 NeverAllow().
141 Without("name", "libc_bionic_ndk").
142 With("product_variables.treble_linker_namespaces.cflags", "*").
143 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100144
145 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100147 }
148}
149
Paul Duffin730f2a52019-06-27 14:08:51 +0100150func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700151 javaDeviceForHostProjectsAllowedList := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700152 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800153 "external/robolectric-shadows",
154 "framework/layoutlib",
155 }
156
Paul Duffin730f2a52019-06-27 14:08:51 +0100157 return []Rule{
158 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700159 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100160 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700161 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800162 }
163}
164
Colin Crossc511bc52020-04-07 16:50:32 +0000165func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700166 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000167 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
168 // This sometimes works because the APEX modules that contain derive_sdk and
169 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
170 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100171 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700172 // These are for apps and shouldn't be used by non-SDK variant modules.
173 "prebuilts/ndk",
174 "tools/test/graphicsbenchmark/apps/sample_app",
175 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700176 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Colin Crossc511bc52020-04-07 16:50:32 +0000177 }
178
Colin Cross440e0d02020-06-11 11:32:11 -0700179 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000180 // android_native_app_glue and libRSSupport use native_window.h but target old
181 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
182 // so they can't add libnativewindow to shared_libs to get the header directory
183 // for the platform variant. Allow them to use the platform variant
184 // property to set shared_libs.
185 "prebuilts/ndk",
186 "frameworks/rs",
187 }
188
189 return []Rule{
190 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700191 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000192 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700193 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000194 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700195 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000196 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700197 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000198 }
199}
200
David Srbeckye033cba2020-05-20 22:20:28 +0100201func createUncompressDexRules() []Rule {
202 return []Rule{
203 NeverAllow().
204 NotIn("art").
205 WithMatcher("uncompress_dex", isSetMatcherInstance).
206 Because("uncompress_dex is only allowed for certain jars for test in art."),
207 }
208}
209
Yifan Hong696ed4d2020-07-27 12:59:58 -0700210func createMakefileGoalRules() []Rule {
211 return []Rule{
212 NeverAllow().
213 ModuleType("makefile_goal").
214 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
215 Because("Only boot images may be imported as a makefile goal."),
216 }
217}
218
Steven Moreland65b3fd92017-12-06 14:18:35 -0800219func neverallowMutator(ctx BottomUpMutatorContext) {
220 m, ok := ctx.Module().(Module)
221 if !ok {
222 return
223 }
224
225 dir := ctx.ModuleDir() + "/"
226 properties := m.GetProperties()
227
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100228 osClass := ctx.Module().Target().Os.Class
229
Paul Duffin115445b2019-08-07 15:31:07 +0100230 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100231 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800232 if !n.appliesToPath(dir) {
233 continue
234 }
235
Colin Crossfd4f7432019-03-05 15:06:16 -0800236 if !n.appliesToModuleType(ctx.ModuleType()) {
237 continue
238 }
239
Steven Moreland65b3fd92017-12-06 14:18:35 -0800240 if !n.appliesToProperties(properties) {
241 continue
242 }
243
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100244 if !n.appliesToOsClass(osClass) {
245 continue
246 }
247
Paul Duffin35781882019-07-25 15:41:09 +0100248 if !n.appliesToDirectDeps(ctx) {
249 continue
250 }
251
Andrei Onea115e7e72020-06-05 21:14:03 +0100252 if !n.appliesToBootclasspathJar(ctx) {
253 continue
254 }
255
Steven Moreland65b3fd92017-12-06 14:18:35 -0800256 ctx.ModuleErrorf("violates " + n.String())
257 }
258}
259
Paul Duffin73bf0542019-07-12 14:12:49 +0100260type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100261 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100262 String() string
263}
264
265type equalMatcher struct {
266 expected string
267}
268
Artur Satayevc5570ac2020-04-09 16:06:36 +0100269func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100270 return m.expected == value
271}
272
273func (m *equalMatcher) String() string {
274 return "=" + m.expected
275}
276
277type anyMatcher struct {
278}
279
Artur Satayevc5570ac2020-04-09 16:06:36 +0100280func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100281 return true
282}
283
284func (m *anyMatcher) String() string {
285 return "=*"
286}
287
288var anyMatcherInstance = &anyMatcher{}
289
Paul Duffinc8111702019-07-22 12:13:55 +0100290type startsWithMatcher struct {
291 prefix string
292}
293
Artur Satayevc5570ac2020-04-09 16:06:36 +0100294func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100295 return strings.HasPrefix(value, m.prefix)
296}
297
298func (m *startsWithMatcher) String() string {
299 return ".starts-with(" + m.prefix + ")"
300}
301
Anton Hansson45376402020-04-09 14:18:21 +0100302type regexMatcher struct {
303 re *regexp.Regexp
304}
305
Artur Satayevc5570ac2020-04-09 16:06:36 +0100306func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100307 return m.re.MatchString(value)
308}
309
310func (m *regexMatcher) String() string {
311 return ".regexp(" + m.re.String() + ")"
312}
313
Andrei Onea115e7e72020-06-05 21:14:03 +0100314type notInListMatcher struct {
315 allowed []string
316}
317
318func (m *notInListMatcher) Test(value string) bool {
319 return !InList(value, m.allowed)
320}
321
322func (m *notInListMatcher) String() string {
323 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
324}
325
Colin Crossc511bc52020-04-07 16:50:32 +0000326type isSetMatcher struct{}
327
Artur Satayevc5570ac2020-04-09 16:06:36 +0100328func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000329 return value != ""
330}
331
332func (m *isSetMatcher) String() string {
333 return ".is-set"
334}
335
336var isSetMatcherInstance = &isSetMatcher{}
337
Steven Moreland65b3fd92017-12-06 14:18:35 -0800338type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100339 fields []string // e.x.: Vndk.Enabled
340 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800341}
342
Paul Duffin730f2a52019-06-27 14:08:51 +0100343// A NeverAllow rule.
344type Rule interface {
345 In(path ...string) Rule
346
347 NotIn(path ...string) Rule
348
Paul Duffin35781882019-07-25 15:41:09 +0100349 InDirectDeps(deps ...string) Rule
350
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100351 WithOsClass(osClasses ...OsClass) Rule
352
Paul Duffin730f2a52019-06-27 14:08:51 +0100353 ModuleType(types ...string) Rule
354
355 NotModuleType(types ...string) Rule
356
Andrei Onea115e7e72020-06-05 21:14:03 +0100357 BootclasspathJar() Rule
358
Paul Duffin730f2a52019-06-27 14:08:51 +0100359 With(properties, value string) Rule
360
Paul Duffinc8111702019-07-22 12:13:55 +0100361 WithMatcher(properties string, matcher ValueMatcher) Rule
362
Paul Duffin730f2a52019-06-27 14:08:51 +0100363 Without(properties, value string) Rule
364
Paul Duffinc8111702019-07-22 12:13:55 +0100365 WithoutMatcher(properties string, matcher ValueMatcher) Rule
366
Paul Duffin730f2a52019-06-27 14:08:51 +0100367 Because(reason string) Rule
368}
369
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370type rule struct {
371 // User string for why this is a thing.
372 reason string
373
374 paths []string
375 unlessPaths []string
376
Paul Duffin35781882019-07-25 15:41:09 +0100377 directDeps map[string]bool
378
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100379 osClasses []OsClass
380
Colin Crossfd4f7432019-03-05 15:06:16 -0800381 moduleTypes []string
382 unlessModuleTypes []string
383
Steven Moreland65b3fd92017-12-06 14:18:35 -0800384 props []ruleProperty
385 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100386
387 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800388}
389
Paul Duffin730f2a52019-06-27 14:08:51 +0100390// Create a new NeverAllow rule.
391func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100392 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800393}
Colin Crossfd4f7432019-03-05 15:06:16 -0800394
Paul Duffin730f2a52019-06-27 14:08:51 +0100395func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800396 r.paths = append(r.paths, cleanPaths(path)...)
397 return r
398}
Colin Crossfd4f7432019-03-05 15:06:16 -0800399
Paul Duffin730f2a52019-06-27 14:08:51 +0100400func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800401 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
402 return r
403}
Colin Crossfd4f7432019-03-05 15:06:16 -0800404
Paul Duffin35781882019-07-25 15:41:09 +0100405func (r *rule) InDirectDeps(deps ...string) Rule {
406 for _, d := range deps {
407 r.directDeps[d] = true
408 }
409 return r
410}
411
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100412func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
413 r.osClasses = append(r.osClasses, osClasses...)
414 return r
415}
416
Paul Duffin730f2a52019-06-27 14:08:51 +0100417func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800418 r.moduleTypes = append(r.moduleTypes, types...)
419 return r
420}
421
Paul Duffin730f2a52019-06-27 14:08:51 +0100422func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800423 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
424 return r
425}
426
Paul Duffin730f2a52019-06-27 14:08:51 +0100427func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100428 return r.WithMatcher(properties, selectMatcher(value))
429}
430
431func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800432 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100433 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100434 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800435 })
436 return r
437}
Colin Crossfd4f7432019-03-05 15:06:16 -0800438
Paul Duffin730f2a52019-06-27 14:08:51 +0100439func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100440 return r.WithoutMatcher(properties, selectMatcher(value))
441}
442
443func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800444 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100445 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100446 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447 })
448 return r
449}
Colin Crossfd4f7432019-03-05 15:06:16 -0800450
Paul Duffin73bf0542019-07-12 14:12:49 +0100451func selectMatcher(expected string) ValueMatcher {
452 if expected == "*" {
453 return anyMatcherInstance
454 }
455 return &equalMatcher{expected: expected}
456}
457
Paul Duffin730f2a52019-06-27 14:08:51 +0100458func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800459 r.reason = reason
460 return r
461}
462
Andrei Onea115e7e72020-06-05 21:14:03 +0100463func (r *rule) BootclasspathJar() Rule {
464 r.onlyBootclasspathJar = true
465 return r
466}
467
Steven Moreland65b3fd92017-12-06 14:18:35 -0800468func (r *rule) String() string {
469 s := "neverallow"
470 for _, v := range r.paths {
471 s += " dir:" + v + "*"
472 }
473 for _, v := range r.unlessPaths {
474 s += " -dir:" + v + "*"
475 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800476 for _, v := range r.moduleTypes {
477 s += " type:" + v
478 }
479 for _, v := range r.unlessModuleTypes {
480 s += " -type:" + v
481 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800482 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100483 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800484 }
485 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100486 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800487 }
Paul Duffin35781882019-07-25 15:41:09 +0100488 for k := range r.directDeps {
489 s += " deps:" + k
490 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100491 for _, v := range r.osClasses {
492 s += " os:" + v.String()
493 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100494 if r.onlyBootclasspathJar {
495 s += " inBcp"
496 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 if len(r.reason) != 0 {
498 s += " which is restricted because " + r.reason
499 }
500 return s
501}
502
503func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800504 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
505 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800506 return includePath && !excludePath
507}
508
Paul Duffin35781882019-07-25 15:41:09 +0100509func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
510 if len(r.directDeps) == 0 {
511 return true
512 }
513
514 matches := false
515 ctx.VisitDirectDeps(func(m Module) {
516 if !matches {
517 name := ctx.OtherModuleName(m)
518 matches = r.directDeps[name]
519 }
520 })
521
522 return matches
523}
524
Andrei Onea115e7e72020-06-05 21:14:03 +0100525func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
526 if !r.onlyBootclasspathJar {
527 return true
528 }
529
530 return InList(ctx.ModuleName(), ctx.Config().BootJars())
531}
532
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100533func (r *rule) appliesToOsClass(osClass OsClass) bool {
534 if len(r.osClasses) == 0 {
535 return true
536 }
537
538 for _, c := range r.osClasses {
539 if c == osClass {
540 return true
541 }
542 }
543
544 return false
545}
546
Colin Crossfd4f7432019-03-05 15:06:16 -0800547func (r *rule) appliesToModuleType(moduleType string) bool {
548 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
549}
550
Steven Moreland65b3fd92017-12-06 14:18:35 -0800551func (r *rule) appliesToProperties(properties []interface{}) bool {
552 includeProps := hasAllProperties(properties, r.props)
553 excludeProps := hasAnyProperty(properties, r.unlessProps)
554 return includeProps && !excludeProps
555}
556
Paul Duffinc8111702019-07-22 12:13:55 +0100557func StartsWith(prefix string) ValueMatcher {
558 return &startsWithMatcher{prefix}
559}
560
Anton Hansson45376402020-04-09 14:18:21 +0100561func Regexp(re string) ValueMatcher {
562 r, err := regexp.Compile(re)
563 if err != nil {
564 panic(err)
565 }
566 return &regexMatcher{r}
567}
568
Andrei Onea115e7e72020-06-05 21:14:03 +0100569func NotInList(allowed []string) ValueMatcher {
570 return &notInListMatcher{allowed}
571}
572
Steven Moreland65b3fd92017-12-06 14:18:35 -0800573// assorted utils
574
575func cleanPaths(paths []string) []string {
576 res := make([]string, len(paths))
577 for i, v := range paths {
578 res[i] = filepath.Clean(v) + "/"
579 }
580 return res
581}
582
583func fieldNamesForProperties(propertyNames string) []string {
584 names := strings.Split(propertyNames, ".")
585 for i, v := range names {
586 names[i] = proptools.FieldNameForProperty(v)
587 }
588 return names
589}
590
Steven Moreland65b3fd92017-12-06 14:18:35 -0800591func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
592 for _, v := range props {
593 if hasProperty(properties, v) {
594 return true
595 }
596 }
597 return false
598}
599
600func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
601 for _, v := range props {
602 if !hasProperty(properties, v) {
603 return false
604 }
605 }
606 return true
607}
608
609func hasProperty(properties []interface{}, prop ruleProperty) bool {
610 for _, propertyStruct := range properties {
611 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
612 for _, v := range prop.fields {
613 if !propertiesValue.IsValid() {
614 break
615 }
616 propertiesValue = propertiesValue.FieldByName(v)
617 }
618 if !propertiesValue.IsValid() {
619 continue
620 }
621
Paul Duffin73bf0542019-07-12 14:12:49 +0100622 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100623 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800624 }
625
626 if matchValue(propertiesValue, check) {
627 return true
628 }
629 }
630 return false
631}
632
633func matchValue(value reflect.Value, check func(string) bool) bool {
634 if !value.IsValid() {
635 return false
636 }
637
638 if value.Kind() == reflect.Ptr {
639 if value.IsNil() {
640 return check("")
641 }
642 value = value.Elem()
643 }
644
645 switch value.Kind() {
646 case reflect.String:
647 return check(value.String())
648 case reflect.Bool:
649 return check(strconv.FormatBool(value.Bool()))
650 case reflect.Int:
651 return check(strconv.FormatInt(value.Int(), 10))
652 case reflect.Slice:
653 slice, ok := value.Interface().([]string)
654 if !ok {
655 panic("Can only handle slice of string")
656 }
657 for _, v := range slice {
658 if check(v) {
659 return true
660 }
661 }
662 return false
663 }
664
665 panic("Can't handle type: " + value.Kind().String())
666}
Paul Duffin115445b2019-08-07 15:31:07 +0100667
668var neverallowRulesKey = NewOnceKey("neverallowRules")
669
670func neverallowRules(config Config) []Rule {
671 return config.Once(neverallowRulesKey, func() interface{} {
672 // No test rules were set by setTestNeverallowRules, use the global rules
673 return neverallows
674 }).([]Rule)
675}
676
677// Overrides the default neverallow rules for the supplied config.
678//
679// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100680func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100681 config.Once(neverallowRulesKey, func() interface{} { return testRules })
682}
Paul Duffin45338f02021-03-30 23:07:52 +0100683
684// Prepares for a test by setting neverallow rules and enabling the mutator.
685//
686// If the supplied rules are nil then the default rules are used.
687func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
688 return GroupFixturePreparers(
689 FixtureModifyConfig(func(config Config) {
690 if testRules != nil {
691 setTestNeverallowRules(config, testRules)
692 }
693 }),
694 FixtureRegisterWithContext(func(ctx RegistrationContext) {
695 ctx.PostDepsMutators(registerNeverallowMutator)
696 }),
697 )
698}