Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 102 additions & 8 deletions analyzers/slice_bounds.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
}
}
Expand All @@ -250,6 +278,7 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) {
}
}
}
resolveNilSliceAccesses(pass, nilSliceAccesses, nilLenGuards, issues)
}

for ifref, binop := range ifs {
Expand Down Expand Up @@ -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:
Expand Down
86 changes: 86 additions & 0 deletions testutils/g602_samples.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()},
}
Loading