Chromium Chronicle #15:限制目标可见性

第 15 集:作者:Joe Mason,位于帕克萨斯州蒙特利尔(2020 年 11 月)
上一集

Chrome 是一个大型项目,包含许多子系统。为某个组件编写的代码在其他地方很有用,但可能存在隐藏的限制。为安全起见,请限制外部对危险功能的访问权限。 例如,针对特定性能需求进行调整的自定义函数:

// Blazing fast for 2-char strings, O(n^3) otherwise.
std::string ConcatShortStringsFast(const std::string& a, const std::string& b);

您可以通过多种方式限制访问权限。GN 可见性规则会根据目标阻止组件外部的代码。默认情况下,目标对所有人可见,但您可以对其进行修改:

# In components/restricted_component/BUILD.gn
visibility = [
  # Applies to all targets in this file.
  # Only the given targets can depend on them.
  "//components/restricted_component:*",
  "//components/authorized_other_component:a_single_target",
]
source_set("internal") {
  # This dangerous target should be locked down even more.
  visibility = [ "//components/restricted_component:privileged_target" ]
}

可见性声明通过 gn check 进行验证,后者作为每个 GN build 的一部分运行。

另一种机制是 DEPS include_rules,它可限制对头文件的访问。每个目录都会从其父级继承 include_rules,并且可以在自己的 DEPS 文件中修改这些规则。从外部目录包含的所有头文件必须获得 include_rules 的许可。

# In //components/authorized_other_component/DEPS
include_rules = [
  # Common directories like //base are inherited from
  # //components/DEPS or //DEPS. Also allow includes from
  # restricted_component, but not restricted_component/internal.
  "+components/restricted_component",
  "-components/restricted_component/internal",
  # But do allow a single header from internal, for testing.
  "+components/restricted_component/internal/test_support.h",
]

为确保这些依赖项正确,将目录添加到 include_rules 的更改必须获得该目录的 OWNERS 的批准。无需批准即可使用 include_rules 限制目录!您可以通过添加 include_rule 来禁止某些标头,确保更改组件的每个人都记得不要使用它们。

include_rules 由提交前检查,因此在您尝试上传更改之前,您不会看到任何错误。如需在不上传的情况下测试 include_rules,请运行 buildtools/checkdeps/checkdeps.py <directory>

资源