blob: cef73fb9c896cca8003946c75350953822533138 [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 Duffin730f2a52019-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 Duffin730f2a52019-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 Duffin730f2a52019-06-27 14:08:51 +010048var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080049
Paul Duffin730f2a52019-06-27 14:08:51 +010050func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010051 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010052 AddNeverAllowRules(createTrebleRules()...)
53 AddNeverAllowRules(createLibcoreRules()...)
54 AddNeverAllowRules(createMediaRules()...)
55 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010056}
Steven Moreland65b3fd92017-12-06 14:18:35 -080057
Paul Duffin730f2a52019-06-27 14:08:51 +010058// Add a NeverAllow rule to the set of rules to apply.
59func AddNeverAllowRules(rules ...Rule) {
60 neverallows = append(neverallows, rules...)
61}
62
Paul Duffinc8111702019-07-22 12:13:55 +010063func createIncludeDirsRules() []Rule {
64 // The list of paths that cannot be referenced using include_dirs
65 paths := []string{
66 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000067 "art/libnativebridge",
68 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010069 "libcore",
70 "libnativehelper",
71 "external/apache-harmony",
72 "external/apache-xml",
73 "external/boringssl",
74 "external/bouncycastle",
75 "external/conscrypt",
76 "external/icu",
77 "external/okhttp",
78 "external/vixl",
79 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010080 }
81
82 // Create a composite matcher that will match if the value starts with any of the restricted
83 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
84 // XY.
85 rules := make([]Rule, 0, len(paths))
86 for _, path := range paths {
87 rule :=
88 NeverAllow().
89 WithMatcher("include_dirs", StartsWith(path+"/")).
90 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
91 " to use alternate mechanisms and so can no longer be used.")
92
93 rules = append(rules, rule)
94 }
95
96 return rules
97}
98
Paul Duffin730f2a52019-06-27 14:08:51 +010099func createTrebleRules() []Rule {
100 return []Rule{
101 NeverAllow().
102 In("vendor", "device").
103 With("vndk.enabled", "true").
104 Without("vendor", "true").
105 Because("the VNDK can never contain a library that is device dependent."),
106 NeverAllow().
107 With("vndk.enabled", "true").
108 Without("vendor", "true").
109 Without("owner", "").
110 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800111
Neil Fullerdf5f3562018-10-21 17:19:10 +0100112 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100113 NeverAllow().
114 Without("name", "libhidltransport-impl-internal").
115 With("product_variables.enforce_vintf_manifest.cflags", "*").
116 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100117
118 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100119 NeverAllow().
120 Without("name", "libc_bionic_ndk").
121 With("product_variables.treble_linker_namespaces.cflags", "*").
122 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100123
124 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100125 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100126 }
127}
128
Paul Duffin730f2a52019-06-27 14:08:51 +0100129func createLibcoreRules() []Rule {
Neil Fullerdf5f3562018-10-21 17:19:10 +0100130 var coreLibraryProjects = []string{
131 "libcore",
132 "external/apache-harmony",
133 "external/apache-xml",
134 "external/bouncycastle",
135 "external/conscrypt",
136 "external/icu",
137 "external/okhttp",
138 "external/wycheproof",
139 }
140
Paul Duffina3d09862019-06-11 13:40:47 +0100141 // Core library constraints. The sdk_version: "none" can only be used in core library projects.
142 // Access to core library targets is restricted using visibility rules.
Paul Duffin730f2a52019-06-27 14:08:51 +0100143 rules := []Rule{
144 NeverAllow().
145 NotIn(coreLibraryProjects...).
146 With("sdk_version", "none"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100147 }
148
Neil Fullerdf5f3562018-10-21 17:19:10 +0100149 return rules
Steven Moreland65b3fd92017-12-06 14:18:35 -0800150}
151
Paul Duffin730f2a52019-06-27 14:08:51 +0100152func createMediaRules() []Rule {
153 return []Rule{
154 NeverAllow().
155 With("libs", "updatable-media").
156 Because("updatable-media includes private APIs. Use updatable_media_stubs instead."),
Dongwon Kang50a299f2019-02-04 09:00:51 -0800157 }
158}
159
Paul Duffin730f2a52019-06-27 14:08:51 +0100160func createJavaDeviceForHostRules() []Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800161 javaDeviceForHostProjectsWhitelist := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700162 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800163 "external/robolectric-shadows",
164 "framework/layoutlib",
165 }
166
Paul Duffin730f2a52019-06-27 14:08:51 +0100167 return []Rule{
168 NeverAllow().
169 NotIn(javaDeviceForHostProjectsWhitelist...).
170 ModuleType("java_device_for_host", "java_host_for_device").
171 Because("java_device_for_host can only be used in whitelisted projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800172 }
173}
174
Steven Moreland65b3fd92017-12-06 14:18:35 -0800175func neverallowMutator(ctx BottomUpMutatorContext) {
176 m, ok := ctx.Module().(Module)
177 if !ok {
178 return
179 }
180
181 dir := ctx.ModuleDir() + "/"
182 properties := m.GetProperties()
183
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100184 osClass := ctx.Module().Target().Os.Class
185
Paul Duffin115445b2019-08-07 15:31:07 +0100186 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100187 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800188 if !n.appliesToPath(dir) {
189 continue
190 }
191
Colin Crossfd4f7432019-03-05 15:06:16 -0800192 if !n.appliesToModuleType(ctx.ModuleType()) {
193 continue
194 }
195
Steven Moreland65b3fd92017-12-06 14:18:35 -0800196 if !n.appliesToProperties(properties) {
197 continue
198 }
199
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100200 if !n.appliesToOsClass(osClass) {
201 continue
202 }
203
Paul Duffin35781882019-07-25 15:41:09 +0100204 if !n.appliesToDirectDeps(ctx) {
205 continue
206 }
207
Steven Moreland65b3fd92017-12-06 14:18:35 -0800208 ctx.ModuleErrorf("violates " + n.String())
209 }
210}
211
Paul Duffin73bf0542019-07-12 14:12:49 +0100212type ValueMatcher interface {
213 test(string) bool
214 String() string
215}
216
217type equalMatcher struct {
218 expected string
219}
220
221func (m *equalMatcher) test(value string) bool {
222 return m.expected == value
223}
224
225func (m *equalMatcher) String() string {
226 return "=" + m.expected
227}
228
229type anyMatcher struct {
230}
231
232func (m *anyMatcher) test(value string) bool {
233 return true
234}
235
236func (m *anyMatcher) String() string {
237 return "=*"
238}
239
240var anyMatcherInstance = &anyMatcher{}
241
Paul Duffinc8111702019-07-22 12:13:55 +0100242type startsWithMatcher struct {
243 prefix string
244}
245
246func (m *startsWithMatcher) test(value string) bool {
247 return strings.HasPrefix(value, m.prefix)
248}
249
250func (m *startsWithMatcher) String() string {
251 return ".starts-with(" + m.prefix + ")"
252}
253
Steven Moreland65b3fd92017-12-06 14:18:35 -0800254type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100255 fields []string // e.x.: Vndk.Enabled
256 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800257}
258
Paul Duffin730f2a52019-06-27 14:08:51 +0100259// A NeverAllow rule.
260type Rule interface {
261 In(path ...string) Rule
262
263 NotIn(path ...string) Rule
264
Paul Duffin35781882019-07-25 15:41:09 +0100265 InDirectDeps(deps ...string) Rule
266
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100267 WithOsClass(osClasses ...OsClass) Rule
268
Paul Duffin730f2a52019-06-27 14:08:51 +0100269 ModuleType(types ...string) Rule
270
271 NotModuleType(types ...string) Rule
272
273 With(properties, value string) Rule
274
Paul Duffinc8111702019-07-22 12:13:55 +0100275 WithMatcher(properties string, matcher ValueMatcher) Rule
276
Paul Duffin730f2a52019-06-27 14:08:51 +0100277 Without(properties, value string) Rule
278
Paul Duffinc8111702019-07-22 12:13:55 +0100279 WithoutMatcher(properties string, matcher ValueMatcher) Rule
280
Paul Duffin730f2a52019-06-27 14:08:51 +0100281 Because(reason string) Rule
282}
283
Steven Moreland65b3fd92017-12-06 14:18:35 -0800284type rule struct {
285 // User string for why this is a thing.
286 reason string
287
288 paths []string
289 unlessPaths []string
290
Paul Duffin35781882019-07-25 15:41:09 +0100291 directDeps map[string]bool
292
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100293 osClasses []OsClass
294
Colin Crossfd4f7432019-03-05 15:06:16 -0800295 moduleTypes []string
296 unlessModuleTypes []string
297
Steven Moreland65b3fd92017-12-06 14:18:35 -0800298 props []ruleProperty
299 unlessProps []ruleProperty
300}
301
Paul Duffin730f2a52019-06-27 14:08:51 +0100302// Create a new NeverAllow rule.
303func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100304 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800305}
Colin Crossfd4f7432019-03-05 15:06:16 -0800306
Paul Duffin730f2a52019-06-27 14:08:51 +0100307func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800308 r.paths = append(r.paths, cleanPaths(path)...)
309 return r
310}
Colin Crossfd4f7432019-03-05 15:06:16 -0800311
Paul Duffin730f2a52019-06-27 14:08:51 +0100312func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800313 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
314 return r
315}
Colin Crossfd4f7432019-03-05 15:06:16 -0800316
Paul Duffin35781882019-07-25 15:41:09 +0100317func (r *rule) InDirectDeps(deps ...string) Rule {
318 for _, d := range deps {
319 r.directDeps[d] = true
320 }
321 return r
322}
323
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100324func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
325 r.osClasses = append(r.osClasses, osClasses...)
326 return r
327}
328
Paul Duffin730f2a52019-06-27 14:08:51 +0100329func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800330 r.moduleTypes = append(r.moduleTypes, types...)
331 return r
332}
333
Paul Duffin730f2a52019-06-27 14:08:51 +0100334func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800335 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
336 return r
337}
338
Paul Duffin730f2a52019-06-27 14:08:51 +0100339func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100340 return r.WithMatcher(properties, selectMatcher(value))
341}
342
343func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800344 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100345 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100346 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800347 })
348 return r
349}
Colin Crossfd4f7432019-03-05 15:06:16 -0800350
Paul Duffin730f2a52019-06-27 14:08:51 +0100351func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100352 return r.WithoutMatcher(properties, selectMatcher(value))
353}
354
355func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800356 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100357 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100358 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800359 })
360 return r
361}
Colin Crossfd4f7432019-03-05 15:06:16 -0800362
Paul Duffin73bf0542019-07-12 14:12:49 +0100363func selectMatcher(expected string) ValueMatcher {
364 if expected == "*" {
365 return anyMatcherInstance
366 }
367 return &equalMatcher{expected: expected}
368}
369
Paul Duffin730f2a52019-06-27 14:08:51 +0100370func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800371 r.reason = reason
372 return r
373}
374
375func (r *rule) String() string {
376 s := "neverallow"
377 for _, v := range r.paths {
378 s += " dir:" + v + "*"
379 }
380 for _, v := range r.unlessPaths {
381 s += " -dir:" + v + "*"
382 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800383 for _, v := range r.moduleTypes {
384 s += " type:" + v
385 }
386 for _, v := range r.unlessModuleTypes {
387 s += " -type:" + v
388 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800389 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100390 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800391 }
392 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100393 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800394 }
Paul Duffin35781882019-07-25 15:41:09 +0100395 for k := range r.directDeps {
396 s += " deps:" + k
397 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100398 for _, v := range r.osClasses {
399 s += " os:" + v.String()
400 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800401 if len(r.reason) != 0 {
402 s += " which is restricted because " + r.reason
403 }
404 return s
405}
406
407func (r *rule) appliesToPath(dir string) bool {
408 includePath := len(r.paths) == 0 || hasAnyPrefix(dir, r.paths)
409 excludePath := hasAnyPrefix(dir, r.unlessPaths)
410 return includePath && !excludePath
411}
412
Paul Duffin35781882019-07-25 15:41:09 +0100413func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
414 if len(r.directDeps) == 0 {
415 return true
416 }
417
418 matches := false
419 ctx.VisitDirectDeps(func(m Module) {
420 if !matches {
421 name := ctx.OtherModuleName(m)
422 matches = r.directDeps[name]
423 }
424 })
425
426 return matches
427}
428
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100429func (r *rule) appliesToOsClass(osClass OsClass) bool {
430 if len(r.osClasses) == 0 {
431 return true
432 }
433
434 for _, c := range r.osClasses {
435 if c == osClass {
436 return true
437 }
438 }
439
440 return false
441}
442
Colin Crossfd4f7432019-03-05 15:06:16 -0800443func (r *rule) appliesToModuleType(moduleType string) bool {
444 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
445}
446
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447func (r *rule) appliesToProperties(properties []interface{}) bool {
448 includeProps := hasAllProperties(properties, r.props)
449 excludeProps := hasAnyProperty(properties, r.unlessProps)
450 return includeProps && !excludeProps
451}
452
Paul Duffinc8111702019-07-22 12:13:55 +0100453func StartsWith(prefix string) ValueMatcher {
454 return &startsWithMatcher{prefix}
455}
456
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457// assorted utils
458
459func cleanPaths(paths []string) []string {
460 res := make([]string, len(paths))
461 for i, v := range paths {
462 res[i] = filepath.Clean(v) + "/"
463 }
464 return res
465}
466
467func fieldNamesForProperties(propertyNames string) []string {
468 names := strings.Split(propertyNames, ".")
469 for i, v := range names {
470 names[i] = proptools.FieldNameForProperty(v)
471 }
472 return names
473}
474
475func hasAnyPrefix(s string, prefixes []string) bool {
476 for _, prefix := range prefixes {
477 if strings.HasPrefix(s, prefix) {
478 return true
479 }
480 }
481 return false
482}
483
484func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
485 for _, v := range props {
486 if hasProperty(properties, v) {
487 return true
488 }
489 }
490 return false
491}
492
493func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
494 for _, v := range props {
495 if !hasProperty(properties, v) {
496 return false
497 }
498 }
499 return true
500}
501
502func hasProperty(properties []interface{}, prop ruleProperty) bool {
503 for _, propertyStruct := range properties {
504 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
505 for _, v := range prop.fields {
506 if !propertiesValue.IsValid() {
507 break
508 }
509 propertiesValue = propertiesValue.FieldByName(v)
510 }
511 if !propertiesValue.IsValid() {
512 continue
513 }
514
Paul Duffin73bf0542019-07-12 14:12:49 +0100515 check := func(value string) bool {
516 return prop.matcher.test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800517 }
518
519 if matchValue(propertiesValue, check) {
520 return true
521 }
522 }
523 return false
524}
525
526func matchValue(value reflect.Value, check func(string) bool) bool {
527 if !value.IsValid() {
528 return false
529 }
530
531 if value.Kind() == reflect.Ptr {
532 if value.IsNil() {
533 return check("")
534 }
535 value = value.Elem()
536 }
537
538 switch value.Kind() {
539 case reflect.String:
540 return check(value.String())
541 case reflect.Bool:
542 return check(strconv.FormatBool(value.Bool()))
543 case reflect.Int:
544 return check(strconv.FormatInt(value.Int(), 10))
545 case reflect.Slice:
546 slice, ok := value.Interface().([]string)
547 if !ok {
548 panic("Can only handle slice of string")
549 }
550 for _, v := range slice {
551 if check(v) {
552 return true
553 }
554 }
555 return false
556 }
557
558 panic("Can't handle type: " + value.Kind().String())
559}
Paul Duffin115445b2019-08-07 15:31:07 +0100560
561var neverallowRulesKey = NewOnceKey("neverallowRules")
562
563func neverallowRules(config Config) []Rule {
564 return config.Once(neverallowRulesKey, func() interface{} {
565 // No test rules were set by setTestNeverallowRules, use the global rules
566 return neverallows
567 }).([]Rule)
568}
569
570// Overrides the default neverallow rules for the supplied config.
571//
572// For testing only.
573func setTestNeverallowRules(config Config, testRules []Rule) {
574 config.Once(neverallowRulesKey, func() interface{} { return testRules })
575}