Skip to content

Commit 5736e8b

Browse files
authored
fix: G602 false positive for array element access (#1499)
Fixes #1495
1 parent 1b7e1e9 commit 5736e8b

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

analyzers/slice_bounds.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,10 @@ func runSliceBounds(pass *analysis.Pass) (result any, err error) {
195195
issue.Low,
196196
issue.High)
197197
case *ssa.IndexAddr:
198+
// Skip IndexAddr that directly accesses the original array (not the slice)
199+
if s.X == instr {
200+
continue
201+
}
198202
issues[s] = newIssue(
199203
pass.Analyzer.Name,
200204
"slice index out of range",
@@ -578,6 +582,8 @@ func (s *sliceBoundsState) extractIntValueIndexAddr(refinstr *ssa.IndexAddr, sli
578582
if !isSliceIndexInsideBounds(sliceCap+sliceIncr, finalIdx) {
579583
return finalIdx, nil
580584
}
585+
// Constant index is within bounds; avoid BFS exploring shared SSA constant referrers
586+
return 0, errNoFound
581587
}
582588

583589
// Case 2: Base is a Phi node (loop counter)

testutils/g602_samples.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,4 +651,49 @@ func main() {
651651
fmt.Println(s[idx])
652652
}
653653
`}, 1, gosec.NewConfig()},
654+
// Issue #1495: G602 false positive for array element access with coexisting slice expression
655+
{[]string{`
656+
package main
657+
import (
658+
"log/slog"
659+
"runtime"
660+
"time"
661+
)
662+
func main() {
663+
var pcs [1]uintptr
664+
runtime.Callers(2, pcs[:])
665+
r := slog.NewRecord(time.Now(), slog.LevelError, "test", pcs[0])
666+
_ = r
667+
}
668+
`}, 0, gosec.NewConfig()},
669+
{[]string{`
670+
package main
671+
func main() {
672+
var buf [4]byte
673+
copy(buf[:], []byte("test"))
674+
_ = buf[0]
675+
_ = buf[1]
676+
_ = buf[2]
677+
_ = buf[3]
678+
}
679+
`}, 0, gosec.NewConfig()},
680+
{[]string{`
681+
package main
682+
func main() {
683+
var buf [2]byte
684+
copy(buf[:], []byte("ab"))
685+
idx := 3
686+
_ = buf[idx]
687+
}
688+
`}, 1, gosec.NewConfig()},
689+
{[]string{`
690+
package main
691+
func doWork(s []int) {}
692+
func main() {
693+
var arr [5]int
694+
doWork(arr[:])
695+
_ = arr[0]
696+
_ = arr[4]
697+
}
698+
`}, 0, gosec.NewConfig()},
654699
}

0 commit comments

Comments
 (0)