Skip to content

Commit

Permalink
x/image/tiff: fix division by zero when decoding empty image
Browse files Browse the repository at this point in the history
Return a zero width or zero height image of the appropriate type.

Fixes golang/go#10393.

Change-Id: I3aa7b6125447726600fb072ce1e8682373ce2a57
Reviewed-on: https://go-review.googlesource.com/9182
Reviewed-by: Nigel Tao <[email protected]>
  • Loading branch information
RafayGhafoorf committed Dec 24, 2022
1 parent ca428d5 commit 3e4f3cd
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
19 changes: 16 additions & 3 deletions tiff/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,13 @@ func Decode(r io.Reader) (img image.Image, err error) {
blocksAcross := 1
blocksDown := 1

if d.config.Width == 0 {
blocksAcross = 0
}
if d.config.Height == 0 {
blocksDown = 0
}

var blockOffsets, blockCounts []uint

if int(d.firstVal(tTileWidth)) != 0 {
Expand All @@ -496,8 +503,12 @@ func Decode(r io.Reader) (img image.Image, err error) {
blockWidth = int(d.firstVal(tTileWidth))
blockHeight = int(d.firstVal(tTileLength))

blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
if blockWidth != 0 {
blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
}
if blockHeight != 0 {
blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
}

blockCounts = d.features[tTileByteCounts]
blockOffsets = d.features[tTileOffsets]
Expand All @@ -507,7 +518,9 @@ func Decode(r io.Reader) (img image.Image, err error) {
blockHeight = int(d.firstVal(tRowsPerStrip))
}

blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
if blockHeight != 0 {
blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
}

blockOffsets = d.features[tStripOffsets]
blockCounts = d.features[tStripByteCounts]
Expand Down
26 changes: 26 additions & 0 deletions tiff/reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package tiff

import (
"bytes"
"image"
"io/ioutil"
"os"
Expand Down Expand Up @@ -162,6 +163,31 @@ func TestDecompress(t *testing.T) {
}
}

// Do not panic when image dimensions are zero, return zero-sized
// image instead.
// Issue 10393.
func TestZeroSizedImages(t *testing.T) {
testsizes := []struct {
w, h int
}{
{0, 0},
{1, 0},
{0, 1},
{1, 1},
}
for _, r := range testsizes {
img := image.NewRGBA(image.Rect(0, 0, r.w, r.h))
var buf bytes.Buffer
if err := Encode(&buf, img, nil); err != nil {
t.Errorf("encode w=%d h=%d: %v", r.w, r.h, err)
continue
}
if _, err := Decode(&buf); err != nil {
t.Errorf("decode w=%d h=%d: %v", r.w, r.h, err)
}
}
}

// benchmarkDecode benchmarks the decoding of an image.
func benchmarkDecode(b *testing.B, filename string) {
b.StopTimer()
Expand Down

0 comments on commit 3e4f3cd

Please sign in to comment.