Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(G602): do not clear indices in the else branch of an equality guard
invBound maps bounded to itself, so both successors of "if len(s) == N"
are walked with bound=bounded and value=N. Entering the else branch only
proves the length is not N, yet the *ssa.IndexAddr arm cleared every
constant index in [0, N) there.

Restrict the suppression to the then successor (i == 0) and cover the
inverted branch with samples.

Fixes part of #1727
  • Loading branch information
askalf committed Sep 14, 2026
commit 64aec5bc2669de8070f4dc10fc70a48741dd8e3e
6 changes: 5 additions & 1 deletion analyzers/slice_bounds.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,12 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) {
delete(issues, instr)
}
case *ssa.IndexAddr:
// invBound maps bounded to itself, so the "else" successor
// is walked with the same bound and value even though it
// only proves the length is *not* the asserted one. Trust
// the asserted length in the "then" successor alone.
if indexValue, ok := GetConstantInt64(tinstr.Index); ok {
if isSliceIndexInsideBounds(assertedLen(binop, value), int(indexValue)) {
if i == 0 && isSliceIndexInsideBounds(assertedLen(binop, value), int(indexValue)) {
delete(issues, instr)
}
}
Expand Down
38 changes: 38 additions & 0 deletions testutils/g602_samples.go
Original file line number Diff line number Diff line change
Expand Up @@ -790,4 +790,42 @@ func main() {
}
}
`}, 0, gosec.NewConfig()},
{[]string{`
package main

import "fmt"

func main() {
s := make([]int, 0)
if len(s) == 3 {
} else {
fmt.Println(s[1])
}
}
`}, 1, gosec.NewConfig()},
{[]string{`
package main

import "fmt"

func main() {
s := make([]int, 0)
if len(s)-1 == 1 {
} else {
fmt.Println(s[0])
}
}
`}, 1, gosec.NewConfig()},
{[]string{`
package main

import "fmt"

func main() {
s := make([]int, 0)
if len(s) == 0 {
fmt.Println(s[0])
}
}
`}, 1, gosec.NewConfig()},
}