carlos / platform Public

C2 Task 1: root's scope from the units that run as root

J4's reference graph (now censusGraph, shared by J4 and the census within
one process) is walked for linux from main.go:main, following only the
case clauses of verbs a root unit runs (and the boot verbs user_data runs)
in main and runSystem, plus every init and var-initializer call of the
root binary's packages. A reached type reaches its standard-library
callback methods. J4's own walk is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1e49f4af72078ab910b1415f00e9e641dd62e3d5 parent 197957c
3 files changed, +752 −140
  • internal/provision/census_scope_fixture_test.go +222 −0
  • internal/provision/census_scope_test.go +503 −0
  • internal/provision/plan14_input_inventory_test.go +27 −140
diff --git a/internal/provision/census_scope_fixture_test.go b/internal/provision/census_scope_fixture_test.go
new file mode 100644
index 000000000..9dbdc67e1
--- /dev/null
+++ b/internal/provision/census_scope_fixture_test.go
@@ -0,0 +1,222 @@
+package provision
+
+// The census's scope (C2) on a fixture module: which units root runs,
+// found from the systemd units that run as root, walked through the real
+// reference graph.
+
+import (
+ "strings"
+ "testing"
+)
+
+// scopeFiles is a small module shaped like the platform: main.go and
+// system.go dispatch verbs, internal/host/units holds the systemd units
+// (two run as root, two do not), and each package is reached from root, or
+// from the agent or the console only.
+func scopeFiles() map[string]string {
+ return map[string]string{
+ "go.mod": "module fixture/root\n\ngo 1.24\n",
+ "main.go": `package main
+
+import (
+ "os"
+
+ "fixture/root/internal/console"
+ "fixture/root/internal/host"
+)
+
+func main() {
+ host.Setup()
+ cmd := os.Args[1]
+ switch cmd {
+ case "adopt":
+ host.RunAdopt()
+ case "agent":
+ host.RunAgent()
+ case "console":
+ console.Serve()
+ case "bootstrap":
+ host.RunBootstrap()
+ case "system":
+ runSystem(os.Args[2:])
+ }
+}
+`,
+ "system.go": `package main
+
+import "fixture/root/internal/host"
+
+func runSystem(args []string) {
+ verb := args[0]
+ switch verb {
+ case "apply":
+ host.RunApply()
+ case "install-channel", "host-env":
+ host.RunBoot()
+ case "status":
+ host.RunStatus()
+ }
+}
+`,
+ "internal/host/units/carlos-adopt.service": "[Service]\nExecStart=/opt/carlos/carlos adopt --config-only\n",
+ "internal/host/units/carlos-system-update.service": "[Service]\nExecStart=/bin/sh -c 'if [ -x /opt/carlos/carlos.prev ]; then exec /opt/carlos/carlos.prev system apply; fi; exec /opt/carlos/carlos system apply'\n",
+ "internal/host/units/carlos-edge.service": "[Service]\nUser=carlos\nExecStart=/opt/carlos/carlos agent\n",
+ "internal/host/units/carlos-dbread@.service": "[Service]\nExecStart=/opt/carlos/carlos system status\nDynamicUser=yes\n",
+ "internal/host/host.go": `package host
+
+import (
+ "embed"
+ "fmt"
+ "os"
+
+ "fixture/root/internal/helper"
+ _ "fixture/root/internal/initpkg"
+)
+
+//go:embed units/*.service
+var units embed.FS
+
+func Setup() {}
+
+func RunAdopt() { readConfig() }
+
+func readConfig() { os.ReadFile("/data/config") }
+
+func RunAgent() {
+ agentRead()
+ helper.Load()
+}
+
+func agentRead() { os.ReadFile("/data/agent") }
+
+func RunApply() { _ = units }
+
+func RunBootstrap() {}
+
+func RunBoot() { fmt.Println(bootValue{}) }
+
+func RunStatus() { os.ReadFile("/data/status") }
+
+type bootValue struct{}
+
+func (bootValue) String() string {
+ os.ReadFile("/data/boot")
+ return ""
+}
+
+func (bootValue) unused() { os.ReadFile("/data/unused") }
+`,
+ "internal/host/run.sh": "cat /data/host\n",
+ "internal/initpkg/init.go": `package initpkg
+
+import "os"
+
+func init() { initRead() }
+
+func initRead() { os.ReadFile("/data/init") }
+
+var v = varRead()
+
+func varRead() int {
+ os.ReadFile("/data/var")
+ return 1
+}
+`,
+ "internal/helper/helper.go": "package helper\n\nimport \"os\"\n\nfunc Load() { os.ReadFile(\"/data/helper\") }\n",
+ "internal/console/console.go": `package console
+
+import (
+ _ "embed"
+ "os"
+)
+
+//go:embed templates/page.html
+var page string
+
+func Serve() { consoleRead() }
+
+func consoleRead() {
+ os.ReadFile("/data/console")
+ _ = page
+}
+`,
+ "internal/console/templates/page.html": "<p>hello</p>\n",
+ "scripts/tool.sh": "cat /data/tool\n",
+ "infra/modules/box/main.tf": "resource \"null\" \"x\" {}\n",
+ }
+}
+
+func scopeTree(t *testing.T) string {
+ t.Helper()
+ t.Setenv("GOFLAGS", "-buildvcs=false")
+ root := t.TempDir()
+ writeTree(t, root, scopeFiles())
+ return root
+}
+
+func TestCensusRootVerbs(t *testing.T) {
+ got, err := rootVerbs(scopeTree(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]string{"main.go:main": "adopt,bootstrap,system", "system.go:runSystem": "apply,host-env,install-channel"}
+ for key, labels := range want {
+ var have []string
+ for l := range got[key] {
+ have = append(have, l)
+ }
+ if joined := strings.Join(sortedStrings(have), ","); joined != labels {
+ t.Errorf("%s: verbs %s, want %s", key, joined, labels)
+ }
+ }
+ if len(got) != len(want) {
+ t.Errorf("dispatchers %v", got)
+ }
+}
+
+func TestCensusRootScope(t *testing.T) {
+ root := scopeTree(t)
+ s, err := rootScopeOf(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{
+ "main.go:main", "system.go:runSystem",
+ "internal/host/host.go:RunAdopt", "internal/host/host.go:readConfig",
+ "internal/host/host.go:RunApply", "internal/host/host.go:var units",
+ "internal/host/units/carlos-edge.service:external",
+ "internal/host/host.go:RunBootstrap", "internal/host/host.go:RunBoot",
+ "internal/host/host.go:bootValue.String",
+ "internal/initpkg/init.go:init", "internal/initpkg/init.go:initRead", "internal/initpkg/init.go:varRead",
+ } {
+ if _, ok := s.Reached[k]; !ok {
+ t.Errorf("%s not in scope", k)
+ }
+ }
+ for _, k := range []string{
+ "internal/host/host.go:RunAgent", "internal/host/host.go:agentRead",
+ "internal/host/host.go:RunStatus", "internal/host/host.go:bootValue.unused",
+ "internal/helper/helper.go:Load",
+ "internal/console/console.go:Serve", "internal/console/console.go:consoleRead",
+ "internal/console/templates/page.html:external",
+ } {
+ if why, ok := s.Reached[k]; ok {
+ t.Errorf("%s in scope, reached from %s", k, why)
+ }
+ }
+}
+
+// A root unit that runs a verb the dispatcher has no case for fails: the
+// census must not lose the verb.
+func TestCensusScopeUnknownRootVerbFails(t *testing.T) {
+ root := scopeTree(t)
+ writeTree(t, root, map[string]string{"internal/host/units/carlos-new.service": "[Service]\nExecStart=/opt/carlos/carlos frobnicate\n"})
+ if _, err := rootScopeOf(root); err == nil || !strings.Contains(err.Error(), "frobnicate") {
+ t.Fatalf("err = %v, want the unknown verb named", err)
+ }
+ root = scopeTree(t)
+ writeTree(t, root, map[string]string{"internal/host/units/carlos-new.service": "[Service]\nExecStart=/opt/carlos/carlos system\n"})
+ if _, err := rootScopeOf(root); err == nil || !strings.Contains(err.Error(), "system") {
+ t.Fatalf("err = %v, want the missing system verb named", err)
+ }
+}
diff --git a/internal/provision/census_scope_test.go b/internal/provision/census_scope_test.go
new file mode 100644
index 000000000..81b08ee47
--- /dev/null
+++ b/internal/provision/census_scope_test.go
@@ -0,0 +1,503 @@
+package provision
+
+// The census's scope (C2; Paul's ruling 2 on #280, 2026-10-25, and his go
+// on #404, 2026-10-26): the root-read census covers only code root runs.
+// Root's entry points come from the systemd units that run as root; the
+// units they reach come from J4's reference graph (inputPlatformCallers),
+// built for linux, the only platform root runs on, and walked from those
+// entry points instead of main.go:main.
+
+import (
+ "fmt"
+ "go/ast"
+ "go/token"
+ "go/types"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sort"
+ "strings"
+ "sync"
+
+ "golang.org/x/tools/go/packages"
+)
+
+// rootDispatcher is a function that picks a verb with a switch on Tag.
+// Walking it from root follows everything outside that switch and only the
+// case clauses of verbs root runs. Verb is the verb main dispatches to it
+// ("" for main itself).
+type rootDispatcher struct{ Key, Tag, Verb string }
+
+var rootDispatchers = []rootDispatcher{
+ {Key: "main.go:main", Tag: "cmd"},
+ {Key: "system.go:runSystem", Tag: "verb", Verb: "system"},
+}
+
+// rootBootVerbs are run as root by a box's user_data at first boot (the
+// launch template lives in the infra repository, so no unit here names
+// them): carlos bootstrap, and on a box a region's group launches, system
+// host-env write and system install-channel.
+var rootBootVerbs = []string{"bootstrap", "system install-channel", "system host-env"}
+
+// rootCallbackMethods are the methods the standard library calls by name
+// through its own interfaces (fmt, encoding/json, errors, io, sort, net/http,
+// database/sql, io/fs). The graph sees no call for them, so a reached type
+// reaches these methods of its own.
+var rootCallbackMethods = map[string]bool{}
+
+func init() {
+ for _, name := range strings.Fields(`Error String GoString Format MarshalJSON UnmarshalJSON MarshalText UnmarshalText MarshalBinary UnmarshalBinary Scan Value Unwrap Is As Len Less Swap Push Pop Read Write Close Seek ReadAt WriteAt WriteTo ReadFrom ReadDir Stat Open ServeHTTP RoundTrip Deadline Done Err LogValue Set Get Flush`) {
+ rootCallbackMethods[name] = true
+ }
+}
+
+// rootUnitExec finds the carlos binary and the verb (and sub-verb) it is
+// given in a unit's Exec line, inside an inline sh -c script too.
+var rootUnitExec = regexp.MustCompile(`/opt/carlos/(?:system/guard/)?carlos(?:\.prev)?\s+([a-z][a-z0-9-]*)(?:\s+([a-z][a-z0-9-]*))?`)
+
+// rootVerbs is the verb labels root runs, per dispatcher: every verb in an
+// Exec line of a unit in internal/host/units with no User= (or User=root)
+// and no DynamicUser=, and the boot verbs. A verb that has its own
+// dispatcher ("system") needs a sub-verb.
+func rootVerbs(root string) (map[string]map[string]bool, error) {
+ dir := filepath.Join(root, "internal/host/units")
+ names, err := filepath.Glob(filepath.Join(dir, "*.service"))
+ if err != nil {
+ return nil, err
+ }
+ if len(names) == 0 {
+ return nil, fmt.Errorf("census scope: no units in %s", dir)
+ }
+ sort.Strings(names)
+ var verbs [][2]string
+ for _, name := range names {
+ raw, err := os.ReadFile(name)
+ if err != nil {
+ return nil, err
+ }
+ asRoot := true
+ var execs []string
+ for _, line := range strings.Split(string(raw), "\n") {
+ line = strings.TrimSpace(line)
+ key, value, _ := strings.Cut(line, "=")
+ switch {
+ case key == "User" && strings.TrimSpace(value) != "root" && strings.TrimSpace(value) != "":
+ asRoot = false
+ case key == "DynamicUser" && (strings.TrimSpace(value) == "yes" || strings.TrimSpace(value) == "true"):
+ asRoot = false
+ case strings.HasPrefix(key, "Exec"):
+ execs = append(execs, value)
+ }
+ }
+ if !asRoot {
+ continue
+ }
+ for _, line := range execs {
+ for _, m := range rootUnitExec.FindAllStringSubmatch(line, -1) {
+ verbs = append(verbs, [2]string{m[1], m[2]})
+ }
+ }
+ }
+ for _, v := range rootBootVerbs {
+ verb, sub, _ := strings.Cut(v, " ")
+ verbs = append(verbs, [2]string{verb, sub})
+ }
+ out := map[string]map[string]bool{}
+ add := func(key, label string) {
+ if out[key] == nil {
+ out[key] = map[string]bool{}
+ }
+ out[key][label] = true
+ }
+ for _, v := range verbs {
+ add(rootDispatchers[0].Key, v[0])
+ for _, d := range rootDispatchers[1:] {
+ if d.Verb != v[0] {
+ continue
+ }
+ if v[1] == "" {
+ return nil, fmt.Errorf("census scope: a root unit runs %q with no sub-verb", v[0])
+ }
+ add(d.Key, v[1])
+ }
+ }
+ return out, nil
+}
+
+type refMethod struct{ Name, Key string }
+
+// refGraph is J4's reference graph for one platform: every declaration
+// (keyed as the census keys it, rootReadDeclName) to what it references.
+type refGraph struct {
+ // Edges: identifier uses, interface dispatch to every implementing
+ // method, json.Unmarshal to UnmarshalJSON, //go:embed to the embedded
+ // file ("<path>:external"). Every case of every dispatcher.
+ Edges map[string]map[string]bool
+ // Cases splits a dispatcher's edges by case label of its verb switch;
+ // "" holds everything outside that switch's labelled cases.
+ Cases map[string]map[string]map[string]bool
+ // Labels is every case label of each dispatcher's verb switch.
+ Labels map[string]map[string]bool
+ // Methods: a type's declaration key to its methods.
+ Methods map[string][]refMethod
+ // Inits: every init function, and every function a package-level var
+ // initializer calls, in the packages linked into the binary at root.
+ Inits []string
+}
+
+func newRefGraph() *refGraph {
+ return &refGraph{Edges: map[string]map[string]bool{}, Cases: map[string]map[string]map[string]bool{}, Labels: map[string]map[string]bool{}, Methods: map[string][]refMethod{}}
+}
+
+func refAdd(g map[string]map[string]bool, a, b string) {
+ if a == "" || b == "" || a == b {
+ return
+ }
+ if g[a] == nil {
+ g[a] = map[string]bool{}
+ }
+ g[a][b] = true
+}
+
+// censusGraph loads root's module for one platform and builds its graph.
+func censusGraph(root, platform string) (*refGraph, error) {
+ cfg := &packages.Config{Dir: root, Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports, Env: append(os.Environ(), "GOOS="+platform, "GOARCH=amd64", "CGO_ENABLED=0")}
+ pkgs, err := packages.Load(cfg, "./...")
+ if err != nil {
+ return nil, err
+ }
+ if packages.PrintErrors(pkgs) > 0 {
+ return nil, fmt.Errorf("production package loading failed")
+ }
+ type decl struct {
+ key string
+ node ast.Decl
+ pkg *packages.Package
+ }
+ var decls []decl
+ objects := map[types.Object]string{}
+ methods := map[string][]*types.Func{}
+ for _, p := range pkgs {
+ for _, f := range p.Syntax {
+ file, _ := filepath.Rel(root, p.Fset.Position(f.Pos()).Filename)
+ file = filepath.ToSlash(file)
+ grouped := map[string]int{}
+ for _, d := range f.Decls {
+ name, ok := rootReadDeclName(d, grouped)
+ if !ok {
+ continue
+ }
+ key := file + ":" + name
+ switch d := d.(type) {
+ case *ast.FuncDecl:
+ if obj, ok := p.TypesInfo.Defs[d.Name].(*types.Func); ok {
+ objects[obj] = key
+ if obj.Type().(*types.Signature).Recv() != nil {
+ methods[obj.Name()] = append(methods[obj.Name()], obj)
+ }
+ }
+ case *ast.GenDecl:
+ ast.Inspect(d, func(n ast.Node) bool {
+ if id, ok := n.(*ast.Ident); ok {
+ if obj := p.TypesInfo.Defs[id]; obj != nil {
+ objects[obj] = key
+ }
+ }
+ return true
+ })
+ }
+ decls = append(decls, decl{key, d, p})
+ }
+ }
+ }
+ g := newRefGraph()
+ for _, ms := range methods {
+ for _, m := range ms {
+ r := m.Type().(*types.Signature).Recv().Type()
+ if ptr, ok := r.(*types.Pointer); ok {
+ r = ptr.Elem()
+ }
+ if n, ok := r.(*types.Named); ok {
+ if tk := objects[n.Origin().Obj()]; tk != "" {
+ g.Methods[tk] = append(g.Methods[tk], refMethod{m.Name(), objects[m]})
+ }
+ }
+ }
+ }
+ // nodeRefs is one node's references, as J4 has always counted them.
+ nodeRefs := func(d decl, n ast.Node, add func(string)) {
+ if call, ok := n.(*ast.CallExpr); ok && len(call.Args) == 2 {
+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
+ obj := d.pkg.TypesInfo.Uses[sel.Sel]
+ if obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "encoding/json" && obj.Name() == "Unmarshal" {
+ for _, method := range inputJSONMethods(d.pkg.TypesInfo.TypeOf(call.Args[1]), map[types.Type]bool{}) {
+ add(objects[method])
+ }
+ }
+ }
+ }
+ if id, ok := n.(*ast.Ident); ok {
+ add(objects[d.pkg.TypesInfo.Uses[id]])
+ }
+ if s, ok := n.(*ast.SelectorExpr); ok {
+ if sel := d.pkg.TypesInfo.Selections[s]; sel != nil {
+ if iface, ok := sel.Recv().Underlying().(*types.Interface); ok {
+ if method, ok := sel.Obj().(*types.Func); ok {
+ for _, candidate := range methods[method.Name()] {
+ sig := candidate.Type().(*types.Signature)
+ if types.Implements(sig.Recv().Type(), iface) || types.Implements(types.NewPointer(sig.Recv().Type()), iface) {
+ add(objects[candidate])
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ walk := func(d decl, n ast.Node, add func(string)) {
+ if n == nil {
+ return
+ }
+ ast.Inspect(n, func(n ast.Node) bool {
+ nodeRefs(d, n, add)
+ return true
+ })
+ }
+ tags := map[string]string{}
+ for _, rd := range rootDispatchers {
+ tags[rd.Key] = rd.Tag
+ }
+ for _, d := range decls {
+ walk(d, d.node, func(to string) { refAdd(g.Edges, d.key, to) })
+ // The embedded unit is an input to the reachable installer declaration.
+ if gd, ok := d.node.(*ast.GenDecl); ok && gd.Doc != nil {
+ for _, c := range gd.Doc.List {
+ if strings.HasPrefix(c.Text, "//go:embed ") {
+ for _, pattern := range strings.Fields(strings.TrimPrefix(c.Text, "//go:embed ")) {
+ matches, _ := filepath.Glob(filepath.Join(root, filepath.Dir(strings.Split(d.key, ":")[0]), pattern))
+ for _, path := range matches {
+ rel, _ := filepath.Rel(root, path)
+ refAdd(g.Edges, d.key, filepath.ToSlash(rel)+":external")
+ }
+ }
+ }
+ }
+ }
+ tag, dispatcher := tags[d.key]
+ if !dispatcher {
+ continue
+ }
+ cases := map[string]map[string]bool{}
+ g.Cases[d.key] = cases
+ g.Labels[d.key] = map[string]bool{}
+ into := func(label string) func(string) {
+ return func(to string) { refAdd(cases, label, to) }
+ }
+ ast.Inspect(d.node, func(n ast.Node) bool {
+ sw, ok := n.(*ast.SwitchStmt)
+ if ok {
+ id, isIdent := sw.Tag.(*ast.Ident)
+ ok = isIdent && id.Name == tag
+ }
+ if !ok {
+ nodeRefs(d, n, into(""))
+ return true
+ }
+ walk(d, sw.Init, into(""))
+ walk(d, sw.Tag, into(""))
+ for _, s := range sw.Body.List {
+ cc := s.(*ast.CaseClause)
+ var labels []string
+ for _, e := range cc.List {
+ lit, ok := e.(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ labels = nil
+ break
+ }
+ labels = append(labels, strings.Trim(lit.Value, "\"`"))
+ }
+ if len(labels) == 0 {
+ labels = []string{""}
+ }
+ for _, l := range labels {
+ if l != "" {
+ g.Labels[d.key][l] = true
+ }
+ for _, e := range cc.List {
+ walk(d, e, into(l))
+ }
+ for _, st := range cc.Body {
+ walk(d, st, into(l))
+ }
+ }
+ }
+ return false
+ })
+ }
+ // The packages linked into the binary built from root's own directory.
+ linked := map[string]bool{}
+ var link func(p *packages.Package)
+ link = func(p *packages.Package) {
+ if linked[p.PkgPath] {
+ return
+ }
+ linked[p.PkgPath] = true
+ for _, q := range p.Imports {
+ link(q)
+ }
+ }
+ for _, p := range pkgs {
+ if p.Name == "main" && len(p.GoFiles) > 0 && filepath.Clean(filepath.Dir(p.GoFiles[0])) == filepath.Clean(root) {
+ link(p)
+ }
+ }
+ for _, d := range decls {
+ if !linked[d.pkg.PkgPath] {
+ continue
+ }
+ switch n := d.node.(type) {
+ case *ast.FuncDecl:
+ if n.Recv == nil && n.Name.Name == "init" {
+ g.Inits = append(g.Inits, d.key)
+ }
+ case *ast.GenDecl:
+ if n.Tok != token.VAR {
+ continue
+ }
+ ast.Inspect(n, func(x ast.Node) bool {
+ call, ok := x.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ var id *ast.Ident
+ switch f := call.Fun.(type) {
+ case *ast.Ident:
+ id = f
+ case *ast.SelectorExpr:
+ id = f.Sel
+ }
+ if id != nil {
+ if fn, ok := d.pkg.TypesInfo.Uses[id].(*types.Func); ok && objects[fn] != "" {
+ g.Inits = append(g.Inits, objects[fn])
+ }
+ }
+ return true
+ })
+ }
+ }
+ sort.Strings(g.Inits)
+ return g, nil
+}
+
+// censusGraphs caches the repository's graphs within one test process, so
+// the census and J4 load linux once between them. Fixture trees, which
+// tests edit between loads, use censusGraph directly.
+var censusGraphs sync.Map
+
+type censusGraphOnce struct {
+ once sync.Once
+ g *refGraph
+ err error
+}
+
+func censusGraphShared(root, platform string) (*refGraph, error) {
+ v, _ := censusGraphs.LoadOrStore(root+"\x00"+platform, &censusGraphOnce{})
+ c := v.(*censusGraphOnce)
+ c.once.Do(func() { c.g, c.err = censusGraph(root, platform) })
+ return c.g, c.err
+}
+
+// reach walks the graph from start. A dispatcher in allowed is expanded by
+// its "" edges and its allowed labels' only; a reached type reaches its
+// standard-library callback methods.
+func (g *refGraph) reach(start map[string]string, allowed map[string]map[string]bool) map[string]string {
+ reached := map[string]string{}
+ var queue []string
+ push := func(to, from string) {
+ if to == "" {
+ return
+ }
+ if _, ok := reached[to]; !ok {
+ reached[to] = from
+ queue = append(queue, to)
+ }
+ }
+ var seeds []string
+ for k := range start {
+ seeds = append(seeds, k)
+ }
+ sort.Strings(seeds)
+ for _, k := range seeds {
+ push(k, start[k])
+ }
+ for len(queue) > 0 {
+ from := queue[0]
+ queue = queue[1:]
+ var next []string
+ if labels, ok := allowed[from]; ok && g.Cases[from] != nil {
+ for to := range g.Cases[from][""] {
+ next = append(next, to)
+ }
+ for l := range labels {
+ for to := range g.Cases[from][l] {
+ next = append(next, to)
+ }
+ }
+ } else {
+ for to := range g.Edges[from] {
+ next = append(next, to)
+ }
+ }
+ for _, m := range g.Methods[from] {
+ if rootCallbackMethods[m.Name] {
+ next = append(next, m.Key)
+ }
+ }
+ sort.Strings(next)
+ for _, to := range next {
+ push(to, from)
+ }
+ }
+ return reached
+}
+
+// rootScope is what root runs: every declaration (and embedded file,
+// "<path>:external") reached from root's entry points, each with the
+// declaration it was reached from.
+type rootScope struct {
+ Reached map[string]string
+}
+
+// rootScopeOf builds root's scope from the tree at root.
+func rootScopeOf(root string) (rootScope, error) {
+ g, err := censusGraph(root, "linux")
+ if err != nil {
+ return rootScope{}, err
+ }
+ return rootScopeFrom(root, g)
+}
+
+func rootScopeFrom(root string, g *refGraph) (rootScope, error) {
+ allowed, err := rootVerbs(root)
+ if err != nil {
+ return rootScope{}, err
+ }
+ for key, labels := range allowed {
+ for l := range labels {
+ if !g.Labels[key][l] {
+ return rootScope{}, fmt.Errorf("census scope: root runs verb %q, but %s has no case for it", l, key)
+ }
+ }
+ }
+ start := map[string]string{rootDispatchers[0].Key: "root entry point"}
+ for _, k := range g.Inits {
+ start[k] = "init in the root binary"
+ }
+ return rootScope{Reached: g.reach(start, allowed)}, nil
+}
+
+func sortedStrings(s []string) []string {
+ out := append([]string(nil), s...)
+ sort.Strings(out)
+ return out
+}
diff --git a/internal/provision/plan14_input_inventory_test.go b/internal/provision/plan14_input_inventory_test.go
index d13f3635e..b61b86381 100644
--- a/internal/provision/plan14_input_inventory_test.go
+++ b/internal/provision/plan14_input_inventory_test.go
@@ -13,8 +13,6 @@ import (
"strings"
"sync"
"testing"
-
- "golang.org/x/tools/go/packages"
)
type inputFamily struct {
@@ -126,11 +124,22 @@ func inputTests(root string) (map[string]bool, error) {
return out, err
}
-// This is a conservative, typed production call/reference graph. Function values
+// This is a conservative, typed production call/reference graph (built by
+// censusGraph, which the census shares). Function values
// count as possible calls; interface dispatch includes only implementing methods.
// Type/var declarations use references (not imaginary calls). Tests never enter
// the graph. Every accepted row records its reachable immediate predecessor.
func inputCallers(root string) (map[string]string, error) {
+ return inputCallersWith(root, censusGraph)
+}
+
+// inputCallersShared is inputCallers on the graphs the census shares
+// within one test process (censusGraphShared).
+func inputCallersShared(root string) (map[string]string, error) {
+ return inputCallersWith(root, censusGraphShared)
+}
+
+func inputCallersWith(root string, load func(root, platform string) (*refGraph, error)) (map[string]string, error) {
// Each platform's load type-checks the whole module (most of this
// test's time), and the three are independent, so they run side by
// side. The merge below still takes them in this fixed order, so a key
@@ -140,7 +149,14 @@ func inputCallers(root string) (map[string]string, error) {
errs := make([]error, len(platforms))
var wg sync.WaitGroup
for i, platform := range platforms {
- wg.Go(func() { loaded[i], errs[i] = inputPlatformCallers(root, platform) })
+ wg.Go(func() {
+ g, err := load(root, platform)
+ if err != nil {
+ errs[i] = err
+ return
+ }
+ loaded[i] = inputPlatformCallers(g)
+ })
}
wg.Wait()
out := map[string]string{}
@@ -157,139 +173,10 @@ func inputCallers(root string) (map[string]string, error) {
}
return out, nil
}
-func inputPlatformCallers(root, platform string) (map[string]string, error) {
- cfg := &packages.Config{Dir: root, Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports, Env: append(os.Environ(), "GOOS="+platform, "GOARCH=amd64", "CGO_ENABLED=0")}
- pkgs, err := packages.Load(cfg, "./...")
- if err != nil {
- return nil, err
- }
- if packages.PrintErrors(pkgs) > 0 {
- return nil, fmt.Errorf("production package loading failed")
- }
- type decl struct {
- key string
- node ast.Node
- pkg *packages.Package
- }
- var decls []decl
- objects := map[types.Object]string{}
- methods := map[string][]*types.Func{}
- graph := map[string]map[string]bool{}
- add := func(a, b string) {
- if a == "" || b == "" || a == b {
- return
- }
- if graph[a] == nil {
- graph[a] = map[string]bool{}
- }
- graph[a][b] = true
- }
- for _, p := range pkgs {
- for _, f := range p.Syntax {
- file, _ := filepath.Rel(root, p.Fset.Position(f.Pos()).Filename)
- file = filepath.ToSlash(file)
- grouped := map[token.Token]int{}
- for _, d := range f.Decls {
- name := ""
- var defs []types.Object
- switch d := d.(type) {
- case *ast.FuncDecl:
- name = d.Name.Name
- if obj, ok := p.TypesInfo.Defs[d.Name].(*types.Func); ok {
- defs = append(defs, obj)
- sig := obj.Type().(*types.Signature)
- if sig.Recv() != nil {
- r := sig.Recv().Type()
- if ptr, ok := r.(*types.Pointer); ok {
- r = ptr.Elem()
- }
- if n, ok := r.(*types.Named); ok {
- name = n.Obj().Name() + "." + name
- }
- methods[obj.Name()] = append(methods[obj.Name()], obj)
- }
- }
- case *ast.GenDecl:
- if d.Tok == token.IMPORT {
- continue
- }
- if d.Lparen.IsValid() {
- grouped[d.Tok]++
- name = fmt.Sprintf("%s#%d", d.Tok, grouped[d.Tok])
- } else {
- switch s := d.Specs[0].(type) {
- case *ast.TypeSpec:
- name = "type " + s.Name.Name
- case *ast.ValueSpec:
- name = d.Tok.String() + " " + s.Names[0].Name
- }
- }
- ast.Inspect(d, func(n ast.Node) bool {
- if id, ok := n.(*ast.Ident); ok {
- if obj := p.TypesInfo.Defs[id]; obj != nil {
- defs = append(defs, obj)
- }
- }
- return true
- })
- }
- if name == "" {
- continue
- }
- key := file + ":" + name
- decls = append(decls, decl{key, d, p})
- for _, obj := range defs {
- objects[obj] = key
- }
- }
- }
- }
- for _, d := range decls {
- ast.Inspect(d.node, func(n ast.Node) bool {
- if call, ok := n.(*ast.CallExpr); ok && len(call.Args) == 2 {
- if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
- obj := d.pkg.TypesInfo.Uses[sel.Sel]
- if obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "encoding/json" && obj.Name() == "Unmarshal" {
- for _, method := range inputJSONMethods(d.pkg.TypesInfo.TypeOf(call.Args[1]), map[types.Type]bool{}) {
- add(d.key, objects[method])
- }
- }
- }
- }
- if id, ok := n.(*ast.Ident); ok {
- add(d.key, objects[d.pkg.TypesInfo.Uses[id]])
- }
- if s, ok := n.(*ast.SelectorExpr); ok {
- if sel := d.pkg.TypesInfo.Selections[s]; sel != nil {
- if iface, ok := sel.Recv().Underlying().(*types.Interface); ok {
- if method, ok := sel.Obj().(*types.Func); ok {
- for _, candidate := range methods[method.Name()] {
- sig := candidate.Type().(*types.Signature)
- if types.Implements(sig.Recv().Type(), iface) || types.Implements(types.NewPointer(sig.Recv().Type()), iface) {
- add(d.key, objects[candidate])
- }
- }
- }
- }
- }
- }
- return true
- })
- // The embedded unit is an input to the reachable installer declaration.
- if gd, ok := d.node.(*ast.GenDecl); ok && gd.Doc != nil {
- for _, c := range gd.Doc.List {
- if strings.HasPrefix(c.Text, "//go:embed ") {
- for _, pattern := range strings.Fields(strings.TrimPrefix(c.Text, "//go:embed ")) {
- matches, _ := filepath.Glob(filepath.Join(root, filepath.Dir(strings.Split(d.key, ":")[0]), pattern))
- for _, path := range matches {
- rel, _ := filepath.Rel(root, path)
- add(d.key, filepath.ToSlash(rel)+":external")
- }
- }
- }
- }
- }
- }
+
+// inputPlatformCallers walks one platform's graph (censusGraph) from the
+// two shipped executables' entry points.
+func inputPlatformCallers(g *refGraph) map[string]string {
// The console is a separate shipped executable. Its floor admission and
// control-store writers were explicitly classified as authority; they do
// not become unreachable because they are outside the carlos binary.
@@ -299,7 +186,7 @@ func inputPlatformCallers(root, platform string) (map[string]string, error) {
from := queue[0]
queue = queue[1:]
var next []string
- for to := range graph[from] {
+ for to := range g.Edges[from] {
next = append(next, to)
}
sort.Strings(next)
@@ -310,7 +197,7 @@ func inputPlatformCallers(root, platform string) (map[string]string, error) {
}
}
}
- return reached, nil
+ return reached
}
// encoding/json invokes these typed callbacks through reflection, outside the
@@ -578,7 +465,7 @@ func TestPlan14RootInputInventoryCoverage(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- callers, err := inputCallers(root)
+ callers, err := inputCallersShared(root)
if err != nil {
t.Fatal(err)
}