blob: 04366d3537cc5cf25bb459db44ff2c26ad014002 [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "path/filepath"
19 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010020 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080021 "strconv"
22 "strings"
23
24 "github.com/google/blueprint/proptools"
25)
26
27// "neverallow" rules for the build system.
28//
29// This allows things which aren't related to the build system and are enforced
Joe Onoratob4638c12021-10-27 15:47:06 -070030// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080031// straightforward away disjoint from implementations and tests which should
32// work regardless of these restrictions.
33//
34// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010035// - it is in one of the "In" paths
36// - it is not in one of the "NotIn" paths
37// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080038// - - values are matched in their entirety
39// - - nil is interpreted as an empty string
40// - - nested properties are separated with a '.'
41// - - if the property is a list, any of the values in the list being matches
42// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010043// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080044
Paul Duffin45338f02021-03-30 23:07:52 +010045func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080046 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
47}
48
Paul Duffin730f2a52019-06-27 14:08:51 +010049var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080050
Paul Duffin730f2a52019-06-27 14:08:51 +010051func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010052 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010053 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000055 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010056 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070057 AddNeverAllowRules(createMakefileGoalRules()...)
Inseob Kim800d1142021-06-14 12:03:51 +090058 AddNeverAllowRules(createInitFirstStageRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010059}
Steven Moreland65b3fd92017-12-06 14:18:35 -080060
Paul Duffin730f2a52019-06-27 14:08:51 +010061// Add a NeverAllow rule to the set of rules to apply.
62func AddNeverAllowRules(rules ...Rule) {
63 neverallows = append(neverallows, rules...)
64}
65
Paul Duffinc8111702019-07-22 12:13:55 +010066func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000067 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010068 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000069 "art/libnativebridge",
70 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010071 "libcore",
72 "libnativehelper",
73 "external/apache-harmony",
74 "external/apache-xml",
75 "external/boringssl",
76 "external/bouncycastle",
77 "external/conscrypt",
78 "external/icu",
79 "external/okhttp",
80 "external/vixl",
81 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010082 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000083 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000084 "frameworks/av/apex",
85 "frameworks/av/tools",
86 "frameworks/native/cmds",
87 "system/apex",
88 "system/bpf",
89 "system/gatekeeper",
90 "system/hwservicemanager",
91 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000092 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000093 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000094 }
Paul Duffinc8111702019-07-22 12:13:55 +010095
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
97
98 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +010099 rule :=
100 NeverAllow().
101 WithMatcher("include_dirs", StartsWith(path+"/")).
102 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
103 " to use alternate mechanisms and so can no longer be used.")
104
105 rules = append(rules, rule)
106 }
107
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000108 for _, path := range noUseIncludeDir {
109 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
110 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
111 " to use alternate mechanisms and so can no longer be used.")
112 rules = append(rules, rule)
113 }
114
Paul Duffinc8111702019-07-22 12:13:55 +0100115 return rules
116}
117
Paul Duffin730f2a52019-06-27 14:08:51 +0100118func createTrebleRules() []Rule {
119 return []Rule{
120 NeverAllow().
121 In("vendor", "device").
122 With("vndk.enabled", "true").
123 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900124 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100125 Because("the VNDK can never contain a library that is device dependent."),
126 NeverAllow().
127 With("vndk.enabled", "true").
128 Without("vendor", "true").
129 Without("owner", "").
130 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800131
Neil Fullerdf5f3562018-10-21 17:19:10 +0100132 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100133 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800134 Without("name", "libhidlbase-combined-impl").
135 Without("name", "libhidlbase").
136 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100137 With("product_variables.enforce_vintf_manifest.cflags", "*").
138 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100139
140 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100141 NeverAllow().
142 Without("name", "libc_bionic_ndk").
143 With("product_variables.treble_linker_namespaces.cflags", "*").
144 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145
146 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100148 }
149}
150
Paul Duffin730f2a52019-06-27 14:08:51 +0100151func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700152 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700153 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700154 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800155 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000156 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800157 }
158
Paul Duffin730f2a52019-06-27 14:08:51 +0100159 return []Rule{
160 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700161 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100162 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700163 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800164 }
165}
166
Colin Crossc511bc52020-04-07 16:50:32 +0000167func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700168 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000169 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
170 // This sometimes works because the APEX modules that contain derive_sdk and
171 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
172 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100173 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700174 // These are for apps and shouldn't be used by non-SDK variant modules.
175 "prebuilts/ndk",
176 "tools/test/graphicsbenchmark/apps/sample_app",
177 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700178 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000179 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000180 }
181
Colin Cross440e0d02020-06-11 11:32:11 -0700182 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000183 // android_native_app_glue and libRSSupport use native_window.h but target old
184 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
185 // so they can't add libnativewindow to shared_libs to get the header directory
186 // for the platform variant. Allow them to use the platform variant
187 // property to set shared_libs.
188 "prebuilts/ndk",
189 "frameworks/rs",
190 }
191
192 return []Rule{
193 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700194 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000195 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700196 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000197 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700198 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000199 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700200 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000201 }
202}
203
David Srbeckye033cba2020-05-20 22:20:28 +0100204func createUncompressDexRules() []Rule {
205 return []Rule{
206 NeverAllow().
207 NotIn("art").
208 WithMatcher("uncompress_dex", isSetMatcherInstance).
209 Because("uncompress_dex is only allowed for certain jars for test in art."),
210 }
211}
212
Yifan Hong696ed4d2020-07-27 12:59:58 -0700213func createMakefileGoalRules() []Rule {
214 return []Rule{
215 NeverAllow().
216 ModuleType("makefile_goal").
217 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Inseob Kima9078742021-12-29 08:59:00 +0000218 Because("Only boot images may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700219 }
220}
221
Inseob Kim800d1142021-06-14 12:03:51 +0900222func createInitFirstStageRules() []Rule {
223 return []Rule{
224 NeverAllow().
225 Without("name", "init_first_stage").
226 With("install_in_root", "true").
227 Because("install_in_root is only for init_first_stage."),
228 }
229}
230
Steven Moreland65b3fd92017-12-06 14:18:35 -0800231func neverallowMutator(ctx BottomUpMutatorContext) {
232 m, ok := ctx.Module().(Module)
233 if !ok {
234 return
235 }
236
237 dir := ctx.ModuleDir() + "/"
238 properties := m.GetProperties()
239
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100240 osClass := ctx.Module().Target().Os.Class
241
Paul Duffin115445b2019-08-07 15:31:07 +0100242 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100243 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800244 if !n.appliesToPath(dir) {
245 continue
246 }
247
Colin Crossfd4f7432019-03-05 15:06:16 -0800248 if !n.appliesToModuleType(ctx.ModuleType()) {
249 continue
250 }
251
Steven Moreland65b3fd92017-12-06 14:18:35 -0800252 if !n.appliesToProperties(properties) {
253 continue
254 }
255
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100256 if !n.appliesToOsClass(osClass) {
257 continue
258 }
259
Paul Duffin35781882019-07-25 15:41:09 +0100260 if !n.appliesToDirectDeps(ctx) {
261 continue
262 }
263
Andrei Onea115e7e72020-06-05 21:14:03 +0100264 if !n.appliesToBootclasspathJar(ctx) {
265 continue
266 }
267
Steven Moreland65b3fd92017-12-06 14:18:35 -0800268 ctx.ModuleErrorf("violates " + n.String())
269 }
270}
271
Paul Duffin73bf0542019-07-12 14:12:49 +0100272type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100273 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100274 String() string
275}
276
277type equalMatcher struct {
278 expected string
279}
280
Artur Satayevc5570ac2020-04-09 16:06:36 +0100281func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100282 return m.expected == value
283}
284
285func (m *equalMatcher) String() string {
286 return "=" + m.expected
287}
288
289type anyMatcher struct {
290}
291
Artur Satayevc5570ac2020-04-09 16:06:36 +0100292func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100293 return true
294}
295
296func (m *anyMatcher) String() string {
297 return "=*"
298}
299
300var anyMatcherInstance = &anyMatcher{}
301
Paul Duffinc8111702019-07-22 12:13:55 +0100302type startsWithMatcher struct {
303 prefix string
304}
305
Artur Satayevc5570ac2020-04-09 16:06:36 +0100306func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100307 return strings.HasPrefix(value, m.prefix)
308}
309
310func (m *startsWithMatcher) String() string {
311 return ".starts-with(" + m.prefix + ")"
312}
313
Anton Hansson45376402020-04-09 14:18:21 +0100314type regexMatcher struct {
315 re *regexp.Regexp
316}
317
Artur Satayevc5570ac2020-04-09 16:06:36 +0100318func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100319 return m.re.MatchString(value)
320}
321
322func (m *regexMatcher) String() string {
323 return ".regexp(" + m.re.String() + ")"
324}
325
Andrei Onea115e7e72020-06-05 21:14:03 +0100326type notInListMatcher struct {
327 allowed []string
328}
329
330func (m *notInListMatcher) Test(value string) bool {
331 return !InList(value, m.allowed)
332}
333
334func (m *notInListMatcher) String() string {
335 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
336}
337
Colin Crossc511bc52020-04-07 16:50:32 +0000338type isSetMatcher struct{}
339
Artur Satayevc5570ac2020-04-09 16:06:36 +0100340func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000341 return value != ""
342}
343
344func (m *isSetMatcher) String() string {
345 return ".is-set"
346}
347
348var isSetMatcherInstance = &isSetMatcher{}
349
Steven Moreland65b3fd92017-12-06 14:18:35 -0800350type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100351 fields []string // e.x.: Vndk.Enabled
352 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800353}
354
Paul Duffin730f2a52019-06-27 14:08:51 +0100355// A NeverAllow rule.
356type Rule interface {
357 In(path ...string) Rule
358
359 NotIn(path ...string) Rule
360
Paul Duffin35781882019-07-25 15:41:09 +0100361 InDirectDeps(deps ...string) Rule
362
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100363 WithOsClass(osClasses ...OsClass) Rule
364
Paul Duffin730f2a52019-06-27 14:08:51 +0100365 ModuleType(types ...string) Rule
366
367 NotModuleType(types ...string) Rule
368
Andrei Onea115e7e72020-06-05 21:14:03 +0100369 BootclasspathJar() Rule
370
Paul Duffin730f2a52019-06-27 14:08:51 +0100371 With(properties, value string) Rule
372
Paul Duffinc8111702019-07-22 12:13:55 +0100373 WithMatcher(properties string, matcher ValueMatcher) Rule
374
Paul Duffin730f2a52019-06-27 14:08:51 +0100375 Without(properties, value string) Rule
376
Paul Duffinc8111702019-07-22 12:13:55 +0100377 WithoutMatcher(properties string, matcher ValueMatcher) Rule
378
Paul Duffin730f2a52019-06-27 14:08:51 +0100379 Because(reason string) Rule
380}
381
Steven Moreland65b3fd92017-12-06 14:18:35 -0800382type rule struct {
383 // User string for why this is a thing.
384 reason string
385
386 paths []string
387 unlessPaths []string
388
Paul Duffin35781882019-07-25 15:41:09 +0100389 directDeps map[string]bool
390
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100391 osClasses []OsClass
392
Colin Crossfd4f7432019-03-05 15:06:16 -0800393 moduleTypes []string
394 unlessModuleTypes []string
395
Steven Moreland65b3fd92017-12-06 14:18:35 -0800396 props []ruleProperty
397 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100398
399 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800400}
401
Paul Duffin730f2a52019-06-27 14:08:51 +0100402// Create a new NeverAllow rule.
403func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100404 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800405}
Colin Crossfd4f7432019-03-05 15:06:16 -0800406
Paul Duffin730f2a52019-06-27 14:08:51 +0100407func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800408 r.paths = append(r.paths, cleanPaths(path)...)
409 return r
410}
Colin Crossfd4f7432019-03-05 15:06:16 -0800411
Paul Duffin730f2a52019-06-27 14:08:51 +0100412func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800413 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
414 return r
415}
Colin Crossfd4f7432019-03-05 15:06:16 -0800416
Paul Duffin35781882019-07-25 15:41:09 +0100417func (r *rule) InDirectDeps(deps ...string) Rule {
418 for _, d := range deps {
419 r.directDeps[d] = true
420 }
421 return r
422}
423
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100424func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
425 r.osClasses = append(r.osClasses, osClasses...)
426 return r
427}
428
Paul Duffin730f2a52019-06-27 14:08:51 +0100429func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800430 r.moduleTypes = append(r.moduleTypes, types...)
431 return r
432}
433
Paul Duffin730f2a52019-06-27 14:08:51 +0100434func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800435 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
436 return r
437}
438
Paul Duffin730f2a52019-06-27 14:08:51 +0100439func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100440 return r.WithMatcher(properties, selectMatcher(value))
441}
442
443func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800444 r.props = append(r.props, 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 Duffin730f2a52019-06-27 14:08:51 +0100451func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100452 return r.WithoutMatcher(properties, selectMatcher(value))
453}
454
455func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800456 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100457 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100458 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800459 })
460 return r
461}
Colin Crossfd4f7432019-03-05 15:06:16 -0800462
Paul Duffin73bf0542019-07-12 14:12:49 +0100463func selectMatcher(expected string) ValueMatcher {
464 if expected == "*" {
465 return anyMatcherInstance
466 }
467 return &equalMatcher{expected: expected}
468}
469
Paul Duffin730f2a52019-06-27 14:08:51 +0100470func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800471 r.reason = reason
472 return r
473}
474
Andrei Onea115e7e72020-06-05 21:14:03 +0100475func (r *rule) BootclasspathJar() Rule {
476 r.onlyBootclasspathJar = true
477 return r
478}
479
Steven Moreland65b3fd92017-12-06 14:18:35 -0800480func (r *rule) String() string {
481 s := "neverallow"
482 for _, v := range r.paths {
483 s += " dir:" + v + "*"
484 }
485 for _, v := range r.unlessPaths {
486 s += " -dir:" + v + "*"
487 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800488 for _, v := range r.moduleTypes {
489 s += " type:" + v
490 }
491 for _, v := range r.unlessModuleTypes {
492 s += " -type:" + v
493 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800494 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100495 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800496 }
497 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100498 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800499 }
Paul Duffin35781882019-07-25 15:41:09 +0100500 for k := range r.directDeps {
501 s += " deps:" + k
502 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100503 for _, v := range r.osClasses {
504 s += " os:" + v.String()
505 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100506 if r.onlyBootclasspathJar {
507 s += " inBcp"
508 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800509 if len(r.reason) != 0 {
510 s += " which is restricted because " + r.reason
511 }
512 return s
513}
514
515func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800516 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
517 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800518 return includePath && !excludePath
519}
520
Paul Duffin35781882019-07-25 15:41:09 +0100521func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
522 if len(r.directDeps) == 0 {
523 return true
524 }
525
526 matches := false
527 ctx.VisitDirectDeps(func(m Module) {
528 if !matches {
529 name := ctx.OtherModuleName(m)
530 matches = r.directDeps[name]
531 }
532 })
533
534 return matches
535}
536
Andrei Onea115e7e72020-06-05 21:14:03 +0100537func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
538 if !r.onlyBootclasspathJar {
539 return true
540 }
541
542 return InList(ctx.ModuleName(), ctx.Config().BootJars())
543}
544
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100545func (r *rule) appliesToOsClass(osClass OsClass) bool {
546 if len(r.osClasses) == 0 {
547 return true
548 }
549
550 for _, c := range r.osClasses {
551 if c == osClass {
552 return true
553 }
554 }
555
556 return false
557}
558
Colin Crossfd4f7432019-03-05 15:06:16 -0800559func (r *rule) appliesToModuleType(moduleType string) bool {
560 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
561}
562
Steven Moreland65b3fd92017-12-06 14:18:35 -0800563func (r *rule) appliesToProperties(properties []interface{}) bool {
564 includeProps := hasAllProperties(properties, r.props)
565 excludeProps := hasAnyProperty(properties, r.unlessProps)
566 return includeProps && !excludeProps
567}
568
Paul Duffinc8111702019-07-22 12:13:55 +0100569func StartsWith(prefix string) ValueMatcher {
570 return &startsWithMatcher{prefix}
571}
572
Anton Hansson45376402020-04-09 14:18:21 +0100573func Regexp(re string) ValueMatcher {
574 r, err := regexp.Compile(re)
575 if err != nil {
576 panic(err)
577 }
578 return &regexMatcher{r}
579}
580
Andrei Onea115e7e72020-06-05 21:14:03 +0100581func NotInList(allowed []string) ValueMatcher {
582 return &notInListMatcher{allowed}
583}
584
Steven Moreland65b3fd92017-12-06 14:18:35 -0800585// assorted utils
586
587func cleanPaths(paths []string) []string {
588 res := make([]string, len(paths))
589 for i, v := range paths {
590 res[i] = filepath.Clean(v) + "/"
591 }
592 return res
593}
594
595func fieldNamesForProperties(propertyNames string) []string {
596 names := strings.Split(propertyNames, ".")
597 for i, v := range names {
598 names[i] = proptools.FieldNameForProperty(v)
599 }
600 return names
601}
602
Steven Moreland65b3fd92017-12-06 14:18:35 -0800603func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
604 for _, v := range props {
605 if hasProperty(properties, v) {
606 return true
607 }
608 }
609 return false
610}
611
612func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
613 for _, v := range props {
614 if !hasProperty(properties, v) {
615 return false
616 }
617 }
618 return true
619}
620
621func hasProperty(properties []interface{}, prop ruleProperty) bool {
622 for _, propertyStruct := range properties {
623 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
624 for _, v := range prop.fields {
625 if !propertiesValue.IsValid() {
626 break
627 }
628 propertiesValue = propertiesValue.FieldByName(v)
629 }
630 if !propertiesValue.IsValid() {
631 continue
632 }
633
Paul Duffin73bf0542019-07-12 14:12:49 +0100634 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100635 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800636 }
637
638 if matchValue(propertiesValue, check) {
639 return true
640 }
641 }
642 return false
643}
644
645func matchValue(value reflect.Value, check func(string) bool) bool {
646 if !value.IsValid() {
647 return false
648 }
649
650 if value.Kind() == reflect.Ptr {
651 if value.IsNil() {
652 return check("")
653 }
654 value = value.Elem()
655 }
656
657 switch value.Kind() {
658 case reflect.String:
659 return check(value.String())
660 case reflect.Bool:
661 return check(strconv.FormatBool(value.Bool()))
662 case reflect.Int:
663 return check(strconv.FormatInt(value.Int(), 10))
664 case reflect.Slice:
665 slice, ok := value.Interface().([]string)
666 if !ok {
667 panic("Can only handle slice of string")
668 }
669 for _, v := range slice {
670 if check(v) {
671 return true
672 }
673 }
674 return false
675 }
676
677 panic("Can't handle type: " + value.Kind().String())
678}
Paul Duffin115445b2019-08-07 15:31:07 +0100679
680var neverallowRulesKey = NewOnceKey("neverallowRules")
681
682func neverallowRules(config Config) []Rule {
683 return config.Once(neverallowRulesKey, func() interface{} {
684 // No test rules were set by setTestNeverallowRules, use the global rules
685 return neverallows
686 }).([]Rule)
687}
688
689// Overrides the default neverallow rules for the supplied config.
690//
691// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100692func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100693 config.Once(neverallowRulesKey, func() interface{} { return testRules })
694}
Paul Duffin45338f02021-03-30 23:07:52 +0100695
696// Prepares for a test by setting neverallow rules and enabling the mutator.
697//
698// If the supplied rules are nil then the default rules are used.
699func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
700 return GroupFixturePreparers(
701 FixtureModifyConfig(func(config Config) {
702 if testRules != nil {
703 setTestNeverallowRules(config, testRules)
704 }
705 }),
706 FixtureRegisterWithContext(func(ctx RegistrationContext) {
707 ctx.PostDepsMutators(registerNeverallowMutator)
708 }),
709 )
710}