From 8e66eef0bbe31710174c336ea6600cdc534490c8 Mon Sep 17 00:00:00 2001 From: cipherprofessor Date: Sat, 19 Sep 2026 19:58:15 +0530 Subject: [PATCH] fix(G602): trust len(nilSlice) == N guards, matching make()-backed slices A nil-declared slice's IndexAddr was flagged unconditionally regardless of any surrounding "if len(s) == N" guard, because it's caught by an early, value-based check that never enters the trackSliceBounds/ifs correlation pipeline #1746/#1749 use to trust an equality guard for make()/literal slices. Same guard shape, inconsistent answer, purely because of how the empty slice was constructed -- verified against master via an SSA dump (nil case resolves to a bare *ssa.Const, the make() case to a *ssa.Slice with a real Alloc, only the latter feeds the existing pipeline). Defer nil-slice-constant accesses instead of flagging them immediately, separately collect "len(nilConst) == N" guards (reusing the existing extractSliceIfLenCondition helper), and resolve each access after its function is fully walked: if the guard's safe (then) successor block dominates the access and the index fits the asserted length, trust it, same as the make() case already does. Keying is by the specific *ssa.Const each len()/access involves, not by type -- verified empirically that Go's SSA builder allocates a distinct constant per nil-typed variable even when the type is identical, so this can't confuse "var a []int" with "var b []int" sharing a type. A guard is only trusted when it's the sole one recorded for its const; multiple guards on the same const fall back to flagging unconditionally, same as before this change. Adds regression coverage for: a nil slice safely covered by a guard, one where the index isn't covered, two distinct same-type nil slices each independently guarded and safe, and two distinct nil slices where only one is guarded (the unguarded one must still fire). Fixes the remaining part of #1727 not already covered by #1746/#1749. --- analyzers/slice_bounds.go | 110 +++++++++++++++++++++++++++++++++++--- testutils/g602_samples.go | 86 +++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+), 8 deletions(-) diff --git a/analyzers/slice_bounds.go b/analyzers/slice_bounds.go index 6318d5af20..72b51a2b93 100644 --- a/analyzers/slice_bounds.go +++ b/analyzers/slice_bounds.go @@ -56,6 +56,19 @@ type valOffset struct { offset int } +// nilLenGuard records an "if len(nilSliceConst) == N" guard found anywhere in +// a function, keyed by the specific *ssa.Const instance the len() call was +// made on (see resolveNilSliceAccesses). Distinct nil-typed variables get +// distinct *ssa.Const objects from Go's SSA builder even when their type is +// identical -- verified empirically, not assumed -- so keying by the const's +// own identity correctly separates "var a []int; var b []int" without +// needing type-level disambiguation. +type nilLenGuard struct { + ifInstr *ssa.If + binop *ssa.BinOp + value int +} + type sliceBoundsState struct { *BaseAnalyzerState trackCache map[trackCacheKey]*trackCacheValue @@ -159,9 +172,26 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) { var violations []ssa.Instruction for _, mcall := range ssaResult.SSA.SrcFuncs { state.Reset() + // Per-function: nil-slice-constant accesses deferred for guard + // resolution, and the "len(nilConst) == N" guards found to resolve + // them against -- both keyed by the specific *ssa.Const instance + // involved, which Go's SSA builder allocates one-per-variable (see + // nilLenGuard), so a guard on one nil-typed variable can never be + // looked up against a different variable's access even when they + // share a type. See resolveNilSliceAccesses. + nilSliceAccesses := map[*ssa.Const][]*ssa.IndexAddr{} + nilLenGuards := map[*ssa.Const][]nilLenGuard{} for _, block := range mcall.DomPreorder() { for _, instr := range block.Instrs { switch instr := instr.(type) { + case *ssa.Call: + if nilConst, ok := nilSliceLenArg(instr); ok { + if ifref, binop := extractSliceIfLenCondition(instr); ifref != nil && binop != nil { + if bnd, value, err := extractBinOpBound(binop); err == nil && bnd == bounded { + nilLenGuards[nilConst] = append(nilLenGuards[nilConst], nilLenGuard{ifInstr: ifref, binop: binop, value: value}) + } + } + } case *ssa.Alloc: if sliceCap, ok := extractArrayLen(instr.Type()); ok { allocRefs := instr.Referrers() @@ -220,14 +250,12 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) { case *ssa.Const: if _, ok := indexInstr.Type().Underlying().(*types.Slice); ok { if indexInstr.Value == nil { - issues[instr] = newIssue( - pass.Analyzer.Name, - "slice index out of range", - pass.Fset, - instr.Pos(), - issue.Low, - issue.High) - + // Defer: a "len(nilConst) == N" guard covering this + // exact const (checked once the whole function has + // been scanned, see resolveNilSliceAccesses) can + // prove it safe, the same way #1746 already trusts + // such a guard for make()/literal-backed slices. + nilSliceAccesses[indexInstr] = append(nilSliceAccesses[indexInstr], instr) break } } @@ -250,6 +278,7 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) { } } } + resolveNilSliceAccesses(pass, nilSliceAccesses, nilLenGuards, issues) } for ifref, binop := range ifs { @@ -875,6 +904,71 @@ func extractSliceIfLenCondition(call *ssa.Call) (*ssa.If, *ssa.BinOp) { return nil, nil } +// nilSliceLenArg reports whether call is a builtin len() invocation whose +// single argument is a nil slice constant, returning that constant. +func nilSliceLenArg(call *ssa.Call) (*ssa.Const, bool) { + builtin, ok := call.Call.Value.(*ssa.Builtin) + if !ok || builtin.Name() != "len" || len(call.Call.Args) != 1 { + return nil, false + } + c, ok := call.Call.Args[0].(*ssa.Const) + if !ok || c.Value != nil { + return nil, false + } + if _, ok := c.Type().Underlying().(*types.Slice); !ok { + return nil, false + } + return c, true +} + +// resolveNilSliceAccesses decides, for every nil-slice-constant access +// deferred while walking a function, whether an "if len(nilConst) == N" +// guard already proves it safe -- mirroring the trust #1746 established for +// make()/literal-backed slices ("if the guard asserts a length, and the +// index fits within it, the access is safe") -- or whether it must still be +// flagged. +// +// Both maps are keyed by the specific *ssa.Const the access/guard involves +// (Go's SSA builder allocates a distinct nil constant per variable, verified +// empirically -- "var a []int; var b []int" never share one), so a guard on +// one variable can only ever be looked up against that same variable's own +// accesses. A guard is trusted only when it is the sole one recorded for its +// const *and* its safe (then) successor block dominates the access -- real +// control-flow reachability, so a guard can't reach across an unrelated +// branch. Zero or multiple guards for a given const fall back to flagging +// every access of that const unconditionally, exactly as before this change +// (multiple guards on the very same variable, e.g. re-checked after a +// mutation, is the one remaining case this doesn't attempt to reason about). +func resolveNilSliceAccesses(pass *analysis.Pass, accessesByConst map[*ssa.Const][]*ssa.IndexAddr, guardsByConst map[*ssa.Const][]nilLenGuard, issues map[ssa.Instruction]*issue.Issue) { + for c, accesses := range accessesByConst { + guards := guardsByConst[c] + var thenBlock *ssa.BasicBlock + var assertedLength int + if len(guards) == 1 { + if ifBlock := guards[0].ifInstr.Block(); ifBlock != nil && len(ifBlock.Succs) > 0 { + thenBlock = ifBlock.Succs[0] + assertedLength = assertedLen(guards[0].binop, guards[0].value) + } + } + for _, access := range accesses { + if thenBlock != nil { + if indexValue, ok := GetConstantInt64(access.Index); ok { + if isSliceIndexInsideBounds(assertedLength, int(indexValue)) && thenBlock.Dominates(access.Block()) { + continue // proven safe by the sole guard on this variable + } + } + } + issues[access] = newIssue( + pass.Analyzer.Name, + "slice index out of range", + pass.Fset, + access.Pos(), + issue.Low, + issue.High) + } + } +} + func invBound(bound bound) bound { switch bound { case lowerUnbounded: diff --git a/testutils/g602_samples.go b/testutils/g602_samples.go index a32efe6454..7ff942f00a 100644 --- a/testutils/g602_samples.go +++ b/testutils/g602_samples.go @@ -1254,4 +1254,90 @@ func main() { } } `}, 1, gosec.NewConfig()}, + + // Issue #1727 (continued): a nil-declared slice under an equality guard + // should be trusted exactly the way a make()/literal-backed slice already + // is (see the earlier #1727 cases above) -- index 2 is safe once len(s) + // is asserted to be 3. + {[]string{` +package main + +import "fmt" + +func main() { + var s []int + if len(s) == 3 { + fmt.Println(s[2]) + } +} +`}, 0, gosec.NewConfig()}, + // Same nil slice, but the guarded index is not covered by the asserted + // length -- must still be flagged. + {[]string{` +package main + +import "fmt" + +func main() { + var s []int + if len(s) == 3 { + fmt.Println(s[3]) + } +} +`}, 1, gosec.NewConfig()}, + // Safety case: two distinct nil-declared slices of the same type in one + // function. Only "a" is guarded; "b" must still be flagged even though + // Go's SSA builder represents both as the same canonical nil constant -- + // the fix must not let a's guard silence b's unguarded access. + {[]string{` +package main + +import "fmt" + +func main() { + var a []int + var b []int + if len(a) == 3 { + fmt.Println(a[2]) + } + fmt.Println(b[2]) +} +`}, 1, gosec.NewConfig()}, + // Same shape, but the unguarded access sits textually before the guard -- + // still must be flagged (the guard's block cannot dominate it either way). + {[]string{` +package main + +import "fmt" + +func main() { + var a []int + var b []int + fmt.Println(b[2]) + if len(a) == 3 { + fmt.Println(a[2]) + } +} +`}, 1, gosec.NewConfig()}, + // Two distinct nil-declared slices of the same type, EACH independently + // guarded and safe: both accesses must be cleared. Go's SSA builder gives + // "a" and "b" distinct constant objects even though their type is + // identical, so a's guard and b's guard must not be conflated into a + // false "ambiguous, flag everything" fallback for one another. + {[]string{` +package main + +import "fmt" + +func main() { + var a []int + var b []int + if len(a) == 3 { + fmt.Println(a[2]) + } + if len(b) == 5 { + fmt.Println(b[2]) + } +} +`}, 0, gosec.NewConfig()}, }