Skip to content

Commit 4906a00

Browse files
acln0dvyukov
authored andcommitted
image/png: add Fuzz function
Add a Fuzz function to package png, under the gofuzz build tag. This function is based on the png/png.go code, from github.com/dvyukov/go-fuzz-corpus, modified to use direct comparison of image bounds rather than reflect.DeepEqual. Updates #30979 Updates #19109 Change-Id: Idb86e7ded0c2d78e6cadbeda84c7b1f35b8c579c Reviewed-on: https://go-review.googlesource.com/c/go/+/168558 Reviewed-by: thepudds <[email protected]> Reviewed-by: Dmitry Vyukov <[email protected]> Run-TryBot: Dmitry Vyukov <[email protected]>
1 parent 9a49b17 commit 4906a00

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/image/png/fuzz.go

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright 2019 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// +build gofuzz
6+
7+
package png
8+
9+
import (
10+
"bytes"
11+
"fmt"
12+
)
13+
14+
func Fuzz(data []byte) int {
15+
cfg, err := DecodeConfig(bytes.NewReader(data))
16+
if err != nil {
17+
return 0
18+
}
19+
if cfg.Width*cfg.Height > 1e6 {
20+
return 0
21+
}
22+
img, err := Decode(bytes.NewReader(data))
23+
if err != nil {
24+
return 0
25+
}
26+
levels := []CompressionLevel{
27+
DefaultCompression,
28+
NoCompression,
29+
BestSpeed,
30+
BestCompression,
31+
}
32+
for _, l := range levels {
33+
var w bytes.Buffer
34+
e := &Encoder{CompressionLevel: l}
35+
err = e.Encode(&w, img)
36+
if err != nil {
37+
panic(err)
38+
}
39+
img1, err := Decode(&w)
40+
if err != nil {
41+
panic(err)
42+
}
43+
got := img1.Bounds()
44+
want := img.Bounds()
45+
if !got.Eq(want) {
46+
fmt.Printf("bounds0: %#v\n", want)
47+
fmt.Printf("bounds1: %#v\n", got)
48+
panic("bounds have changed")
49+
}
50+
}
51+
return 1
52+
}

0 commit comments

Comments
 (0)