Skip to content

Commit dca707b

Browse files
committed
cmd/compile: guard against loads with negative offset from readonly constants
CL 154057 adds guards agaist out-of-bound reads from readonly constants. It turns out that in dead code, the offset can also be negative. Guard against negative offset as well. Fixes #30257. Change-Id: I47c2a2e434dd466c08ae6f50f213999a358c796e Reviewed-on: https://go-review.googlesource.com/c/162819 Reviewed-by: Keith Randall <[email protected]>
1 parent ef454fd commit dca707b

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/cmd/compile/internal/ssa/rewrite.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -1142,7 +1142,7 @@ func symIsRO(sym interface{}) bool {
11421142
// read8 reads one byte from the read-only global sym at offset off.
11431143
func read8(sym interface{}, off int64) uint8 {
11441144
lsym := sym.(*obj.LSym)
1145-
if off >= int64(len(lsym.P)) {
1145+
if off >= int64(len(lsym.P)) || off < 0 {
11461146
// Invalid index into the global sym.
11471147
// This can happen in dead code, so we don't want to panic.
11481148
// Just return any value, it will eventually get ignored.
@@ -1155,7 +1155,7 @@ func read8(sym interface{}, off int64) uint8 {
11551155
// read16 reads two bytes from the read-only global sym at offset off.
11561156
func read16(sym interface{}, off int64, bigEndian bool) uint16 {
11571157
lsym := sym.(*obj.LSym)
1158-
if off >= int64(len(lsym.P))-1 {
1158+
if off >= int64(len(lsym.P))-1 || off < 0 {
11591159
return 0
11601160
}
11611161
if bigEndian {
@@ -1168,7 +1168,7 @@ func read16(sym interface{}, off int64, bigEndian bool) uint16 {
11681168
// read32 reads four bytes from the read-only global sym at offset off.
11691169
func read32(sym interface{}, off int64, bigEndian bool) uint32 {
11701170
lsym := sym.(*obj.LSym)
1171-
if off >= int64(len(lsym.P))-3 {
1171+
if off >= int64(len(lsym.P))-3 || off < 0 {
11721172
return 0
11731173
}
11741174
if bigEndian {
@@ -1181,7 +1181,7 @@ func read32(sym interface{}, off int64, bigEndian bool) uint32 {
11811181
// read64 reads eight bytes from the read-only global sym at offset off.
11821182
func read64(sym interface{}, off int64, bigEndian bool) uint64 {
11831183
lsym := sym.(*obj.LSym)
1184-
if off >= int64(len(lsym.P))-7 {
1184+
if off >= int64(len(lsym.P))-7 || off < 0 {
11851185
return 0
11861186
}
11871187
if bigEndian {

test/fixedbugs/issue29215.go

+17
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,20 @@ func f() {
1616
}
1717
_ = s == "bbb"
1818
}
19+
20+
// Another case: load from negative offset of a symbol
21+
// in dead code (issue 30257).
22+
func g() {
23+
var i int
24+
var s string
25+
26+
if true {
27+
s = "a"
28+
}
29+
30+
if f := 0.0; -f < 0 {
31+
i = len(s[:4])
32+
}
33+
34+
_ = s[i-1:0] != "bb" && true
35+
}

0 commit comments

Comments
 (0)