From 43b4b8d664ba1a3cb509b82a8cd0039c27ee5c57 Mon Sep 17 00:00:00 2001 From: wiredfool Date: Sat, 26 Mar 2016 13:41:00 -0700 Subject: [PATCH] Fix for UnboundLocalError with corrupt jpeg2k file --- PIL/Jpeg2KImagePlugin.py | 6 +++++- Tests/images/unbound_variable.jp2 | Bin 0 -> 80 bytes Tests/test_file_jpeg2k.py | 12 ++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 Tests/images/unbound_variable.jp2 diff --git a/PIL/Jpeg2KImagePlugin.py b/PIL/Jpeg2KImagePlugin.py index b82acdd98..238500448 100644 --- a/PIL/Jpeg2KImagePlugin.py +++ b/PIL/Jpeg2KImagePlugin.py @@ -84,7 +84,8 @@ def _parse_jp2_header(fp): size = None mode = None bpc = None - + nc = None + hio = io.BytesIO(header) while True: lbox, tbox = struct.unpack('>I4s', hio.read(8)) @@ -141,6 +142,9 @@ def _parse_jp2_header(fp): mode = 'RGBA' break + if size is None or mode is None: + raise SyntaxError("Malformed jp2 header") + return (size, mode) ## diff --git a/Tests/images/unbound_variable.jp2 b/Tests/images/unbound_variable.jp2 new file mode 100644 index 0000000000000000000000000000000000000000..ed6d5943e47960cade2280edc4388b401caef001 GIT binary patch literal 80 zcmZQzVBpCLP*C9IYUg5LU=T?wsVvAUFj4@r8KAT-kj?;d#WXWgih#5O7&G#-18D{Z P{^b0eB1SM%5Xb`n4fqRl literal 0 HcmV?d00001 diff --git a/Tests/test_file_jpeg2k.py b/Tests/test_file_jpeg2k.py index 4b7286a20..7e23e091a 100644 --- a/Tests/test_file_jpeg2k.py +++ b/Tests/test_file_jpeg2k.py @@ -170,6 +170,18 @@ class TestFileJpeg2k(PillowTestCase): im = self.roundtrip(jp2) self.assert_image_equal(im, jp2) + def test_unbound_local(self): + # prepatch, a malformed jp2 file could cause an UnboundLocalError + # exception. + try: + jp2 = Image.open('Tests/images/unbound_variable.jp2') + self.assertTrue(False, 'Expecting an exception') + except SyntaxError as err: + self.assertTrue(True, 'Expecting a syntax error') + except IOError as err: + self.assertTrue(True, 'Expecting an IO error') + except UnboundLocalError as err: + self.assertTrue(False, "Prepatch error") if __name__ == '__main__': unittest.main()