Skip to content

Commit

Permalink
s2: Fix EstimateBlockSize on 6&7 length input (#867)
Browse files Browse the repository at this point in the history
Fixes `panic: runtime error: index out of range [7] with length 5` when providing short input to EstimateBlockSize.

Found via #866
  • Loading branch information
klauspost authored Sep 26, 2023
1 parent c634b49 commit e670df9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion s2/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func Encode(dst, src []byte) []byte {
// The function returns -1 if no improvement could be achieved.
// Using actual compression will most often produce better compression than the estimate.
func EstimateBlockSize(src []byte) (d int) {
if len(src) < 6 || int64(len(src)) > 0xffffffff {
if len(src) <= inputMargin || int64(len(src)) > 0xffffffff {
return -1
}
if len(src) <= 1024 {
Expand Down
2 changes: 2 additions & 0 deletions s2/encode_go.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ func matchLen(a []byte, b []byte) int {
return len(a) + checked
}

// input must be > inputMargin
func calcBlockSize(src []byte) (d int) {
// Initialize the hash table.
const (
Expand Down Expand Up @@ -501,6 +502,7 @@ emitRemainder:
return d
}

// length must be > inputMargin.
func calcBlockSizeSmall(src []byte) (d int) {
// Initialize the hash table.
const (
Expand Down
8 changes: 8 additions & 0 deletions s2/s2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1652,6 +1652,14 @@ func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
return nil
}

func TestEstimateBlockSize(t *testing.T) {
var input []byte
for i := 0; i < 100; i++ {
EstimateBlockSize(input)
input = append(input, 0)
}
}

func benchFile(b *testing.B, i int, decode bool) {
if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
b.Fatalf("failed to download testdata: %s", err)
Expand Down

0 comments on commit e670df9

Please sign in to comment.