diff --git a/Tests/images/mmap_error.bmp b/Tests/images/mmap_error.bmp new file mode 100644 index 000000000..04df163d7 Binary files /dev/null and b/Tests/images/mmap_error.bmp differ diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py index d58666b44..604d54d88 100644 --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -39,6 +39,13 @@ def test_invalid_file(): BmpImagePlugin.BmpImageFile(fp) +def test_fallback_if_mmap_errors(): + # This image has been truncated, + # so that the buffer is not large enough when using mmap + with Image.open("Tests/images/mmap_error.bmp") as im: + assert_image_equal_tofile(im, "Tests/images/pal8_offset.bmp") + + def test_save_to_bytes(): output = io.BytesIO() im = hopper() diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py index 9f08493c1..f281b9e14 100644 --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -192,6 +192,9 @@ class ImageFile(Image.Image): with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) + if offset + self.size[1] * args[1] > self.map.size(): + # buffer is not large enough + raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args )