blob: 3d1454ef2e83ff75f9869f4c31b38d4cba870e07 [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"
20 "strconv"
21 "strings"
22
23 "github.com/google/blueprint/proptools"
24)
25
26// "neverallow" rules for the build system.
27//
28// This allows things which aren't related to the build system and are enforced
29// for sanity, in progress code refactors, or policy to be expressed in a
30// straightforward away disjoint from implementations and tests which should
31// work regardless of these restrictions.
32//
33// A module is disallowed if all of the following are true:
Paul Duffinaebc02a2019-06-27 14:08:51 +010034// - it is in one of the "In" paths
35// - it is not in one of the "NotIn" paths
36// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080037// - - values are matched in their entirety
38// - - nil is interpreted as an empty string
39// - - nested properties are separated with a '.'
40// - - if the property is a list, any of the values in the list being matches
41// counts as a match
Paul Duffinaebc02a2019-06-27 14:08:51 +010042// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080043
44func registerNeverallowMutator(ctx RegisterMutatorsContext) {
45 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
46}
47
Paul Duffinaebc02a2019-06-27 14:08:51 +010048var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080049
Paul Duffinaebc02a2019-06-27 14:08:51 +010050func init() {
Paul Duffin2ac2bef2019-07-16 14:18:22 +010051 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffinaebc02a2019-06-27 14:08:51 +010052 AddNeverAllowRules(createTrebleRules()...)
53 AddNeverAllowRules(createLibcoreRules()...)
54 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010055}
Steven Moreland65b3fd92017-12-06 14:18:35 -080056
Paul Duffinaebc02a2019-06-27 14:08:51 +010057// Add a NeverAllow rule to the set of rules to apply.
58func AddNeverAllowRules(rules ...Rule) {
59 neverallows = append(neverallows, rules...)
60}
61
Paul Duffin2ac2bef2019-07-16 14:18:22 +010062func createIncludeDirsRules() []Rule {
63 // The list of paths that cannot be referenced using include_dirs
64 paths := []string{
65 "art",
66 "libcore",
67 "libnativehelper",
68 "external/apache-harmony",
69 "external/apache-xml",
70 "external/boringssl",
71 "external/bouncycastle",
72 "external/conscrypt",
73 "external/icu",
74 "external/okhttp",
75 "external/vixl",
76 "external/wycheproof",
77 "system/core/libnativebridge",
78 "system/core/libnativehelper",
79 }
80
81 // Create a composite matcher that will match if the value starts with any of the restricted
82 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
83 // XY.
84 rules := make([]Rule, 0, len(paths))
85 for _, path := range paths {
86 rule :=
87 NeverAllow().
88 WithMatcher("include_dirs", StartsWith(path+"/")).
89 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
90 " to use alternate mechanisms and so can no longer be used.")
91
92 rules = append(rules, rule)
93 }
94
95 return rules
96}
97
Paul Duffinaebc02a2019-06-27 14:08:51 +010098func createTrebleRules() []Rule {
99 return []Rule{
100 NeverAllow().
101 In("vendor", "device").
102 With("vndk.enabled", "true").
103 Without("vendor", "true").
104 Because("the VNDK can never contain a library that is device dependent."),
105 NeverAllow().
106 With("vndk.enabled", "true").
107 Without("vendor", "true").
108 Without("owner", "").
109 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800110
Neil Fullerdf5f3562018-10-21 17:19:10 +0100111 // TODO(b/67974785): always enforce the manifest
Paul Duffinaebc02a2019-06-27 14:08:51 +0100112 NeverAllow().
113 Without("name", "libhidltransport").
114 With("product_variables.enforce_vintf_manifest.cflags", "*").
115 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100116
117 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffinaebc02a2019-06-27 14:08:51 +0100118 NeverAllow().
119 Without("name", "libc_bionic_ndk").
120 With("product_variables.treble_linker_namespaces.cflags", "*").
121 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100122
123 // Example:
Paul Duffinaebc02a2019-06-27 14:08:51 +0100124 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100125 }
126}
127
Paul Duffinaebc02a2019-06-27 14:08:51 +0100128func createLibcoreRules() []Rule {
Neil Fullerdf5f3562018-10-21 17:19:10 +0100129 var coreLibraryProjects = []string{
130 "libcore",
131 "external/apache-harmony",
132 "external/apache-xml",
133 "external/bouncycastle",
134 "external/conscrypt",
135 "external/icu",
136 "external/okhttp",
137 "external/wycheproof",
Paul Duffinb6c6bdd2019-06-07 11:43:55 +0100138
139 // Not really a core library but still needs access to same capabilities.
140 "development",
Neil Fullerdf5f3562018-10-21 17:19:10 +0100141 }
142
Paul Duffina3d09862019-06-11 13:40:47 +0100143 // Core library constraints. The sdk_version: "none" can only be used in core library projects.
144 // Access to core library targets is restricted using visibility rules.
Paul Duffinaebc02a2019-06-27 14:08:51 +0100145 rules := []Rule{
146 NeverAllow().
147 NotIn(coreLibraryProjects...).
148 With("sdk_version", "none"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100149 }
150
Neil Fullerdf5f3562018-10-21 17:19:10 +0100151 return rules
Steven Moreland65b3fd92017-12-06 14:18:35 -0800152}
153
Paul Duffinaebc02a2019-06-27 14:08:51 +0100154func createJavaDeviceForHostRules() []Rule {
Colin Crossc35c5f92019-03-05 15:06:16 -0800155 javaDeviceForHostProjectsWhitelist := []string{
Colin Cross97add502019-04-11 14:07:38 -0700156 "external/guava",
Colin Crossc35c5f92019-03-05 15:06:16 -0800157 "external/robolectric-shadows",
158 "framework/layoutlib",
159 }
160
Paul Duffinaebc02a2019-06-27 14:08:51 +0100161 return []Rule{
162 NeverAllow().
163 NotIn(javaDeviceForHostProjectsWhitelist...).
164 ModuleType("java_device_for_host", "java_host_for_device").
165 Because("java_device_for_host can only be used in whitelisted projects"),
Colin Crossc35c5f92019-03-05 15:06:16 -0800166 }
167}
168
Steven Moreland65b3fd92017-12-06 14:18:35 -0800169func neverallowMutator(ctx BottomUpMutatorContext) {
170 m, ok := ctx.Module().(Module)
171 if !ok {
172 return
173 }
174
175 dir := ctx.ModuleDir() + "/"
176 properties := m.GetProperties()
177
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100178 osClass := ctx.Module().Target().Os.Class
179
Paul Duffin115445b2019-08-07 15:31:07 +0100180 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffinaebc02a2019-06-27 14:08:51 +0100181 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800182 if !n.appliesToPath(dir) {
183 continue
184 }
185
Colin Crossc35c5f92019-03-05 15:06:16 -0800186 if !n.appliesToModuleType(ctx.ModuleType()) {
187 continue
188 }
189
Steven Moreland65b3fd92017-12-06 14:18:35 -0800190 if !n.appliesToProperties(properties) {
191 continue
192 }
193
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100194 if !n.appliesToOsClass(osClass) {
195 continue
196 }
197
Paul Duffin35781882019-07-25 15:41:09 +0100198 if !n.appliesToDirectDeps(ctx) {
199 continue
200 }
201
Steven Moreland65b3fd92017-12-06 14:18:35 -0800202 ctx.ModuleErrorf("violates " + n.String())
203 }
204}
205
Paul Duffin73bf0542019-07-12 14:12:49 +0100206type ValueMatcher interface {
207 test(string) bool
208 String() string
209}
210
211type equalMatcher struct {
212 expected string
213}
214
215func (m *equalMatcher) test(value string) bool {
216 return m.expected == value
217}
218
219func (m *equalMatcher) String() string {
220 return "=" + m.expected
221}
222
223type anyMatcher struct {
224}
225
226func (m *anyMatcher) test(value string) bool {
227 return true
228}
229
230func (m *anyMatcher) String() string {
231 return "=*"
232}
233
234var anyMatcherInstance = &anyMatcher{}
235
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100236type startsWithMatcher struct {
237 prefix string
238}
239
240func (m *startsWithMatcher) test(value string) bool {
241 return strings.HasPrefix(value, m.prefix)
242}
243
244func (m *startsWithMatcher) String() string {
245 return ".starts-with(" + m.prefix + ")"
246}
247
Steven Moreland65b3fd92017-12-06 14:18:35 -0800248type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100249 fields []string // e.x.: Vndk.Enabled
250 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800251}
252
Paul Duffinaebc02a2019-06-27 14:08:51 +0100253// A NeverAllow rule.
254type Rule interface {
255 In(path ...string) Rule
256
257 NotIn(path ...string) Rule
258
Paul Duffin35781882019-07-25 15:41:09 +0100259 InDirectDeps(deps ...string) Rule
260
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100261 WithOsClass(osClasses ...OsClass) Rule
262
Paul Duffinaebc02a2019-06-27 14:08:51 +0100263 ModuleType(types ...string) Rule
264
265 NotModuleType(types ...string) Rule
266
267 With(properties, value string) Rule
268
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100269 WithMatcher(properties string, matcher ValueMatcher) Rule
270
Paul Duffinaebc02a2019-06-27 14:08:51 +0100271 Without(properties, value string) Rule
272
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100273 WithoutMatcher(properties string, matcher ValueMatcher) Rule
274
Paul Duffinaebc02a2019-06-27 14:08:51 +0100275 Because(reason string) Rule
276}
277
Steven Moreland65b3fd92017-12-06 14:18:35 -0800278type rule struct {
279 // User string for why this is a thing.
280 reason string
281
282 paths []string
283 unlessPaths []string
284
Paul Duffin35781882019-07-25 15:41:09 +0100285 directDeps map[string]bool
286
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100287 osClasses []OsClass
288
Colin Crossc35c5f92019-03-05 15:06:16 -0800289 moduleTypes []string
290 unlessModuleTypes []string
291
Steven Moreland65b3fd92017-12-06 14:18:35 -0800292 props []ruleProperty
293 unlessProps []ruleProperty
294}
295
Paul Duffinaebc02a2019-06-27 14:08:51 +0100296// Create a new NeverAllow rule.
297func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100298 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800299}
Colin Crossc35c5f92019-03-05 15:06:16 -0800300
Paul Duffinaebc02a2019-06-27 14:08:51 +0100301func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800302 r.paths = append(r.paths, cleanPaths(path)...)
303 return r
304}
Colin Crossc35c5f92019-03-05 15:06:16 -0800305
Paul Duffinaebc02a2019-06-27 14:08:51 +0100306func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800307 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
308 return r
309}
Colin Crossc35c5f92019-03-05 15:06:16 -0800310
Paul Duffin35781882019-07-25 15:41:09 +0100311func (r *rule) InDirectDeps(deps ...string) Rule {
312 for _, d := range deps {
313 r.directDeps[d] = true
314 }
315 return r
316}
317
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100318func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
319 r.osClasses = append(r.osClasses, osClasses...)
320 return r
321}
322
Paul Duffinaebc02a2019-06-27 14:08:51 +0100323func (r *rule) ModuleType(types ...string) Rule {
Colin Crossc35c5f92019-03-05 15:06:16 -0800324 r.moduleTypes = append(r.moduleTypes, types...)
325 return r
326}
327
Paul Duffinaebc02a2019-06-27 14:08:51 +0100328func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossc35c5f92019-03-05 15:06:16 -0800329 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
330 return r
331}
332
Paul Duffinaebc02a2019-06-27 14:08:51 +0100333func (r *rule) With(properties, value string) Rule {
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100334 return r.WithMatcher(properties, selectMatcher(value))
335}
336
337func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800338 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100339 fields: fieldNamesForProperties(properties),
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100340 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800341 })
342 return r
343}
Colin Crossc35c5f92019-03-05 15:06:16 -0800344
Paul Duffinaebc02a2019-06-27 14:08:51 +0100345func (r *rule) Without(properties, value string) Rule {
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100346 return r.WithoutMatcher(properties, selectMatcher(value))
347}
348
349func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800350 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100351 fields: fieldNamesForProperties(properties),
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100352 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800353 })
354 return r
355}
Colin Crossc35c5f92019-03-05 15:06:16 -0800356
Paul Duffin73bf0542019-07-12 14:12:49 +0100357func selectMatcher(expected string) ValueMatcher {
358 if expected == "*" {
359 return anyMatcherInstance
360 }
361 return &equalMatcher{expected: expected}
362}
363
Paul Duffinaebc02a2019-06-27 14:08:51 +0100364func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800365 r.reason = reason
366 return r
367}
368
369func (r *rule) String() string {
370 s := "neverallow"
371 for _, v := range r.paths {
372 s += " dir:" + v + "*"
373 }
374 for _, v := range r.unlessPaths {
375 s += " -dir:" + v + "*"
376 }
Colin Crossc35c5f92019-03-05 15:06:16 -0800377 for _, v := range r.moduleTypes {
378 s += " type:" + v
379 }
380 for _, v := range r.unlessModuleTypes {
381 s += " -type:" + v
382 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800383 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100384 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385 }
386 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100387 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800388 }
Paul Duffin35781882019-07-25 15:41:09 +0100389 for k := range r.directDeps {
390 s += " deps:" + k
391 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100392 for _, v := range r.osClasses {
393 s += " os:" + v.String()
394 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800395 if len(r.reason) != 0 {
396 s += " which is restricted because " + r.reason
397 }
398 return s
399}
400
401func (r *rule) appliesToPath(dir string) bool {
402 includePath := len(r.paths) == 0 || hasAnyPrefix(dir, r.paths)
403 excludePath := hasAnyPrefix(dir, r.unlessPaths)
404 return includePath && !excludePath
405}
406
Paul Duffin35781882019-07-25 15:41:09 +0100407func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
408 if len(r.directDeps) == 0 {
409 return true
410 }
411
412 matches := false
413 ctx.VisitDirectDeps(func(m Module) {
414 if !matches {
415 name := ctx.OtherModuleName(m)
416 matches = r.directDeps[name]
417 }
418 })
419
420 return matches
421}
422
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100423func (r *rule) appliesToOsClass(osClass OsClass) bool {
424 if len(r.osClasses) == 0 {
425 return true
426 }
427
428 for _, c := range r.osClasses {
429 if c == osClass {
430 return true
431 }
432 }
433
434 return false
435}
436
Colin Crossc35c5f92019-03-05 15:06:16 -0800437func (r *rule) appliesToModuleType(moduleType string) bool {
438 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
439}
440
Steven Moreland65b3fd92017-12-06 14:18:35 -0800441func (r *rule) appliesToProperties(properties []interface{}) bool {
442 includeProps := hasAllProperties(properties, r.props)
443 excludeProps := hasAnyProperty(properties, r.unlessProps)
444 return includeProps && !excludeProps
445}
446
Paul Duffin2ac2bef2019-07-16 14:18:22 +0100447func StartsWith(prefix string) ValueMatcher {
448 return &startsWithMatcher{prefix}
449}
450
Steven Moreland65b3fd92017-12-06 14:18:35 -0800451// assorted utils
452
453func cleanPaths(paths []string) []string {
454 res := make([]string, len(paths))
455 for i, v := range paths {
456 res[i] = filepath.Clean(v) + "/"
457 }
458 return res
459}
460
461func fieldNamesForProperties(propertyNames string) []string {
462 names := strings.Split(propertyNames, ".")
463 for i, v := range names {
464 names[i] = proptools.FieldNameForProperty(v)
465 }
466 return names
467}
468
469func hasAnyPrefix(s string, prefixes []string) bool {
470 for _, prefix := range prefixes {
471 if strings.HasPrefix(s, prefix) {
472 return true
473 }
474 }
475 return false
476}
477
478func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
479 for _, v := range props {
480 if hasProperty(properties, v) {
481 return true
482 }
483 }
484 return false
485}
486
487func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
488 for _, v := range props {
489 if !hasProperty(properties, v) {
490 return false
491 }
492 }
493 return true
494}
495
496func hasProperty(properties []interface{}, prop ruleProperty) bool {
497 for _, propertyStruct := range properties {
498 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
499 for _, v := range prop.fields {
500 if !propertiesValue.IsValid() {
501 break
502 }
503 propertiesValue = propertiesValue.FieldByName(v)
504 }
505 if !propertiesValue.IsValid() {
506 continue
507 }
508
Paul Duffin73bf0542019-07-12 14:12:49 +0100509 check := func(value string) bool {
510 return prop.matcher.test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800511 }
512
513 if matchValue(propertiesValue, check) {
514 return true
515 }
516 }
517 return false
518}
519
520func matchValue(value reflect.Value, check func(string) bool) bool {
521 if !value.IsValid() {
522 return false
523 }
524
525 if value.Kind() == reflect.Ptr {
526 if value.IsNil() {
527 return check("")
528 }
529 value = value.Elem()
530 }
531
532 switch value.Kind() {
533 case reflect.String:
534 return check(value.String())
535 case reflect.Bool:
536 return check(strconv.FormatBool(value.Bool()))
537 case reflect.Int:
538 return check(strconv.FormatInt(value.Int(), 10))
539 case reflect.Slice:
540 slice, ok := value.Interface().([]string)
541 if !ok {
542 panic("Can only handle slice of string")
543 }
544 for _, v := range slice {
545 if check(v) {
546 return true
547 }
548 }
549 return false
550 }
551
552 panic("Can't handle type: " + value.Kind().String())
553}
Paul Duffin115445b2019-08-07 15:31:07 +0100554
555var neverallowRulesKey = NewOnceKey("neverallowRules")
556
557func neverallowRules(config Config) []Rule {
558 return config.Once(neverallowRulesKey, func() interface{} {
559 // No test rules were set by setTestNeverallowRules, use the global rules
560 return neverallows
561 }).([]Rule)
562}
563
564// Overrides the default neverallow rules for the supplied config.
565//
566// For testing only.
567func setTestNeverallowRules(config Config, testRules []Rule) {
568 config.Once(neverallowRulesKey, func() interface{} { return testRules })
569}