blob: 79a534f56b346a711d60ffe77559a2db13634b1d [file] [log] [blame]
Paul Duffin2e61fa62019-03-28 14:10:57 +00001// Copyright 2019 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 "fmt"
19 "regexp"
Paul Duffin157f40f2020-09-29 16:01:08 +010020 "sort"
Paul Duffin2e61fa62019-03-28 14:10:57 +000021 "strings"
22 "sync"
Paul Duffin78ac5b92020-01-14 12:42:08 +000023
24 "github.com/google/blueprint"
Paul Duffin2e61fa62019-03-28 14:10:57 +000025)
26
27// Enforces visibility rules between modules.
28//
Paul Duffine2453c72019-05-31 14:00:04 +010029// Multi stage process:
30// * First stage works bottom up, before defaults expansion, to check the syntax of the visibility
31// rules that have been specified.
32//
33// * Second stage works bottom up to extract the package info for each package and store them in a
34// map by package name. See package.go for functionality for this.
35//
36// * Third stage works bottom up to extract visibility information from the modules, parse it,
Paul Duffin2e61fa62019-03-28 14:10:57 +000037// create visibilityRule structures and store them in a map keyed by the module's
38// qualifiedModuleName instance, i.e. //<pkg>:<name>. The map is stored in the context rather
39// than a global variable for testing. Each test has its own Config so they do not share a map
Paul Duffine2453c72019-05-31 14:00:04 +010040// and so can be run in parallel. If a module has no visibility specified then it uses the
41// default package visibility if specified.
Paul Duffin2e61fa62019-03-28 14:10:57 +000042//
Paul Duffine2453c72019-05-31 14:00:04 +010043// * Fourth stage works top down and iterates over all the deps for each module. If the dep is in
Paul Duffin2e61fa62019-03-28 14:10:57 +000044// the same package then it is automatically visible. Otherwise, for each dep it first extracts
45// its visibilityRule from the config map. If one could not be found then it assumes that it is
46// publicly visible. Otherwise, it calls the visibility rule to check that the module can see
47// the dependency. If it cannot then an error is reported.
48//
49// TODO(b/130631145) - Make visibility work properly with prebuilts.
Paul Duffin2e61fa62019-03-28 14:10:57 +000050
51// Patterns for the values that can be specified in visibility property.
52const (
53 packagePattern = `//([^/:]+(?:/[^/:]+)*)`
54 namePattern = `:([^/:]+)`
55 visibilityRulePattern = `^(?:` + packagePattern + `)?(?:` + namePattern + `)?$`
56)
57
58var visibilityRuleRegexp = regexp.MustCompile(visibilityRulePattern)
59
Cole Faust894bb3b2024-02-07 11:28:26 -080060type visibilityModuleReference struct {
61 name qualifiedModuleName
62 isPartitionModule bool
63}
64
65func createVisibilityModuleReference(name, dir, typ string) visibilityModuleReference {
66 isPartitionModule := false
67 switch typ {
68 case "android_filesystem", "android_system_image":
69 isPartitionModule = true
70 }
71 return visibilityModuleReference{
72 name: createQualifiedModuleName(name, dir),
73 isPartitionModule: isPartitionModule,
74 }
75}
76
Paul Duffin2e61fa62019-03-28 14:10:57 +000077// A visibility rule is associated with a module and determines which other modules it is visible
78// to, i.e. which other modules can depend on the rule's module.
79type visibilityRule interface {
80 // Check to see whether this rules matches m.
81 // Returns true if it does, false otherwise.
Cole Faust894bb3b2024-02-07 11:28:26 -080082 matches(m visibilityModuleReference) bool
Paul Duffin2e61fa62019-03-28 14:10:57 +000083
84 String() string
85}
86
Paul Duffine2453c72019-05-31 14:00:04 +010087// Describes the properties provided by a module that contain visibility rules.
88type visibilityPropertyImpl struct {
Paul Duffin63c6e182019-07-24 14:24:38 +010089 name string
90 stringsProperty *[]string
Paul Duffine2453c72019-05-31 14:00:04 +010091}
92
93type visibilityProperty interface {
94 getName() string
95 getStrings() []string
96}
97
Paul Duffin63c6e182019-07-24 14:24:38 +010098func newVisibilityProperty(name string, stringsProperty *[]string) visibilityProperty {
Paul Duffine2453c72019-05-31 14:00:04 +010099 return visibilityPropertyImpl{
Paul Duffin63c6e182019-07-24 14:24:38 +0100100 name: name,
101 stringsProperty: stringsProperty,
Paul Duffine2453c72019-05-31 14:00:04 +0100102 }
103}
104
105func (p visibilityPropertyImpl) getName() string {
106 return p.name
107}
108
109func (p visibilityPropertyImpl) getStrings() []string {
Paul Duffin63c6e182019-07-24 14:24:38 +0100110 return *p.stringsProperty
Paul Duffine2453c72019-05-31 14:00:04 +0100111}
112
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100113// A compositeRule is a visibility rule composed from a list of atomic visibility rules.
114//
115// The list corresponds to the list of strings in the visibility property after defaults expansion.
116// Even though //visibility:public is not allowed together with other rules in the visibility list
117// of a single module, it is allowed here to permit a module to override an inherited visibility
118// spec with public visibility.
119//
120// //visibility:private is not allowed in the same way, since we'd need to check for it during the
121// defaults expansion to make that work. No non-private visibility rules are allowed in a
122// compositeRule containing a privateRule.
123//
Paul Duffin2e61fa62019-03-28 14:10:57 +0000124// This array will only be [] if all the rules are invalid and will behave as if visibility was
125// ["//visibility:private"].
126type compositeRule []visibilityRule
127
Cole Faust894bb3b2024-02-07 11:28:26 -0800128var _ visibilityRule = compositeRule{}
129
Paul Duffin2e61fa62019-03-28 14:10:57 +0000130// A compositeRule matches if and only if any of its rules matches.
Cole Faust894bb3b2024-02-07 11:28:26 -0800131func (c compositeRule) matches(m visibilityModuleReference) bool {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000132 for _, r := range c {
133 if r.matches(m) {
134 return true
135 }
136 }
137 return false
138}
139
Paul Duffine2453c72019-05-31 14:00:04 +0100140func (c compositeRule) String() string {
Paul Duffin593b3c92019-12-05 14:31:48 +0000141 return "[" + strings.Join(c.Strings(), ", ") + "]"
142}
143
144func (c compositeRule) Strings() []string {
Paul Duffine2453c72019-05-31 14:00:04 +0100145 s := make([]string, 0, len(c))
146 for _, r := range c {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000147 s = append(s, r.String())
148 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000149 return s
Paul Duffin2e61fa62019-03-28 14:10:57 +0000150}
151
152// A packageRule is a visibility rule that matches modules in a specific package (i.e. directory).
153type packageRule struct {
154 pkg string
155}
156
Cole Faust894bb3b2024-02-07 11:28:26 -0800157var _ visibilityRule = packageRule{}
158
159func (r packageRule) matches(m visibilityModuleReference) bool {
160 return m.name.pkg == r.pkg
Paul Duffin2e61fa62019-03-28 14:10:57 +0000161}
162
163func (r packageRule) String() string {
Martin Stjernholm01407c52020-05-13 01:54:21 +0100164 return fmt.Sprintf("//%s", r.pkg) // :__pkg__ is the default, so skip it.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000165}
166
167// A subpackagesRule is a visibility rule that matches modules in a specific package (i.e.
168// directory) or any of its subpackages (i.e. subdirectories).
169type subpackagesRule struct {
170 pkgPrefix string
171}
172
Cole Faust894bb3b2024-02-07 11:28:26 -0800173var _ visibilityRule = subpackagesRule{}
174
175func (r subpackagesRule) matches(m visibilityModuleReference) bool {
176 return isAncestor(r.pkgPrefix, m.name.pkg)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000177}
178
179func isAncestor(p1 string, p2 string) bool {
Cole Faust3ac7db82023-01-12 10:36:17 -0800180 // Equivalent to strings.HasPrefix(p2+"/", p1+"/"), but without the string copies
181 // The check for a trailing slash is so that we don't consider sibling
182 // directories with common prefixes to be ancestors, e.g. "fooo/bar" should not be
183 // a descendant of "foo".
184 return strings.HasPrefix(p2, p1) && (len(p2) == len(p1) || p2[len(p1)] == '/')
Paul Duffin2e61fa62019-03-28 14:10:57 +0000185}
186
187func (r subpackagesRule) String() string {
188 return fmt.Sprintf("//%s:__subpackages__", r.pkgPrefix)
189}
190
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100191// visibilityRule for //visibility:public
192type publicRule struct{}
193
Cole Faust894bb3b2024-02-07 11:28:26 -0800194var _ visibilityRule = publicRule{}
195
196func (r publicRule) matches(_ visibilityModuleReference) bool {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100197 return true
198}
199
200func (r publicRule) String() string {
201 return "//visibility:public"
202}
203
204// visibilityRule for //visibility:private
205type privateRule struct{}
206
Cole Faust894bb3b2024-02-07 11:28:26 -0800207var _ visibilityRule = privateRule{}
208
209func (r privateRule) matches(_ visibilityModuleReference) bool {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100210 return false
211}
212
213func (r privateRule) String() string {
214 return "//visibility:private"
215}
216
Cole Faust894bb3b2024-02-07 11:28:26 -0800217// visibilityRule for //visibility:any_partition
218type anyPartitionRule struct{}
219
220var _ visibilityRule = anyPartitionRule{}
221
222func (r anyPartitionRule) matches(m visibilityModuleReference) bool {
223 return m.isPartitionModule
224}
225
226func (r anyPartitionRule) String() string {
227 return "//visibility:any_partition"
228}
229
Paul Duffin2e61fa62019-03-28 14:10:57 +0000230var visibilityRuleMap = NewOnceKey("visibilityRuleMap")
231
232// The map from qualifiedModuleName to visibilityRule.
Paul Duffin44885e22020-02-19 16:10:09 +0000233func moduleToVisibilityRuleMap(config Config) *sync.Map {
234 return config.Once(visibilityRuleMap, func() interface{} {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000235 return &sync.Map{}
236 }).(*sync.Map)
237}
238
Paul Duffin78ac5b92020-01-14 12:42:08 +0000239// Marker interface that identifies dependencies that are excluded from visibility
240// enforcement.
241type ExcludeFromVisibilityEnforcementTag interface {
242 blueprint.DependencyTag
243
244 // Method that differentiates this interface from others.
245 ExcludeFromVisibilityEnforcement()
246}
247
Paul Duffin530483c2021-03-07 13:20:38 +0000248// The visibility mutators.
249var PrepareForTestWithVisibility = FixtureRegisterWithContext(registerVisibilityMutators)
250
251func registerVisibilityMutators(ctx RegistrationContext) {
Paul Duffincfd33742021-02-27 11:59:02 +0000252 ctx.PreArchMutators(RegisterVisibilityRuleChecker)
Paul Duffincfd33742021-02-27 11:59:02 +0000253 ctx.PreArchMutators(RegisterVisibilityRuleGatherer)
Paul Duffincfd33742021-02-27 11:59:02 +0000254 ctx.PostDepsMutators(RegisterVisibilityRuleEnforcer)
Paul Duffin530483c2021-03-07 13:20:38 +0000255}
Paul Duffincfd33742021-02-27 11:59:02 +0000256
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100257// The rule checker needs to be registered before defaults expansion to correctly check that
258// //visibility:xxx isn't combined with other packages in the same list in any one module.
Paul Duffin593b3c92019-12-05 14:31:48 +0000259func RegisterVisibilityRuleChecker(ctx RegisterMutatorsContext) {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100260 ctx.BottomUp("visibilityRuleChecker", visibilityRuleChecker).Parallel()
261}
262
Paul Duffine2453c72019-05-31 14:00:04 +0100263// Registers the function that gathers the visibility rules for each module.
264//
Paul Duffin2e61fa62019-03-28 14:10:57 +0000265// Visibility is not dependent on arch so this must be registered before the arch phase to avoid
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100266// having to process multiple variants for each module. This goes after defaults expansion to gather
Paul Duffine2453c72019-05-31 14:00:04 +0100267// the complete visibility lists from flat lists and after the package info is gathered to ensure
268// that default_visibility is available.
Paul Duffin593b3c92019-12-05 14:31:48 +0000269func RegisterVisibilityRuleGatherer(ctx RegisterMutatorsContext) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000270 ctx.BottomUp("visibilityRuleGatherer", visibilityRuleGatherer).Parallel()
271}
272
273// This must be registered after the deps have been resolved.
Paul Duffin593b3c92019-12-05 14:31:48 +0000274func RegisterVisibilityRuleEnforcer(ctx RegisterMutatorsContext) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000275 ctx.TopDown("visibilityRuleEnforcer", visibilityRuleEnforcer).Parallel()
276}
277
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100278// Checks the per-module visibility rule lists before defaults expansion.
279func visibilityRuleChecker(ctx BottomUpMutatorContext) {
Cole Faust894bb3b2024-02-07 11:28:26 -0800280 visibilityProperties := ctx.Module().visibilityProperties()
281 for _, p := range visibilityProperties {
282 if visibility := p.getStrings(); visibility != nil {
283 checkRules(ctx, ctx.ModuleDir(), p.getName(), visibility)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100284 }
285 }
286}
287
Paul Duffine2453c72019-05-31 14:00:04 +0100288func checkRules(ctx BaseModuleContext, currentPkg, property string, visibility []string) {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100289 ruleCount := len(visibility)
290 if ruleCount == 0 {
291 // This prohibits an empty list as its meaning is unclear, e.g. it could mean no visibility and
292 // it could mean public visibility. Requiring at least one rule makes the owner's intent
293 // clearer.
Paul Duffine2453c72019-05-31 14:00:04 +0100294 ctx.PropertyErrorf(property, "must contain at least one visibility rule")
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100295 return
296 }
297
Paul Duffin51084ff2020-05-05 19:19:22 +0100298 for i, v := range visibility {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100299 ok, pkg, name := splitRule(ctx, v, currentPkg, property)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100300 if !ok {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100301 continue
302 }
303
304 if pkg == "visibility" {
305 switch name {
Jeongik Cha31be3522024-03-12 19:34:29 +0900306 case "private", "public":
307 case "any_partition":
308 // any_partition can be used with another visibility fields
309 continue
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100310 case "legacy_public":
Paul Duffine2453c72019-05-31 14:00:04 +0100311 ctx.PropertyErrorf(property, "//visibility:legacy_public must not be used")
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100312 continue
Paul Duffin51084ff2020-05-05 19:19:22 +0100313 case "override":
314 // This keyword does not create a rule so pretend it does not exist.
315 ruleCount -= 1
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100316 default:
Paul Duffine2453c72019-05-31 14:00:04 +0100317 ctx.PropertyErrorf(property, "unrecognized visibility rule %q", v)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100318 continue
319 }
Paul Duffin51084ff2020-05-05 19:19:22 +0100320 if name == "override" {
321 if i != 0 {
322 ctx.PropertyErrorf(property, `"%v" may only be used at the start of the visibility rules`, v)
323 }
324 } else if ruleCount != 1 {
Paul Duffine2453c72019-05-31 14:00:04 +0100325 ctx.PropertyErrorf(property, "cannot mix %q with any other visibility rules", v)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100326 continue
327 }
328 }
329
330 // If the current directory is not in the vendor tree then there are some additional
331 // restrictions on the rules.
332 if !isAncestor("vendor", currentPkg) {
333 if !isAllowedFromOutsideVendor(pkg, name) {
Paul Duffine2453c72019-05-31 14:00:04 +0100334 ctx.PropertyErrorf(property,
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100335 "%q is not allowed. Packages outside //vendor cannot make themselves visible to specific"+
336 " targets within //vendor, they can only use //vendor:__subpackages__.", v)
337 continue
338 }
339 }
340 }
341}
342
343// Gathers the flattened visibility rules after defaults expansion, parses the visibility
344// properties, stores them in a map by qualifiedModuleName for retrieval during enforcement.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000345//
346// See ../README.md#Visibility for information on the format of the visibility rules.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000347func visibilityRuleGatherer(ctx BottomUpMutatorContext) {
Cole Faust894bb3b2024-02-07 11:28:26 -0800348 m := ctx.Module()
Paul Duffin2e61fa62019-03-28 14:10:57 +0000349
Paul Duffine2453c72019-05-31 14:00:04 +0100350 qualifiedModuleId := m.qualifiedModuleId(ctx)
351 currentPkg := qualifiedModuleId.pkg
Paul Duffin2e61fa62019-03-28 14:10:57 +0000352
Paul Duffin63c6e182019-07-24 14:24:38 +0100353 // Parse the visibility rules that control access to the module and store them by id
354 // for use when enforcing the rules.
Paul Duffin0c83aba2020-05-01 18:13:36 +0100355 primaryProperty := m.base().primaryVisibilityProperty
356 if primaryProperty != nil {
357 if visibility := primaryProperty.getStrings(); visibility != nil {
358 rule := parseRules(ctx, currentPkg, primaryProperty.getName(), visibility)
359 if rule != nil {
360 moduleToVisibilityRuleMap(ctx.Config()).Store(qualifiedModuleId, rule)
361 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000362 }
363 }
364}
365
Paul Duffin0c83aba2020-05-01 18:13:36 +0100366func parseRules(ctx BaseModuleContext, currentPkg, property string, visibility []string) compositeRule {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100367 rules := make(compositeRule, 0, len(visibility))
368 hasPrivateRule := false
Paul Duffin44885e22020-02-19 16:10:09 +0000369 hasPublicRule := false
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100370 hasNonPrivateRule := false
Paul Duffin2e61fa62019-03-28 14:10:57 +0000371 for _, v := range visibility {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100372 ok, pkg, name := splitRule(ctx, v, currentPkg, property)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000373 if !ok {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000374 continue
375 }
376
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100377 var r visibilityRule
378 isPrivateRule := false
Paul Duffin2e61fa62019-03-28 14:10:57 +0000379 if pkg == "visibility" {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000380 switch name {
381 case "private":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100382 r = privateRule{}
383 isPrivateRule = true
Paul Duffin2e61fa62019-03-28 14:10:57 +0000384 case "public":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100385 r = publicRule{}
Paul Duffin44885e22020-02-19 16:10:09 +0000386 hasPublicRule = true
Paul Duffin51084ff2020-05-05 19:19:22 +0100387 case "override":
388 // Discard all preceding rules and any state based on them.
389 rules = nil
390 hasPrivateRule = false
391 hasPublicRule = false
392 hasNonPrivateRule = false
393 // This does not actually create a rule so continue onto the next rule.
394 continue
Cole Faust894bb3b2024-02-07 11:28:26 -0800395 case "any_partition":
396 r = anyPartitionRule{}
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100397 }
398 } else {
399 switch name {
400 case "__pkg__":
401 r = packageRule{pkg}
402 case "__subpackages__":
403 r = subpackagesRule{pkg}
Paul Duffin2e61fa62019-03-28 14:10:57 +0000404 default:
Liz Kammer873f4b62020-10-15 08:42:01 -0700405 ctx.PropertyErrorf(property, "invalid visibility pattern %q. Must match "+
406 " //<package>:<scope>, //<package> or :<scope> "+
407 "where <scope> is one of \"__pkg__\", \"__subpackages__\"",
408 v)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000409 }
410 }
411
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100412 if isPrivateRule {
413 hasPrivateRule = true
414 } else {
415 hasNonPrivateRule = true
Paul Duffin2e61fa62019-03-28 14:10:57 +0000416 }
417
418 rules = append(rules, r)
419 }
420
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100421 if hasPrivateRule && hasNonPrivateRule {
422 ctx.PropertyErrorf("visibility",
423 "cannot mix \"//visibility:private\" with any other visibility rules")
424 return compositeRule{privateRule{}}
425 }
426
Paul Duffin44885e22020-02-19 16:10:09 +0000427 if hasPublicRule {
428 // Public overrides all other rules so just return it.
429 return compositeRule{publicRule{}}
430 }
431
Paul Duffin2e61fa62019-03-28 14:10:57 +0000432 return rules
433}
434
435func isAllowedFromOutsideVendor(pkg string, name string) bool {
436 if pkg == "vendor" {
Cole Faust894bb3b2024-02-07 11:28:26 -0800437 return name == "__subpackages__"
Paul Duffin2e61fa62019-03-28 14:10:57 +0000438 }
439
440 return !isAncestor("vendor", pkg)
441}
442
Paul Duffin0c83aba2020-05-01 18:13:36 +0100443func splitRule(ctx BaseModuleContext, ruleExpression string, currentPkg, property string) (bool, string, string) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000444 // Make sure that the rule is of the correct format.
445 matches := visibilityRuleRegexp.FindStringSubmatch(ruleExpression)
446 if ruleExpression == "" || matches == nil {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100447 // Visibility rule is invalid so ignore it. Keep going rather than aborting straight away to
448 // ensure all the rules on this module are checked.
449 ctx.PropertyErrorf(property,
450 "invalid visibility pattern %q must match"+
Liz Kammer873f4b62020-10-15 08:42:01 -0700451 " //<package>:<scope>, //<package> or :<scope> "+
452 "where <scope> is one of \"__pkg__\", \"__subpackages__\"",
Paul Duffin0c83aba2020-05-01 18:13:36 +0100453 ruleExpression)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000454 return false, "", ""
455 }
456
457 // Extract the package and name.
458 pkg := matches[1]
459 name := matches[2]
460
461 // Normalize the short hands
462 if pkg == "" {
463 pkg = currentPkg
464 }
465 if name == "" {
466 name = "__pkg__"
467 }
468
469 return true, pkg, name
470}
471
472func visibilityRuleEnforcer(ctx TopDownMutatorContext) {
Cole Faust894bb3b2024-02-07 11:28:26 -0800473 qualified := createVisibilityModuleReference(ctx.ModuleName(), ctx.ModuleDir(), ctx.ModuleType())
Paul Duffin2e61fa62019-03-28 14:10:57 +0000474
Paul Duffin2e61fa62019-03-28 14:10:57 +0000475 // Visit all the dependencies making sure that this module has access to them all.
476 ctx.VisitDirectDeps(func(dep Module) {
Paul Duffin78ac5b92020-01-14 12:42:08 +0000477 // Ignore dependencies that have an ExcludeFromVisibilityEnforcementTag
478 tag := ctx.OtherModuleDependencyTag(dep)
479 if _, ok := tag.(ExcludeFromVisibilityEnforcementTag); ok {
480 return
481 }
482
Paul Duffin2e61fa62019-03-28 14:10:57 +0000483 depName := ctx.OtherModuleName(dep)
484 depDir := ctx.OtherModuleDir(dep)
485 depQualified := qualifiedModuleName{depDir, depName}
486
487 // Targets are always visible to other targets in their own package.
Cole Faust894bb3b2024-02-07 11:28:26 -0800488 if depQualified.pkg == qualified.name.pkg {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000489 return
490 }
491
Paul Duffin44885e22020-02-19 16:10:09 +0000492 rule := effectiveVisibilityRules(ctx.Config(), depQualified)
Paul Duffind99d9972020-09-29 16:00:55 +0100493 if !rule.matches(qualified) {
Liz Kammere501bb42020-10-15 11:46:38 -0700494 ctx.ModuleErrorf("depends on %s which is not visible to this module\nYou may need to add %q to its visibility", depQualified, "//"+ctx.ModuleDir())
Paul Duffine2453c72019-05-31 14:00:04 +0100495 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000496 })
497}
498
Paul Duffind99d9972020-09-29 16:00:55 +0100499// Default visibility is public.
500var defaultVisibility = compositeRule{publicRule{}}
501
502// Return the effective visibility rules.
503//
504// If no rules have been specified this will return the default visibility rule
505// which is currently //visibility:public.
Paul Duffin44885e22020-02-19 16:10:09 +0000506func effectiveVisibilityRules(config Config, qualified qualifiedModuleName) compositeRule {
507 moduleToVisibilityRule := moduleToVisibilityRuleMap(config)
Paul Duffin593b3c92019-12-05 14:31:48 +0000508 value, ok := moduleToVisibilityRule.Load(qualified)
509 var rule compositeRule
510 if ok {
511 rule = value.(compositeRule)
512 } else {
Cole Faust894bb3b2024-02-07 11:28:26 -0800513 rule = packageDefaultVisibility(moduleToVisibilityRule, qualified)
Paul Duffin593b3c92019-12-05 14:31:48 +0000514 }
Paul Duffind99d9972020-09-29 16:00:55 +0100515
516 // If no rule is specified then return the default visibility rule to avoid
517 // every caller having to treat nil as public.
518 if rule == nil {
519 rule = defaultVisibility
520 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000521 return rule
522}
523
Bob Badoureef4c1c2022-05-16 12:20:04 -0700524func createQualifiedModuleName(moduleName, dir string) qualifiedModuleName {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000525 qualified := qualifiedModuleName{dir, moduleName}
526 return qualified
527}
Paul Duffine484f472019-06-20 16:38:08 +0100528
Cole Faust894bb3b2024-02-07 11:28:26 -0800529func packageDefaultVisibility(moduleToVisibilityRule *sync.Map, moduleId qualifiedModuleName) compositeRule {
Paul Duffine484f472019-06-20 16:38:08 +0100530 packageQualifiedId := moduleId.getContainingPackageId()
531 for {
532 value, ok := moduleToVisibilityRule.Load(packageQualifiedId)
533 if ok {
534 return value.(compositeRule)
535 }
536
537 if packageQualifiedId.isRootPackage() {
538 return nil
539 }
540
541 packageQualifiedId = packageQualifiedId.getContainingPackageId()
542 }
543}
Paul Duffin593b3c92019-12-05 14:31:48 +0000544
Paul Duffin157f40f2020-09-29 16:01:08 +0100545type VisibilityRuleSet interface {
546 // Widen the visibility with some extra rules.
547 Widen(extra []string) error
548
549 Strings() []string
550}
551
552type visibilityRuleSet struct {
553 rules []string
554}
555
556var _ VisibilityRuleSet = (*visibilityRuleSet)(nil)
557
558func (v *visibilityRuleSet) Widen(extra []string) error {
559 // Check the extra rules first just in case they are invalid. Otherwise, if
560 // the current visibility is public then the extra rules will just be ignored.
561 if len(extra) == 1 {
562 singularRule := extra[0]
563 switch singularRule {
564 case "//visibility:public":
565 // Public overrides everything so just discard any existing rules.
566 v.rules = extra
567 return nil
568 case "//visibility:private":
569 // Extending rule with private is an error.
570 return fmt.Errorf("%q does not widen the visibility", singularRule)
571 }
572 }
573
574 if len(v.rules) == 1 {
575 switch v.rules[0] {
576 case "//visibility:public":
577 // No point in adding rules to something which is already public.
578 return nil
579 case "//visibility:private":
580 // Adding any rules to private means it is no longer private so the
581 // private can be discarded.
582 v.rules = nil
583 }
584 }
585
586 v.rules = FirstUniqueStrings(append(v.rules, extra...))
587 sort.Strings(v.rules)
588 return nil
589}
590
591func (v *visibilityRuleSet) Strings() []string {
592 return v.rules
593}
594
Paul Duffin593b3c92019-12-05 14:31:48 +0000595// Get the effective visibility rules, i.e. the actual rules that affect the visibility of the
596// property irrespective of where they are defined.
597//
598// Includes visibility rules specified by package default_visibility and/or on defaults.
599// Short hand forms, e.g. //:__subpackages__ are replaced with their full form, e.g.
600// //package/containing/rule:__subpackages__.
Paul Duffin157f40f2020-09-29 16:01:08 +0100601func EffectiveVisibilityRules(ctx BaseModuleContext, module Module) VisibilityRuleSet {
Paul Duffin593b3c92019-12-05 14:31:48 +0000602 moduleName := ctx.OtherModuleName(module)
603 dir := ctx.OtherModuleDir(module)
604 qualified := qualifiedModuleName{dir, moduleName}
605
Paul Duffin44885e22020-02-19 16:10:09 +0000606 rule := effectiveVisibilityRules(ctx.Config(), qualified)
Paul Duffin593b3c92019-12-05 14:31:48 +0000607
Cole Faust894bb3b2024-02-07 11:28:26 -0800608 currentModule := createVisibilityModuleReference(moduleName, dir, ctx.OtherModuleType(module))
609
Martin Stjernholm0641d182020-05-13 02:20:06 +0100610 // Modules are implicitly visible to other modules in the same package,
611 // without checking the visibility rules. Here we need to add that visibility
612 // explicitly.
Cole Faust894bb3b2024-02-07 11:28:26 -0800613 if !rule.matches(currentModule) {
Martin Stjernholm64aeaad2020-05-13 22:11:40 +0100614 if len(rule) == 1 {
615 if _, ok := rule[0].(privateRule); ok {
616 // If the rule is //visibility:private we can't append another
617 // visibility to it. Semantically we need to convert it to a package
618 // visibility rule for the location where the result is used, but since
619 // modules are implicitly visible within the package we get the same
620 // result without any rule at all, so just make it an empty list to be
621 // appended below.
Paul Duffind99d9972020-09-29 16:00:55 +0100622 rule = nil
Martin Stjernholm64aeaad2020-05-13 22:11:40 +0100623 }
624 }
Martin Stjernholm0641d182020-05-13 02:20:06 +0100625 rule = append(rule, packageRule{dir})
626 }
627
Paul Duffin157f40f2020-09-29 16:01:08 +0100628 return &visibilityRuleSet{rule.Strings()}
Paul Duffin593b3c92019-12-05 14:31:48 +0000629}
Paul Duffin5ec73ec2020-05-01 17:52:01 +0100630
631// Clear the default visibility properties so they can be replaced.
632func clearVisibilityProperties(module Module) {
633 module.base().visibilityPropertyInfo = nil
634}
635
636// Add a property that contains visibility rules so that they are checked for
637// correctness.
638func AddVisibilityProperty(module Module, name string, stringsProperty *[]string) {
639 addVisibilityProperty(module, name, stringsProperty)
640}
641
642func addVisibilityProperty(module Module, name string, stringsProperty *[]string) visibilityProperty {
643 base := module.base()
644 property := newVisibilityProperty(name, stringsProperty)
645 base.visibilityPropertyInfo = append(base.visibilityPropertyInfo, property)
646 return property
647}
648
649// Set the primary visibility property.
650//
651// Also adds the property to the list of properties to be validated.
652func setPrimaryVisibilityProperty(module Module, name string, stringsProperty *[]string) {
653 module.base().primaryVisibilityProperty = addVisibilityProperty(module, name, stringsProperty)
654}