carlos / platform Public

console: gate guard follows helpers, marshallers and pins blind spots

Review round 1 (five P2s):
- trace package-local returns, multi-result and range assignments,
  structs in locals, maps or receivers filled by package callees, and
  wrappers that wrap their parameter; what cannot be followed is pinned
  in gsUnresolved (three sites, each read by hand), failing on change
- a type with MarshalJSON/MarshalText, promoted or not, gets no shadow
  protection: every field it holds is walked (registry.ColdRows)
- memoise and track embedding by type identity (typeutil.Map)
- mirror encoding/json's isValidTag
- go-toolchain.sh: 1.26.11 carries the GO-2026-6859 fix and a separate
  deadlocking change; the trigger needs an over-limit body.
  GOTOOLCHAIN unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev beb2201513facb9cfd9e2d7af53b263644765e78 parent e73abf3
2 files changed, +893 −226
  • .amadan/go-toolchain.sh +7 −5
  • internal/console/gate_shadow_guard_test.go +886 −221

CI passed — run details

diff --git a/.amadan/go-toolchain.sh b/.amadan/go-toolchain.sh
index b3e48ac13..549fe8de5 100644
--- a/.amadan/go-toolchain.sh
+++ b/.amadan/go-toolchain.sh
@@ -18,11 +18,13 @@
# Re-check when Go ships a fix for the deadlock: move this to that version,
# with the early subtests as the witness.
#
-# GO-2026-6859 is present in 1.26.10 but needs a body read on another
-# goroutine than the handler's while it writes headers, with net/http's own
-# response writer passed to MaxBytesReader; #904 checked every production
-# MaxBytesReader site and found none. Its fix in 1.26.11 is the same change
-# that brings the deadlock, so moving the pin waits for both.
+# GO-2026-6859 is present in 1.26.10. Triggering it needs a request body
+# that exceeds its MaxBytesReader limit, read on another goroutine than the
+# handler's while the handler writes headers, with net/http's own response
+# writer passed to MaxBytesReader; #904 checked every production
+# MaxBytesReader site and found none. Go 1.26.11 contains both the
+# GO-2026-6859 fix and a separate change that deadlocks the edge proxy, and
+# no release yet has the fix without the deadlock.
GOTOOLCHAIN=go1.26.10+auto
export GOTOOLCHAIN
go version
diff --git a/internal/console/gate_shadow_guard_test.go b/internal/console/gate_shadow_guard_test.go
index 9f4fa6f96..a8229571b 100644
--- a/internal/console/gate_shadow_guard_test.go
+++ b/internal/console/gate_shadow_guard_test.go
@@ -10,32 +10,40 @@ package console
// It type-checks the package once and finds every JSON sink in it, by the
// callee's types.Func.FullName: writeJSON (its body), json.Marshal,
// json.MarshalIndent and (*json.Encoder).Encode, plus every function of the
-// package that hands one of its own interface-typed parameters straight to a
-// sink (demoClaimReply, demoOperatorJSON, relayConn.send: a wrapper), found to
-// a fixed point. For each call it takes the static type of the body argument;
-// where that is an interface or holds interfaces (map[string]any), it looks
-// through a composite literal's values, an any(x) conversion and append's
-// arguments, and through a local variable to everything the enclosing
-// function assigns to it or to its elements. It then walks each type as
-// encoding/json would (exported fields; embedded structs promoted, with the
-// shallowest field of a JSON name winning, a tagged one breaking a tie and an
-// untied pair dropping both; pointers, slices, arrays and map values) and
-// fails where a Gate field wins under its own JSON name ("gate" for Record,
-// "Gate" for Route, which has no tag), naming the call site.
+// package whose sink body can carry one of its own interface-holding
+// parameters (demoClaimReply, relayConn.send, or one that wraps the parameter
+// in a map: a wrapper), found to a fixed point.
+//
+// For each call it takes the static type of the body argument. Where a value
+// can hide another type (an interface, or a map, slice, array, pointer or
+// struct holding one) it follows the value back: a composite literal's
+// values in such slots, any(x), append, a type assertion, a local variable or
+// one of its fields or elements to everything the function assigns there
+// (multi-result and range assignments included), and a call to a function of
+// the package into its return expressions, binding its parameters to the
+// call's arguments. What it cannot follow (a function value, a callee given a
+// map or pointer to fill, a package variable, a struct field read off a
+// parameter, a call outside the package) is an unresolved site, and
+// gsUnresolved pins that inventory: a site appearing or disappearing fails,
+// so a new blind spot is always seen and checked by hand.
+//
+// Each type is then walked as encoding/json walks it (exported fields;
+// embedded structs promoted, the shallowest field of a JSON name winning, a
+// tagged one breaking a tie and an untied pair dropping both; invalid tag
+// names ignored; pointers, slices, arrays and map values), failing where a
+// Gate field wins under its own JSON name ("gate" for Record, "Gate" for
+// Route, which has no tag). A type whose method set, promoted methods
+// included, has MarshalJSON or MarshalText is not encoded field by field, so
+// no shadow protects it: every field it holds, exported or not, is walked,
+// and any Gate reached fails (registry.ColdRows writes its whole Route).
//
// json.Marshal also builds what the console stores, and a stored record must
// keep its hash. Those few calls are named in gsNotResponses, by enclosing
// function and body type; an entry that no longer matches fails.
//
-// A type with its own MarshalJSON is walked as if it had none: the guard
-// cannot read what the method writes, so it assumes the fields
-// (registry.ColdRows marshals a whole Route that way). Not seen: a value
-// stored in a struct or map field and marshalled elsewhere (systemJob's
-// result), a map filled by a callee (echoCreatedRegion), and a sink reached
-// through a function value. Those still need a reviewer.
-//
// A negative control type-checks a small in-memory package against the same
-// provision and registry types and must flag exactly its leak* functions.
+// provision and registry types: exactly its leak* functions must be flagged
+// and exactly its unresolved* functions reported as unresolved.
import (
"fmt"
@@ -49,6 +57,7 @@ import (
"sort"
"strings"
"testing"
+ "unicode"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
@@ -59,6 +68,34 @@ const (
gsRegistry = "github.com/carlosframework/platform/internal/registry"
)
+// gsNotResponses are the json.Marshal calls that must carry the hash because
+// they are not answers: an enclosing function (FullName) and the body types it
+// may marshal whole. Adding one is a ruling; the reason goes beside it.
+var gsNotResponses = map[string][]string{
+ // The record a new lifetime writes to the bucket (Allocation.Body ->
+ // provision.WriteRecord): the bucket is where the hash lives.
+ "(*" + sgConsole + ".Server).createRecordWithLifetimeLocked": {gsProvision + ".Record"},
+ // An in-memory change stamp for the replica placement cache, compared
+ // and never sent.
+ sgConsole + ".replicaStamp": {gsProvision + ".Record"},
+}
+
+// gsUnresolved is every place a JSON body's value comes from that the guard
+// cannot follow, as "function: kind expression". Each was read by hand and
+// carries no record or route. A new one fails until it is made traceable or
+// read and added; one that disappears fails until removed.
+var gsUnresolved = []string{
+ // stamp is a local func value: nil, or a time formatted RFC 3339.
+ "(*Server).handleAPIAppList: call stamp",
+ // region is filled by echoCreatedRegion inside a closure: region codes,
+ // names, a label, a source and the available list, no record.
+ "(*Server).handleAPICreateApp: handed to maps.Copy",
+ // The job comes from s.systemJobs; its Result is set only by
+ // setResult, whose one caller (apisystemgeoip.go) stores a
+ // geoip.Pointer.
+ "(*Server).handleAPISystemJob: receiver s",
+}
+
func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
@@ -80,8 +117,8 @@ func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
gates := gsGateFields(t, deps)
res := gsScan(pkg.Fset, pkg.TypesInfo, pkg.Syntax, pkg.Types, gates)
- t.Logf("%d JSON sink calls checked; %d shadowed Gate fields seen; wrappers: %s",
- res.calls, res.shadowed, strings.Join(res.wrappers, ", "))
+ t.Logf("%d JSON sink calls checked; %d shadowed Gate fields seen; %d unresolved sites; wrappers: %s",
+ res.calls, res.shadowed, len(res.open), strings.Join(res.wrappers, ", "))
used := map[string]bool{}
for _, f := range res.findings {
if slices.Contains(gsNotResponses[f.fn], f.root) {
@@ -95,6 +132,16 @@ func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
t.Errorf("gsNotResponses names %s, which no longer marshals a gate hash; remove the entry", fn)
}
}
+ for _, k := range gsSortedKeys(res.open) {
+ if !slices.Contains(gsUnresolved, k) {
+ t.Errorf("%s: the guard cannot follow %q into a JSON body; make it traceable, or read it by hand and add it to gsUnresolved", res.open[k].pos, k)
+ }
+ }
+ for _, k := range gsUnresolved {
+ if _, ok := res.open[k]; !ok {
+ t.Errorf("gsUnresolved lists %q, which the guard no longer finds; remove it", k)
+ }
+ }
// The guard must have seen what it guards: the record views' shadows,
// and the sinks it is named for. Zero means it went blind (a field or
// sink renamed), not that the package is clean.
@@ -110,16 +157,19 @@ func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
}
info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{},
Uses: map[*ast.Ident]types.Object{}, Selections: map[*ast.SelectorExpr]*types.Selection{},
- Instances: map[*ast.Ident]types.Instance{}}
+ Instances: map[*ast.Ident]types.Instance{}, Implicits: map[ast.Node]types.Object{}}
conf := types.Config{Importer: gsImporter(deps)}
fix, err := conf.Check("example.com/gateshadowfixture", fset, []*ast.File{file}, info)
if err != nil {
t.Fatalf("type-check the fixture: %v", err)
}
res := gsScan(fset, info, []*ast.File{file}, fix, gates)
- got := map[string]bool{}
+ flagged, open := map[string]bool{}, map[string]bool{}
for _, f := range res.findings {
- got[f.in] = true
+ flagged[f.in] = true
+ }
+ for _, o := range res.open {
+ open[o.in] = true
}
for _, d := range file.Decls {
fd, ok := d.(*ast.FuncDecl)
@@ -127,23 +177,36 @@ func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
continue
}
name := fd.Name.Name
- switch want := strings.HasPrefix(name, "leak"); {
- case want && !got[name]:
+ switch leak := strings.HasPrefix(name, "leak"); {
+ case leak && !flagged[name]:
t.Errorf("fixture %s leaks the gate hash but was not flagged", name)
- case !want && got[name]:
+ case !leak && flagged[name]:
t.Errorf("fixture %s shadows the gate hash but was flagged", name)
}
+ switch unres := strings.HasPrefix(name, "unresolved"); {
+ case unres && !open[name]:
+ t.Errorf("fixture %s cannot be followed but was not reported unresolved", name)
+ case !unres && open[name]:
+ t.Errorf("fixture %s was reported unresolved", name)
+ }
+ }
+ if t.Failed() {
+ for _, k := range gsSortedKeys(res.open) {
+ t.Logf("unresolved: %s", k)
+ }
}
})
}
-// gsFixtureSrc is the negative control. The first two are the plan's; the
-// rest pin each way the scan looks through a body.
+// gsFixtureSrc is the negative control. Each leak* function must be flagged,
+// each unresolved* one reported unresolved, and nothing else either.
const gsFixtureSrc = `package gateshadowfixture
import (
"encoding/json"
"io"
+ "maps"
+ "time"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
@@ -211,20 +274,133 @@ func leakEncoderMethod() {
enc := json.NewEncoder(io.Discard)
_ = enc.Encode(struct{ R *registry.Route }{})
}
-`
-// gsNotResponses are the json.Marshal calls that must carry the hash because
-// they are not answers: an enclosing function (FullName) and the body types it
-// may marshal whole. Adding one is a ruling; the reason goes beside it.
-var gsNotResponses = map[string][]string{
- // The record a new lifetime writes to the bucket (Allocation.Body ->
- // provision.WriteRecord): the bucket is where the hash lives.
- "(*" + sgConsole + ".Server).createRecordWithLifetimeLocked": {gsProvision + ".Record"},
- // An in-memory change stamp for the replica placement cache, compared
- // and never sent.
- sgConsole + ".replicaStamp": {gsProvision + ".Record"},
+// Returns of the package's own functions, with their parameters bound.
+func answer() map[string]any { return map[string]any{"rec": provision.Record{}} }
+
+func leakHelperReturn() { _, _ = json.Marshal(answer()) }
+
+func wrapIt(x any) map[string]any {
+ out := map[string]any{}
+ out["x"] = x
+ return out
+}
+
+func leakHelperParam() { _, _ = json.Marshal(wrapIt(v{})) }
+
+func safeHelperParam() { _, _ = json.Marshal(wrapIt(w{})) }
+
+func scanReply() (any, error) { return v{}, nil }
+
+func leakMultiResult() {
+ reply, err := scanReply()
+ if err != nil {
+ return
+ }
+ _, _ = json.Marshal(reply)
+}
+
+func named() (out any) {
+ out = &v{}
+ return
+}
+
+func leakNamedResult() { _, _ = json.Marshal(named()) }
+
+// Structs held in locals.
+func leakStructLocal() {
+ resp := struct{ X any }{X: v{}}
+ _, _ = json.Marshal(resp)
+}
+
+func leakStructFieldAssign() {
+ var resp struct{ X any }
+ resp.X = []v{}
+ _, _ = json.Marshal(&resp)
+}
+
+func leakRange() {
+ items := []any{v{}}
+ for _, it := range items {
+ _, _ = json.Marshal(it)
+ }
+}
+
+// A wrapper that wraps its parameter before encoding it.
+func replyData(dst io.Writer, body any) {
+ _ = json.NewEncoder(dst).Encode(map[string]any{"data": body})
+}
+
+func leakWrapperWrapsParam() { replyData(io.Discard, v{}) }
+
+func safeWrapperWrapsParam() { replyData(io.Discard, w{}) }
+
+// A promoted MarshalJSON makes the shadow useless: ColdRows writes its
+// whole Route.
+type coldView struct {
+ registry.ColdRows
+ Route struct{}
+}
+
+func leakPromotedMarshaler() { _, _ = json.Marshal(coldView{}) }
+
+func safeMarshaler() { _, _ = json.Marshal(struct{ At time.Time }{}) }
+
+// Two local types of one name are two types.
+func safeLocalType() {
+ type response struct{ OK bool }
+ _, _ = json.Marshal(response{})
+}
+
+func leakLocalType() {
+ type response struct{ provision.Record }
+ _, _ = json.Marshal(response{})
+}
+
+// An invalid tag name is ignored: A and B keep their Go names, both emitted.
+func leakInvalidTags() {
+ _, _ = json.Marshal(struct {
+ A provision.Record ` + "`json:\"\\t\"`" + `
+ B provision.Record ` + "`json:\"\\t\"`" + `
+ }{})
+}
+
+// A map or receiver a function of the package fills.
+func fill(m map[string]any) { m["rec"] = v{} }
+
+func leakFilledByCallee() {
+ out := make(map[string]any)
+ fill(out)
+ _, _ = json.Marshal(out)
+}
+
+type bag struct{ M map[string]any }
+
+func (b *bag) put(x any) { b.M["x"] = x }
+
+func leakFilledByMethod() {
+ b := bag{M: map[string]any{}}
+ b.put(v{})
+ _, _ = json.Marshal(b)
+}
+
+// What the guard cannot follow.
+func unresolvedCallee() {
+ out := map[string]any{}
+ maps.Copy(out, map[string]any{})
+ _, _ = json.Marshal(out)
}
+func unresolvedFuncValue() {
+ f := func() any { return v{} }
+ _, _ = json.Marshal(f())
+}
+
+var held any
+
+func unresolvedPackageVar() { _, _ = json.Marshal(held) }
+`
+
// gsGate is a guarded field and the JSON name it is emitted under.
type gsGate struct {
owner string
@@ -293,6 +469,15 @@ func (m gsImporter) Import(path string) (*types.Package, error) {
return nil, fmt.Errorf("import %q not loaded", path)
}
+func gsSortedKeys[V any](m map[string]V) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
type gsFinding struct {
pos token.Position
in string // enclosing function's name, "" at package level
@@ -301,149 +486,232 @@ type gsFinding struct {
path string // e.g. apiThing.Record.gate
}
+// gsOpen is one place a body's value comes from that the trace cannot follow.
+type gsOpen struct {
+ pos token.Position
+ in string // the function it is in, by name
+}
+
type gsResult struct {
findings []gsFinding
+ open map[string]gsOpen // by "function: kind expression"
calls int
shadowed int
wrappers []string
}
+// gsScanner holds what one package's scan shares.
+type gsScanner struct {
+ fset *token.FileSet
+ info *types.Info
+ pkg *types.Package
+ decls map[*types.Func]*ast.FuncDecl
+ sinks map[string]map[int]bool // callee FullName -> body parameter indexes
+ hidem typeutil.Map // types.Type -> bool
+}
+
+func (sc *gsScanner) sinkParams(call *ast.CallExpr) map[int]bool {
+ if fn, ok := typeutil.Callee(sc.info, call).(*types.Func); ok {
+ return sc.sinks[fn.Origin().FullName()]
+ }
+ return nil
+}
+
+func (sc *gsScanner) short(fn *types.Func) string {
+ return strings.ReplaceAll(fn.FullName(), sc.pkg.Path()+".", "")
+}
+
+// hides reports whether a value of t can carry a type its static type does
+// not show: an interface, or a pointer, map, slice, array or struct holding
+// one.
+func (sc *gsScanner) hides(t types.Type) bool {
+ if t == nil {
+ return false
+ }
+ if r := sc.hidem.At(t); r != nil {
+ return r.(bool)
+ }
+ sc.hidem.Set(t, false) // a cycle adds nothing
+ h := false
+ switch u := t.Underlying().(type) {
+ case *types.Interface:
+ h = true
+ case *types.Pointer:
+ h = sc.hides(u.Elem())
+ case *types.Slice:
+ h = sc.hides(u.Elem())
+ case *types.Array:
+ h = sc.hides(u.Elem())
+ case *types.Map:
+ h = sc.hides(u.Elem())
+ case *types.Struct:
+ for i := 0; i < u.NumFields() && !h; i++ {
+ f := u.Field(i)
+ h = (f.Exported() || f.Embedded()) && sc.hides(f.Type())
+ }
+ }
+ sc.hidem.Set(t, h)
+ return h
+}
+
// gsScan finds every JSON sink call in files and walks its body's types.
func gsScan(fset *token.FileSet, info *types.Info, files []*ast.File, pkg *types.Package, gates map[*types.Var]gsGate) gsResult {
- // sinks: callee FullName -> indexes of the parameters it encodes.
- sinks := map[string]map[int]bool{
- "encoding/json.Marshal": {0: true},
- "encoding/json.MarshalIndent": {0: true},
- "(*encoding/json.Encoder).Encode": {0: true},
+ sc := &gsScanner{fset: fset, info: info, pkg: pkg, decls: map[*types.Func]*ast.FuncDecl{},
+ sinks: map[string]map[int]bool{
+ "encoding/json.Marshal": {0: true},
+ "encoding/json.MarshalIndent": {0: true},
+ "(*encoding/json.Encoder).Encode": {0: true},
+ }}
+ for _, file := range files {
+ for _, d := range file.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
+ sc.decls[fn] = fd
+ }
+ }
+ }
}
if fn, ok := pkg.Scope().Lookup("writeJSON").(*types.Func); ok {
sig := fn.Type().(*types.Signature)
for i := 0; i < sig.Params().Len(); i++ {
if sig.Params().At(i).Name() == "body" {
- sinks[fn.FullName()] = map[int]bool{i: true}
+ sc.sinks[fn.FullName()] = map[int]bool{i: true}
}
}
}
- calleeName := func(call *ast.CallExpr) string {
- if fn, ok := typeutil.Callee(info, call).(*types.Func); ok {
- return fn.FullName()
- }
- return ""
+ // eachSink calls visit for every sink body argument in n.
+ eachSink := func(n ast.Node, visit func(arg ast.Expr, call *ast.CallExpr)) {
+ ast.Inspect(n, func(n ast.Node) bool {
+ if call, ok := n.(*ast.CallExpr); ok {
+ for i := range sc.sinkParams(call) {
+ if i < len(call.Args) {
+ visit(call.Args[i], call)
+ }
+ }
+ }
+ return true
+ })
}
- // Wrappers, to a fixed point: a function that passes its own
- // interface-typed parameter, as is, to a sink's body is a sink.
+ // Wrappers, to a fixed point: a function whose sink body can carry its
+ // own parameter is a sink for that parameter.
var wrappers []string
for changed := true; changed; {
changed = false
- for _, file := range files {
- for _, d := range file.Decls {
- fd, ok := d.(*ast.FuncDecl)
- if !ok || fd.Body == nil {
- continue
- }
- fn, _ := info.Defs[fd.Name].(*types.Func)
- if fn == nil {
- continue
- }
- params := fn.Type().(*types.Signature).Params()
- ast.Inspect(fd.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
+ for fn, fd := range sc.decls {
+ if fd.Body == nil {
+ continue
+ }
+ eachSink(fd.Body, func(arg ast.Expr, _ *ast.CallExpr) {
+ tr := sc.trace()
+ tr.types(&gsFrame{decl: fd, fn: fn}, arg)
+ for j := range tr.hits {
+ name := fn.FullName()
+ if sc.sinks[name] == nil {
+ sc.sinks[name] = map[int]bool{}
+ wrappers = append(wrappers, sc.short(fn))
}
- for i := range sinks[calleeName(call)] {
- if i >= len(call.Args) {
- continue
- }
- id, ok := ast.Unparen(call.Args[i]).(*ast.Ident)
- if !ok {
- continue
- }
- for j := 0; j < params.Len(); j++ {
- p := params.At(j)
- if info.Uses[id] != p || !types.IsInterface(p.Type()) {
- continue
- }
- if sinks[fn.FullName()] == nil {
- sinks[fn.FullName()] = map[int]bool{}
- wrappers = append(wrappers, strings.ReplaceAll(fn.FullName(), pkg.Path()+".", ""))
- }
- if !sinks[fn.FullName()][j] {
- sinks[fn.FullName()][j] = true
- changed = true
- }
- }
+ if !sc.sinks[name][j] {
+ sc.sinks[name][j] = true
+ changed = true
}
- return true
- })
- }
+ }
+ })
}
}
sort.Strings(wrappers)
- res := gsResult{wrappers: wrappers}
- w := &gsWalker{gates: gates, memo: map[string][]string{}}
- check := func(fd *ast.FuncDecl, n ast.Node) {
- ast.Inspect(n, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- for i := range sinks[calleeName(call)] {
- if i >= len(call.Args) {
+ res := gsResult{wrappers: wrappers, open: map[string]gsOpen{}}
+ w := &gsWalker{gates: gates}
+ for _, file := range files {
+ for _, d := range file.Decls {
+ frame := &gsFrame{}
+ var n ast.Node = d
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fd.Body == nil {
continue
}
+ fn, _ := info.Defs[fd.Name].(*types.Func)
+ frame, n = &gsFrame{decl: fd, fn: fn}, fd.Body
+ }
+ eachSink(n, func(arg ast.Expr, call *ast.CallExpr) {
res.calls++
- tr := &gsTracer{info: info, fn: fd, seen: map[types.Object]bool{}}
- for _, typ := range tr.types(call.Args[i]) {
+ tr := sc.trace()
+ for _, typ := range tr.types(frame, arg) {
leaks, shadowed := w.walk(typ)
res.shadowed += shadowed
for _, l := range leaks {
f := gsFinding{pos: fset.Position(call.Pos()), root: types.TypeString(typ, nil), path: l}
- if fd != nil {
- f.in = fd.Name.Name
- if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
- f.fn = fn.FullName()
- }
+ if frame.fn != nil {
+ f.in, f.fn = frame.fn.Name(), frame.fn.FullName()
}
res.findings = append(res.findings, f)
}
}
- }
- return true
- })
- }
- for _, file := range files {
- for _, d := range file.Decls {
- if fd, ok := d.(*ast.FuncDecl); ok {
- if fd.Body != nil {
- check(fd, fd.Body)
+ for k, o := range tr.open {
+ if _, ok := res.open[k]; !ok {
+ res.open[k] = o
+ }
}
- continue
- }
- check(nil, d)
+ })
}
}
return res
}
-// gsTracer finds the static types a sink's body argument can carry.
-type gsTracer struct {
- info *types.Info
- fn *ast.FuncDecl
- seen map[types.Object]bool
+// gsFrame is one function the trace is in. A frame entered through a call
+// binds the callee's parameters (and receiver) to the call's arguments,
+// read in the caller's frame.
+type gsFrame struct {
+ decl *ast.FuncDecl // nil at package level
+ fn *types.Func
+ caller *gsFrame
+ args map[*types.Var]ast.Expr
+}
+
+// gsTrace follows one sink body argument back to the types it can carry.
+type gsTrace struct {
+ sc *gsScanner
+ followed map[*ast.CallExpr]bool
+ hand map[gsHand]bool
+ seen map[gsSeen]bool
+ hits map[int]bool // the outermost function's parameters reached
+ open map[string]gsOpen
+}
+
+type gsSeen struct {
+ f *gsFrame
+ v *types.Var
+}
+
+func (sc *gsScanner) trace() *gsTrace {
+ return &gsTrace{sc: sc, followed: map[*ast.CallExpr]bool{}, hand: map[gsHand]bool{}, seen: map[gsSeen]bool{},
+ hits: map[int]bool{}, open: map[string]gsOpen{}}
+}
+
+func (tr *gsTrace) unresolved(f *gsFrame, kind string, e ast.Expr) {
+ in, name := "package level", ""
+ if f.fn != nil {
+ in, name = tr.sc.short(f.fn), f.fn.Name()
+ }
+ k := in + ": " + kind + " " + types.ExprString(e)
+ if _, ok := tr.open[k]; !ok {
+ tr.open[k] = gsOpen{pos: tr.sc.fset.Position(e.Pos()), in: name}
+ }
}
-func (tr *gsTracer) types(e ast.Expr) []types.Type {
+// types is e's static type and, where e can hide others, every type it can
+// carry.
+func (tr *gsTrace) types(f *gsFrame, e ast.Expr) []types.Type {
+ info := tr.sc.info
e = ast.Unparen(e)
- out := []types.Type{tr.info.TypeOf(e)}
+ t := info.TypeOf(e)
+ out := []types.Type{t}
+ hides := tr.sc.hides(t)
switch x := e.(type) {
case *ast.CompositeLit:
- // A literal's own type is walked above; its values only matter
- // where the slot they fill is an interface, which hides them.
- lit := tr.info.TypeOf(x)
- if lit == nil {
+ // Values only matter in slots that hide them.
+ if t == nil {
break
}
for i, el := range x.Elts {
@@ -451,36 +719,64 @@ func (tr *gsTracer) types(e ast.Expr) []types.Type {
if kv, ok := el.(*ast.KeyValueExpr); ok {
key, el = kv.Key, kv.Value
}
- if gsHoldsInterface(tr.slot(lit, key, i)) {
- out = append(out, tr.types(el)...)
+ if tr.sc.hides(tr.slot(t, key, i)) {
+ out = append(out, tr.types(f, el)...)
}
}
case *ast.UnaryExpr:
if x.Op == token.AND {
- out = append(out, tr.types(x.X)...)
+ out = append(out, tr.types(f, x.X)...)
+ } else if hides {
+ tr.unresolved(f, "expression", x)
}
case *ast.CallExpr:
- if tv, ok := tr.info.Types[x.Fun]; ok && tv.IsType() && len(x.Args) == 1 {
- out = append(out, tr.types(x.Args[0])...) // any(x)
- } else if b, ok := tr.builtin(x); ok && b == "append" {
+ if !hides {
+ break
+ }
+ if tv, ok := info.Types[x.Fun]; ok && tv.IsType() {
+ if len(x.Args) == 1 {
+ out = append(out, tr.types(f, x.Args[0])...) // any(x)
+ }
+ break
+ }
+ if b, ok := tr.builtin(x); ok {
+ if b == "make" || b == "new" {
+ break // an empty value: it carries what is assigned to it later
+ }
+ if b != "append" {
+ tr.unresolved(f, "builtin", x)
+ break
+ }
for _, a := range x.Args {
- out = append(out, tr.types(a)...)
+ out = append(out, tr.types(f, a)...)
}
+ break
}
+ out = append(out, tr.results(f, x, 0)...)
case *ast.Ident:
- v, ok := tr.info.Uses[x].(*types.Var)
- if !ok || v.IsField() || tr.fn == nil || tr.seen[v] || !gsHoldsInterface(v.Type()) {
- break
+ if hides {
+ out = append(out, tr.ident(f, x)...)
+ }
+ case *ast.SelectorExpr, *ast.IndexExpr, *ast.StarExpr:
+ if hides {
+ out = append(out, tr.rooted(f, e)...)
+ }
+ case *ast.TypeAssertExpr:
+ if hides {
+ out = append(out, tr.types(f, x.X)...)
+ }
+ case *ast.BasicLit, *ast.FuncLit:
+ default:
+ if hides {
+ tr.unresolved(f, "expression", e)
}
- tr.seen[v] = true
- out = append(out, tr.assigned(v)...)
}
return out
}
// slot is the type the i'th element of a composite literal of type lit
// fills: a map's or a list's element type, or a struct's field.
-func (tr *gsTracer) slot(lit types.Type, key ast.Expr, i int) types.Type {
+func (tr *gsTrace) slot(lit types.Type, key ast.Expr, i int) types.Type {
switch u := lit.Underlying().(type) {
case *types.Map:
return u.Elem()
@@ -490,7 +786,7 @@ func (tr *gsTracer) slot(lit types.Type, key ast.Expr, i int) types.Type {
return u.Elem()
case *types.Struct:
if id, ok := key.(*ast.Ident); ok {
- if f, ok := tr.info.Uses[id].(*types.Var); ok {
+ if f, ok := tr.sc.info.Uses[id].(*types.Var); ok {
return f.Type()
}
} else if key == nil && i < u.NumFields() {
@@ -500,70 +796,349 @@ func (tr *gsTracer) slot(lit types.Type, key ast.Expr, i int) types.Type {
return types.Typ[types.Invalid]
}
-func (tr *gsTracer) builtin(call *ast.CallExpr) (string, bool) {
+func (tr *gsTrace) builtin(call *ast.CallExpr) (string, bool) {
id, ok := ast.Unparen(call.Fun).(*ast.Ident)
if !ok {
return "", false
}
- b, ok := tr.info.Uses[id].(*types.Builtin)
+ b, ok := tr.sc.info.Uses[id].(*types.Builtin)
if !ok {
return "", false
}
return b.Name(), true
}
-// assigned is every type the enclosing function stores in v or in v's
-// elements (v[k] = x).
-func (tr *gsTracer) assigned(v *types.Var) []types.Type {
- is := func(e ast.Expr) bool {
- id, ok := ast.Unparen(e).(*ast.Ident)
- return ok && (tr.info.Uses[id] == v || tr.info.Defs[id] == v)
+// rooted follows a field, element or dereference back to the value it is
+// read from; everything that value can carry covers the part.
+func (tr *gsTrace) rooted(f *gsFrame, e ast.Expr) []types.Type {
+ x := e
+ for {
+ switch y := ast.Unparen(x).(type) {
+ case *ast.SelectorExpr:
+ sel := tr.sc.info.Selections[y]
+ if sel == nil { // a qualified identifier: another package's variable
+ return tr.ident(f, y.Sel)
+ }
+ if sel.Kind() != types.FieldVal {
+ tr.unresolved(f, "method value", e)
+ return nil
+ }
+ x = y.X
+ case *ast.IndexExpr:
+ x = y.X
+ case *ast.StarExpr:
+ x = y.X
+ case *ast.Ident:
+ return tr.ident(f, y)
+ default:
+ return tr.types(f, y)
+ }
}
+}
+
+// ident follows a variable: a bound parameter to its argument, the
+// outermost function's parameter to a wrapper hit, and a local to
+// everything assigned to it.
+func (tr *gsTrace) ident(f *gsFrame, id *ast.Ident) []types.Type {
+ v, ok := tr.sc.info.Uses[id].(*types.Var)
+ if !ok {
+ return nil // a constant, function or nil
+ }
+ return tr.variable(f, v, id)
+}
+
+func (tr *gsTrace) variable(f *gsFrame, v *types.Var, id ast.Expr) []types.Type {
+ if v.Pkg() != tr.sc.pkg || v.Parent() == tr.sc.pkg.Scope() {
+ tr.unresolved(f, "package variable", id)
+ return nil
+ }
+ if f.decl == nil {
+ tr.unresolved(f, "variable", id)
+ return nil
+ }
+ k := gsSeen{f, v}
+ if tr.seen[k] {
+ return nil
+ }
+ tr.seen[k] = true
var out []types.Type
- ast.Inspect(tr.fn, func(n ast.Node) bool {
+ sig := f.fn.Type().(*types.Signature)
+ isParam := false
+ if arg, ok := f.args[v]; ok {
+ isParam = true
+ out = append(out, tr.types(f.caller, arg)...)
+ } else if v == sig.Recv() {
+ tr.unresolved(f, "receiver", id)
+ return nil
+ } else {
+ for j := 0; j < sig.Params().Len(); j++ {
+ if sig.Params().At(j) != v {
+ continue
+ }
+ isParam = true
+ if f.caller == nil {
+ tr.hits[j] = true
+ } else {
+ tr.unresolved(f, "parameter", id)
+ }
+ }
+ for j := 0; j < sig.Results().Len(); j++ {
+ if sig.Results().At(j) == v {
+ isParam = true // a named result, assigned in the body
+ }
+ }
+ }
+ got, defined := tr.assigned(f, v)
+ out = append(out, got...)
+ if !defined && !isParam {
+ tr.unresolved(f, "variable", id)
+ }
+ return out
+}
+
+// gsRootIs reports whether e is v or a field, element or dereference of it.
+func gsRootIs(info *types.Info, e ast.Expr, v *types.Var) bool {
+ for {
+ switch y := ast.Unparen(e).(type) {
+ case *ast.SelectorExpr:
+ if sel := info.Selections[y]; sel == nil || sel.Kind() != types.FieldVal {
+ return false
+ }
+ e = y.X
+ case *ast.IndexExpr:
+ e = y.X
+ case *ast.StarExpr:
+ e = y.X
+ case *ast.Ident:
+ return info.Uses[y] == v || info.Defs[y] == v
+ default:
+ return false
+ }
+ }
+}
+
+// assigned is every type the frame's function stores in v or in a part of
+// it, and whether it defines v. A map or pointer handed to a callee, or a
+// method called on v, may be filled where the trace cannot see: unresolved.
+func (tr *gsTrace) assigned(f *gsFrame, v *types.Var) (out []types.Type, defined bool) {
+ info := tr.sc.info
+ isV := func(e ast.Expr) bool {
+ id, ok := ast.Unparen(e).(*ast.Ident)
+ return ok && (info.Uses[id] == v || info.Defs[id] == v)
+ }
+ ast.Inspect(f.decl, func(n ast.Node) bool {
switch s := n.(type) {
case *ast.AssignStmt:
- if len(s.Lhs) != len(s.Rhs) {
- break
- }
for i, l := range s.Lhs {
- if ix, ok := l.(*ast.IndexExpr); ok && is(ix.X) || is(l) {
- out = append(out, tr.types(s.Rhs[i])...)
+ if !gsRootIs(info, l, v) {
+ continue
+ }
+ if isV(l) {
+ defined = true
+ }
+ switch {
+ case len(s.Lhs) == len(s.Rhs):
+ out = append(out, tr.types(f, s.Rhs[i])...)
+ case len(s.Rhs) == 1:
+ out = append(out, tr.multi(f, s.Rhs[0], i)...)
}
}
case *ast.ValueSpec:
for i, name := range s.Names {
- if tr.info.Defs[name] == v && i < len(s.Values) {
- out = append(out, tr.types(s.Values[i])...)
+ if info.Defs[name] != v {
+ continue
+ }
+ defined = true
+ switch {
+ case len(s.Values) == len(s.Names):
+ out = append(out, tr.types(f, s.Values[i])...)
+ case len(s.Values) == 1:
+ out = append(out, tr.multi(f, s.Values[0], i)...)
+ }
+ }
+ case *ast.RangeStmt:
+ if (s.Key != nil && isV(s.Key)) || (s.Value != nil && isV(s.Value)) {
+ defined = true
+ out = append(out, tr.types(f, s.X)...)
+ }
+ case *ast.CallExpr:
+ if tr.sc.sinkParams(s) != nil {
+ break
+ }
+ if _, ok := tr.builtin(s); ok {
+ break
+ }
+ fn, _ := typeutil.Callee(info, s).(*types.Func)
+ var sig *types.Signature
+ if fn != nil {
+ fn = fn.Origin()
+ sig = fn.Type().(*types.Signature)
+ }
+ if sel, ok := ast.Unparen(s.Fun).(*ast.SelectorExpr); ok && isV(sel.X) && !types.IsInterface(v.Type()) {
+ if m := info.Selections[sel]; m != nil && m.Kind() == types.MethodVal {
+ var recv *types.Var
+ if sig != nil {
+ recv = sig.Recv()
+ }
+ out = append(out, tr.handed(f, s, fn, recv, "method call")...)
+ }
+ }
+ for j, a := range s.Args {
+ a = ast.Unparen(a)
+ u, ok := a.(*ast.UnaryExpr)
+ if ok && u.Op == token.AND && gsRootIs(info, u.X, v) || isV(a) && gsMutable(v.Type()) {
+ var param *types.Var
+ if sig != nil && j < sig.Params().Len() && !(sig.Variadic() && j == sig.Params().Len()-1) {
+ param = sig.Params().At(j)
+ }
+ out = append(out, tr.handed(f, s, fn, param, "handed to")...)
}
}
}
return true
})
- return out
+ return out, defined
}
-// gsHoldsInterface reports whether a value of t can hide another type: an
-// interface, or a map, slice or array of them.
-func gsHoldsInterface(t types.Type) bool {
- switch u := t.Underlying().(type) {
- case *types.Interface:
+// gsMutable reports whether a callee given a value of t can change what
+// the caller's value holds.
+func gsMutable(t types.Type) bool {
+ switch t.Underlying().(type) {
+ case *types.Map, *types.Pointer:
return true
- case *types.Map:
- return gsHoldsInterface(u.Elem())
- case *types.Slice:
- return gsHoldsInterface(u.Elem())
- case *types.Array:
- return gsHoldsInterface(u.Elem())
}
return false
}
+// multi is the i'th value of a multi-value right-hand side.
+func (tr *gsTrace) multi(f *gsFrame, rhs ast.Expr, i int) []types.Type {
+ switch r := ast.Unparen(rhs).(type) {
+ case *ast.CallExpr:
+ return tr.results(f, r, i)
+ case *ast.IndexExpr: // v, ok := m[k]
+ if i == 0 {
+ return tr.rooted(f, r)
+ }
+ case *ast.TypeAssertExpr: // v, ok := x.(T)
+ if i == 0 {
+ return tr.types(f, r.X)
+ }
+ default:
+ if i == 0 && tr.sc.hides(tr.sc.info.TypeOf(r)) {
+ tr.unresolved(f, "expression", r)
+ }
+ }
+ return nil
+}
+
+// results is what the i'th result of a call can carry: for a function of
+// the package, its return expressions read in a frame that binds its
+// parameters to the call's arguments.
+func (tr *gsTrace) results(f *gsFrame, call *ast.CallExpr, i int) []types.Type {
+ info := tr.sc.info
+ rt := info.TypeOf(call)
+ var out []types.Type
+ if tup, ok := rt.(*types.Tuple); ok {
+ if i >= tup.Len() {
+ return nil
+ }
+ rt = tup.At(i).Type()
+ out = append(out, rt)
+ }
+ if !tr.sc.hides(rt) || tr.followed[call] {
+ return out
+ }
+ tr.followed[call] = true
+ fn, _ := typeutil.Callee(info, call).(*types.Func)
+ if fn != nil {
+ fn = fn.Origin()
+ }
+ g := tr.enter(f, call, fn)
+ if g == nil {
+ tr.unresolved(f, "call", call.Fun)
+ return out
+ }
+ decl := g.decl
+ res := fn.Type().(*types.Signature).Results()
+ ast.Inspect(decl.Body, func(n ast.Node) bool {
+ switch r := n.(type) {
+ case *ast.FuncLit:
+ return false
+ case *ast.ReturnStmt:
+ switch {
+ case len(r.Results) == res.Len():
+ out = append(out, tr.types(g, r.Results[i])...)
+ case len(r.Results) == 1:
+ out = append(out, tr.multi(g, r.Results[0], i)...)
+ case len(r.Results) == 0 && res.At(i).Name() != "":
+ // A bare return: the named result, as assigned.
+ out = append(out, tr.variable(g, res.At(i), decl.Name)...)
+ }
+ }
+ return true
+ })
+ return out
+}
+
+// enter is the frame of a call to fn, a function of the package, with its
+// parameters and receiver bound to the call's arguments; nil when fn has no
+// body here.
+func (tr *gsTrace) enter(f *gsFrame, call *ast.CallExpr, fn *types.Func) *gsFrame {
+ if fn == nil {
+ return nil
+ }
+ decl := tr.sc.decls[fn]
+ if decl == nil || decl.Body == nil {
+ return nil
+ }
+ sig := fn.Type().(*types.Signature)
+ g := &gsFrame{decl: decl, fn: fn, caller: f, args: map[*types.Var]ast.Expr{}}
+ params := sig.Params()
+ if len(call.Args) == params.Len() || sig.Variadic() && len(call.Args) >= params.Len()-1 {
+ for j := 0; j < params.Len() && j < len(call.Args); j++ {
+ if sig.Variadic() && j == params.Len()-1 {
+ break
+ }
+ g.args[params.At(j)] = call.Args[j]
+ }
+ }
+ if recv := sig.Recv(); recv != nil {
+ if sel, ok := ast.Unparen(call.Fun).(*ast.SelectorExpr); ok {
+ g.args[recv] = sel.X
+ }
+ }
+ return g
+}
+
+// handed follows a value the caller handed to fn (as param, or as the
+// receiver) into what fn stores in it. A callee outside the package, a
+// function value or a variadic slot cannot be followed: unresolved.
+func (tr *gsTrace) handed(f *gsFrame, call *ast.CallExpr, fn *types.Func, param *types.Var, kind string) []types.Type {
+ g := tr.enter(f, call, fn)
+ if g == nil || param == nil {
+ tr.unresolved(f, kind, call.Fun)
+ return nil
+ }
+ k := gsHand{call, param}
+ if tr.hand[k] {
+ return nil
+ }
+ tr.hand[k] = true
+ got, _ := tr.assigned(g, param)
+ return got
+}
+
+type gsHand struct {
+ call *ast.CallExpr
+ param *types.Var
+}
+
// gsWalker walks a type as encoding/json encodes it.
type gsWalker struct {
- gates map[*types.Var]gsGate
- memo map[string][]string // type -> leak paths; an entry in progress is nil
- shad int
+ gates map[*types.Var]gsGate
+ memo typeutil.Map // types.Type -> []string, leak paths; nil while in progress
+ opaque typeutil.Map // the same, for types under a custom marshaller
+ shad int
}
// walk returns the paths by which t emits a gate field, and how many gate
@@ -574,45 +1149,104 @@ func (w *gsWalker) walk(t types.Type) ([]string, int) {
return leaks, w.shad
}
-func (w *gsWalker) value(t types.Type) []string {
- if t == nil {
- return nil
- }
+func gsDeref(t types.Type) types.Type {
for {
p, ok := t.Underlying().(*types.Pointer)
if !ok {
- break
+ return t
}
t = p.Elem()
}
- key := types.TypeString(t, nil)
- if leaks, done := w.memo[key]; done {
- return leaks
+}
+
+func gsLabel(t types.Type) string {
+ return types.TypeString(t, func(p *types.Package) string { return p.Name() })
+}
+
+// gsMarshaler reports whether encoding/json hands t, or *t, to its own
+// MarshalJSON or MarshalText, promoted methods included.
+func gsMarshaler(t types.Type) bool {
+ if types.IsInterface(t) {
+ return false
+ }
+ for _, m := range []types.Type{t, types.NewPointer(t)} {
+ ms := types.NewMethodSet(m)
+ if ms.Lookup(nil, "MarshalJSON") != nil || ms.Lookup(nil, "MarshalText") != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func (w *gsWalker) value(t types.Type) []string {
+ if t == nil {
+ return nil
+ }
+ t = gsDeref(t)
+ if r := w.memo.At(t); r != nil {
+ return r.([]string)
+ }
+ w.memo.Set(t, []string(nil)) // a cycle adds nothing new
+ var leaks []string
+ if gsMarshaler(t) {
+ leaks = w.held(t)
+ } else {
+ switch u := t.Underlying().(type) {
+ case *types.Struct:
+ label := gsLabel(t)
+ for _, f := range w.fields(t) {
+ if g, ok := w.gates[f.v]; ok {
+ if f.name == g.name {
+ leaks = append(leaks, label+"."+g.owner+"."+f.name)
+ }
+ continue
+ }
+ for _, l := range w.value(f.v.Type()) {
+ leaks = append(leaks, label+"."+f.name+" -> "+l)
+ }
+ }
+ case *types.Slice:
+ leaks = w.value(u.Elem())
+ case *types.Array:
+ leaks = w.value(u.Elem())
+ case *types.Map:
+ leaks = w.value(u.Elem())
+ }
+ }
+ w.memo.Set(t, leaks)
+ return leaks
+}
+
+// held is every gate field t holds anywhere, exported or not, under any
+// name: what a custom marshaller could write.
+func (w *gsWalker) held(t types.Type) []string {
+ t = gsDeref(t)
+ if r := w.opaque.At(t); r != nil {
+ return r.([]string)
}
- w.memo[key] = nil // a cycle adds nothing new
+ w.opaque.Set(t, []string(nil))
var leaks []string
switch u := t.Underlying().(type) {
case *types.Struct:
- label := types.TypeString(t, func(p *types.Package) string { return p.Name() })
- for _, f := range w.fields(u) {
- if g, ok := w.gates[f.v]; ok {
- if f.name == g.name {
- leaks = append(leaks, label+"."+g.owner+"."+f.name)
- }
+ label := gsLabel(t)
+ for i := 0; i < u.NumFields(); i++ {
+ f := u.Field(i)
+ if g, ok := w.gates[f]; ok {
+ leaks = append(leaks, label+"."+g.owner+".Gate (custom marshaller)")
continue
}
- for _, l := range w.value(f.v.Type()) {
- leaks = append(leaks, label+"."+f.name+" -> "+l)
+ for _, l := range w.held(f.Type()) {
+ leaks = append(leaks, label+"."+f.Name()+" -> "+l)
}
}
case *types.Slice:
- leaks = w.value(u.Elem())
+ leaks = w.held(u.Elem())
case *types.Array:
- leaks = w.value(u.Elem())
+ leaks = w.held(u.Elem())
case *types.Map:
- leaks = w.value(u.Elem())
+ leaks = append(w.held(u.Key()), w.held(u.Elem())...)
}
- w.memo[key] = leaks
+ w.opaque.Set(t, leaks)
return leaks
}
@@ -623,30 +1257,41 @@ type gsField struct {
v *types.Var
}
+func gsCount(m *typeutil.Map, t types.Type) int {
+ if m == nil {
+ return 0
+ }
+ if n := m.At(t); n != nil {
+ return n.(int)
+ }
+ return 0
+}
+
// fields is encoding/json's typeFields over go/types: the fields a struct
-// emits, after promotion and dominance. A gate field that loses to a
-// shallower or tagged one of its name is counted as shadowed.
-func (w *gsWalker) fields(st *types.Struct) []gsField {
+// type emits, after promotion and dominance, keyed by type identity. A gate
+// field that loses to a shallower or tagged one of its name counts as
+// shadowed.
+func (w *gsWalker) fields(t types.Type) []gsField {
type scan struct {
- st *types.Struct
- key string
+ typ types.Type
depth int
}
var all []gsField
- next := []scan{{st: st, key: types.TypeString(st, nil)}}
- var count, nextCount map[string]int
- visited := map[string]bool{}
+ next := []scan{{typ: t}}
+ var count, nextCount *typeutil.Map
+ var visited typeutil.Map
for len(next) > 0 {
current := next
next = nil
- count, nextCount = nextCount, map[string]int{}
+ count, nextCount = nextCount, new(typeutil.Map)
for _, s := range current {
- if visited[s.key] {
+ if visited.At(s.typ) != nil {
continue
}
- visited[s.key] = true
- for i := 0; i < s.st.NumFields(); i++ {
- sf := s.st.Field(i)
+ visited.Set(s.typ, true)
+ st := s.typ.Underlying().(*types.Struct)
+ for i := 0; i < st.NumFields(); i++ {
+ sf := st.Field(i)
ft := sf.Type()
if p, ok := ft.(*types.Pointer); ok {
ft = p.Elem()
@@ -659,7 +1304,7 @@ func (w *gsWalker) fields(st *types.Struct) []gsField {
} else if !sf.Exported() {
continue
}
- name, skip := gsJSONName(s.st.Tag(i))
+ name, skip := gsJSONName(st.Tag(i))
if skip {
continue
}
@@ -669,15 +1314,15 @@ func (w *gsWalker) fields(st *types.Struct) []gsField {
f.name = sf.Name()
}
all = append(all, f)
- if count[s.key] > 1 {
+ if gsCount(count, s.typ) > 1 {
all = append(all, f) // embedded twice at this depth: annihilates
}
continue
}
- key := types.TypeString(ft, nil)
- nextCount[key]++
- if nextCount[key] == 1 {
- next = append(next, scan{st: ft.Underlying().(*types.Struct), key: key, depth: s.depth + 1})
+ n := gsCount(nextCount, ft) + 1
+ nextCount.Set(ft, n)
+ if n == 1 {
+ next = append(next, scan{typ: ft, depth: s.depth + 1})
}
}
}
@@ -713,13 +1358,33 @@ func (w *gsWalker) fields(st *types.Struct) []gsField {
return out
}
-// gsJSONName is a field's json tag name ("" for none) and whether the tag
-// drops the field.
+// gsJSONName is a field's json tag name ("" for none or an invalid one, as
+// encoding/json's isValidTag rules) and whether the tag drops the field.
func gsJSONName(tag string) (string, bool) {
v := reflect.StructTag(tag).Get("json")
if v == "-" {
return "", true
}
name, _, _ := strings.Cut(v, ",")
+ if !gsValidTag(name) {
+ name = ""
+ }
return name, false
}
+
+// gsValidTag is encoding/json's isValidTag.
+func gsValidTag(s string) bool {
+ if s == "" {
+ return false
+ }
+ for _, c := range s {
+ switch {
+ case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
+ // Backslash and quote chars are reserved, but otherwise any
+ // punctuation chars are allowed in a tag name.
+ case !unicode.IsLetter(c) && !unicode.IsDigit(c):
+ return false
+ }
+ }
+ return true
+}