This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-imaging.git


The following commit(s) were added to refs/heads/master by this push:
     new 0efb2bb1 More allocation checks
0efb2bb1 is described below

commit 0efb2bb17e56601997e29781c029013ce52c1c5c
Author: Gary Gregory <[email protected]>
AuthorDate: Mon May 15 20:30:23 2023 -0400

    More allocation checks
---
 .../imaging/formats/ico/IcoImageParser.java        |   2 +-
 .../imaging/formats/jpeg/decoder/JpegDecoder.java  |  20 +-
 .../imaging/formats/xpm/XpmImageParser.java        | 215 ++++++++-------------
 3 files changed, 90 insertions(+), 147 deletions(-)

diff --git 
a/src/main/java/org/apache/commons/imaging/formats/ico/IcoImageParser.java 
b/src/main/java/org/apache/commons/imaging/formats/ico/IcoImageParser.java
index 86cf221a..4fc80592 100644
--- a/src/main/java/org/apache/commons/imaging/formats/ico/IcoImageParser.java
+++ b/src/main/java/org/apache/commons/imaging/formats/ico/IcoImageParser.java
@@ -143,7 +143,7 @@ public class IcoImageParser extends 
ImageParser<IcoImagingParameters> {
 
     abstract static class IconData {
         static final int SHALLOW_SIZE = 16;
-        
+
         public final IconInfo iconInfo;
 
         IconData(final IconInfo iconInfo) {
diff --git 
a/src/main/java/org/apache/commons/imaging/formats/jpeg/decoder/JpegDecoder.java
 
b/src/main/java/org/apache/commons/imaging/formats/jpeg/decoder/JpegDecoder.java
index 603e6a09..23722a84 100644
--- 
a/src/main/java/org/apache/commons/imaging/formats/jpeg/decoder/JpegDecoder.java
+++ 
b/src/main/java/org/apache/commons/imaging/formats/jpeg/decoder/JpegDecoder.java
@@ -449,6 +449,7 @@ public class JpegDecoder extends BinaryFileParser 
implements JpegUtils.Visitor {
             final int[] preds = 
Allocator.intArray(sofnSegment.numberOfComponents);
             ColorModel colorModel;
             WritableRaster raster;
+            Allocator.check(Integer.BYTES * sofnSegment.width * 
sofnSegment.height);
             switch (sofnSegment.numberOfComponents) {
             case 4:
                 colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 
0x000000ff);
@@ -456,18 +457,14 @@ public class JpegDecoder extends BinaryFileParser 
implements JpegUtils.Visitor {
                 raster = Raster.createPackedRaster(DataBuffer.TYPE_INT, 
sofnSegment.width, sofnSegment.height, bandMasks, null);
                 break;
             case 3:
-                colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00,
-                        0x000000ff);
-                raster = Raster.createPackedRaster(DataBuffer.TYPE_INT,
-                        sofnSegment.width, sofnSegment.height, new int[] {
-                                0x00ff0000, 0x0000ff00, 0x000000ff }, null);
+                colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 
0x000000ff);
+                raster = Raster.createPackedRaster(DataBuffer.TYPE_INT, 
sofnSegment.width, sofnSegment.height, new int[] { 0x00ff0000, 0x0000ff00, 
0x000000ff },
+                        null);
                 break;
             case 1:
-                colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00,
-                        0x000000ff);
-                raster = Raster.createPackedRaster(DataBuffer.TYPE_INT,
-                        sofnSegment.width, sofnSegment.height, new int[] {
-                                0x00ff0000, 0x0000ff00, 0x000000ff }, null);
+                colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 
0x000000ff);
+                raster = Raster.createPackedRaster(DataBuffer.TYPE_INT, 
sofnSegment.width, sofnSegment.height, new int[] { 0x00ff0000, 0x0000ff00, 
0x000000ff },
+                        null);
                 // FIXME: why do images come out too bright with CS_GRAY?
                 // colorModel = new ComponentColorModel(
                 // ColorSpace.getInstance(ColorSpace.CS_GRAY), false, true,
@@ -476,8 +473,7 @@ public class JpegDecoder extends BinaryFileParser 
implements JpegUtils.Visitor {
                 // sofnSegment.width, sofnSegment.height);
                 break;
             default:
-                throw new ImagingException(sofnSegment.numberOfComponents
-                        + " components are invalid or unsupported");
+                throw new ImagingException(sofnSegment.numberOfComponents + " 
components are invalid or unsupported");
             }
             final DataBuffer dataBuffer = raster.getDataBuffer();
 
diff --git 
a/src/main/java/org/apache/commons/imaging/formats/xpm/XpmImageParser.java 
b/src/main/java/org/apache/commons/imaging/formats/xpm/XpmImageParser.java
index 142b46a9..d2c9d5c8 100644
--- a/src/main/java/org/apache/commons/imaging/formats/xpm/XpmImageParser.java
+++ b/src/main/java/org/apache/commons/imaging/formats/xpm/XpmImageParser.java
@@ -85,15 +85,15 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
         final int height;
         final int numCharsPerPixel;
         final int numColors;
-        final  Map<Object, PaletteEntry> palette = new HashMap<>();
+        final Map<Object, PaletteEntry> palette = new HashMap<>();
         final int width;
         int xHotSpot = -1;
         final boolean xpmExt;
 
         int yHotSpot = -1;
 
-        XpmHeader(final int width, final int height, final int numColors,
-                final int numCharsPerPixel, final int xHotSpot, final int 
yHotSpot, final boolean xpmExt) {
+        XpmHeader(final int width, final int height, final int numColors, 
final int numCharsPerPixel, final int xHotSpot, final int yHotSpot,
+                final boolean xpmExt) {
             this.width = width;
             this.height = height;
             this.numColors = numColors;
@@ -116,23 +116,21 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             pw.println("XpmExt: " + xpmExt);
         }
     }
+
     private static class XpmParseResult {
         BasicCParser cParser;
         XpmHeader xpmHeader;
     }
+
     private static final String[] ACCEPTED_EXTENSIONS = 
ImageFormats.XPM.getExtensions();
     private static Map<String, Integer> colorNames;
 
     private static final String DEFAULT_EXTENSION = 
ImageFormats.XPM.getDefaultExtension();
 
-    private static final char[] WRITE_PALETTE = { ' ', '.', 'X', 'o', 'O', '+',
-        '@', '#', '$', '%', '&', '*', '=', '-', ';', ':', '>', ',', '<',
-        '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e',
-        'r', 't', 'y', 'u', 'i', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j',
-        'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'M', 'N', 'B', 'V',
-        'C', 'Z', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'P', 'I',
-        'U', 'Y', 'T', 'R', 'E', 'W', 'Q', '!', '~', '^', '/', '(', ')',
-        '_', '`', '\'', ']', '[', '{', '}', '|', };
+    private static final char[] WRITE_PALETTE = { ' ', '.', 'X', 'o', 'O', 
'+', '@', '#', '$', '%', '&', '*', '=', '-', ';', ':', '>', ',', '<', '1', '2', 
'3',
+            '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 
'u', 'i', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v',
+            'b', 'n', 'm', 'M', 'N', 'B', 'V', 'C', 'Z', 'A', 'S', 'D', 'F', 
'G', 'H', 'J', 'K', 'L', 'P', 'I', 'U', 'Y', 'T', 'R', 'E', 'W', 'Q', '!', '~',
+            '^', '/', '(', ')', '_', '`', '\'', ']', '[', '{', '}', '|', };
 
     private static void loadColorNames() throws ImagingException {
         synchronized (XpmImageParser.class) {
@@ -141,8 +139,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             }
 
             try {
-                final InputStream rgbTxtStream =
-                        XpmImageParser.class.getResourceAsStream("rgb.txt");
+                final InputStream rgbTxtStream = 
XpmImageParser.class.getResourceAsStream("rgb.txt");
                 if (rgbTxtStream == null) {
                     throw new ImagingException("Couldn't find rgb.txt in our 
resources");
                 }
@@ -159,8 +156,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
                             final int green = 
Integer.parseInt(line.substring(4, 7).trim());
                             final int blue = 
Integer.parseInt(line.substring(8, 11).trim());
                             final String colorName = line.substring(11).trim();
-                            colors.put(colorName.toLowerCase(Locale.ENGLISH), 
0xff000000 | (red << 16)
-                                    | (green << 8) | blue);
+                            colors.put(colorName.toLowerCase(Locale.ENGLISH), 
0xff000000 | (red << 16) | (green << 8) | blue);
                         } catch (final NumberFormatException nfe) {
                             throw new ImagingException("Couldn't parse color 
in rgb.txt", nfe);
                         }
@@ -174,8 +170,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
     }
 
     @Override
-    public boolean dumpImageFile(final PrintWriter pw, final ByteSource 
byteSource)
-            throws ImagingException, IOException {
+    public boolean dumpImageFile(final PrintWriter pw, final ByteSource 
byteSource) throws ImagingException, IOException {
         readXpmHeader(byteSource).dump(pw);
         return true;
     }
@@ -192,8 +187,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
     }
 
     @Override
-    public final BufferedImage getBufferedImage(final ByteSource byteSource,
-            final XpmImagingParameters params) throws ImagingException, 
IOException {
+    public final BufferedImage getBufferedImage(final ByteSource byteSource, 
final XpmImagingParameters params) throws ImagingException, IOException {
         final XpmParseResult result = parseXpmHeader(byteSource);
         return readXpmImage(result.xpmHeader, result.cParser);
     }
@@ -209,14 +203,12 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
     }
 
     @Override
-    public byte[] getICCProfileBytes(final ByteSource byteSource, final 
XpmImagingParameters params)
-            throws ImagingException, IOException {
+    public byte[] getICCProfileBytes(final ByteSource byteSource, final 
XpmImagingParameters params) throws ImagingException, IOException {
         return null;
     }
 
     @Override
-    public ImageInfo getImageInfo(final ByteSource byteSource, final 
XpmImagingParameters params)
-            throws ImagingException, IOException {
+    public ImageInfo getImageInfo(final ByteSource byteSource, final 
XpmImagingParameters params) throws ImagingException, IOException {
         final XpmHeader xpmHeader = readXpmHeader(byteSource);
         boolean transparent = false;
         ImageInfo.ColorType colorType = ImageInfo.ColorType.BW;
@@ -227,28 +219,22 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             }
             if (paletteEntry.haveColor) {
                 colorType = ImageInfo.ColorType.RGB;
-            } else if (colorType != ImageInfo.ColorType.RGB
-                    && (paletteEntry.haveGray || paletteEntry.haveGray4Level)) 
{
+            } else if (colorType != ImageInfo.ColorType.RGB && 
(paletteEntry.haveGray || paletteEntry.haveGray4Level)) {
                 colorType = ImageInfo.ColorType.GRAYSCALE;
             }
         }
-        return new ImageInfo("XPM version 3", xpmHeader.numCharsPerPixel * 8,
-                new ArrayList<>(), ImageFormats.XPM,
-                "X PixMap", xpmHeader.height, "image/x-xpixmap", 1, 0, 0, 0, 0,
-                xpmHeader.width, false, transparent, true, colorType,
-                ImageInfo.CompressionAlgorithm.NONE);
+        return new ImageInfo("XPM version 3", xpmHeader.numCharsPerPixel * 8, 
new ArrayList<>(), ImageFormats.XPM, "X PixMap", xpmHeader.height,
+                "image/x-xpixmap", 1, 0, 0, 0, 0, xpmHeader.width, false, 
transparent, true, colorType, ImageInfo.CompressionAlgorithm.NONE);
     }
 
     @Override
-    public Dimension getImageSize(final ByteSource byteSource, final 
XpmImagingParameters params)
-            throws ImagingException, IOException {
+    public Dimension getImageSize(final ByteSource byteSource, final 
XpmImagingParameters params) throws ImagingException, IOException {
         final XpmHeader xpmHeader = readXpmHeader(byteSource);
         return new Dimension(xpmHeader.width, xpmHeader.height);
     }
 
     @Override
-    public ImageMetadata getMetadata(final ByteSource byteSource, final 
XpmImagingParameters params)
-            throws ImagingException, IOException {
+    public ImageMetadata getMetadata(final ByteSource byteSource, final 
XpmImagingParameters params) throws ImagingException, IOException {
         return null;
     }
 
@@ -290,8 +276,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             return 0x00000000;
         }
         if (color.charAt(0) == '%') {
-            throw new ImagingException("HSV colors are not implemented "
-                    + "even in the XPM specification!");
+            throw new ImagingException("HSV colors are not implemented " + 
"even in the XPM specification!");
         }
         if ("None".equals(color)) {
             return 0x00000000;
@@ -305,13 +290,11 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
         return 0x00000000;
     }
 
-    private boolean parseNextString(final BasicCParser cParser,
-            final StringBuilder stringBuilder) throws IOException, 
ImagingException {
+    private boolean parseNextString(final BasicCParser cParser, final 
StringBuilder stringBuilder) throws IOException, ImagingException {
         stringBuilder.setLength(0);
         String token = cParser.nextToken();
         if (token.charAt(0) != '"') {
-            throw new ImagingException("Parsing XPM file failed, "
-                    + "no string found where expected");
+            throw new ImagingException("Parsing XPM file failed, " + "no 
string found where expected");
         }
         BasicCParser.unescapeString(stringBuilder, token);
         for (token = cParser.nextToken(); token.charAt(0) == '"'; token = 
cParser.nextToken()) {
@@ -323,12 +306,10 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
         if ("}".equals(token)) {
             return false;
         }
-        throw new ImagingException("Parsing XPM file failed, "
-                + "no ',' or '}' found where expected");
+        throw new ImagingException("Parsing XPM file failed, " + "no ',' or 
'}' found where expected");
     }
 
-    private void parsePaletteEntries(final XpmHeader xpmHeader, final 
BasicCParser cParser)
-            throws IOException, ImagingException {
+    private void parsePaletteEntries(final XpmHeader xpmHeader, final 
BasicCParser cParser) throws IOException, ImagingException {
         final StringBuilder row = new StringBuilder();
         for (int i = 0; i < xpmHeader.numColors; i++) {
             row.setLength(0);
@@ -345,12 +326,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             for (int j = 0; j < tokens.length; j++) {
                 final String token = tokens[j];
                 boolean isKey = false;
-                if (previousKeyIndex < (j - 1)
-                        && "m".equals(token)
-                        || "g4".equals(token)
-                        || "g".equals(token)
-                        || "c".equals(token)
-                        || "s".equals(token)) {
+                if (previousKeyIndex < (j - 1) && "m".equals(token) || 
"g4".equals(token) || "g".equals(token) || "c".equals(token) || 
"s".equals(token)) {
                     isKey = true;
                 }
                 if (isKey) {
@@ -381,100 +357,80 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
         }
     }
 
-    private XpmHeader parseXpmHeader(final BasicCParser cParser)
-            throws ImagingException, IOException {
+    private XpmHeader parseXpmHeader(final BasicCParser cParser) throws 
ImagingException, IOException {
         String name;
         String token;
         token = cParser.nextToken();
         if (!"static".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no 'static' token");
+            throw new ImagingException("Parsing XPM file failed, no 'static' 
token");
         }
         token = cParser.nextToken();
         if (!"char".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no 'char' token");
+            throw new ImagingException("Parsing XPM file failed, no 'char' 
token");
         }
         token = cParser.nextToken();
         if (!"*".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no '*' token");
+            throw new ImagingException("Parsing XPM file failed, no '*' 
token");
         }
         name = cParser.nextToken();
         if (name == null) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no variable name");
+            throw new ImagingException("Parsing XPM file failed, no variable 
name");
         }
         if (name.charAt(0) != '_' && !Character.isLetter(name.charAt(0))) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, variable name "
-                            + "doesn't start with letter or underscore");
+            throw new ImagingException("Parsing XPM file failed, variable name 
" + "doesn't start with letter or underscore");
         }
         for (int i = 0; i < name.length(); i++) {
             final char c = name.charAt(i);
             if (!Character.isLetterOrDigit(c) && c != '_') {
-                throw new ImagingException(
-                        "Parsing XPM file failed, variable name "
-                                + "contains non-letter non-digit 
non-underscore");
+                throw new ImagingException("Parsing XPM file failed, variable 
name " + "contains non-letter non-digit non-underscore");
             }
         }
         token = cParser.nextToken();
         if (!"[".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no '[' token");
+            throw new ImagingException("Parsing XPM file failed, no '[' 
token");
         }
         token = cParser.nextToken();
         if (!"]".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no ']' token");
+            throw new ImagingException("Parsing XPM file failed, no ']' 
token");
         }
         token = cParser.nextToken();
         if (!"=".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no '=' token");
+            throw new ImagingException("Parsing XPM file failed, no '=' 
token");
         }
         token = cParser.nextToken();
         if (!"{".equals(token)) {
-            throw new ImagingException(
-                    "Parsing XPM file failed, no '{' token");
+            throw new ImagingException("Parsing XPM file failed, no '{' 
token");
         }
 
         final StringBuilder row = new StringBuilder();
         final boolean hasMore = parseNextString(cParser, row);
         if (!hasMore) {
-            throw new ImagingException("Parsing XPM file failed, "
-                    + "file too short");
+            throw new ImagingException("Parsing XPM file failed, " + "file too 
short");
         }
         final XpmHeader xpmHeader = parseXpmValuesSection(row.toString());
         parsePaletteEntries(xpmHeader, cParser);
         return xpmHeader;
     }
 
-    private XpmParseResult parseXpmHeader(final ByteSource byteSource)
-            throws ImagingException, IOException {
+    private XpmParseResult parseXpmHeader(final ByteSource byteSource) throws 
ImagingException, IOException {
         try (InputStream is = byteSource.getInputStream()) {
             final StringBuilder firstComment = new StringBuilder();
-            final ByteArrayOutputStream preprocessedFile = 
BasicCParser.preprocess(
-                    is, firstComment, null);
+            final ByteArrayOutputStream preprocessedFile = 
BasicCParser.preprocess(is, firstComment, null);
             if (!"XPM".equals(firstComment.toString().trim())) {
-                throw new ImagingException("Parsing XPM file failed, "
-                        + "signature isn't '/* XPM */'");
+                throw new ImagingException("Parsing XPM file failed, " + 
"signature isn't '/* XPM */'");
             }
 
             final XpmParseResult xpmParseResult = new XpmParseResult();
-            xpmParseResult.cParser = new BasicCParser(new ByteArrayInputStream(
-                    preprocessedFile.toByteArray()));
+            xpmParseResult.cParser = new BasicCParser(new 
ByteArrayInputStream(preprocessedFile.toByteArray()));
             xpmParseResult.xpmHeader = parseXpmHeader(xpmParseResult.cParser);
             return xpmParseResult;
         }
     }
 
-    private XpmHeader parseXpmValuesSection(final String row)
-            throws ImagingException {
+    private XpmHeader parseXpmValuesSection(final String row) throws 
ImagingException {
         final String[] tokens = BasicCParser.tokenizeRow(row);
         if (tokens.length < 4 || tokens.length > 7) {
-            throw new ImagingException("Parsing XPM file failed, "
-                    + "<Values> section has incorrect tokens");
+            throw new ImagingException("Parsing XPM file failed, " + "<Values> 
section has incorrect tokens");
         }
         try {
             final int width = Integer.parseInt(tokens[0]);
@@ -490,16 +446,13 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             }
             if (tokens.length == 5 || tokens.length == 7) {
                 if (!"XPMEXT".equals(tokens[tokens.length - 1])) {
-                    throw new ImagingException("Parsing XPM file failed, "
-                            + "can't parse <Values> section XPMEXT");
+                    throw new ImagingException("Parsing XPM file failed, " + 
"can't parse <Values> section XPMEXT");
                 }
                 xpmExt = true;
             }
-            return new XpmHeader(width, height, numColors, numCharsPerPixel,
-                    xHotSpot, yHotSpot, xpmExt);
+            return new XpmHeader(width, height, numColors, numCharsPerPixel, 
xHotSpot, yHotSpot, xpmExt);
         } catch (final NumberFormatException nfe) {
-            throw new ImagingException("Parsing XPM file failed, "
-                    + "error parsing <Values> section", nfe);
+            throw new ImagingException("Parsing XPM file failed, " + "error 
parsing <Values> section", nfe);
         }
     }
 
@@ -549,13 +502,11 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
         return stringBuilder.toString();
     }
 
-    private XpmHeader readXpmHeader(final ByteSource byteSource)
-            throws ImagingException, IOException {
+    private XpmHeader readXpmHeader(final ByteSource byteSource) throws 
ImagingException, IOException {
         return parseXpmHeader(byteSource).xpmHeader;
     }
 
-    private BufferedImage readXpmImage(final XpmHeader xpmHeader, final 
BasicCParser cParser)
-            throws ImagingException, IOException {
+    private BufferedImage readXpmImage(final XpmHeader xpmHeader, final 
BasicCParser cParser) throws ImagingException, IOException {
         ColorModel colorModel;
         WritableRaster raster;
         int bpp;
@@ -565,11 +516,15 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
                 final PaletteEntry paletteEntry = entry.getValue();
                 palette[paletteEntry.index] = paletteEntry.getBestARGB();
             }
-            colorModel = new IndexColorModel(8, xpmHeader.palette.size(),
-                    palette, 0, true, -1, DataBuffer.TYPE_BYTE);
-            raster = Raster.createInterleavedRaster(
-                    DataBuffer.TYPE_BYTE, xpmHeader.width, xpmHeader.height, 1,
-                    null);
+            colorModel = new IndexColorModel(8, xpmHeader.palette.size(), 
palette, 0, true, -1, DataBuffer.TYPE_BYTE);
+            // Check allocation
+            int bands = 1;
+            int scanlineStride = xpmHeader.width * bands;
+            int pixelStride = bands;
+            int size = scanlineStride * (xpmHeader.height - 1) + // first (h - 
1) scans
+                    pixelStride * xpmHeader.width; // last scan
+            Allocator.check(Byte.SIZE, size);
+            raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, 
xpmHeader.width, xpmHeader.height, bands, null);
             bpp = 8;
         } else if (xpmHeader.palette.size() <= (1 << 16)) {
             final int[] palette = Allocator.intArray(xpmHeader.palette.size());
@@ -577,23 +532,25 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
                 final PaletteEntry paletteEntry = entry.getValue();
                 palette[paletteEntry.index] = paletteEntry.getBestARGB();
             }
-            colorModel = new IndexColorModel(16, xpmHeader.palette.size(),
-                    palette, 0, true, -1, DataBuffer.TYPE_USHORT);
-            raster = Raster.createInterleavedRaster(
-                    DataBuffer.TYPE_USHORT, xpmHeader.width, xpmHeader.height,
-                    1, null);
+            colorModel = new IndexColorModel(16, xpmHeader.palette.size(), 
palette, 0, true, -1, DataBuffer.TYPE_USHORT);
+            // Check allocation
+            int bands = 1;
+            int scanlineStride = xpmHeader.width * bands;
+            int pixelStride = bands;
+            int size = scanlineStride * (xpmHeader.height - 1) + // first (h - 
1) scans
+                    pixelStride * xpmHeader.width; // last scan
+            Allocator.check(Short.SIZE, size);
+            raster = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, 
xpmHeader.width, xpmHeader.height, bands, null);
             bpp = 16;
         } else {
-            colorModel = new DirectColorModel(32, 0x00ff0000, 0x0000ff00,
-                    0x000000ff, 0xff000000);
-            raster = Raster.createPackedRaster(DataBuffer.TYPE_INT,
-                    xpmHeader.width, xpmHeader.height, new int[] { 0x00ff0000,
-                            0x0000ff00, 0x000000ff, 0xff000000 }, null);
+            colorModel = new DirectColorModel(32, 0x00ff0000, 0x0000ff00, 
0x000000ff, 0xff000000);
+            Allocator.check(Integer.SIZE, xpmHeader.width * xpmHeader.height);
+            raster = Raster.createPackedRaster(DataBuffer.TYPE_INT, 
xpmHeader.width, xpmHeader.height,
+                    new int[] { 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 
}, null);
             bpp = 32;
         }
 
-        final BufferedImage image = new BufferedImage(colorModel, raster,
-                colorModel.isAlphaPremultiplied(), new Properties());
+        final BufferedImage image = new BufferedImage(colorModel, raster, 
colorModel.isAlphaPremultiplied(), new Properties());
         final DataBuffer dataBuffer = raster.getDataBuffer();
         final StringBuilder row = new StringBuilder();
         boolean hasMore = true;
@@ -601,23 +558,19 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             row.setLength(0);
             hasMore = parseNextString(cParser, row);
             if (y < (xpmHeader.height - 1) && !hasMore) {
-                throw new ImagingException("Parsing XPM file failed, "
-                        + "insufficient image rows in file");
+                throw new ImagingException("Parsing XPM file failed, " + 
"insufficient image rows in file");
             }
             final int rowOffset = y * xpmHeader.width;
             for (int x = 0; x < xpmHeader.width; x++) {
-                final String index = row.substring(x * 
xpmHeader.numCharsPerPixel,
-                        (x + 1) * xpmHeader.numCharsPerPixel);
+                final String index = row.substring(x * 
xpmHeader.numCharsPerPixel, (x + 1) * xpmHeader.numCharsPerPixel);
                 final PaletteEntry paletteEntry = xpmHeader.palette.get(index);
                 if (paletteEntry == null) {
-                    throw new ImagingException(
-                            "No palette entry was defined " + "for " + index);
+                    throw new ImagingException("No palette entry was defined " 
+ "for " + index);
                 }
                 if (bpp <= 16) {
                     dataBuffer.setElem(rowOffset + x, paletteEntry.index);
                 } else {
-                    dataBuffer.setElem(rowOffset + x,
-                            paletteEntry.getBestARGB());
+                    dataBuffer.setElem(rowOffset + x, 
paletteEntry.getBestARGB());
                 }
             }
         }
@@ -646,16 +599,14 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
     }
 
     @Override
-    public void writeImage(final BufferedImage src, final OutputStream os, 
final XpmImagingParameters params)
-            throws ImagingException, IOException {
+    public void writeImage(final BufferedImage src, final OutputStream os, 
final XpmImagingParameters params) throws ImagingException, IOException {
         final PaletteFactory paletteFactory = new PaletteFactory();
         final boolean hasTransparency = paletteFactory.hasTransparency(src, 1);
         SimplePalette palette = null;
         int maxColors = WRITE_PALETTE.length;
         int charsPerPixel = 1;
         while (palette == null) {
-            palette = paletteFactory.makeExactRgbPaletteSimple(src,
-                    hasTransparency ? maxColors - 1 : maxColors);
+            palette = paletteFactory.makeExactRgbPaletteSimple(src, 
hasTransparency ? maxColors - 1 : maxColors);
 
             // leave the loop if numbers would go beyond Integer.MAX_VALUE to 
avoid infinite loops
             // test every operation from below if it would increase an int 
value beyond Integer.MAX_VALUE
@@ -682,8 +633,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
         os.write(line.getBytes(StandardCharsets.US_ASCII));
         line = "static char *" + randomName() + "[] = {\n";
         os.write(line.getBytes(StandardCharsets.US_ASCII));
-        line = "\"" + src.getWidth() + " " + src.getHeight() + " " + colors
-                + " " + charsPerPixel + "\",\n";
+        line = "\"" + src.getWidth() + " " + src.getHeight() + " " + colors + 
" " + charsPerPixel + "\",\n";
         os.write(line.getBytes(StandardCharsets.US_ASCII));
 
         for (int i = 0; i < colors; i++) {
@@ -693,8 +643,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
             } else {
                 color = "None";
             }
-            line = "\"" + pixelsForIndex(i, charsPerPixel) + " c " + color
-                    + "\",\n";
+            line = "\"" + pixelsForIndex(i, charsPerPixel) + " c " + color + 
"\",\n";
             os.write(line.getBytes(StandardCharsets.US_ASCII));
         }
 
@@ -709,9 +658,7 @@ public class XpmImageParser extends 
ImageParser<XpmImagingParameters> {
                 if ((argb & 0xff000000) == 0) {
                     line = pixelsForIndex(palette.length(), charsPerPixel);
                 } else {
-                    line = pixelsForIndex(
-                            palette.getPaletteIndex(0xffffff & argb),
-                            charsPerPixel);
+                    line = pixelsForIndex(palette.getPaletteIndex(0xffffff & 
argb), charsPerPixel);
                 }
                 os.write(line.getBytes(StandardCharsets.US_ASCII));
             }

Reply via email to