blob: b3875620f0eed52d264cf7296a3b3b91eab8fb24 [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 {
Cole Faust894bb3b2024-02-07 11:28:26 -0800306 case "private", "public", "any_partition":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100307 case "legacy_public":
Paul Duffine2453c72019-05-31 14:00:04 +0100308 ctx.PropertyErrorf(property, "//visibility:legacy_public must not be used")
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100309 continue
Paul Duffin51084ff2020-05-05 19:19:22 +0100310 case "override":
311 // This keyword does not create a rule so pretend it does not exist.
312 ruleCount -= 1
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100313 default:
Paul Duffine2453c72019-05-31 14:00:04 +0100314 ctx.PropertyErrorf(property, "unrecognized visibility rule %q", v)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100315 continue
316 }
Paul Duffin51084ff2020-05-05 19:19:22 +0100317 if name == "override" {
318 if i != 0 {
319 ctx.PropertyErrorf(property, `"%v" may only be used at the start of the visibility rules`, v)
320 }
321 } else if ruleCount != 1 {
Paul Duffine2453c72019-05-31 14:00:04 +0100322 ctx.PropertyErrorf(property, "cannot mix %q with any other visibility rules", v)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100323 continue
324 }
325 }
326
327 // If the current directory is not in the vendor tree then there are some additional
328 // restrictions on the rules.
329 if !isAncestor("vendor", currentPkg) {
330 if !isAllowedFromOutsideVendor(pkg, name) {
Paul Duffine2453c72019-05-31 14:00:04 +0100331 ctx.PropertyErrorf(property,
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100332 "%q is not allowed. Packages outside //vendor cannot make themselves visible to specific"+
333 " targets within //vendor, they can only use //vendor:__subpackages__.", v)
334 continue
335 }
336 }
337 }
338}
339
340// Gathers the flattened visibility rules after defaults expansion, parses the visibility
341// properties, stores them in a map by qualifiedModuleName for retrieval during enforcement.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000342//
343// See ../README.md#Visibility for information on the format of the visibility rules.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000344func visibilityRuleGatherer(ctx BottomUpMutatorContext) {
Cole Faust894bb3b2024-02-07 11:28:26 -0800345 m := ctx.Module()
Paul Duffin2e61fa62019-03-28 14:10:57 +0000346
Paul Duffine2453c72019-05-31 14:00:04 +0100347 qualifiedModuleId := m.qualifiedModuleId(ctx)
348 currentPkg := qualifiedModuleId.pkg
Paul Duffin2e61fa62019-03-28 14:10:57 +0000349
Paul Duffin63c6e182019-07-24 14:24:38 +0100350 // Parse the visibility rules that control access to the module and store them by id
351 // for use when enforcing the rules.
Paul Duffin0c83aba2020-05-01 18:13:36 +0100352 primaryProperty := m.base().primaryVisibilityProperty
353 if primaryProperty != nil {
354 if visibility := primaryProperty.getStrings(); visibility != nil {
355 rule := parseRules(ctx, currentPkg, primaryProperty.getName(), visibility)
356 if rule != nil {
357 moduleToVisibilityRuleMap(ctx.Config()).Store(qualifiedModuleId, rule)
358 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000359 }
360 }
361}
362
Paul Duffin0c83aba2020-05-01 18:13:36 +0100363func parseRules(ctx BaseModuleContext, currentPkg, property string, visibility []string) compositeRule {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100364 rules := make(compositeRule, 0, len(visibility))
365 hasPrivateRule := false
Paul Duffin44885e22020-02-19 16:10:09 +0000366 hasPublicRule := false
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100367 hasNonPrivateRule := false
Paul Duffin2e61fa62019-03-28 14:10:57 +0000368 for _, v := range visibility {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100369 ok, pkg, name := splitRule(ctx, v, currentPkg, property)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000370 if !ok {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000371 continue
372 }
373
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100374 var r visibilityRule
375 isPrivateRule := false
Paul Duffin2e61fa62019-03-28 14:10:57 +0000376 if pkg == "visibility" {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000377 switch name {
378 case "private":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100379 r = privateRule{}
380 isPrivateRule = true
Paul Duffin2e61fa62019-03-28 14:10:57 +0000381 case "public":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100382 r = publicRule{}
Paul Duffin44885e22020-02-19 16:10:09 +0000383 hasPublicRule = true
Paul Duffin51084ff2020-05-05 19:19:22 +0100384 case "override":
385 // Discard all preceding rules and any state based on them.
386 rules = nil
387 hasPrivateRule = false
388 hasPublicRule = false
389 hasNonPrivateRule = false
390 // This does not actually create a rule so continue onto the next rule.
391 continue
Cole Faust894bb3b2024-02-07 11:28:26 -0800392 case "any_partition":
393 r = anyPartitionRule{}
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100394 }
395 } else {
396 switch name {
397 case "__pkg__":
398 r = packageRule{pkg}
399 case "__subpackages__":
400 r = subpackagesRule{pkg}
Paul Duffin2e61fa62019-03-28 14:10:57 +0000401 default:
Liz Kammer873f4b62020-10-15 08:42:01 -0700402 ctx.PropertyErrorf(property, "invalid visibility pattern %q. Must match "+
403 " //<package>:<scope>, //<package> or :<scope> "+
404 "where <scope> is one of \"__pkg__\", \"__subpackages__\"",
405 v)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000406 }
407 }
408
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100409 if isPrivateRule {
410 hasPrivateRule = true
411 } else {
412 hasNonPrivateRule = true
Paul Duffin2e61fa62019-03-28 14:10:57 +0000413 }
414
415 rules = append(rules, r)
416 }
417
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100418 if hasPrivateRule && hasNonPrivateRule {
419 ctx.PropertyErrorf("visibility",
420 "cannot mix \"//visibility:private\" with any other visibility rules")
421 return compositeRule{privateRule{}}
422 }
423
Paul Duffin44885e22020-02-19 16:10:09 +0000424 if hasPublicRule {
425 // Public overrides all other rules so just return it.
426 return compositeRule{publicRule{}}
427 }
428
Paul Duffin2e61fa62019-03-28 14:10:57 +0000429 return rules
430}
431
432func isAllowedFromOutsideVendor(pkg string, name string) bool {
433 if pkg == "vendor" {
Cole Faust894bb3b2024-02-07 11:28:26 -0800434 return name == "__subpackages__"
Paul Duffin2e61fa62019-03-28 14:10:57 +0000435 }
436
437 return !isAncestor("vendor", pkg)
438}
439
Paul Duffin0c83aba2020-05-01 18:13:36 +0100440func splitRule(ctx BaseModuleContext, ruleExpression string, currentPkg, property string) (bool, string, string) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000441 // Make sure that the rule is of the correct format.
442 matches := visibilityRuleRegexp.FindStringSubmatch(ruleExpression)
443 if ruleExpression == "" || matches == nil {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100444 // Visibility rule is invalid so ignore it. Keep going rather than aborting straight away to
445 // ensure all the rules on this module are checked.
446 ctx.PropertyErrorf(property,
447 "invalid visibility pattern %q must match"+
Liz Kammer873f4b62020-10-15 08:42:01 -0700448 " //<package>:<scope>, //<package> or :<scope> "+
449 "where <scope> is one of \"__pkg__\", \"__subpackages__\"",
Paul Duffin0c83aba2020-05-01 18:13:36 +0100450 ruleExpression)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000451 return false, "", ""
452 }
453
454 // Extract the package and name.
455 pkg := matches[1]
456 name := matches[2]
457
458 // Normalize the short hands
459 if pkg == "" {
460 pkg = currentPkg
461 }
462 if name == "" {
463 name = "__pkg__"
464 }
465
466 return true, pkg, name
467}
468
469func visibilityRuleEnforcer(ctx TopDownMutatorContext) {
Cole Faust894bb3b2024-02-07 11:28:26 -0800470 qualified := createVisibilityModuleReference(ctx.ModuleName(), ctx.ModuleDir(), ctx.ModuleType())
Paul Duffin2e61fa62019-03-28 14:10:57 +0000471
Paul Duffin2e61fa62019-03-28 14:10:57 +0000472 // Visit all the dependencies making sure that this module has access to them all.
473 ctx.VisitDirectDeps(func(dep Module) {
Paul Duffin78ac5b92020-01-14 12:42:08 +0000474 // Ignore dependencies that have an ExcludeFromVisibilityEnforcementTag
475 tag := ctx.OtherModuleDependencyTag(dep)
476 if _, ok := tag.(ExcludeFromVisibilityEnforcementTag); ok {
477 return
478 }
479
Paul Duffin2e61fa62019-03-28 14:10:57 +0000480 depName := ctx.OtherModuleName(dep)
481 depDir := ctx.OtherModuleDir(dep)
482 depQualified := qualifiedModuleName{depDir, depName}
483
484 // Targets are always visible to other targets in their own package.
Cole Faust894bb3b2024-02-07 11:28:26 -0800485 if depQualified.pkg == qualified.name.pkg {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000486 return
487 }
488
Paul Duffin44885e22020-02-19 16:10:09 +0000489 rule := effectiveVisibilityRules(ctx.Config(), depQualified)
Paul Duffind99d9972020-09-29 16:00:55 +0100490 if !rule.matches(qualified) {
Liz Kammere501bb42020-10-15 11:46:38 -0700491 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 +0100492 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000493 })
494}
495
Paul Duffind99d9972020-09-29 16:00:55 +0100496// Default visibility is public.
497var defaultVisibility = compositeRule{publicRule{}}
498
499// Return the effective visibility rules.
500//
501// If no rules have been specified this will return the default visibility rule
502// which is currently //visibility:public.
Paul Duffin44885e22020-02-19 16:10:09 +0000503func effectiveVisibilityRules(config Config, qualified qualifiedModuleName) compositeRule {
504 moduleToVisibilityRule := moduleToVisibilityRuleMap(config)
Paul Duffin593b3c92019-12-05 14:31:48 +0000505 value, ok := moduleToVisibilityRule.Load(qualified)
506 var rule compositeRule
507 if ok {
508 rule = value.(compositeRule)
509 } else {
Cole Faust894bb3b2024-02-07 11:28:26 -0800510 rule = packageDefaultVisibility(moduleToVisibilityRule, qualified)
Paul Duffin593b3c92019-12-05 14:31:48 +0000511 }
Paul Duffind99d9972020-09-29 16:00:55 +0100512
513 // If no rule is specified then return the default visibility rule to avoid
514 // every caller having to treat nil as public.
515 if rule == nil {
516 rule = defaultVisibility
517 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000518 return rule
519}
520
Bob Badoureef4c1c2022-05-16 12:20:04 -0700521func createQualifiedModuleName(moduleName, dir string) qualifiedModuleName {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000522 qualified := qualifiedModuleName{dir, moduleName}
523 return qualified
524}
Paul Duffine484f472019-06-20 16:38:08 +0100525
Cole Faust894bb3b2024-02-07 11:28:26 -0800526func packageDefaultVisibility(moduleToVisibilityRule *sync.Map, moduleId qualifiedModuleName) compositeRule {
Paul Duffine484f472019-06-20 16:38:08 +0100527 packageQualifiedId := moduleId.getContainingPackageId()
528 for {
529 value, ok := moduleToVisibilityRule.Load(packageQualifiedId)
530 if ok {
531 return value.(compositeRule)
532 }
533
534 if packageQualifiedId.isRootPackage() {
535 return nil
536 }
537
538 packageQualifiedId = packageQualifiedId.getContainingPackageId()
539 }
540}
Paul Duffin593b3c92019-12-05 14:31:48 +0000541
Paul Duffin157f40f2020-09-29 16:01:08 +0100542type VisibilityRuleSet interface {
543 // Widen the visibility with some extra rules.
544 Widen(extra []string) error
545
546 Strings() []string
547}
548
549type visibilityRuleSet struct {
550 rules []string
551}
552
553var _ VisibilityRuleSet = (*visibilityRuleSet)(nil)
554
555func (v *visibilityRuleSet) Widen(extra []string) error {
556 // Check the extra rules first just in case they are invalid. Otherwise, if
557 // the current visibility is public then the extra rules will just be ignored.
558 if len(extra) == 1 {
559 singularRule := extra[0]
560 switch singularRule {
561 case "//visibility:public":
562 // Public overrides everything so just discard any existing rules.
563 v.rules = extra
564 return nil
565 case "//visibility:private":
566 // Extending rule with private is an error.
567 return fmt.Errorf("%q does not widen the visibility", singularRule)
568 }
569 }
570
571 if len(v.rules) == 1 {
572 switch v.rules[0] {
573 case "//visibility:public":
574 // No point in adding rules to something which is already public.
575 return nil
576 case "//visibility:private":
577 // Adding any rules to private means it is no longer private so the
578 // private can be discarded.
579 v.rules = nil
580 }
581 }
582
583 v.rules = FirstUniqueStrings(append(v.rules, extra...))
584 sort.Strings(v.rules)
585 return nil
586}
587
588func (v *visibilityRuleSet) Strings() []string {
589 return v.rules
590}
591
Paul Duffin593b3c92019-12-05 14:31:48 +0000592// Get the effective visibility rules, i.e. the actual rules that affect the visibility of the
593// property irrespective of where they are defined.
594//
595// Includes visibility rules specified by package default_visibility and/or on defaults.
596// Short hand forms, e.g. //:__subpackages__ are replaced with their full form, e.g.
597// //package/containing/rule:__subpackages__.
Paul Duffin157f40f2020-09-29 16:01:08 +0100598func EffectiveVisibilityRules(ctx BaseModuleContext, module Module) VisibilityRuleSet {
Paul Duffin593b3c92019-12-05 14:31:48 +0000599 moduleName := ctx.OtherModuleName(module)
600 dir := ctx.OtherModuleDir(module)
601 qualified := qualifiedModuleName{dir, moduleName}
602
Paul Duffin44885e22020-02-19 16:10:09 +0000603 rule := effectiveVisibilityRules(ctx.Config(), qualified)
Paul Duffin593b3c92019-12-05 14:31:48 +0000604
Cole Faust894bb3b2024-02-07 11:28:26 -0800605 currentModule := createVisibilityModuleReference(moduleName, dir, ctx.OtherModuleType(module))
606
Martin Stjernholm0641d182020-05-13 02:20:06 +0100607 // Modules are implicitly visible to other modules in the same package,
608 // without checking the visibility rules. Here we need to add that visibility
609 // explicitly.
Cole Faust894bb3b2024-02-07 11:28:26 -0800610 if !rule.matches(currentModule) {
Martin Stjernholm64aeaad2020-05-13 22:11:40 +0100611 if len(rule) == 1 {
612 if _, ok := rule[0].(privateRule); ok {
613 // If the rule is //visibility:private we can't append another
614 // visibility to it. Semantically we need to convert it to a package
615 // visibility rule for the location where the result is used, but since
616 // modules are implicitly visible within the package we get the same
617 // result without any rule at all, so just make it an empty list to be
618 // appended below.
Paul Duffind99d9972020-09-29 16:00:55 +0100619 rule = nil
Martin Stjernholm64aeaad2020-05-13 22:11:40 +0100620 }
621 }
Martin Stjernholm0641d182020-05-13 02:20:06 +0100622 rule = append(rule, packageRule{dir})
623 }
624
Paul Duffin157f40f2020-09-29 16:01:08 +0100625 return &visibilityRuleSet{rule.Strings()}
Paul Duffin593b3c92019-12-05 14:31:48 +0000626}
Paul Duffin5ec73ec2020-05-01 17:52:01 +0100627
628// Clear the default visibility properties so they can be replaced.
629func clearVisibilityProperties(module Module) {
630 module.base().visibilityPropertyInfo = nil
631}
632
633// Add a property that contains visibility rules so that they are checked for
634// correctness.
635func AddVisibilityProperty(module Module, name string, stringsProperty *[]string) {
636 addVisibilityProperty(module, name, stringsProperty)
637}
638
639func addVisibilityProperty(module Module, name string, stringsProperty *[]string) visibilityProperty {
640 base := module.base()
641 property := newVisibilityProperty(name, stringsProperty)
642 base.visibilityPropertyInfo = append(base.visibilityPropertyInfo, property)
643 return property
644}
645
646// Set the primary visibility property.
647//
648// Also adds the property to the list of properties to be validated.
649func setPrimaryVisibilityProperty(module Module, name string, stringsProperty *[]string) {
650 module.base().primaryVisibilityProperty = addVisibilityProperty(module, name, stringsProperty)
651}