Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 116 additions & 87 deletions src/java.desktop/share/classes/sun/awt/image/XbmImageDecoder.java
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JDK 17u patch updates the copyright in this file for the end year to 2025. I think we should do that here as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, done: 5dd495e.

Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,22 @@
* questions.
*/

/*-
/*
* Reads xbitmap format images into a DIBitmap structure.
*/
package sun.awt.image;

import java.io.*;
import java.awt.image.*;
import java.awt.image.ImageConsumer;
import java.awt.image.IndexColorModel;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.Math.multiplyExact;

/**
* Parse files of the form:
Expand All @@ -50,6 +59,8 @@ public class XbmImageDecoder extends ImageDecoder {
ImageConsumer.COMPLETESCANLINES |
ImageConsumer.SINGLEPASS |
ImageConsumer.SINGLEFRAME);
private static final int MAX_XBM_SIZE = 16384;
private static final int HEADER_SCAN_LIMIT = 100;

public XbmImageDecoder(InputStreamImageSource src, InputStream is) {
super(src, is);
Expand All @@ -72,107 +83,125 @@ private static void error(String s1) throws ImageFormatException {
* produce an image from the stream.
*/
public void produceImage() throws IOException, ImageFormatException {
char nm[] = new char[80];
int c;
int i = 0;
int state = 0;
int H = 0;
int W = 0;
int x = 0;
int y = 0;
boolean start = true;
int n = 0;
int state = 0;
byte raster[] = null;
IndexColorModel model = null;
while (!aborted && (c = input.read()) != -1) {
if ('a' <= c && c <= 'z' ||
'A' <= c && c <= 'Z' ||
'0' <= c && c <= '9' || c == '#' || c == '_') {
if (i < 78)
nm[i++] = (char) c;
} else if (i > 0) {
int nc = i;
i = 0;
if (start) {
if (nc != 7 ||
nm[0] != '#' ||
nm[1] != 'd' ||
nm[2] != 'e' ||
nm[3] != 'f' ||
nm[4] != 'i' ||
nm[5] != 'n' ||
nm[6] != 'e')
{
error("Not an XBM file");

String matchRegex = "(0[xX])?[0-9a-fA-F]+[\\s+]?[,|};]";
String replaceRegex = "(0[xX])|,|[\\s+]|[};]";

String line;
int lineNum = 0;

try (BufferedReader br = new BufferedReader(new InputStreamReader(input))) {
// loop to process XBM header - width, height and create raster
while (!aborted && (line = br.readLine()) != null
&& lineNum <= HEADER_SCAN_LIMIT) {
lineNum++;
// process #define stmts
if (line.trim().startsWith("#define")) {
String[] token = line.split("\\s+");
if (token.length != 3) {
error("Error while parsing define statement");
}
try {
if (!token[2].isBlank() && state == 0) {
W = Integer.parseInt(token[2]);
state = 1; // after width is set
} else if (!token[2].isBlank() && state == 1) {
H = Integer.parseInt(token[2]);
state = 2; // after height is set
}
} catch (NumberFormatException nfe) {
// parseInt() can throw NFE
error("Error while parsing width or height.");
}
start = false;
}
if (nm[nc - 1] == 'h')
state = 1; /* expecting width */
else if (nm[nc - 1] == 't' && nc > 1 && nm[nc - 2] == 'h')
state = 2; /* expecting height */
else if (nc > 2 && state < 0 && nm[0] == '0' && nm[1] == 'x') {
int n = 0;
for (int p = 2; p < nc; p++) {
c = nm[p];
if ('0' <= c && c <= '9')
c = c - '0';
else if ('A' <= c && c <= 'Z')
c = c - 'A' + 10;
else if ('a' <= c && c <= 'z')
c = c - 'a' + 10;
else
c = 0;
n = n * 16 + c;

if (state == 2) {
if (W <= 0 || H <= 0) {
error("Invalid values for width or height.");
}
for (int mask = 1; mask <= 0x80; mask <<= 1) {
if (x < W) {
if ((n & mask) != 0)
raster[x] = 1;
else
raster[x] = 0;
}
x++;
if (multiplyExact(W, H) > MAX_XBM_SIZE) {
error("Large XBM file size."
+ " Maximum allowed size: " + MAX_XBM_SIZE);
}
if (x >= W) {
if (setPixels(0, y, W, 1, model, raster, 0, W) <= 0) {
return;
model = new IndexColorModel(8, 2, XbmColormap,
0, false, 0);
setDimensions(W, H);
setColorModel(model);
setHints(XbmHints);
headerComplete();
raster = new byte[W];
state = 3;
break;
}
}

if (state != 3) {
error("Width or Height of XBM file not defined");
}

// loop to process image data
while (!aborted && (line = br.readLine()) != null) {
lineNum++;

if (line.contains("[]")) {
Matcher matcher = Pattern.compile(matchRegex).matcher(line);
while (matcher.find()) {
if (y >= H) {
error("Scan size of XBM file exceeds"
+ " the defined width x height");
}

int startIndex = matcher.start();
int endIndex = matcher.end();
String hexByte = line.substring(startIndex, endIndex);

if (!(hexByte.startsWith("0x")
|| hexByte.startsWith("0X"))) {
error("Invalid hexadecimal number at Ln#:" + lineNum
+ " Col#:" + (startIndex + 1));
}
x = 0;
if (y++ >= H) {
break;
hexByte = hexByte.replaceAll(replaceRegex, "");
if (hexByte.length() != 2) {
error("Invalid hexadecimal number at Ln#:" + lineNum
+ " Col#:" + (startIndex + 1));
}
}
} else {
int n = 0;
for (int p = 0; p < nc; p++)
if ('0' <= (c = nm[p]) && c <= '9')
n = n * 10 + c - '0';
else {
n = -1;
break;

try {
n = Integer.parseInt(hexByte, 16);
} catch (NumberFormatException nfe) {
error("Error parsing hexadecimal at Ln#:" + lineNum
+ " Col#:" + (startIndex + 1));
}
for (int mask = 1; mask <= 0x80; mask <<= 1) {
if (x < W) {
if ((n & mask) != 0)
raster[x] = 1;
else
raster[x] = 0;
}
x++;
}
if (n > 0 && state > 0) {
if (state == 1)
W = n;
else
H = n;
if (W == 0 || H == 0)
state = 0;
else {
model = new IndexColorModel(8, 2, XbmColormap,
0, false, 0);
setDimensions(W, H);
setColorModel(model);
setHints(XbmHints);
headerComplete();
raster = new byte[W];
state = -1;

if (x >= W) {
int result = setPixels(0, y, W, 1, model, raster, 0, W);
if (result <= 0) {
error("Unexpected error occurred during setPixel()");
}
x = 0;
y++;
}
}
}
}
imageComplete(ImageConsumer.STATICIMAGEDONE, true);
}
input.close();
imageComplete(ImageConsumer.STATICIMAGEDONE, true);
}
}
77 changes: 77 additions & 0 deletions test/jdk/java/awt/image/XBMDecoder/XBMDecoderTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

/*
* @test
* @bug 8361748
* @summary Tests XBM image size limits and if XBMImageDecoder.produceImage()
* throws appropriate error when parsing invalid XBM image data.
* @run main XBMDecoderTest
*/

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import javax.swing.ImageIcon;

public class XBMDecoderTest {

public static void main(String[] args) throws Exception {
String dir = System.getProperty("test.src");
PrintStream originalErr = System.err;
boolean validCase;

File currentDir = new File(dir);
File[] files = currentDir.listFiles((File d, String s)
-> s.endsWith(".xbm"));

for (File file : files) {
String fileName = file.getName();
validCase = fileName.startsWith("valid");

System.out.println("--- Testing " + fileName + " ---");
try (FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream errContent = new ByteArrayOutputStream()) {
System.setErr(new PrintStream(errContent));

ImageIcon icon = new ImageIcon(fis.readAllBytes());
boolean isErrEmpty = errContent.toString().isEmpty();
if (!isErrEmpty) {
System.out.println("Expected ImageFormatException occurred.");
System.out.print(errContent);
}

if (validCase && !isErrEmpty) {
throw new RuntimeException("Test failed: Error stream not empty");
} else if (!validCase && isErrEmpty) {
throw new RuntimeException("Test failed: ImageFormatException"
+ " expected but not thrown");
}
System.out.println("PASSED\n");
} finally {
System.setErr(originalErr);
}
}
}
}
2 changes: 2 additions & 0 deletions test/jdk/java/awt/image/XBMDecoder/invalid.xbm
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#define k_ht 3
h` k[] = { 01x0, 42222222222236319330::
3 changes: 3 additions & 0 deletions test/jdk/java/awt/image/XBMDecoder/invalid_hex.xbm
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#define k_wt 16
#define k_ht 1
k[] = { 0x10, 1234567890};
3 changes: 3 additions & 0 deletions test/jdk/java/awt/image/XBMDecoder/invalid_ht.xbm
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#define k_wt 16
#define k_ht 0
k[] = { 0x10, 0x12};
6 changes: 6 additions & 0 deletions test/jdk/java/awt/image/XBMDecoder/valid.xbm
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#define test_width 16
#define test_height 3
#define ht_x 1
#define ht_y 2
static unsigned char test_bits[] = {
0x13, 0x11, 0x15, 0x00, 0xAB, 0xcd };
4 changes: 4 additions & 0 deletions test/jdk/java/awt/image/XBMDecoder/valid_hex.xbm
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#define test_width 16
#define test_height 2
static unsigned char test_bits[] = { 0x13, 0x11,
0xAB, 0xff };