| 1 |
// Copyright 2021 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 |
package gif |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"image" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"strings" |
| 13 |
"testing" |
| 14 |
) |
| 15 |
|
| 16 |
func FuzzDecode(f *testing.F) { |
| 17 |
testdata, err := os.ReadDir("../testdata") |
| 18 |
if err != nil { |
| 19 |
f.Fatalf("failed to read testdata directory: %s", err) |
| 20 |
} |
| 21 |
for _, de := range testdata { |
| 22 |
if de.IsDir() || !strings.HasSuffix(de.Name(), ".gif") { |
| 23 |
continue |
| 24 |
} |
| 25 |
b, err := os.ReadFile(filepath.Join("../testdata", de.Name())) |
| 26 |
if err != nil { |
| 27 |
f.Fatalf("failed to read testdata: %s", err) |
| 28 |
} |
| 29 |
f.Add(b) |
| 30 |
} |
| 31 |
|
| 32 |
f.Fuzz(func(t *testing.T, b []byte) { |
| 33 |
cfg, _, err := image.DecodeConfig(bytes.NewReader(b)) |
| 34 |
if err != nil { |
| 35 |
return |
| 36 |
} |
| 37 |
if cfg.Width*cfg.Height > 1e6 { |
| 38 |
return |
| 39 |
} |
| 40 |
img, typ, err := image.Decode(bytes.NewReader(b)) |
| 41 |
if err != nil || typ != "gif" { |
| 42 |
return |
| 43 |
} |
| 44 |
for q := 1; q <= 256; q++ { |
| 45 |
var w bytes.Buffer |
| 46 |
err := Encode(&w, img, &Options{NumColors: q}) |
| 47 |
if err != nil { |
| 48 |
t.Fatalf("failed to encode valid image: %s", err) |
| 49 |
} |
| 50 |
img1, err := Decode(&w) |
| 51 |
if err != nil { |
| 52 |
t.Fatalf("failed to decode roundtripped image: %s", err) |
| 53 |
} |
| 54 |
got := img1.Bounds() |
| 55 |
want := img.Bounds() |
| 56 |
if !got.Eq(want) { |
| 57 |
t.Fatalf("roundtripped image bounds have changed, got: %v, want: %v", got, want) |
| 58 |
} |
| 59 |
} |
| 60 |
}) |
| 61 |
} |