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
71 changes: 67 additions & 4 deletions analyzers/slice_bounds.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) {
violations = append(violations, slice)
}
} else {
if !isSliceInsideBounds(0, sliceCap, l, h) {
if !isSliceInsideBounds(sliceCap, l, h) {
violations = append(violations, slice)
}
}
Expand Down Expand Up @@ -358,7 +358,7 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) {
switch tinstr := instr.(type) {
case *ssa.Slice:
_, _, m := GetSliceBounds(tinstr)
if !isLenBound && isSliceInsideBounds(0, value, m, value) {
if !isLenBound && isSliceInsideBounds(value, m, value) {
delete(issues, instr)
}
case *ssa.IndexAddr:
Expand Down Expand Up @@ -611,7 +611,9 @@ func (s *sliceBoundsState) trackSliceBounds(depth int, sliceCap int, slice ssa.N
*localViolations = append(*localViolations, refinstr)
}
case *ssa.Call:
if ifref, cond := extractSliceIfLenCondition(refinstr); ifref != nil && cond != nil {
if addedLen, ok := staticAppendGrowth(refinstr, slice); ok {
s.trackSliceBounds(depth, sliceCap+addedLen, refinstr, localViolations, localIfs)
} else if ifref, cond := extractSliceIfLenCondition(refinstr); ifref != nil && cond != nil {
localIfs[*ifref] = cond
} else {
parPos := -1
Expand Down Expand Up @@ -845,7 +847,7 @@ func (s *sliceBoundsState) checkAllSlicesBounds(depth int, sliceCap int, slice *
*violations = append(*violations, slice)
}
} else {
if !isSliceInsideBounds(0, sliceCap, sliceLow, sliceHigh) {
if !isSliceInsideBounds(sliceCap, sliceLow, sliceHigh) {
*violations = append(*violations, slice)
}
}
Expand Down Expand Up @@ -874,6 +876,67 @@ func (s *sliceBoundsState) checkAllSlicesBounds(depth int, sliceCap int, slice *
}
}

// staticAppendGrowth reports the guaranteed number of elements append()
// adds to slice, when call is append(slice, ...) and the appended count
// is statically determinable. Returns false when it isn't (e.g. spreading
// a slice of unknown length) -- no growth is assumed in that case.
func staticAppendGrowth(call *ssa.Call, slice ssa.Node) (int, bool) {
builtin, ok := call.Call.Value.(*ssa.Builtin)
if !ok || builtin.Name() != "append" {
return 0, false
}
sliceVal, ok := slice.(ssa.Value)
if !ok {
return 0, false
}
args := call.Call.Args
if len(args) != 2 || args[0] != sliceVal {
return 0, false
}
// append(s) with zero variadic arguments always lowers to append(s, nil...):
// args[1] is a *ssa.Const placeholder for the empty variadic slice, never a
// *ssa.Slice value, so it has to be recognized here rather than falling
// through to staticSliceLen (which would reject it as "not determinable").
if _, isConst := args[1].(*ssa.Const); isConst {
return 0, true
}
return staticSliceLen(args[1])
}

// staticSliceLen returns v's guaranteed length (not capacity) when v is a
// *ssa.Slice over a *ssa.Alloc-backed fixed-size array with statically-known
// bounds -- reusing the same GetSliceBounds/extractArrayLen machinery already
// used for the make()/composite-literal Alloc case. append() only ever adds
// as many elements as the spread value's length, so capacity is irrelevant
// here even for a 3-index slice: ComputeSliceNewCap(l, h, maxIdx, arrLen)
// returns maxIdx-l (capacity) in that case, not h-l (length), so it is used
// only for the 2-index case below, where the two values coincide.
func staticSliceLen(v ssa.Value) (int, bool) {
sl, ok := v.(*ssa.Slice)
if !ok {
return 0, false
}
alloc, ok := sl.X.(*ssa.Alloc)
if !ok {
return 0, false
}
arrLen, ok := extractArrayLen(alloc.Type())
if !ok {
return 0, false
}
l, h, maxIdx := GetSliceBounds(sl)
if maxIdx > 0 {
if !isThreeIndexSliceInsideBounds(l, h, maxIdx, arrLen) {
return 0, false
}
return h - l, true
}
if !isSliceInsideBounds(arrLen, l, h) {
return 0, false
}
return ComputeSliceNewCap(l, h, maxIdx, arrLen), true
}

func extractSliceIfLenCondition(call *ssa.Call) (*ssa.If, *ssa.BinOp) {
if builtInLen, ok := call.Call.Value.(*ssa.Builtin); ok {
if builtInLen.Name() == "len" {
Expand Down
5 changes: 3 additions & 2 deletions analyzers/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,9 @@ type IntTypeInfo struct {
}

// isSliceInsideBounds checks if the requested slice range is within the parent slice's boundaries.
func isSliceInsideBounds(l, h int, cl, ch int) bool {
return (l <= cl && h >= ch) && (l <= ch && h >= cl)
// The parent's lower bound is always 0, so only its upper bound h is taken.
func isSliceInsideBounds(h int, cl, ch int) bool {
return (0 <= cl && h >= ch) && (0 <= ch && h >= cl)
}

// isThreeIndexSliceInsideBounds validates the boundaries and capacity of a 3-index slice (s[i:j:k]).
Expand Down
159 changes: 159 additions & 0 deletions testutils/g602_samples.go
Original file line number Diff line number Diff line change
Expand Up @@ -1340,4 +1340,163 @@ func main() {
}
}
`}, 0, gosec.NewConfig()},
// Issue #1753: G602 performs no bounds checking at all on the direct
// result of append() -- the IndexAddr base-type dispatch never reaches
// any bounds-checking path for a *ssa.Call. A statically-determinable
// append() growth (literal args) must now be tracked like make()/composite
// literals are, so an out-of-bounds constant index is flagged.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(s, 10)
fmt.Println(s[6])
}
`}, 1, gosec.NewConfig()},
// Same append()-grown slice, but the access is properly guarded by a
// satisfied len() equality check matching the asserted length -- must
// not be flagged.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(s, 10)
if len(s) == 1 {
fmt.Println(s[0])
}
}
`}, 0, gosec.NewConfig()},
// Cross-variable guard mismatch from #1753's own reproduction: a guard on
// one slice's len() must not "protect" a completely different slice's
// out-of-bounds index.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(s, 10)

s2 := []int{10}
if len(s) == 3 {
fmt.Println(s2[6])
}
}
`}, 1, gosec.NewConfig()},
// A spread of a slice whose length is not statically determinable (e.g.
// spreading a function parameter) must not be treated as adding any
// guaranteed growth -- no new false positive from guessing an unknown
// length.
{[]string{`
package main

import "fmt"

func f(other []int) {
s := []int{}
s = append(s, other...)
fmt.Println(s[6])
}

func main() {
f([]int{1, 2, 3})
}
`}, 0, gosec.NewConfig()},
// #1753's own equality-guard case: the constant index (6) falls outside
// the length asserted by the guard (3), so it's flagged under the same
// trust model #1746/#1749 already established for make()/composite-literal
// slices -- an append()-derived slice must reach the same conclusion.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(s, 10)
if len(s) == 3 {
fmt.Println(s[6])
}
}
`}, 1, gosec.NewConfig()},
// #1753's own inequality-guard case: a "len(s) >= N" guard is only a lower
// bound, so it proves indexes below N safe but not s[6]. Since #1757 this
// is flagged for make()-backed slices, and an append()-derived slice must
// reach the same conclusion.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(s, 10)
if len(s) >= 3 {
fmt.Println(s[6])
}
}
`}, 1, gosec.NewConfig()},
// #1753 follow-up: append(s) with zero variadic arguments must still be
// tracked as zero guaranteed growth, not silently dropped (the SSA
// builder lowers this to append(s, nil...), a *ssa.Const, not a
// *ssa.Slice).
{[]string{`
package main

import "fmt"

func main() {
s := []int{1}
t := append(s)
fmt.Println(t[3])
}
`}, 1, gosec.NewConfig()},
// append() inside a loop with an in-bounds index must not be flagged --
// the most common real-world append() shape.
{[]string{`
package main

import "fmt"

func main() {
var s []int
for i := 0; i < 3; i++ {
s = append(s, i)
fmt.Println(s[i])
}
}
`}, 0, gosec.NewConfig()},
// Chained append() calls: the recursion must follow the growth of a
// nested append() result, not just a single level.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(append(s, 1), 2)
fmt.Println(s[5])
}
`}, 1, gosec.NewConfig()},
// A multi-element literal append() must count every added element, not
// just one.
{[]string{`
package main

import "fmt"

func main() {
s := []int{}
s = append(s, 1, 2, 3)
fmt.Println(s[5])
}
`}, 1, gosec.NewConfig()},
}
Loading