Merge
authorlana
Tue Mar 24 19:12:02 2009 -0700 (12 months ago)
changeset 10048e36b37745d4
parent 946bcbeadb4a5d7
parent 10030c69e3ba15f4
child 10056ee1e2a1a833
Merge
src/windows/classes/sun/awt/windows/fontconfig.98.properties
src/windows/classes/sun/awt/windows/fontconfig.Me.properties
--- a/make/sun/awt/Makefile Thu Mar 19 13:25:35 2009 -0700
+++ b/make/sun/awt/Makefile Tue Mar 24 19:12:02 2009 -0700
@@ -339,8 +339,7 @@ ifeq ($(PLATFORM), windows)
FONTCONFIGS_SRC = $(PLATFORM_SRC)/classes/sun/awt/windows
_FONTCONFIGS = \
- fontconfig.properties \
- fontconfig.98.properties
+ fontconfig.properties
FONTCONFIGS_SRC_PREFIX =
--- a/make/sun/xawt/mapfile-vers Thu Mar 19 13:25:35 2009 -0700
+++ b/make/sun/xawt/mapfile-vers Tue Mar 24 19:12:02 2009 -0700
@@ -304,12 +304,14 @@ SUNWprivate_1.1 {
Java_java_awt_FileDialog_initIDs;
Java_sun_awt_X11_XWindow_initIDs;
+ Java_sun_java2d_opengl_OGLContext_getOGLIdString;
Java_sun_java2d_opengl_OGLMaskFill_maskFill;
Java_sun_java2d_opengl_OGLRenderer_drawPoly;
Java_sun_java2d_opengl_OGLRenderQueue_flushBuffer;
Java_sun_java2d_opengl_OGLSurfaceData_initTexture;
Java_sun_java2d_opengl_OGLSurfaceData_initFBObject;
Java_sun_java2d_opengl_OGLSurfaceData_initFlipBackbuffer;
+ Java_sun_java2d_opengl_OGLSurfaceData_getTextureID;
Java_sun_java2d_opengl_OGLSurfaceData_getTextureTarget;
Java_sun_java2d_opengl_OGLTextRenderer_drawGlyphList;
Java_sun_java2d_opengl_GLXGraphicsConfig_getGLXConfigInfo;
--- a/src/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java Tue Mar 24 19:12:02 2009 -0700
@@ -153,7 +153,7 @@ public class GIFImageMetadata extends GI
node.setAttribute("imageWidth", Integer.toString(imageWidth));
node.setAttribute("imageHeight", Integer.toString(imageHeight));
node.setAttribute("interlaceFlag",
- interlaceFlag ? "true" : "false");
+ interlaceFlag ? "TRUE" : "FALSE");
root.appendChild(node);
// Local color table
@@ -185,9 +185,9 @@ public class GIFImageMetadata extends GI
node.setAttribute("disposalMethod",
disposalMethodNames[disposalMethod]);
node.setAttribute("userInputFlag",
- userInputFlag ? "true" : "false");
+ userInputFlag ? "TRUE" : "FALSE");
node.setAttribute("transparentColorFlag",
- transparentColorFlag ? "true" : "false");
+ transparentColorFlag ? "TRUE" : "FALSE");
node.setAttribute("delayTime",
Integer.toString(delayTime));
node.setAttribute("transparentColorIndex",
--- a/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriter.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriter.java Tue Mar 24 19:12:02 2009 -0700
@@ -55,6 +55,7 @@ import org.w3c.dom.NodeList;
import org.w3c.dom.NodeList;
import com.sun.imageio.plugins.common.LZWCompressor;
import com.sun.imageio.plugins.common.PaletteBuilder;
+import sun.awt.image.ByteComponentRaster;
public class GIFImageWriter extends ImageWriter {
private static final boolean DEBUG = false; // XXX false for release!
@@ -905,10 +906,18 @@ public class GIFImageWriter extends Imag
LZWCompressor compressor =
new LZWCompressor(stream, initCodeSize, false);
+ /* At this moment we know that input image is indexed image.
+ * We can directly copy data iff:
+ * - no subsampling required (periodX = 1, periodY = 0)
+ * - we can access data directly (image is non-tiled,
+ * i.e. image data are in single block)
+ * - we can calculate offset in data buffer (next 3 lines)
+ */
boolean isOptimizedCase =
periodX == 1 && periodY == 1 &&
+ image.getNumXTiles() == 1 && image.getNumYTiles() == 1 &&
sampleModel instanceof ComponentSampleModel &&
- image.getNumXTiles() == 1 && image.getNumYTiles() == 1 &&
+ image.getTile(0, 0) instanceof ByteComponentRaster &&
image.getTile(0, 0).getDataBuffer() instanceof DataBufferByte;
int numRowsWritten = 0;
@@ -921,11 +930,14 @@ public class GIFImageWriter extends Imag
if (DEBUG) System.out.println("Writing interlaced");
if (isOptimizedCase) {
- Raster tile = image.getTile(0, 0);
+ ByteComponentRaster tile =
+ (ByteComponentRaster)image.getTile(0, 0);
byte[] data = ((DataBufferByte)tile.getDataBuffer()).getData();
ComponentSampleModel csm =
(ComponentSampleModel)tile.getSampleModel();
int offset = csm.getOffset(sourceXOffset, sourceYOffset, 0);
+ // take into account the raster data offset
+ offset += tile.getDataOffset(0);
int lineStride = csm.getScanlineStride();
writeRowsOpt(data, offset, lineStride, compressor,
--- a/src/share/classes/com/sun/imageio/plugins/gif/GIFMetadata.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/gif/GIFMetadata.java Tue Mar 24 19:12:02 2009 -0700
@@ -158,13 +158,10 @@ abstract class GIFMetadata extends IIOMe
}
}
String value = attr.getNodeValue();
- // XXX Should be able to use equals() here instead of
- // equalsIgnoreCase() but some boolean attributes are incorrectly
- // set to "true" or "false" by the J2SE core metadata classes
- // getAsTree() method (which are duplicated above). See bug 5082756.
- if (value.equalsIgnoreCase("TRUE")) {
+ // Allow lower case booleans for backward compatibility, #5082756
+ if (value.equals("TRUE") || value.equals("true")) {
return true;
- } else if (value.equalsIgnoreCase("FALSE")) {
+ } else if (value.equals("FALSE") || value.equals("false")) {
return false;
} else {
fatal(node, "Attribute " + name + " must be 'TRUE' or 'FALSE'!");
--- a/src/share/classes/com/sun/imageio/plugins/gif/GIFStreamMetadata.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/gif/GIFStreamMetadata.java Tue Mar 24 19:12:02 2009 -0700
@@ -202,7 +202,7 @@ public class GIFStreamMetadata extends G
compression_node.appendChild(node);
node = new IIOMetadataNode("Lossless");
- node.setAttribute("value", "true");
+ node.setAttribute("value", "TRUE");
compression_node.appendChild(node);
// NumProgressiveScans not in stream
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java Tue Mar 24 19:12:02 2009 -0700
@@ -1003,7 +1003,7 @@ class JFIFMarkerSegment extends MarkerSe
3,
new int [] {0, 1, 2},
null);
- ColorModel cm = new ComponentColorModel(JPEG.sRGB,
+ ColorModel cm = new ComponentColorModel(JPEG.JCS.sRGB,
false,
false,
ColorModel.OPAQUE,
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JPEG.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JPEG.java Tue Mar 24 19:12:02 2009 -0700
@@ -208,15 +208,24 @@ public class JPEG {
public static final int [] bOffsRGB = { 2, 1, 0 };
- protected static final ColorSpace sRGB =
- ColorSpace.getInstance(ColorSpace.CS_sRGB);
- protected static ColorSpace YCC = null; // Can't be final
-
- static {
- try {
- YCC = ColorSpace.getInstance(ColorSpace.CS_PYCC);
- } catch (IllegalArgumentException e) {
- // PYCC.pf may not always be installed
+ /* These are kept in the inner class to avoid static initialization
+ * of the CMM class until someone actually needs it.
+ * (e.g. do not init CMM on the request for jpeg mime types)
+ */
+ public static class JCS {
+ public static final ColorSpace sRGB =
+ ColorSpace.getInstance(ColorSpace.CS_sRGB);
+ public static final ColorSpace YCC;
+
+ static {
+ ColorSpace cs = null;
+ try {
+ cs = ColorSpace.getInstance(ColorSpace.CS_PYCC);
+ } catch (IllegalArgumentException e) {
+ // PYCC.pf may not always be installed
+ } finally {
+ YCC = cs;
+ }
}
}
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java Tue Mar 24 19:12:02 2009 -0700
@@ -228,31 +228,31 @@ public class JPEGImageReader extends Ima
(BufferedImage.TYPE_BYTE_GRAY);
defaultTypes[JPEG.JCS_RGB] =
ImageTypeSpecifier.createInterleaved
- (JPEG.sRGB,
+ (JPEG.JCS.sRGB,
JPEG.bOffsRGB,
DataBuffer.TYPE_BYTE,
false,
false);
defaultTypes[JPEG.JCS_RGBA] =
ImageTypeSpecifier.createPacked
- (JPEG.sRGB,
+ (JPEG.JCS.sRGB,
0xff000000,
0x00ff0000,
0x0000ff00,
0x000000ff,
DataBuffer.TYPE_INT,
false);
- if (JPEG.YCC != null) {
+ if (JPEG.JCS.YCC != null) {
defaultTypes[JPEG.JCS_YCC] =
ImageTypeSpecifier.createInterleaved
- (JPEG.YCC,
+ (JPEG.JCS.YCC,
JPEG.bandOffsets[2],
DataBuffer.TYPE_BYTE,
false,
false);
defaultTypes[JPEG.JCS_YCCA] =
ImageTypeSpecifier.createInterleaved
- (JPEG.YCC,
+ (JPEG.JCS.YCC,
JPEG.bandOffsets[3],
DataBuffer.TYPE_BYTE,
true,
@@ -774,7 +774,7 @@ public class JPEGImageReader extends Ima
case JPEG.JCS_RGB:
list.add(raw);
list.add(getImageType(JPEG.JCS_GRAYSCALE));
- if (JPEG.YCC != null) {
+ if (JPEG.JCS.YCC != null) {
list.add(getImageType(JPEG.JCS_YCC));
}
break;
@@ -811,7 +811,7 @@ public class JPEGImageReader extends Ima
}
list.add(getImageType(JPEG.JCS_GRAYSCALE));
- if (JPEG.YCC != null) { // Might be null if PYCC.pf not installed
+ if (JPEG.JCS.YCC != null) { // Might be null if PYCC.pf not installed
list.add(getImageType(JPEG.JCS_YCC));
}
break;
@@ -893,7 +893,7 @@ public class JPEGImageReader extends Ima
(!cs.isCS_sRGB()) &&
(cm.getNumComponents() == numComponents)) {
// Target isn't sRGB, so convert from sRGB to the target
- convert = new ColorConvertOp(JPEG.sRGB, cs, null);
+ convert = new ColorConvertOp(JPEG.JCS.sRGB, cs, null);
} else if (csType != ColorSpace.TYPE_RGB) {
throw new IIOException("Incompatible color conversion");
}
@@ -906,18 +906,18 @@ public class JPEGImageReader extends Ima
}
break;
case JPEG.JCS_YCC:
- if (JPEG.YCC == null) { // We can't do YCC at all
+ if (JPEG.JCS.YCC == null) { // We can't do YCC at all
throw new IIOException("Incompatible color conversion");
}
- if ((cs != JPEG.YCC) &&
+ if ((cs != JPEG.JCS.YCC) &&
(cm.getNumComponents() == numComponents)) {
- convert = new ColorConvertOp(JPEG.YCC, cs, null);
+ convert = new ColorConvertOp(JPEG.JCS.YCC, cs, null);
}
break;
case JPEG.JCS_YCCA:
// No conversions available; image must be YCCA
- if ((JPEG.YCC == null) || // We can't do YCC at all
- (cs != JPEG.YCC) ||
+ if ((JPEG.JCS.YCC == null) || // We can't do YCC at all
+ (cs != JPEG.JCS.YCC) ||
(cm.getNumComponents() != numComponents)) {
throw new IIOException("Incompatible color conversion");
}
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java Tue Mar 24 19:12:02 2009 -0700
@@ -39,8 +39,6 @@ public class JPEGImageReaderSpi extends
private static String [] writerSpiNames =
{"com.sun.imageio.plugins.jpeg.JPEGImageWriterSpi"};
- private boolean registered = false;
-
public JPEGImageReaderSpi() {
super(JPEG.vendor,
JPEG.version,
@@ -59,26 +57,6 @@ public class JPEGImageReaderSpi extends
JPEG.nativeImageMetadataFormatClassName,
null, null
);
- }
-
- public void onRegistration(ServiceRegistry registry,
- Class<?> category) {
- if (registered) {
- return;
- }
- try {
- java.security.AccessController.doPrivileged(
- new sun.security.action.LoadLibraryAction("jpeg"));
- // Stuff it all into one lib for first pass
- //java.security.AccessController.doPrivileged(
- //new sun.security.action.LoadLibraryAction("imageioIJG"));
- } catch (Throwable e) { // Fail on any Throwable
- // if it can't be loaded, deregister and return
- registry.deregisterServiceProvider(this);
- return;
- }
-
- registered = true;
}
public String getDescription(Locale locale) {
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java Tue Mar 24 19:12:02 2009 -0700
@@ -812,13 +812,13 @@ public class JPEGImageWriter extends Ima
}
break;
case ColorSpace.TYPE_3CLR:
- if (cs == JPEG.YCC) {
+ if (cs == JPEG.JCS.YCC) {
if (!alpha) {
if (jfif != null) {
convertTosRGB = true;
convertOp =
new ColorConvertOp(cs,
- JPEG.sRGB,
+ JPEG.JCS.sRGB,
null);
outCsType = JPEG.JCS_YCbCr;
} else if (adobe != null) {
@@ -1494,7 +1494,7 @@ public class JPEGImageWriter extends Ima
}
break;
case ColorSpace.TYPE_3CLR:
- if (cs == JPEG.YCC) {
+ if (cs == JPEG.JCS.YCC) {
if (alpha) {
retval = JPEG.JCS_YCCA;
} else {
@@ -1533,7 +1533,7 @@ public class JPEGImageWriter extends Ima
}
break;
case ColorSpace.TYPE_3CLR:
- if (cs == JPEG.YCC) {
+ if (cs == JPEG.JCS.YCC) {
if (alpha) {
retval = JPEG.JCS_YCCA;
} else {
@@ -1579,7 +1579,7 @@ public class JPEGImageWriter extends Ima
}
break;
case ColorSpace.TYPE_3CLR:
- if (cs == JPEG.YCC) {
+ if (cs == JPEG.JCS.YCC) {
if (alpha) {
retval = JPEG.JCS_YCCA;
} else {
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java Tue Mar 24 19:12:02 2009 -0700
@@ -42,8 +42,6 @@ public class JPEGImageWriterSpi extends
private static String [] readerSpiNames =
{"com.sun.imageio.plugins.jpeg.JPEGImageReaderSpi"};
- private boolean registered = false;
-
public JPEGImageWriterSpi() {
super(JPEG.vendor,
JPEG.version,
@@ -66,23 +64,6 @@ public class JPEGImageWriterSpi extends
public String getDescription(Locale locale) {
return "Standard JPEG Image Writer";
- }
-
- public void onRegistration(ServiceRegistry registry,
- Class<?> category) {
- if (registered) {
- return;
- }
- try {
- java.security.AccessController.doPrivileged(
- new sun.security.action.LoadLibraryAction("jpeg"));
- } catch (Throwable e) { // Fail on any Throwable
- // if it can't be loaded, deregister and return
- registry.deregisterServiceProvider(this);
- return;
- }
-
- registered = true;
}
public boolean isFormatLossless() {
--- a/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java Tue Mar 24 19:12:02 2009 -0700
@@ -490,7 +490,7 @@ public class JPEGMetadata extends IIOMet
}
break;
case ColorSpace.TYPE_3CLR:
- if (cs == JPEG.YCC) {
+ if (cs == JPEG.JCS.YCC) {
wantJFIF = false;
componentIDs[0] = (byte) 'Y';
componentIDs[1] = (byte) 'C';
@@ -955,7 +955,7 @@ public class JPEGMetadata extends IIOMet
// Lossless - false
IIOMetadataNode lossless = new IIOMetadataNode("Lossless");
- lossless.setAttribute("value", "false");
+ lossless.setAttribute("value", "FALSE");
compression.appendChild(lossless);
// NumProgressiveScans - count sos segments
--- a/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java Tue Mar 24 19:12:02 2009 -0700
@@ -37,6 +37,7 @@ import java.io.BufferedInputStream;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
+import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
@@ -59,7 +60,7 @@ import java.io.ByteArrayOutputStream;
import java.io.ByteArrayOutputStream;
import sun.awt.image.ByteInterleavedRaster;
-class PNGImageDataEnumeration implements Enumeration {
+class PNGImageDataEnumeration implements Enumeration<InputStream> {
boolean firstTime = true;
ImageInputStream stream;
@@ -72,7 +73,7 @@ class PNGImageDataEnumeration implements
int type = stream.readInt(); // skip chunk type
}
- public Object nextElement() {
+ public InputStream nextElement() {
try {
firstTime = false;
ImageInputStream iis = new SubImageInputStream(stream, length);
@@ -207,23 +208,15 @@ public class PNGImageReader extends Imag
resetStreamSettings();
}
- private String readNullTerminatedString(String charset) throws IOException {
+ private String readNullTerminatedString(String charset, int maxLen) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b;
- while ((b = stream.read()) != 0) {
+ int count = 0;
+ while ((maxLen > count++) && ((b = stream.read()) != 0)) {
+ if (b == -1) throw new EOFException();
baos.write(b);
}
return new String(baos.toByteArray(), charset);
- }
-
- private String readNullTerminatedString() throws IOException {
- StringBuilder b = new StringBuilder();
- int c;
-
- while ((c = stream.read()) != 0) {
- b.append((char)c);
- }
- return b.toString();
}
private void readHeader() throws IIOException {
@@ -434,7 +427,7 @@ public class PNGImageReader extends Imag
}
private void parse_iCCP_chunk(int chunkLength) throws IOException {
- String keyword = readNullTerminatedString();
+ String keyword = readNullTerminatedString("ISO-8859-1", 80);
metadata.iCCP_profileName = keyword;
metadata.iCCP_compressionMethod = stream.readUnsignedByte();
@@ -450,7 +443,7 @@ public class PNGImageReader extends Imag
private void parse_iTXt_chunk(int chunkLength) throws IOException {
long chunkStart = stream.getStreamPosition();
- String keyword = readNullTerminatedString();
+ String keyword = readNullTerminatedString("ISO-8859-1", 80);
metadata.iTXt_keyword.add(keyword);
int compressionFlag = stream.readUnsignedByte();
@@ -459,15 +452,17 @@ public class PNGImageReader extends Imag
int compressionMethod = stream.readUnsignedByte();
metadata.iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
- String languageTag = readNullTerminatedString("UTF8");
+ String languageTag = readNullTerminatedString("UTF8", 80);
metadata.iTXt_languageTag.add(languageTag);
+ long pos = stream.getStreamPosition();
+ int maxLen = (int)(chunkStart + chunkLength - pos);
String translatedKeyword =
- readNullTerminatedString("UTF8");
+ readNullTerminatedString("UTF8", maxLen);
metadata.iTXt_translatedKeyword.add(translatedKeyword);
String text;
- long pos = stream.getStreamPosition();
+ pos = stream.getStreamPosition();
byte[] b = new byte[(int)(chunkStart + chunkLength - pos)];
stream.readFully(b);
@@ -511,7 +506,7 @@ public class PNGImageReader extends Imag
private void parse_sPLT_chunk(int chunkLength)
throws IOException, IIOException {
- metadata.sPLT_paletteName = readNullTerminatedString();
+ metadata.sPLT_paletteName = readNullTerminatedString("ISO-8859-1", 80);
chunkLength -= metadata.sPLT_paletteName.length() + 1;
int sampleDepth = stream.readUnsignedByte();
@@ -554,12 +549,12 @@ public class PNGImageReader extends Imag
}
private void parse_tEXt_chunk(int chunkLength) throws IOException {
- String keyword = readNullTerminatedString();
+ String keyword = readNullTerminatedString("ISO-8859-1", 80);
metadata.tEXt_keyword.add(keyword);
byte[] b = new byte[chunkLength - keyword.length() - 1];
stream.readFully(b);
- metadata.tEXt_text.add(new String(b));
+ metadata.tEXt_text.add(new String(b, "ISO-8859-1"));
}
private void parse_tIME_chunk() throws IOException {
@@ -640,7 +635,7 @@ public class PNGImageReader extends Imag
}
private void parse_zTXt_chunk(int chunkLength) throws IOException {
- String keyword = readNullTerminatedString();
+ String keyword = readNullTerminatedString("ISO-8859-1", 80);
metadata.zTXt_keyword.add(keyword);
int method = stream.readUnsignedByte();
@@ -648,7 +643,7 @@ public class PNGImageReader extends Imag
byte[] b = new byte[chunkLength - keyword.length() - 2];
stream.readFully(b);
- metadata.zTXt_text.add(new String(inflate(b)));
+ metadata.zTXt_text.add(new String(inflate(b), "ISO-8859-1"));
}
private void readMetadata() throws IIOException {
@@ -1263,7 +1258,7 @@ public class PNGImageReader extends Imag
try {
stream.seek(imageStartPosition);
- Enumeration e = new PNGImageDataEnumeration(stream);
+ Enumeration<InputStream> e = new PNGImageDataEnumeration(stream);
InputStream is = new SequenceInputStream(e);
/* InflaterInputStream uses an Inflater instance which consumes
--- a/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java Tue Mar 24 19:12:02 2009 -0700
@@ -674,13 +674,8 @@ public class PNGImageWriter extends Imag
private byte[] deflate(byte[] b) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
-
- int len = b.length;
- for (int i = 0; i < len; i++) {
- dos.write((int)(0xff & b[i]));
- }
+ dos.write(b);
dos.close();
-
return baos.toByteArray();
}
@@ -736,7 +731,7 @@ public class PNGImageWriter extends Imag
cs.writeByte(compressionMethod);
String text = (String)textIter.next();
- cs.write(deflate(text.getBytes()));
+ cs.write(deflate(text.getBytes("ISO-8859-1")));
cs.finish();
}
}
--- a/src/share/classes/com/sun/imageio/plugins/png/PNGMetadata.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/plugins/png/PNGMetadata.java Tue Mar 24 19:12:02 2009 -0700
@@ -211,8 +211,8 @@ public class PNGMetadata extends IIOMeta
public int sRGB_renderingIntent;
// tEXt chunk
- public ArrayList tEXt_keyword = new ArrayList(); // 1-79 char Strings
- public ArrayList tEXt_text = new ArrayList(); // Strings
+ public ArrayList<String> tEXt_keyword = new ArrayList<String>(); // 1-79 characters
+ public ArrayList<String> tEXt_text = new ArrayList<String>();
// tIME chunk
public boolean tIME_present;
@@ -235,13 +235,13 @@ public class PNGMetadata extends IIOMeta
public int tRNS_blue;
// zTXt chunk
- public ArrayList zTXt_keyword = new ArrayList(); // Strings
- public ArrayList zTXt_compressionMethod = new ArrayList(); // Integers
- public ArrayList zTXt_text = new ArrayList(); // Strings
+ public ArrayList<String> zTXt_keyword = new ArrayList<String>();
+ public ArrayList<Integer> zTXt_compressionMethod = new ArrayList<Integer>();
+ public ArrayList<String> zTXt_text = new ArrayList<String>();
// Unknown chunks
- public ArrayList unknownChunkType = new ArrayList(); // Strings
- public ArrayList unknownChunkData = new ArrayList(); // byte arrays
+ public ArrayList<String> unknownChunkType = new ArrayList<String>();
+ public ArrayList<byte[]> unknownChunkData = new ArrayList<byte[]>();
public PNGMetadata() {
super(true,
@@ -426,21 +426,14 @@ public class PNGMetadata extends IIOMeta
return false;
}
- private ArrayList cloneBytesArrayList(ArrayList in) {
+ private ArrayList<byte[]> cloneBytesArrayList(ArrayList<byte[]> in) {
if (in == null) {
return null;
} else {
- ArrayList list = new ArrayList(in.size());
- Iterator iter = in.iterator();
- while (iter.hasNext()) {
- Object o = iter.next();
- if (o == null) {
- list.add(null);
- } else {
- list.add(((byte[])o).clone());
- }
- }
-
+ ArrayList<byte[]> list = new ArrayList<byte[]>(in.size());
+ for (byte[] b: in) {
+ list.add((b == null) ? null : (byte[])b.clone());
+ }
return list;
}
}
@@ -600,7 +593,7 @@ public class PNGMetadata extends IIOMeta
IIOMetadataNode iTXt_node = new IIOMetadataNode("iTXtEntry");
iTXt_node.setAttribute("keyword", iTXt_keyword.get(i));
iTXt_node.setAttribute("compressionFlag",
- iTXt_compressionFlag.get(i) ? "1" : "0");
+ iTXt_compressionFlag.get(i) ? "TRUE" : "FALSE");
iTXt_node.setAttribute("compressionMethod",
iTXt_compressionMethod.get(i).toString());
iTXt_node.setAttribute("languageTag",
@@ -832,7 +825,7 @@ public class PNGMetadata extends IIOMeta
}
node = new IIOMetadataNode("BlackIsZero");
- node.setAttribute("value", "true");
+ node.setAttribute("value", "TRUE");
chroma_node.appendChild(node);
if (PLTE_present) {
@@ -894,7 +887,7 @@ public class PNGMetadata extends IIOMeta
compression_node.appendChild(node);
node = new IIOMetadataNode("Lossless");
- node.setAttribute("value", "true");
+ node.setAttribute("value", "TRUE");
compression_node.appendChild(node);
node = new IIOMetadataNode("NumProgressiveScans");
@@ -1040,7 +1033,7 @@ public class PNGMetadata extends IIOMeta
node.setAttribute("language",
iTXt_languageTag.get(i));
if (iTXt_compressionFlag.get(i)) {
- node.setAttribute("compression", "deflate");
+ node.setAttribute("compression", "zip");
} else {
node.setAttribute("compression", "none");
}
@@ -1052,7 +1045,7 @@ public class PNGMetadata extends IIOMeta
node = new IIOMetadataNode("TextEntry");
node.setAttribute("keyword", (String)zTXt_keyword.get(i));
node.setAttribute("value", (String)zTXt_text.get(i));
- node.setAttribute("compression", "deflate");
+ node.setAttribute("compression", "zip");
text_node.appendChild(node);
}
@@ -1162,12 +1155,13 @@ public class PNGMetadata extends IIOMeta
}
}
String value = attr.getNodeValue();
- if (value.equals("true")) {
+ // Allow lower case booleans for backward compatibility, #5082756
+ if (value.equals("TRUE") || value.equals("true")) {
return true;
- } else if (value.equals("false")) {
+ } else if (value.equals("FALSE") || value.equals("false")) {
return false;
} else {
- fatal(node, "Attribute " + name + " must be 'true' or 'false'!");
+ fatal(node, "Attribute " + name + " must be 'TRUE' or 'FALSE'!");
return false;
}
}
@@ -1421,26 +1415,30 @@ public class PNGMetadata extends IIOMeta
}
String keyword = getAttribute(iTXt_node, "keyword");
- iTXt_keyword.add(keyword);
-
- boolean compressionFlag =
- getBooleanAttribute(iTXt_node, "compressionFlag");
- iTXt_compressionFlag.add(Boolean.valueOf(compressionFlag));
-
- String compressionMethod =
- getAttribute(iTXt_node, "compressionMethod");
- iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
-
- String languageTag =
- getAttribute(iTXt_node, "languageTag");
- iTXt_languageTag.add(languageTag);
-
- String translatedKeyword =
- getAttribute(iTXt_node, "translatedKeyword");
- iTXt_translatedKeyword.add(translatedKeyword);
-
- String text = getAttribute(iTXt_node, "text");
- iTXt_text.add(text);
+ if (isValidKeyword(keyword)) {
+ iTXt_keyword.add(keyword);
+
+ boolean compressionFlag =
+ getBooleanAttribute(iTXt_node, "compressionFlag");
+ iTXt_compressionFlag.add(Boolean.valueOf(compressionFlag));
+
+ String compressionMethod =
+ getAttribute(iTXt_node, "compressionMethod");
+ iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
+
+ String languageTag =
+ getAttribute(iTXt_node, "languageTag");
+ iTXt_languageTag.add(languageTag);
+
+ String translatedKeyword =
+ getAttribute(iTXt_node, "translatedKeyword");
+ iTXt_translatedKeyword.add(translatedKeyword);
+
+ String text = getAttribute(iTXt_node, "text");
+ iTXt_text.add(text);
+
+ }
+ // silently skip invalid text entry
iTXt_node = iTXt_node.getNextSibling();
}
@@ -1692,11 +1690,45 @@ public class PNGMetadata extends IIOMeta
}
}
- private boolean isISOLatin(String s) {
+ /*
+ * Accrding to PNG spec, keywords are restricted to 1 to 79 bytes
+ * in length. Keywords shall contain only printable Latin-1 characters
+ * and spaces; To reduce the chances for human misreading of a keyword,
+ * leading spaces, trailing spaces, and consecutive spaces are not
+ * permitted in keywords.
+ *
+ * See: http://www.w3.org/TR/PNG/#11keywords
+ */
+ private boolean isValidKeyword(String s) {
+ int len = s.length();
+ if (len < 1 || len >= 80) {
+ return false;
+ }
+ if (s.startsWith(" ") || s.endsWith(" ") || s.contains(" ")) {
+ return false;
+ }
+ return isISOLatin(s, false);
+ }
+
+ /*
+ * According to PNG spec, keyword shall contain only printable
+ * Latin-1 [ISO-8859-1] characters and spaces; that is, only
+ * character codes 32-126 and 161-255 decimal are allowed.
+ * For Latin-1 value fields the 0x10 (linefeed) control
+ * character is aloowed too.
+ *
+ * See: http://www.w3.org/TR/PNG/#11keywords
+ */
+ private boolean isISOLatin(String s, boolean isLineFeedAllowed) {
int len = s.length();
for (int i = 0; i < len; i++) {
- if (s.charAt(i) > 255) {
- return false;
+ char c = s.charAt(i);
+ if (c < 32 || c > 255 || (c > 126 && c < 161)) {
+ // not printable. Check whether this is an allowed
+ // control char
+ if (!isLineFeedAllowed || c != 0x10) {
+ return false;
+ }
}
}
return true;
@@ -1929,19 +1961,22 @@ public class PNGMetadata extends IIOMeta
while (child != null) {
String childName = child.getNodeName();
if (childName.equals("TextEntry")) {
- String keyword = getAttribute(child, "keyword");
+ String keyword =
+ getAttribute(child, "keyword", "", false);
String value = getAttribute(child, "value");
- String encoding = getAttribute(child, "encoding");
- String language = getAttribute(child, "language");
+ String language =
+ getAttribute(child, "language", "", false);
String compression =
- getAttribute(child, "compression");
-
- if (isISOLatin(value)) {
+ getAttribute(child, "compression", "none", false);
+
+ if (!isValidKeyword(keyword)) {
+ // Just ignore this node, PNG requires keywords
+ } else if (isISOLatin(value, true)) {
if (compression.equals("zip")) {
// Use a zTXt node
zTXt_keyword.add(keyword);
zTXt_text.add(value);
- zTXt_compressionMethod.add(new Integer(0));
+ zTXt_compressionMethod.add(Integer.valueOf(0));
} else {
// Use a tEXt node
tEXt_keyword.add(keyword);
@@ -1998,14 +2033,14 @@ public class PNGMetadata extends IIOMeta
sBIT_present = false;
sPLT_present = false;
sRGB_present = false;
- tEXt_keyword = new ArrayList();
- tEXt_text = new ArrayList();
+ tEXt_keyword = new ArrayList<String>();
+ tEXt_text = new ArrayList<String>();
tIME_present = false;
tRNS_present = false;
- zTXt_keyword = new ArrayList();
- zTXt_compressionMethod = new ArrayList();
- zTXt_text = new ArrayList();
- unknownChunkType = new ArrayList();
- unknownChunkData = new ArrayList();
+ zTXt_keyword = new ArrayList<String>();
+ zTXt_compressionMethod = new ArrayList<Integer>();
+ zTXt_text = new ArrayList<String>();
+ unknownChunkType = new ArrayList<String>();
+ unknownChunkData = new ArrayList<byte[]>();
}
}
--- a/src/share/classes/com/sun/imageio/stream/StreamCloser.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/com/sun/imageio/stream/StreamCloser.java Tue Mar 24 19:12:02 2009 -0700
@@ -94,6 +94,10 @@ public class StreamCloser {
tgn != null;
tg = tgn, tgn = tg.getParent());
streamCloser = new Thread(tg, streamCloserRunnable);
+ /* Set context class loader to null in order to avoid
+ * keeping a strong reference to an application classloader.
+ */
+ streamCloser.setContextClassLoader(null);
Runtime.getRuntime().addShutdownHook(streamCloser);
return null;
}
--- a/src/share/classes/java/awt/GraphicsEnvironment.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/java/awt/GraphicsEnvironment.java Tue Mar 24 19:12:02 2009 -0700
@@ -356,6 +356,9 @@ public abstract class GraphicsEnvironmen
* @since 1.5
*/
public void preferLocaleFonts() {
+ if (!(this instanceof SunGraphicsEnvironment)) {
+ return;
+ }
sun.font.FontManager.preferLocaleFonts();
}
@@ -376,6 +379,9 @@ public abstract class GraphicsEnvironmen
* @since 1.5
*/
public void preferProportionalFonts() {
+ if (!(this instanceof SunGraphicsEnvironment)) {
+ return;
+ }
sun.font.FontManager.preferProportionalFonts();
}
--- a/src/share/classes/java/awt/color/ICC_Profile.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/java/awt/color/ICC_Profile.java Tue Mar 24 19:12:02 2009 -0700
@@ -737,7 +737,7 @@ public class ICC_Profile implements Seri
ICC_Profile(ProfileDeferralInfo pdi) {
this.deferralInfo = pdi;
this.profileActivator = new ProfileActivator() {
- public void activate() {
+ public void activate() throws ProfileDataException {
activateDeferredProfile();
}
};
@@ -830,20 +830,16 @@ public class ICC_Profile implements Seri
case ColorSpace.CS_sRGB:
synchronized(ICC_Profile.class) {
if (sRGBprofile == null) {
- try {
- /*
- * Deferral is only used for standard profiles.
- * Enabling the appropriate access privileges is handled
- * at a lower level.
- */
- sRGBprofile = getDeferredInstance(
- new ProfileDeferralInfo("sRGB.pf",
- ColorSpace.TYPE_RGB,
- 3, CLASS_DISPLAY));
- } catch (IOException e) {
- throw new IllegalArgumentException(
- "Can't load standard profile: sRGB.pf");
- }
+ /*
+ * Deferral is only used for standard profiles.
+ * Enabling the appropriate access privileges is handled
+ * at a lower level.
+ */
+ ProfileDeferralInfo pInfo =
+ new ProfileDeferralInfo("sRGB.pf",
+ ColorSpace.TYPE_RGB, 3,
+ CLASS_DISPLAY);
+ sRGBprofile = getDeferredInstance(pInfo);
}
thisProfile = sRGBprofile;
}
@@ -853,7 +849,11 @@ public class ICC_Profile implements Seri
case ColorSpace.CS_CIEXYZ:
synchronized(ICC_Profile.class) {
if (XYZprofile == null) {
- XYZprofile = getStandardProfile("CIEXYZ.pf");
+ ProfileDeferralInfo pInfo =
+ new ProfileDeferralInfo("CIEXYZ.pf",
+ ColorSpace.TYPE_XYZ, 3,
+ CLASS_DISPLAY);
+ XYZprofile = getDeferredInstance(pInfo);
}
thisProfile = XYZprofile;
}
@@ -863,7 +863,11 @@ public class ICC_Profile implements Seri
case ColorSpace.CS_PYCC:
synchronized(ICC_Profile.class) {
if (PYCCprofile == null) {
- PYCCprofile = getStandardProfile("PYCC.pf");
+ ProfileDeferralInfo pInfo =
+ new ProfileDeferralInfo("PYCC.pf",
+ ColorSpace.TYPE_3CLR, 3,
+ CLASS_DISPLAY);
+ PYCCprofile = getDeferredInstance(pInfo);
}
thisProfile = PYCCprofile;
}
@@ -873,7 +877,11 @@ public class ICC_Profile implements Seri
case ColorSpace.CS_GRAY:
synchronized(ICC_Profile.class) {
if (GRAYprofile == null) {
- GRAYprofile = getStandardProfile("GRAY.pf");
+ ProfileDeferralInfo pInfo =
+ new ProfileDeferralInfo("GRAY.pf",
+ ColorSpace.TYPE_GRAY, 1,
+ CLASS_DISPLAY);
+ GRAYprofile = getDeferredInstance(pInfo);
}
thisProfile = GRAYprofile;
}
@@ -883,7 +891,11 @@ public class ICC_Profile implements Seri
case ColorSpace.CS_LINEAR_RGB:
synchronized(ICC_Profile.class) {
if (LINEAR_RGBprofile == null) {
- LINEAR_RGBprofile = getStandardProfile("LINEAR_RGB.pf");
+ ProfileDeferralInfo pInfo =
+ new ProfileDeferralInfo("LINEAR_RGB.pf",
+ ColorSpace.TYPE_RGB, 3,
+ CLASS_DISPLAY);
+ LINEAR_RGBprofile = getDeferredInstance(pInfo);
}
thisProfile = LINEAR_RGBprofile;
}
@@ -1047,9 +1059,7 @@ public class ICC_Profile implements Seri
* code will take care of access privileges.
* @see activateDeferredProfile()
*/
- static ICC_Profile getDeferredInstance(ProfileDeferralInfo pdi)
- throws IOException {
-
+ static ICC_Profile getDeferredInstance(ProfileDeferralInfo pdi) {
if (!ProfileDeferralMgr.deferring) {
return getStandardProfile(pdi.filename);
}
@@ -1063,33 +1073,37 @@ public class ICC_Profile implements Seri
}
- void activateDeferredProfile() {
- byte profileData[];
- FileInputStream fis;
- String fileName = deferralInfo.filename;
+ void activateDeferredProfile() throws ProfileDataException {
+ byte profileData[];
+ FileInputStream fis;
+ String fileName = deferralInfo.filename;
profileActivator = null;
deferralInfo = null;
if ((fis = openProfile(fileName)) == null) {
- throw new IllegalArgumentException("Cannot open file " + fileName);
+ throw new ProfileDataException("Cannot open file " + fileName);
}
try {
profileData = getProfileDataFromStream(fis);
fis.close(); /* close the file */
}
catch (IOException e) {
- throw new IllegalArgumentException("Invalid ICC Profile Data" +
- fileName);
+ ProfileDataException pde = new
+ ProfileDataException("Invalid ICC Profile Data" + fileName);
+ pde.initCause(e);
+ throw pde;
}
if (profileData == null) {
- throw new IllegalArgumentException("Invalid ICC Profile Data" +
+ throw new ProfileDataException("Invalid ICC Profile Data" +
fileName);
}
try {
ID = CMSManager.getModule().loadProfile(profileData);
} catch (CMMException c) {
- throw new IllegalArgumentException("Invalid ICC Profile Data" +
- fileName);
+ ProfileDataException pde = new
+ ProfileDataException("Invalid ICC Profile Data" + fileName);
+ pde.initCause(c);
+ throw pde;
}
}
--- a/src/share/classes/java/util/logging/LogManager.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/java/util/logging/LogManager.java Tue Mar 24 19:12:02 2009 -0700
@@ -215,6 +215,14 @@ public class LogManager {
// This private class is used as a shutdown hook.
// It does a "reset" to close all open handlers.
private class Cleaner extends Thread {
+
+ private Cleaner() {
+ /* Set context class loader to null in order to avoid
+ * keeping a strong reference to an application classloader.
+ */
+ this.setContextClassLoader(null);
+ }
+
public void run() {
// This is to ensure the LogManager.<clinit> is completed
// before synchronized block. Otherwise deadlocks are possible.
--- a/src/share/classes/javax/imageio/ImageTypeSpecifier.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/javax/imageio/ImageTypeSpecifier.java Tue Mar 24 19:12:02 2009 -0700
@@ -67,126 +67,13 @@ public class ImageTypeSpecifier {
* <code>BufferedImage</code> types.
*/
private static ImageTypeSpecifier[] BISpecifier;
-
+ private static ColorSpace sRGB;
// Initialize the standard specifiers
static {
- ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
+ sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
BISpecifier =
new ImageTypeSpecifier[BufferedImage.TYPE_BYTE_INDEXED + 1];
-
- BISpecifier[BufferedImage.TYPE_CUSTOM] = null;
-
- BISpecifier[BufferedImage.TYPE_INT_RGB] =
- createPacked(sRGB,
- 0x00ff0000,
- 0x0000ff00,
- 0x000000ff,
- 0x0,
- DataBuffer.TYPE_INT,
- false);
-
- BISpecifier[BufferedImage.TYPE_INT_ARGB] =
- createPacked(sRGB,
- 0x00ff0000,
- 0x0000ff00,
- 0x000000ff,
- 0xff000000,
- DataBuffer.TYPE_INT,
- false);
-
- BISpecifier[BufferedImage.TYPE_INT_ARGB_PRE] =
- createPacked(sRGB,
- 0x00ff0000,
- 0x0000ff00,
- 0x000000ff,
- 0xff000000,
- DataBuffer.TYPE_INT,
- true);
-
- BISpecifier[BufferedImage.TYPE_INT_BGR] =
- createPacked(sRGB,
- 0x000000ff,
- 0x0000ff00,
- 0x00ff0000,
- 0x0,
- DataBuffer.TYPE_INT,
- false);
-
- int[] bOffsRGB = { 2, 1, 0 };
- BISpecifier[BufferedImage.TYPE_3BYTE_BGR] =
- createInterleaved(sRGB,
- bOffsRGB,
- DataBuffer.TYPE_BYTE,
- false,
- false);
-
- int[] bOffsABGR = { 3, 2, 1, 0 };
- BISpecifier[BufferedImage.TYPE_4BYTE_ABGR] =
- createInterleaved(sRGB,
- bOffsABGR,
- DataBuffer.TYPE_BYTE,
- true,
- false);
-
- BISpecifier[BufferedImage.TYPE_4BYTE_ABGR_PRE] =
- createInterleaved(sRGB,
- bOffsABGR,
- DataBuffer.TYPE_BYTE,
- true,
- true);
-
- BISpecifier[BufferedImage.TYPE_USHORT_565_RGB] =
- createPacked(sRGB,
- 0xF800,
- 0x07E0,
- 0x001F,
- 0x0,
- DataBuffer.TYPE_USHORT,
- false);
-
- BISpecifier[BufferedImage.TYPE_USHORT_555_RGB] =
- createPacked(sRGB,
- 0x7C00,
- 0x03E0,
- 0x001F,
- 0x0,
- DataBuffer.TYPE_USHORT,
- false);
-
- BISpecifier[BufferedImage.TYPE_BYTE_GRAY] =
- createGrayscale(8,
- DataBuffer.TYPE_BYTE,
- false);
-
- BISpecifier[BufferedImage.TYPE_USHORT_GRAY] =
- createGrayscale(16,
- DataBuffer.TYPE_USHORT,
- false);
-
- BISpecifier[BufferedImage.TYPE_BYTE_BINARY] =
- createGrayscale(1,
- DataBuffer.TYPE_BYTE,
- false);
-
- BufferedImage bi =
- new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_INDEXED);
- IndexColorModel icm = (IndexColorModel)bi.getColorModel();
- int mapSize = icm.getMapSize();
- byte[] redLUT = new byte[mapSize];
- byte[] greenLUT = new byte[mapSize];
- byte[] blueLUT = new byte[mapSize];
- byte[] alphaLUT = new byte[mapSize];
-
- icm.getReds(redLUT);
- icm.getGreens(greenLUT);
- icm.getBlues(blueLUT);
- icm.getAlphas(alphaLUT);
-
- BISpecifier[BufferedImage.TYPE_BYTE_INDEXED] =
- createIndexed(redLUT, greenLUT, blueLUT, alphaLUT,
- 8,
- DataBuffer.TYPE_BYTE);
}
/**
@@ -1011,7 +898,7 @@ public class ImageTypeSpecifier {
ImageTypeSpecifier createFromBufferedImageType(int bufferedImageType) {
if (bufferedImageType >= BufferedImage.TYPE_INT_RGB &&
bufferedImageType <= BufferedImage.TYPE_BYTE_INDEXED) {
- return BISpecifier[bufferedImageType];
+ return getSpecifier(bufferedImageType);
} else if (bufferedImageType == BufferedImage.TYPE_CUSTOM) {
throw new IllegalArgumentException("Cannot create from TYPE_CUSTOM!");
} else {
@@ -1041,7 +928,7 @@ public class ImageTypeSpecifier {
if (image instanceof BufferedImage) {
int bufferedImageType = ((BufferedImage)image).getType();
if (bufferedImageType != BufferedImage.TYPE_CUSTOM) {
- return BISpecifier[bufferedImageType];
+ return getSpecifier(bufferedImageType);
}
}
@@ -1225,4 +1112,130 @@ public class ImageTypeSpecifier {
public int hashCode() {
return (9 * colorModel.hashCode()) + (14 * sampleModel.hashCode());
}
+
+ private static ImageTypeSpecifier getSpecifier(int type) {
+ if (BISpecifier[type] == null) {
+ BISpecifier[type] = createSpecifier(type);
+ }
+ return BISpecifier[type];
+ }
+
+ private static ImageTypeSpecifier createSpecifier(int type) {
+ switch(type) {
+ case BufferedImage.TYPE_INT_RGB:
+ return createPacked(sRGB,
+ 0x00ff0000,
+ 0x0000ff00,
+ 0x000000ff,
+ 0x0,
+ DataBuffer.TYPE_INT,
+ false);
+
+ case BufferedImage.TYPE_INT_ARGB:
+ return createPacked(sRGB,
+ 0x00ff0000,
+ 0x0000ff00,
+ 0x000000ff,
+ 0xff000000,
+ DataBuffer.TYPE_INT,
+ false);
+
+ case BufferedImage.TYPE_INT_ARGB_PRE:
+ return createPacked(sRGB,
+ 0x00ff0000,
+ 0x0000ff00,
+ 0x000000ff,
+ 0xff000000,
+ DataBuffer.TYPE_INT,
+ true);
+
+ case BufferedImage.TYPE_INT_BGR:
+ return createPacked(sRGB,
+ 0x000000ff,
+ 0x0000ff00,
+ 0x00ff0000,
+ 0x0,
+ DataBuffer.TYPE_INT,
+ false);
+
+ case BufferedImage.TYPE_3BYTE_BGR:
+ return createInterleaved(sRGB,
+ new int[] { 2, 1, 0 },
+ DataBuffer.TYPE_BYTE,
+ false,
+ false);
+
+ case BufferedImage.TYPE_4BYTE_ABGR:
+ return createInterleaved(sRGB,
+ new int[] { 3, 2, 1, 0 },
+ DataBuffer.TYPE_BYTE,
+ true,
+ false);
+
+ case BufferedImage.TYPE_4BYTE_ABGR_PRE:
+ return createInterleaved(sRGB,
+ new int[] { 3, 2, 1, 0 },
+ DataBuffer.TYPE_BYTE,
+ true,
+ true);
+
+ case BufferedImage.TYPE_USHORT_565_RGB:
+ return createPacked(sRGB,
+ 0xF800,
+ 0x07E0,
+ 0x001F,
+ 0x0,
+ DataBuffer.TYPE_USHORT,
+ false);
+
+ case BufferedImage.TYPE_USHORT_555_RGB:
+ return createPacked(sRGB,
+ 0x7C00,
+ 0x03E0,
+ 0x001F,
+ 0x0,
+ DataBuffer.TYPE_USHORT,
+ false);
+
+ case BufferedImage.TYPE_BYTE_GRAY:
+ return createGrayscale(8,
+ DataBuffer.TYPE_BYTE,
+ false);
+
+ case BufferedImage.TYPE_USHORT_GRAY:
+ return createGrayscale(16,
+ DataBuffer.TYPE_USHORT,
+ false);
+
+ case BufferedImage.TYPE_BYTE_BINARY:
+ return createGrayscale(1,
+ DataBuffer.TYPE_BYTE,
+ false);
+
+ case BufferedImage.TYPE_BYTE_INDEXED:
+ {
+
+ BufferedImage bi =
+ new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_INDEXED);
+ IndexColorModel icm = (IndexColorModel)bi.getColorModel();
+ int mapSize = icm.getMapSize();
+ byte[] redLUT = new byte[mapSize];
+ byte[] greenLUT = new byte[mapSize];
+ byte[] blueLUT = new byte[mapSize];
+ byte[] alphaLUT = new byte[mapSize];
+
+ icm.getReds(redLUT);
+ icm.getGreens(greenLUT);
+ icm.getBlues(blueLUT);
+ icm.getAlphas(alphaLUT);
+
+ return createIndexed(redLUT, greenLUT, blueLUT, alphaLUT,
+ 8,
+ DataBuffer.TYPE_BYTE);
+ }
+ default:
+ throw new IllegalArgumentException("Invalid BufferedImage type!");
+ }
+ }
+
}
--- a/src/share/classes/javax/imageio/metadata/IIOMetadataFormat.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/javax/imageio/metadata/IIOMetadataFormat.java Tue Mar 24 19:12:02 2009 -0700
@@ -242,8 +242,12 @@ public interface IIOMetadataFormat {
/**
* A constant returned by <code>getAttributeDataType</code>
- * indicating that the value of an attribute is one of 'true' or
- * 'false'.
+ * indicating that the value of an attribute is one of the boolean
+ * values 'true' or 'false'.
+ * Attribute values of type DATATYPE_BOOLEAN should be marked as
+ * enumerations, and the permitted values should be the string
+ * literal values "TRUE" or "FALSE", although a plugin may also
+ * recognise lower or mixed case equivalents.
*/
int DATATYPE_BOOLEAN = 1;
--- a/src/share/classes/sun/awt/FontConfiguration.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/awt/FontConfiguration.java Tue Mar 24 19:12:02 2009 -0700
@@ -98,7 +98,7 @@ public abstract class FontConfiguration
if (!inited) {
this.preferLocaleFonts = false;
this.preferPropFonts = false;
- fontConfig = this; /* static initialization */
+ setFontConfiguration();
readFontConfigFile(fontConfigFile);
initFontConfig();
inited = true;
@@ -1242,6 +1242,10 @@ public abstract class FontConfiguration
/* subclass support */
protected static FontConfiguration getFontConfiguration() {
return fontConfig;
+ }
+
+ protected void setFontConfiguration() {
+ fontConfig = this; /* static initialization */
}
//////////////////////////////////////////////////////////////////////
--- a/src/share/classes/sun/font/FileFontStrike.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/font/FileFontStrike.java Tue Mar 24 19:12:02 2009 -0700
@@ -26,6 +26,7 @@ package sun.font;
package sun.font;
import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
@@ -842,8 +843,36 @@ public class FileFontStrike extends Phys
return fileFont.getGlyphOutlineBounds(pScalerContext, glyphCode);
}
+ private
+ WeakReference<ConcurrentHashMap<Integer,GeneralPath>> outlineMapRef;
+
GeneralPath getGlyphOutline(int glyphCode, float x, float y) {
- return fileFont.getGlyphOutline(pScalerContext, glyphCode, x, y);
+
+ GeneralPath gp = null;
+ ConcurrentHashMap<Integer, GeneralPath> outlineMap = null;
+
+ if (outlineMapRef != null) {
+ outlineMap = outlineMapRef.get();
+ if (outlineMap != null) {
+ gp = (GeneralPath)outlineMap.get(glyphCode);
+ }
+ }
+
+ if (gp == null) {
+ gp = fileFont.getGlyphOutline(pScalerContext, glyphCode, 0, 0);
+ if (outlineMap == null) {
+ outlineMap = new ConcurrentHashMap<Integer, GeneralPath>();
+ outlineMapRef =
+ new WeakReference
+ <ConcurrentHashMap<Integer,GeneralPath>>(outlineMap);
+ }
+ outlineMap.put(glyphCode, gp);
+ }
+ gp = (GeneralPath)gp.clone(); // mutable!
+ if (x != 0f || y != 0f) {
+ gp.transform(AffineTransform.getTranslateInstance(x, y));
+ }
+ return gp;
}
GeneralPath getGlyphVectorOutline(int[] glyphs, float x, float y) {
--- a/src/share/classes/sun/font/FontManager.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/font/FontManager.java Tue Mar 24 19:12:02 2009 -0700
@@ -1601,18 +1601,27 @@ public final class FontManager {
/* Path may be absolute or a base file name relative to one of
* the platform font directories
*/
- private static String getPathName(String s) {
+ private static String getPathName(final String s) {
File f = new File(s);
if (f.isAbsolute()) {
return s;
} else if (pathDirs.length==1) {
return pathDirs[0] + File.separator + s;
} else {
- for (int p=0; p<pathDirs.length; p++) {
- f = new File(pathDirs[p] + File.separator + s);
- if (f.exists()) {
- return f.getAbsolutePath();
- }
+ String path = java.security.AccessController.doPrivileged(
+ new java.security.PrivilegedAction<String>() {
+ public String run() {
+ for (int p=0; p<pathDirs.length; p++) {
+ File f = new File(pathDirs[p] +File.separator+ s);
+ if (f.exists()) {
+ return f.getAbsolutePath();
+ }
+ }
+ return null;
+ }
+ });
+ if (path != null) {
+ return path;
}
}
return s; // shouldn't happen, but harmless
--- a/src/share/classes/sun/font/GlyphLayout.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/font/GlyphLayout.java Tue Mar 24 19:12:02 2009 -0700
@@ -338,6 +338,8 @@ public final class GlyphLayout {
cache = new ConcurrentHashMap<SDKey, SDCache>(10);
cacheRef = new
SoftReference<ConcurrentHashMap<SDKey, SDCache>>(cache);
+ } else if (cache.size() >= 512) {
+ cache.clear();
}
cache.put(key, res);
}
--- a/src/share/classes/sun/font/StrikeCache.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/font/StrikeCache.java Tue Mar 24 19:12:02 2009 -0700
@@ -232,6 +232,16 @@ public final class StrikeCache {
if (disposer.pScalerContext != 0L) {
freeLongMemory(new long[0], disposer.pScalerContext);
}
+ } else if (disposer.pScalerContext != 0L) {
+ /* Rarely a strike may have been created that never cached
+ * any glyphs. In this case we still want to free the scaler
+ * context.
+ */
+ if (FontManager.longAddresses) {
+ freeLongMemory(new long[0], disposer.pScalerContext);
+ } else {
+ freeIntMemory(new int[0], disposer.pScalerContext);
+ }
}
}
--- a/src/share/classes/sun/java2d/cmm/ProfileActivator.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/java2d/cmm/ProfileActivator.java Tue Mar 24 19:12:02 2009 -0700
@@ -25,6 +25,7 @@
package sun.java2d.cmm;
+import java.awt.color.ProfileDataException;
/**
* An interface to allow the ProfileDeferralMgr to activate a
@@ -35,6 +36,6 @@ public interface ProfileActivator {
/**
* Activate a previously deferred ICC_Profile object.
*/
- public void activate();
+ public void activate() throws ProfileDataException;
}
--- a/src/share/classes/sun/java2d/cmm/ProfileDeferralMgr.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/java2d/cmm/ProfileDeferralMgr.java Tue Mar 24 19:12:02 2009 -0700
@@ -25,6 +25,7 @@
package sun.java2d.cmm;
+import java.awt.color.ProfileDataException;
import java.util.Vector;
@@ -39,7 +40,7 @@ public class ProfileDeferralMgr {
public class ProfileDeferralMgr {
public static boolean deferring = true;
- private static Vector aVector;
+ private static Vector<ProfileActivator> aVector;
/**
* Records a ProfileActivator object whose activate method will
@@ -51,7 +52,7 @@ public class ProfileDeferralMgr {
return;
}
if (aVector == null) {
- aVector = new Vector(3, 3);
+ aVector = new Vector<ProfileActivator>(3, 3);
}
aVector.addElement(pa);
return;
@@ -89,8 +90,26 @@ public class ProfileDeferralMgr {
return;
}
n = aVector.size();
- for (i = 0; i < n; i++) {
- ((ProfileActivator) aVector.get(i)).activate();
+ for (ProfileActivator pa : aVector) {
+ try {
+ pa.activate();
+ } catch (ProfileDataException e) {
+ /*
+ * Ignore profile activation error for now:
+ * such exception is pssible due to absence
+ * or corruption of standard color profile.
+ * As for now we expect all profiles should
+ * be shiped with jre and presence of this
+ * exception is indication of some configuration
+ * problem in jre installation.
+ *
+ * NB: we still are greedy loading deferred profiles
+ * and load them all if any of them is needed.
+ * Therefore broken profile (if any) might be never used.
+ * If there will be attempt to use broken profile then
+ * it will result in CMMException.
+ */
+ }
}
aVector.removeAllElements();
aVector = null;
--- a/src/share/classes/sun/java2d/pisces/Dasher.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/java2d/pisces/Dasher.java Tue Mar 24 19:12:02 2009 -0700
@@ -120,7 +120,7 @@ public class Dasher extends LineSink {
// Normalize so 0 <= phase < dash[0]
int idx = 0;
- dashOn = false;
+ dashOn = true;
int d;
while (phase >= (d = dash[idx])) {
phase -= d;
--- a/src/share/classes/sun/java2d/pisces/PiscesRenderingEngine.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/java2d/pisces/PiscesRenderingEngine.java Tue Mar 24 19:12:02 2009 -0700
@@ -245,6 +245,7 @@ public class PiscesRenderingEngine exten
FloatToS15_16(coords[1]));
break;
case PathIterator.SEG_CLOSE:
+ lsink.lineJoin();
lsink.close();
break;
default:
--- a/src/share/classes/sun/print/ServiceDialog.java Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/classes/sun/print/ServiceDialog.java Tue Mar 24 19:12:02 2009 -0700
@@ -2149,55 +2149,51 @@ public class ServiceDialog extends JDial
}
}
}
-
- rbPortrait.setEnabled(pSupported);
- rbLandscape.setEnabled(lSupported);
- rbRevPortrait.setEnabled(rpSupported);
- rbRevLandscape.setEnabled(rlSupported);
-
- OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory);
- if (or == null ||
- !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
-
- or = (OrientationRequested)psCurrent.getDefaultAttributeValue(orCategory);
- // need to validate if default is not supported
- if (!psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
- or = null;
- values =
- psCurrent.getSupportedAttributeValues(orCategory,
- docFlavor,
- asCurrent);
- if (values instanceof OrientationRequested[]) {
- OrientationRequested[] orValues =
- (OrientationRequested[])values;
- if (orValues.length > 1) {
- // get the first in the list
- or = orValues[0];
- }
+ }
+
+
+ rbPortrait.setEnabled(pSupported);
+ rbLandscape.setEnabled(lSupported);
+ rbRevPortrait.setEnabled(rpSupported);
+ rbRevLandscape.setEnabled(rlSupported);
+
+ OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory);
+ if (or == null ||
+ !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
+
+ or = (OrientationRequested)psCurrent.getDefaultAttributeValue(orCategory);
+ // need to validate if default is not supported
+ if ((or != null) &&
+ !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
+ or = null;
+ Object values =
+ psCurrent.getSupportedAttributeValues(orCategory,
+ docFlavor,
+ asCurrent);
+ if (values instanceof OrientationRequested[]) {
+ OrientationRequested[] orValues =
+ (OrientationRequested[])values;
+ if (orValues.length > 1) {
+ // get the first in the list
+ or = orValues[0];
}
}
-
- if (or == null) {
- or = OrientationRequested.PORTRAIT;
- }
- asCurrent.add(or);
- }
-
- if (or == OrientationRequested.PORTRAIT) {
- rbPortrait.setSelected(true);
- } else if (or == OrientationRequested.LANDSCAPE) {
- rbLandscape.setSelected(true);
- } else if (or == OrientationRequested.REVERSE_PORTRAIT) {
- rbRevPortrait.setSelected(true);
- } else { // if (or == OrientationRequested.REVERSE_LANDSCAPE)
- rbRevLandscape.setSelected(true);
- }
- } else {
- rbPortrait.setEnabled(pSupported);
- rbLandscape.setEnabled(lSupported);
- rbRevPortrait.setEnabled(rpSupported);
- rbRevLandscape.setEnabled(rlSupported);
-
+ }
+
+ if (or == null) {
+ or = OrientationRequested.PORTRAIT;
+ }
+ asCurrent.add(or);
+ }
+
+ if (or == OrientationRequested.PORTRAIT) {
+ rbPortrait.setSelected(true);
+ } else if (or == OrientationRequested.LANDSCAPE) {
+ rbLandscape.setSelected(true);
+ } else if (or == OrientationRequested.REVERSE_PORTRAIT) {
+ rbRevPortrait.setSelected(true);
+ } else { // if (or == OrientationRequested.REVERSE_LANDSCAPE)
+ rbRevLandscape.setSelected(true);
}
}
}
--- a/src/share/native/sun/awt/image/dither.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/awt/image/dither.c Tue Mar 24 19:12:02 2009 -0700
@@ -169,6 +169,7 @@ initCubemap(int* cmap,
int cubesize = cube_dim * cube_dim * cube_dim;
unsigned char *useFlags;
unsigned char *newILut = (unsigned char*)malloc(cubesize);
+ int cmap_mid = (cmap_len >> 1) + (cmap_len & 0x1);
if (newILut) {
useFlags = (unsigned char *)calloc(cubesize, 1);
@@ -188,7 +189,7 @@ initCubemap(int* cmap,
currentState.iLUT = newILut;
currentState.rgb = (unsigned short *)
- malloc(256 * sizeof(unsigned short));
+ malloc(cmap_len * sizeof(unsigned short));
if (currentState.rgb == NULL) {
free(newILut);
free(useFlags);
@@ -199,7 +200,7 @@ initCubemap(int* cmap,
}
currentState.indices = (unsigned char *)
- malloc(256 * sizeof(unsigned char));
+ malloc(cmap_len * sizeof(unsigned char));
if (currentState.indices == NULL) {
free(currentState.rgb);
free(newILut);
@@ -210,18 +211,18 @@ initCubemap(int* cmap,
return NULL;
}
- for (i = 0; i < 128; i++) {
+ for (i = 0; i < cmap_mid; i++) {
unsigned short rgb;
int pixel = cmap[i];
rgb = (pixel & 0x00f80000) >> 9;
rgb |= (pixel & 0x0000f800) >> 6;
rgb |= (pixel & 0xf8) >> 3;
INSERTNEW(currentState, rgb, i);
- pixel = cmap[255-i];
+ pixel = cmap[cmap_len - i - 1];
rgb = (pixel & 0x00f80000) >> 9;
rgb |= (pixel & 0x0000f800) >> 6;
rgb |= (pixel & 0xf8) >> 3;
- INSERTNEW(currentState, rgb, 255-i);
+ INSERTNEW(currentState, rgb, cmap_len - i - 1);
}
if (!recurseLevel(&currentState)) {
--- a/src/share/native/sun/awt/image/jpeg/imageioJPEG.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/awt/image/jpeg/imageioJPEG.c Tue Mar 24 19:12:02 2009 -0700
@@ -396,7 +396,7 @@ static imageIODataPtr initImageioData (J
data->jpegObj = cinfo;
cinfo->client_data = data;
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("new structures: data is %p, cinfo is %p\n", data, cinfo);
#endif
@@ -673,7 +673,7 @@ static int setQTables(JNIEnv *env,
j_decompress_ptr decomp;
qlen = (*env)->GetArrayLength(env, qtables);
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("in setQTables, qlen = %d, write is %d\n", qlen, write);
#endif
for (i = 0; i < qlen; i++) {
@@ -876,7 +876,7 @@ imageio_fill_input_buffer(j_decompress_p
return FALSE;
}
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("Filling input buffer, remaining skip is %ld, ",
sb->remaining_skip);
printf("Buffer length is %d\n", sb->bufferLength);
@@ -906,7 +906,7 @@ imageio_fill_input_buffer(j_decompress_p
cinfo->err->error_exit((j_common_ptr) cinfo);
}
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("Buffer filled. ret = %d\n", ret);
#endif
/*
@@ -917,7 +917,7 @@ imageio_fill_input_buffer(j_decompress_p
*/
if (ret <= 0) {
jobject reader = data->imageIOobj;
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("YO! Early EOI! ret = %d\n", ret);
#endif
RELEASE_ARRAYS(env, data, src->next_input_byte);
@@ -1216,21 +1216,24 @@ read_icc_profile (JNIEnv *env, j_decompr
{
jpeg_saved_marker_ptr marker;
int num_markers = 0;
+ int num_found_markers = 0;
int seq_no;
JOCTET *icc_data;
+ JOCTET *dst_ptr;
unsigned int total_length;
#define MAX_SEQ_NO 255 // sufficient since marker numbers are bytes
- char marker_present[MAX_SEQ_NO+1]; // 1 if marker found
- unsigned int data_length[MAX_SEQ_NO+1]; // size of profile data in marker
- unsigned int data_offset[MAX_SEQ_NO+1]; // offset for data in marker
+ jpeg_saved_marker_ptr icc_markers[MAX_SEQ_NO + 1];
+ int first; // index of the first marker in the icc_markers array
+ int last; // index of the last marker in the icc_markers array
jbyteArray data = NULL;
/* This first pass over the saved markers discovers whether there are
* any ICC markers and verifies the consistency of the marker numbering.
*/
- for (seq_no = 1; seq_no <= MAX_SEQ_NO; seq_no++)
- marker_present[seq_no] = 0;
+ for (seq_no = 0; seq_no <= MAX_SEQ_NO; seq_no++)
+ icc_markers[seq_no] = NULL;
+
for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
if (marker_is_icc(marker)) {
@@ -1242,37 +1245,58 @@ read_icc_profile (JNIEnv *env, j_decompr
return NULL;
}
seq_no = GETJOCTET(marker->data[12]);
- if (seq_no <= 0 || seq_no > num_markers) {
+
+ /* Some third-party tools produce images with profile chunk
+ * numeration started from zero. It is inconsistent with ICC
+ * spec, but seems to be recognized by majority of image
+ * processing tools, so we should be more tolerant to this
+ * departure from the spec.
+ */
+ if (seq_no < 0 || seq_no > num_markers) {
JNU_ThrowByName(env, "javax/imageio/IIOException",
"Invalid icc profile: bad sequence number");
return NULL;
}
- if (marker_present[seq_no]) {
+ if (icc_markers[seq_no] != NULL) {
JNU_ThrowByName(env, "javax/imageio/IIOException",
"Invalid icc profile: duplicate sequence numbers");
return NULL;
}
- marker_present[seq_no] = 1;
- data_length[seq_no] = marker->data_length - ICC_OVERHEAD_LEN;
+ icc_markers[seq_no] = marker;
+ num_found_markers ++;
}
}
if (num_markers == 0)
return NULL; // There is no profile
- /* Check for missing markers, count total space needed,
- * compute offset of each marker's part of the data.
+ if (num_markers != num_found_markers) {
+ JNU_ThrowByName(env, "javax/imageio/IIOException",
+ "Invalid icc profile: invalid number of icc markers");
+ return NULL;
+ }
+
+ first = icc_markers[0] ? 0 : 1;
+ last = num_found_markers + first;
+
+ /* Check for missing markers, count total space needed.
*/
-
total_length = 0;
- for (seq_no = 1; seq_no <= num_markers; seq_no++) {
- if (marker_present[seq_no] == 0) {
+ for (seq_no = first; seq_no < last; seq_no++) {
+ unsigned int length;
+ if (icc_markers[seq_no] == NULL) {
JNU_ThrowByName(env, "javax/imageio/IIOException",
"Invalid icc profile: missing sequence number");
return NULL;
}
- data_offset[seq_no] = total_length;
- total_length += data_length[seq_no];
+ /* check the data length correctness */
+ length = icc_markers[seq_no]->data_length;
+ if (ICC_OVERHEAD_LEN > length || length > MAX_BYTES_IN_MARKER) {
+ JNU_ThrowByName(env, "javax/imageio/IIOException",
+ "Invalid icc profile: invalid data length");
+ return NULL;
+ }
+ total_length += (length - ICC_OVERHEAD_LEN);
}
if (total_length <= 0) {
@@ -1301,19 +1325,14 @@ read_icc_profile (JNIEnv *env, j_decompr
}
/* and fill it in */
- for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
- if (marker_is_icc(marker)) {
- JOCTET FAR *src_ptr;
- JOCTET *dst_ptr;
- unsigned int length;
- seq_no = GETJOCTET(marker->data[12]);
- dst_ptr = icc_data + data_offset[seq_no];
- src_ptr = marker->data + ICC_OVERHEAD_LEN;
- length = data_length[seq_no];
- while (length--) {
- *dst_ptr++ = *src_ptr++;
- }
- }
+ dst_ptr = icc_data;
+ for (seq_no = first; seq_no < last; seq_no++) {
+ JOCTET FAR *src_ptr = icc_markers[seq_no]->data + ICC_OVERHEAD_LEN;
+ unsigned int length =
+ icc_markers[seq_no]->data_length - ICC_OVERHEAD_LEN;
+
+ memcpy(dst_ptr, src_ptr, length);
+ dst_ptr += length;
}
/* finally, unpin the array */
@@ -1530,6 +1549,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
j_decompress_ptr cinfo;
struct jpeg_source_mgr *src;
sun_jpeg_error_ptr jerr;
+ jbyteArray profileData = NULL;
if (data == NULL) {
JNU_ThrowByName(env,
@@ -1557,7 +1577,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
return retval;
}
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("In readImageHeader, data is %p cinfo is %p\n", data, cinfo);
printf("clearFirst is %d\n", clearFirst);
#endif
@@ -1584,7 +1604,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
if (ret == JPEG_HEADER_TABLES_ONLY) {
retval = JNI_TRUE;
imageio_term_source(cinfo); // Pushback remaining buffer contents
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("just read tables-only image; q table 0 at %p\n",
cinfo->quant_tbl_ptrs[0]);
#endif
@@ -1691,6 +1711,14 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
}
}
RELEASE_ARRAYS(env, data, src->next_input_byte);
+
+ /* read icc profile data */
+ profileData = read_icc_profile(env, cinfo);
+
+ if ((*env)->ExceptionCheck(env)) {
+ return retval;
+ }
+
(*env)->CallVoidMethod(env, this,
JPEGImageReader_setImageDataID,
cinfo->image_width,
@@ -1698,7 +1726,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
cinfo->jpeg_color_space,
cinfo->out_color_space,
cinfo->num_components,
- read_icc_profile(env, cinfo));
+ profileData);
if (reset) {
jpeg_abort_decompress(cinfo);
}
@@ -1827,7 +1855,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
(*env)->ReleaseIntArrayElements(env, srcBands, body, JNI_ABORT);
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("---- in reader.read ----\n");
printf("numBands is %d\n", numBands);
printf("bands array: ");
@@ -2487,7 +2515,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
data->streamBuf.suspendable = FALSE;
if (qtables != NULL) {
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("in writeTables: qtables not NULL\n");
#endif
setQTables(env, (j_common_ptr) cinfo, qtables, TRUE);
@@ -2763,7 +2791,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
cinfo->restart_interval = restartInterval;
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
printf("writer setup complete, starting compressor\n");
#endif
@@ -2812,13 +2840,13 @@ Java_com_sun_imageio_plugins_jpeg_JPEGIm
for (i = 0; i < numBands; i++) {
if (scale !=NULL && scale[i] != NULL) {
*out++ = scale[i][*(in+i)];
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
if (in == data->pixelBuf.buf.bp){ // Just the first pixel
printf("in %d -> out %d, ", *(in+i), *(out-i-1));
}
#endif
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
if (in == data->pixelBuf.buf.bp){ // Just the first pixel
printf("\n");
}
--- a/src/share/native/sun/font/freetypeScaler.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/font/freetypeScaler.c Tue Mar 24 19:12:02 2009 -0700
@@ -394,12 +394,14 @@ static int setupFTContext(JNIEnv *env,
scalerInfo->env = env;
scalerInfo->font2D = font2D;
- FT_Set_Transform(scalerInfo->face, &context->transform, NULL);
-
- errCode = FT_Set_Char_Size(scalerInfo->face, 0, context->ptsz, 72, 72);
-
- if (errCode == 0) {
- errCode = FT_Activate_Size(scalerInfo->face->size);
+ if (context != NULL) {
+ FT_Set_Transform(scalerInfo->face, &context->transform, NULL);
+
+ errCode = FT_Set_Char_Size(scalerInfo->face, 0, context->ptsz, 72, 72);
+
+ if (errCode == 0) {
+ errCode = FT_Activate_Size(scalerInfo->face->size);
+ }
}
return errCode;
@@ -885,6 +887,14 @@ Java_sun_font_FreetypeFontScaler_dispose
JNIEnv *env, jobject scaler, jlong pScaler) {
FTScalerInfo* scalerInfo = (FTScalerInfo *) jlong_to_ptr(pScaler);
+ /* Freetype functions *may* cause callback to java
+ that can use cached values. Make sure our cache is up to date.
+ NB: scaler context is not important at this point, can use NULL. */
+ int errCode = setupFTContext(env, scaler, scalerInfo, NULL);
+ if (errCode) {
+ return;
+ }
+
freeNativeResources(env, scalerInfo);
}
@@ -932,9 +942,18 @@ Java_sun_font_FreetypeFontScaler_getGlyp
JNIEnv *env, jobject scaler, jlong pScaler, jchar charCode) {
FTScalerInfo* scalerInfo = (FTScalerInfo *) jlong_to_ptr(pScaler);
+ int errCode;
if (scaler == NULL || scalerInfo->face == NULL) { /* bad/null scaler */
invalidateJavaScaler(env, scaler, scalerInfo);
+ return 0;
+ }
+
+ /* Freetype functions *may* cause callback to java
+ that can use cached values. Make sure our cache is up to date.
+ Scaler context is not important here, can use NULL. */
+ errCode = setupFTContext(env, scaler, scalerInfo, NULL);
+ if (errCode) {
return 0;
}
--- a/src/share/native/sun/java2d/cmm/lcms/LCMS.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/LCMS.c Tue Mar 24 19:12:02 2009 -0700
@@ -30,6 +30,41 @@
#include "Disposer.h"
#include "lcms.h"
+
+#define ALIGNLONG(x) (((x)+3) & ~(3)) // Aligns to DWORD boundary
+
+#ifdef USE_BIG_ENDIAN
+#define AdjustEndianess32(a)
+#else
+
+static
+void AdjustEndianess32(LPBYTE pByte)
+{
+ BYTE temp1;
+ BYTE temp2;
+
+ temp1 = *pByte++;
+ temp2 = *pByte++;
+ *(pByte-1) = *pByte;
+ *pByte++ = temp2;
+ *(pByte-3) = *pByte;
+ *pByte = temp1;
+}
+
+#endif
+
+// Transports to properly encoded values - note that icc profiles does use
+// big endian notation.
+
+static
+icInt32Number TransportValue32(icInt32Number Value)
+{
+ icInt32Number Temp = Value;
+
+ AdjustEndianess32((LPBYTE) &Temp);
+ return Temp;
+}
+
#define SigMake(a,b,c,d) \
( ( ((int) ((unsigned char) (a))) << 24) | \
( ((int) ((unsigned char) (b))) << 16) | \
@@ -182,6 +217,8 @@ JNIEXPORT jlong JNICALL Java_sun_java2d_
sProf.pf = cmsOpenProfileFromMem((LPVOID)dataArray, (DWORD) dataSize);
+ (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
+
if (sProf.pf == NULL) {
JNU_ThrowIllegalArgumentException(env, "Invalid profile data");
}
@@ -337,6 +374,10 @@ JNIEXPORT void JNICALL Java_sun_java2d_c
return;
}
+// Modify data for a tag in a profile
+LCMSBOOL LCMSEXPORT _cmsModifyTagData(cmsHPROFILE hProfile,
+ icTagSignature sig, void *data, size_t size);
+
/*
* Class: sun_java2d_cmm_lcms_LCMS
* Method: setTagData
@@ -345,7 +386,23 @@ JNIEXPORT void JNICALL Java_sun_java2d_c
JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagData
(JNIEnv *env, jobject obj, jlong id, jint tagSig, jbyteArray data)
{
- fprintf(stderr, "setTagData operation is not implemented");
+ cmsHPROFILE profile;
+ storeID_t sProf;
+ jbyte* dataArray;
+ int tagSize;
+
+ if (tagSig == SigHead) {
+ J2dRlsTraceLn(J2D_TRACE_ERROR, "LCMS_setTagData on icSigHead not "
+ "permitted");
+ return;
+ }
+
+ sProf.j = id;
+ profile = (cmsHPROFILE) sProf.pf;
+ dataArray = (*env)->GetByteArrayElements(env, data, 0);
+ tagSize =(*env)->GetArrayLength(env, data);
+ _cmsModifyTagData(profile, (icTagSignature) tagSig, dataArray, tagSize);
+ (*env)->ReleaseByteArrayElements(env, data, dataArray, 0);
}
void* getILData (JNIEnv *env, jobject img, jint* pDataType,
@@ -507,3 +564,174 @@ JNIEXPORT void JNICALL Java_sun_java2d_c
PF_ID_fID = (*env)->GetFieldID (env, Pf, "ID", "J");
}
+
+LCMSBOOL _cmsModifyTagData(cmsHPROFILE hProfile, icTagSignature sig,
+ void *data, size_t size)
+{
+ LCMSBOOL isNew;
+ int i, idx, delta, count;
+ LPBYTE padChars[3] = {0, 0, 0};
+ LPBYTE beforeBuf, afterBuf, ptr;
+ size_t beforeSize, afterSize;
+ icUInt32Number profileSize, temp;
+ LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+
+ isNew = FALSE;
+ idx = _cmsSearchTag(Icc, sig, FALSE);
+ if (idx < 0) {
+ isNew = TRUE;
+ idx = Icc->TagCount++;
+ if (Icc->TagCount >= MAX_TABLE_TAG) {
+ J2dRlsTraceLn1(J2D_TRACE_ERROR, "_cmsModifyTagData: Too many tags "
+ "(%d)\n", Icc->TagCount);
+ Icc->TagCount = MAX_TABLE_TAG-1;
+ return FALSE;
+ }
+ }
+
+ /* Read in size from header */
+ Icc->Seek(Icc, 0);
+ Icc->Read(&profileSize, sizeof(icUInt32Number), 1, Icc);
+ AdjustEndianess32((LPBYTE) &profileSize);
+
+ /* Compute the change in profile size */
+ if (isNew) {
+ delta = sizeof(icTag) + ALIGNLONG(size);
+ } else {
+ delta = ALIGNLONG(size) - ALIGNLONG(Icc->TagSizes[idx]);
+ }
+ /* Add tag to internal structures */
+ ptr = malloc(size);
+ if (ptr == NULL) {
+ if(isNew) {
+ Icc->TagCount--;
+ }
+ J2dRlsTraceLn(J2D_TRACE_ERROR, "_cmsModifyTagData: ptr == NULL");
+ return FALSE;
+ }
+
+ if (!Icc->Grow(Icc, delta)) {
+ free(ptr);
+ if(isNew) {
+ Icc->TagCount--;
+ }
+ J2dRlsTraceLn(J2D_TRACE_ERROR,
+ "_cmsModifyTagData: Icc->Grow() == FALSE");
+ return FALSE;
+ }
+
+ /* Compute size of tag data before/after the modified tag */
+ beforeSize = ((isNew)?profileSize:Icc->TagOffsets[idx]) -
+ Icc->TagOffsets[0];
+ if (Icc->TagCount == (idx + 1)) {
+ afterSize = 0;
+ } else {
+ afterSize = profileSize - Icc->TagOffsets[idx+1];
+ }
+ /* Make copies of the data before/after the modified tag */
+ if (beforeSize > 0) {
+ beforeBuf = malloc(beforeSize);
+ if (!beforeBuf) {
+ if(isNew) {
+ Icc->TagCount--;
+ }
+ free(ptr);
+ J2dRlsTraceLn(J2D_TRACE_ERROR,
+ "_cmsModifyTagData: beforeBuf == NULL");
+ return FALSE;
+ }
+ Icc->Seek(Icc, Icc->TagOffsets[0]);
+ Icc->Read(beforeBuf, beforeSize, 1, Icc);
+ }
+
+ if (afterSize > 0) {
+ afterBuf = malloc(afterSize);
+ if (!afterBuf) {
+ free(ptr);
+ if(isNew) {
+ Icc->TagCount--;
+ }
+ if (beforeSize > 0) {
+ free(beforeBuf);
+ }
+ J2dRlsTraceLn(J2D_TRACE_ERROR,
+ "_cmsModifyTagData: afterBuf == NULL");
+ return FALSE;
+ }
+ Icc->Seek(Icc, Icc->TagOffsets[idx+1]);
+ Icc->Read(afterBuf, afterSize, 1, Icc);
+ }
+
+ CopyMemory(ptr, data, size);
+ Icc->TagSizes[idx] = size;
+ Icc->TagNames[idx] = sig;
+ if (Icc->TagPtrs[idx]) {
+ free(Icc->TagPtrs[idx]);
+ }
+ Icc->TagPtrs[idx] = ptr;
+ if (isNew) {
+ Icc->TagOffsets[idx] = profileSize;
+ }
+
+
+ /* Update the profile size in the header */
+ profileSize += delta;
+ Icc->Seek(Icc, 0);
+ temp = TransportValue32(profileSize);
+ Icc->Write(Icc, sizeof(icUInt32Number), &temp);
+
+
+ /* Adjust tag offsets: if the tag is new, we must account
+ for the new tag table entry; otherwise, only those tags after
+ the modified tag are changed (by delta) */
+ if (isNew) {
+ for (i = 0; i < Icc->TagCount; ++i) {
+ Icc->TagOffsets[i] += sizeof(icTag);
+ }
+ } else {
+ for (i = idx+1; i < Icc->TagCount; ++i) {
+ Icc->TagOffsets[i] += delta;
+ }
+ }
+
+ /* Write out a new tag table */
+ count = 0;
+ for (i = 0; i < Icc->TagCount; ++i) {
+ if (Icc->TagNames[i] != 0) {
+ ++count;
+ }
+ }
+ Icc->Seek(Icc, sizeof(icHeader));
+ temp = TransportValue32(count);
+ Icc->Write(Icc, sizeof(icUInt32Number), &temp);
+
+ for (i = 0; i < Icc->TagCount; ++i) {
+ if (Icc->TagNames[i] != 0) {
+ icTag tag;
+ tag.sig = TransportValue32(Icc->TagNames[i]);
+ tag.offset = TransportValue32((icInt32Number) Icc->TagOffsets[i]);
+ tag.size = TransportValue32((icInt32Number) Icc->TagSizes[i]);
+ Icc->Write(Icc, sizeof(icTag), &tag);
+ }
+ }
+
+ /* Write unchanged data before the modified tag */
+ if (beforeSize > 0) {
+ Icc->Write(Icc, beforeSize, beforeBuf);
+ free(beforeBuf);
+ }
+
+ /* Write modified tag data */
+ Icc->Write(Icc, size, data);
+ if (size % 4) {
+ Icc->Write(Icc, 4 - (size % 4), padChars);
+ }
+
+ /* Write unchanged data after the modified tag */
+ if (afterSize > 0) {
+ Icc->Write(Icc, afterSize, afterBuf);
+ free(afterBuf);
+ }
+
+ return TRUE;
+}
--- a/src/share/native/sun/java2d/cmm/lcms/cmscam02.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscam02.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -51,7 +51,7 @@
-// CIECAM 02 appearance model
+// CIECAM 02 appearance model. Many thanks to Jordi Vilar for the debugging.
#include "lcms.h"
@@ -196,6 +196,10 @@ CAM02COLOR NonlinearCompression(CAM02COL
clr.RGBpa[i] = (400.0 * temp) / (temp + 27.13) + 0.1;
}
}
+
+ clr.A = (((2.0 * clr.RGBpa[0]) + clr.RGBpa[1] +
+ (clr.RGBpa[2] / 20.0)) - 0.305) * pMod->Nbb;
+
return clr;
}
@@ -248,9 +252,6 @@ CAM02COLOR ComputeCorrelates(CAM02COLOR
temp = ((clr.h - 237.53)/1.2) + ((360 - clr.h + 20.14)/0.8);
clr.H = 300 + ((100*((clr.h - 237.53)/1.2)) / temp);
}
-
- clr.A = (((2.0 * clr.RGBpa[0]) + clr.RGBpa[1] +
- (clr.RGBpa[2] / 20.0)) - 0.305) * pMod->Nbb;
clr.J = 100.0 * pow((clr.A / pMod->adoptedWhite.A),
(pMod->c * pMod->z));
@@ -395,7 +396,7 @@ LCMSHANDLE LCMSEXPORT cmsCIECAM02Init(LP
LPcmsCIECAM02 lpMod;
- if((lpMod = (LPcmsCIECAM02) malloc(sizeof(cmsCIECAM02))) == NULL) {
+ if((lpMod = (LPcmsCIECAM02) _cmsMalloc(sizeof(cmsCIECAM02))) == NULL) {
return (LCMSHANDLE) NULL;
}
@@ -449,14 +450,19 @@ LCMSHANDLE LCMSEXPORT cmsCIECAM02Init(LP
lpMod -> z = compute_z(lpMod);
lpMod -> Nbb = computeNbb(lpMod);
lpMod -> FL = computeFL(lpMod);
+
+ if (lpMod -> D == D_CALCULATE ||
+ lpMod -> D == D_CALCULATE_DISCOUNT) {
+
lpMod -> D = computeD(lpMod);
+ }
+
lpMod -> Ncb = lpMod -> Nbb;
lpMod -> adoptedWhite = XYZtoCAT02(lpMod -> adoptedWhite);
lpMod -> adoptedWhite = ChromaticAdaptation(lpMod -> adoptedWhite, lpMod);
lpMod -> adoptedWhite = CAT02toHPE(lpMod -> adoptedWhite);
lpMod -> adoptedWhite = NonlinearCompression(lpMod -> adoptedWhite, lpMod);
- lpMod -> adoptedWhite = ComputeCorrelates(lpMod -> adoptedWhite, lpMod);
return (LCMSHANDLE) lpMod;
@@ -465,7 +471,7 @@ void LCMSEXPORT cmsCIECAM02Done(LCMSHAND
void LCMSEXPORT cmsCIECAM02Done(LCMSHANDLE hModel)
{
LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
- if (lpMod) free(lpMod);
+ if (lpMod) _cmsFree(lpMod);
}
@@ -510,3 +516,4 @@ void LCMSEXPORT cmsCIECAM02Reverse(LCMSH
pOut ->Z = clr.XYZ[2];
}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmscam97.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscam97.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -174,7 +174,7 @@ LCMSAPI void LCMSEXPORT cmsCIECAM97sDone
LCMSAPI void LCMSEXPORT cmsCIECAM97sDone(LCMSHANDLE hModel)
{
LPcmsCIECAM97s lpMod = (LPcmsCIECAM97s) (LPSTR) hModel;
- if (lpMod) free(lpMod);
+ if (lpMod) _cmsFree(lpMod);
}
// Partial discounting for adaptation degree computation
@@ -331,7 +331,7 @@ LCMSAPI LCMSHANDLE LCMSEXPORT cmsCIECAM9
LPcmsCIECAM97s lpMod;
VEC3 tmp;
- if((lpMod = (LPcmsCIECAM97s) malloc(sizeof(cmsCIECAM97s))) == NULL) {
+ if((lpMod = (LPcmsCIECAM97s) _cmsMalloc(sizeof(cmsCIECAM97s))) == NULL) {
return (LCMSHANDLE) NULL;
}
@@ -449,7 +449,7 @@ LCMSAPI LCMSHANDLE LCMSEXPORT cmsCIECAM9
// RGB_subw = [MlamRigg][WP/YWp]
#ifdef USE_CIECAM97s2
- MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, (LPVEC3) &lpMod -> WP);
+ MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, &lpMod -> WP);
#else
VEC3divK(&tmp, (LPVEC3) &lpMod -> WP, lpMod->WP.Y);
MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, &tmp);
--- a/src/share/native/sun/java2d/cmm/lcms/cmscgats.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscgats.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -65,22 +65,25 @@ LCMSAPI int LCMSEXPORT cmsIT
// Persistence
LCMSAPI LCMSHANDLE LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName);
LCMSAPI LCMSHANDLE LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
// Properties
LCMSAPI const char* LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
-
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
-
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
+
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
+
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char* cSubProp, const char *Val);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
LCMSAPI const char* LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* cProp);
LCMSAPI double LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, char ***PropertyNames);
+LCMSAPI const char* LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char *cSubProp);
+LCMSAPI int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, const char ***PropertyNames);
+LCMSAPI int LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char*** SubpropertyNames);
// Datasets
@@ -89,10 +92,10 @@ LCMSAPI const char* LCMSEXPORT cmsIT
LCMSAPI const char* LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE IT8, int row, int col);
LCMSAPI double LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE IT8, int col, int row);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
const char* Val);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
double Val);
LCMSAPI const char* LCMSEXPORT cmsIT8GetData(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
@@ -100,15 +103,15 @@ LCMSAPI const char* LCMSEXPORT cmsIT
LCMSAPI double LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
const char* cSample,
const char *Val);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
const char* cSample,
double Val);
-LCMSAPI BOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
LCMSAPI int LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE IT8, char ***SampleNames);
LCMSAPI void LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE IT8, const char* Formatter);
@@ -126,7 +129,7 @@ LCMSAPI int LCMSEXPORT cmsIT
// #define STRICT_CGATS 1
#define MAXID 128 // Max lenght of identifier
-#define MAXSTR 255 // Max lenght of string
+#define MAXSTR 1024 // Max lenght of string
#define MAXTABLES 255 // Max Number of tables in a single stream
#define MAXINCLUDE 20 // Max number of nested includes
@@ -137,6 +140,9 @@ LCMSAPI int LCMSEXPORT cmsIT
#ifndef NON_WINDOWS
#include <io.h>
+#define DIR_CHAR '\\'
+#else
+#define DIR_CHAR '/'
#endif
// Symbols
@@ -160,6 +166,7 @@ typedef enum {
SEND_DATA,
SEND_DATA_FORMAT,
SKEYWORD,
+ SDATA_FORMAT_ID,
SINCLUDE
} SYMBOL;
@@ -171,7 +178,8 @@ typedef enum {
WRITE_UNCOOKED,
WRITE_STRINGIFY,
WRITE_HEXADECIMAL,
- WRITE_BINARY
+ WRITE_BINARY,
+ WRITE_PAIR
} WRITEMODE;
@@ -181,6 +189,8 @@ typedef struct _KeyVal {
struct _KeyVal* Next;
char* Keyword; // Name of variable
+ struct _KeyVal* NextSubkey; // If key is a dictionary, points to the next item
+ char* Subkey; // If key is a dictionary, points to the subkey name
char* Value; // Points to value
WRITEMODE WriteAs; // How to write the value
@@ -220,7 +230,12 @@ typedef struct _Table {
} TABLE, *LPTABLE;
-
+// File stream being parsed
+
+typedef struct _FileContext {
+ char FileName[MAX_PATH]; // File name if being readed from file
+ FILE* Stream; // File stream or NULL if holded in memory
+ } FILECTX, *LPFILECTX;
// This struct hold all information about an openened
// IT8 handler. Only one dataset is allowed.
@@ -257,9 +272,9 @@ typedef struct {
char* Source; // Points to loc. being parsed
int lineno; // line counter for error reporting
- char FileName[MAX_PATH]; // File name if being readed from file
- FILE* Stream[MAXINCLUDE]; // File stream or NULL if holded in memory
+ LPFILECTX FileStack[MAXINCLUDE]; // Stack of files being parsed
int IncludeSP; // Include Stack Pointer
+
char* MemoryBlock; // The stream if holded in memory
char DoubleFormatter[MAXID]; // Printf-like 'double' formatter
@@ -270,14 +285,14 @@ typedef struct {
typedef struct {
- FILE* stream; // For save-to-file behaviour
-
- LPBYTE Base;
- LPBYTE Ptr; // For save-to-mem behaviour
- size_t Used;
- size_t Max;
-
- } SAVESTREAM, FAR* LPSAVESTREAM;
+ FILE* stream; // For save-to-file behaviour
+
+ LPBYTE Base;
+ LPBYTE Ptr; // For save-to-mem behaviour
+ size_t Used;
+ size_t Max;
+
+ } SAVESTREAM, FAR* LPSAVESTREAM;
// ------------------------------------------------------ IT8 parsing routines
@@ -298,59 +313,104 @@ static const KEYWORD TabKeys[] = {
{".INCLUDE", SINCLUDE},
{"BEGIN_DATA", SBEGIN_DATA },
{"BEGIN_DATA_FORMAT", SBEGIN_DATA_FORMAT },
+ {"DATA_FORMAT_IDENTIFIER", SDATA_FORMAT_ID},
{"END_DATA", SEND_DATA},
{"END_DATA_FORMAT", SEND_DATA_FORMAT},
{"KEYWORD", SKEYWORD}
-
};
#define NUMKEYS (sizeof(TabKeys)/sizeof(KEYWORD))
// Predefined properties
-static const char* PredefinedProperties[] = {
-
- "NUMBER_OF_FIELDS", // Required - NUMBER OF FIELDS
- "NUMBER_OF_SETS", // Required - NUMBER OF SETS
- "ORIGINATOR", // Required - Identifies the specific system, organization or individual that created the data file.
- "FILE_DESCRIPTOR", // Required - Describes the purpose or contents of the data file.
- "CREATED", // Required - Indicates date of creation of the data file.
- "DESCRIPTOR", // Required - Describes the purpose or contents of the data file.
- "DIFFUSE_GEOMETRY", // The diffuse geometry used. Allowed values are "sphere" or "opal".
- "MANUFACTURER",
- "MANUFACTURE", // Some broken Fuji targets does store this value
- "PROD_DATE", // Identifies year and month of production of the target in the form yyyy:mm.
- "SERIAL", // Uniquely identifies individual physical target.
-
- "MATERIAL", // Identifies the material on which the target was produced using a code
+// A property
+typedef struct {
+ const char *id;
+ WRITEMODE as;
+ } PROPERTY;
+
+static PROPERTY PredefinedProperties[] = {
+
+ {"NUMBER_OF_FIELDS", WRITE_UNCOOKED}, // Required - NUMBER OF FIELDS
+ {"NUMBER_OF_SETS", WRITE_UNCOOKED}, // Required - NUMBER OF SETS
+ {"ORIGINATOR", WRITE_STRINGIFY}, // Required - Identifies the specific system, organization or individual that created the data file.
+ {"FILE_DESCRIPTOR", WRITE_STRINGIFY}, // Required - Describes the purpose or contents of the data file.
+ {"CREATED", WRITE_STRINGIFY}, // Required - Indicates date of creation of the data file.
+ {"DESCRIPTOR", WRITE_STRINGIFY}, // Required - Describes the purpose or contents of the data file.
+ {"DIFFUSE_GEOMETRY", WRITE_STRINGIFY}, // The diffuse geometry used. Allowed values are "sphere" or "opal".
+ {"MANUFACTURER", WRITE_STRINGIFY},
+ {"MANUFACTURE", WRITE_STRINGIFY}, // Some broken Fuji targets does store this value
+ {"PROD_DATE", WRITE_STRINGIFY}, // Identifies year and month of production of the target in the form yyyy:mm.
+ {"SERIAL", WRITE_STRINGIFY}, // Uniquely identifies individual physical target.
+
+ {"MATERIAL", WRITE_STRINGIFY}, // Identifies the material on which the target was produced using a code
// uniquely identifying th e material. This is intend ed to be used for IT8.7
// physical targets only (i.e . IT8.7/1 a nd IT8.7/2).
- "INSTRUMENTATION", // Used to report the specific instrumentation used (manufacturer and
+ {"INSTRUMENTATION", WRITE_STRINGIFY}, // Used to report the specific instrumentation used (manufacturer and
// model number) to generate the data reported. This data will often
// provide more information about the particular data collected than an
// extensive list of specific details. This is particularly important for
// spectral data or data derived from spectrophotometry.
- "MEASUREMENT_SOURCE", // Illumination used for spectral measurements. This data helps provide
+ {"MEASUREMENT_SOURCE", WRITE_STRINGIFY}, // Illumination used for spectral measurements. This data helps provide
// a guide to the potential for issues of paper fluorescence, etc.
- "PRINT_CONDITIONS", // Used to define the characteristics of the printed sheet being reported.
+ {"PRINT_CONDITIONS", WRITE_STRINGIFY}, // Used to define the characteristics of the printed sheet being reported.
// Where standard conditions have been defined (e.g., SWOP at nominal)
// named conditions may suffice. Otherwise, detailed information is
// needed.
- "SAMPLE_BACKING", // Identifies the backing material used behind the sample during
- // measurement. Allowed values are “black”, “white”, or "na".
-
- "CHISQ_DOF" // Degrees of freedom associated with the Chi squared statistic
+ {"SAMPLE_BACKING", WRITE_STRINGIFY}, // Identifies the backing material used behind the sample during
+ // measurement. Allowed values are “black”, “white”, or {"na".
+
+ {"CHISQ_DOF", WRITE_STRINGIFY}, // Degrees of freedom associated with the Chi squared statistic
+
+// new in recent specs:
+ {"MEASUREMENT_GEOMETRY", WRITE_STRINGIFY}, // The type of measurement, either reflection or transmission, should be indicated
+ // along with details of the geometry and the aperture size and shape. For example,
+ // for transmission measurements it is important to identify 0/diffuse, diffuse/0,
+ // opal or integrating sphere, etc. For reflection it is important to identify 0/45,
+ // 45/0, sphere (specular included or excluded), etc.
+
+ {"FILTER", WRITE_STRINGIFY}, // Identifies the use of physical filter(s) during measurement. Typically used to
+ // denote the use of filters such as none, D65, Red, Green or Blue.
+
+ {"POLARIZATION", WRITE_STRINGIFY}, // Identifies the use of a physical polarization filter during measurement. Allowed
+ // values are {"yes”, “white”, “none” or “na”.
+
+ {"WEIGHTING_FUNCTION", WRITE_PAIR}, // Indicates such functions as: the CIE standard observer functions used in the
+ // calculation of various data parameters (2 degree and 10 degree), CIE standard
+ // illuminant functions used in the calculation of various data parameters (e.g., D50,
+ // D65, etc.), density status response, etc. If used there shall be at least one
+ // name-value pair following the WEIGHTING_FUNCTION tag/keyword. The first attribute
+ // in the set shall be {"name" and shall identify the particular parameter used.
+ // The second shall be {"value" and shall provide the value associated with that name.
+ // For ASCII data, a string containing the Name and Value attribute pairs shall follow
+ // the weighting function keyword. A semi-colon separates attribute pairs from each
+ // other and within the attribute the name and value are separated by a comma.
+
+ {"COMPUTATIONAL_PARAMETER", WRITE_PAIR}, // Parameter that is used in computing a value from measured data. Name is the name
+ // of the calculation, parameter is the name of the parameter used in the calculation
+ // and value is the value of the parameter.
+
+ {"TARGET_TYPE", WRITE_STRINGIFY}, // The type of target being measured, e.g. IT8.7/1, IT8.7/3, user defined, etc.
+
+ {"COLORANT", WRITE_STRINGIFY}, // Identifies the colorant(s) used in creating the target.
+
+ {"TABLE_DESCRIPTOR", WRITE_STRINGIFY}, // Describes the purpose or contents of a data table.
+
+ {"TABLE_NAME", WRITE_STRINGIFY} // Provides a short name for a data table.
};
-#define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(char *))
+#define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(PROPERTY))
// Predefined sample types on dataset
static const char* PredefinedSampleID[] = {
+ "SAMPLE_ID", // Identifies sample that data represents
+ "STRING", // Identifies label, or other non-machine readable value.
+ // Value must begin and end with a " symbol
"CMYK_C", // Cyan component of CMYK data expressed as a percentage
"CMYK_M", // Magenta component of CMYK data expressed as a percentage
@@ -378,7 +438,7 @@ static const char* PredefinedSampleID[]
"LAB_B", // b* component of Lab data
"LAB_C", // C*ab component of Lab data
"LAB_H", // hab component of Lab data
- "LAB_DE" // CIE dE
+ "LAB_DE", // CIE dE
"LAB_DE_94", // CIE dE using CIE 94
"LAB_DE_CMC", // dE using CMC
"LAB_DE_2000", // CIE dE using CIE DE 2000
@@ -388,7 +448,7 @@ static const char* PredefinedSampleID[]
"STDEV_Y", // Standard deviation of Y (tristimulus data)
"STDEV_Z", // Standard deviation of Z (tristimulus data)
"STDEV_L", // Standard deviation of L*
- "STDEV_A" // Standard deviation of a*
+ "STDEV_A", // Standard deviation of a*
"STDEV_B", // Standard deviation of b*
"STDEV_DE", // Standard deviation of CIE dE
"CHI_SQD_PAR"}; // The average of the standard deviations of L*, a* and b*. It is
@@ -397,57 +457,120 @@ static const char* PredefinedSampleID[]
#define NUMPREDEFINEDSAMPLEID (sizeof(PredefinedSampleID)/sizeof(char *))
+//Forward declaration of some internal functions
+static
+void* AllocChunk(LPIT8 it8, size_t size);
+
// Checks if c is a separator
static
-BOOL isseparator(int c)
+LCMSBOOL isseparator(int c)
{
return (c == ' ') || (c == '\t') || (c == '\r');
}
// Checks whatever if c is a valid identifier char
-
-static
-BOOL ismiddle(int c)
+static
+LCMSBOOL ismiddle(int c)
{
return (!isseparator(c) && (c != '#') && (c !='\"') && (c != '\'') && (c > 32) && (c < 127));
}
// Checks whatsever if c is a valid identifier middle char.
static
-BOOL isidchar(int c)
+LCMSBOOL isidchar(int c)
{
return isalnum(c) || ismiddle(c);
}
// Checks whatsever if c is a valid identifier first char.
static
-BOOL isfirstidchar(int c)
+LCMSBOOL isfirstidchar(int c)
{
return !isdigit(c) && ismiddle(c);
}
-
-static
-BOOL SynError(LPIT8 it8, const char *Txt, ...)
+// checks whether the supplied path looks like an absolute path
+// NOTE: this function doesn't checks if the path exists or even if it's legal
+static
+LCMSBOOL isabsolutepath(const char *path)
+{
+ if(path == NULL)
+ return FALSE;
+
+ if(path[0] == DIR_CHAR)
+ return TRUE;
+
+#ifndef NON_WINDOWS
+ if(isalpha(path[0]) && path[1] == ':')
+ return TRUE;
+#endif
+ return FALSE;
+}
+
+// Makes a file path based on a given reference path
+// NOTE: buffer is assumed to point to at least MAX_PATH bytes
+// NOTE: both relPath and basePath are assumed to be no more than MAX_PATH characters long (including the null terminator!)
+// NOTE: this function doesn't check if the path exists or even if it's legal
+static
+LCMSBOOL _cmsMakePath(const char *relPath, const char *basePath, char *buffer)
+{
+ if (!isabsolutepath(relPath)) {
+
+ char *tail;
+
+ strncpy(buffer, basePath, MAX_PATH-1);
+ tail = strrchr(buffer, DIR_CHAR);
+ if (tail != NULL) {
+
+ size_t len = tail - buffer;
+ strncpy(tail + 1, relPath, MAX_PATH - len -1);
+ // TODO: if combined path is longer than MAX_PATH, this should return FALSE!
+ return TRUE;
+ }
+ }
+ strncpy(buffer, relPath, MAX_PATH - 1);
+ buffer[MAX_PATH-1] = 0;
+ return TRUE;
+}
+
+
+// Make sure no exploit is being even tried
+
+static
+const char* NoMeta(const char* str)
+{
+ if (strchr(str, '%') != NULL)
+ return "**** CORRUPTED FORMAT STRING ***";
+
+ return str;
+}
+
+
+// Syntax error
+static
+LCMSBOOL SynError(LPIT8 it8, const char *Txt, ...)
{
char Buffer[256], ErrMsg[1024];
va_list args;
va_start(args, Txt);
- vsprintf(Buffer, Txt, args);
+ vsnprintf(Buffer, 255, Txt, args);
+ Buffer[255] = 0;
va_end(args);
- sprintf(ErrMsg, "%s: Line %d, %s", it8->FileName, it8->lineno, Buffer);
+ snprintf(ErrMsg, 1023, "%s: Line %d, %s", it8->FileStack[it8 ->IncludeSP]->FileName, it8->lineno, Buffer);
+ ErrMsg[1023] = 0;
it8->sy = SSYNERROR;
- cmsSignalError(LCMS_ERRC_ABORTED, ErrMsg);
+ cmsSignalError(LCMS_ERRC_ABORTED, "%s", ErrMsg);
return FALSE;
}
-static
-BOOL Check(LPIT8 it8, SYMBOL sy, const char* Err)
+// Check if current symbol is same as specified. issue an error else.
+static
+LCMSBOOL Check(LPIT8 it8, SYMBOL sy, const char* Err)
{
if (it8 -> sy != sy)
- return SynError(it8, Err);
+ return SynError(it8, NoMeta(Err));
return TRUE;
}
@@ -457,15 +580,15 @@ static
static
void NextCh(LPIT8 it8)
{
- if (it8 -> Stream[it8 ->IncludeSP]) {
-
- it8 ->ch = fgetc(it8 ->Stream[it8 ->IncludeSP]);
-
- if (feof(it8 -> Stream[it8 ->IncludeSP])) {
+ if (it8 -> FileStack[it8 ->IncludeSP]->Stream) {
+
+ it8 ->ch = fgetc(it8 ->FileStack[it8 ->IncludeSP]->Stream);
+
+ if (feof(it8 -> FileStack[it8 ->IncludeSP]->Stream)) {
if (it8 ->IncludeSP > 0) {
- fclose(it8 ->Stream[it8->IncludeSP--]);
+ fclose(it8 ->FileStack[it8->IncludeSP--]->Stream);
it8 -> ch = ' '; // Whitespace to be ignored
} else
@@ -476,7 +599,6 @@ void NextCh(LPIT8 it8)
}
else {
-
it8->ch = *it8->Source;
if (it8->ch) it8->Source++;
}
@@ -799,18 +921,39 @@ void InSymbol(LPIT8 it8)
if (it8 -> sy == SINCLUDE) {
- FILE* IncludeFile;
+ LPFILECTX FileNest;
+
+ if(it8 -> IncludeSP >= (MAXINCLUDE-1))
+ {
+ SynError(it8, "Too many recursion levels");
+ return;
+ }
InSymbol(it8);
if (!Check(it8, SSTRING, "Filename expected")) return;
- IncludeFile = fopen(it8 -> str, "rt");
- if (IncludeFile == NULL) {
-
- SynError(it8, "File %s not found", it8 ->str);
+
+ FileNest = it8 -> FileStack[it8 -> IncludeSP + 1];
+ if(FileNest == NULL)
+ {
+ FileNest = it8 ->FileStack[it8 -> IncludeSP + 1] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+ //if(FileNest == NULL)
+ // TODO: how to manage out-of-memory conditions?
+ }
+
+ if(_cmsMakePath(it8->str, it8->FileStack[it8->IncludeSP]->FileName, FileNest->FileName) == FALSE)
+ {
+ SynError(it8, "File path too long");
+ return;
+ }
+
+ FileNest->Stream = fopen(FileNest->FileName, "rt");
+ if (FileNest->Stream == NULL) {
+
+ SynError(it8, "File %s not found", FileNest->FileName);
return;
}
-
- it8 -> Stream[++it8 -> IncludeSP] = IncludeFile;
+ it8->IncludeSP++;
+
it8 ->ch = ' ';
InSymbol(it8);
}
@@ -819,7 +962,7 @@ void InSymbol(LPIT8 it8)
// Checks end of line separator
static
-BOOL CheckEOLN(LPIT8 it8)
+LCMSBOOL CheckEOLN(LPIT8 it8)
{
if (!Check(it8, SEOLN, "Expected separator")) return FALSE;
while (it8 -> sy == SEOLN)
@@ -850,21 +993,26 @@ void SkipEOLN(LPIT8 it8)
// Returns a string holding current value
static
-BOOL GetVal(LPIT8 it8, char* Buffer, const char* ErrorTitle)
+LCMSBOOL GetVal(LPIT8 it8, char* Buffer, size_t max, const char* ErrorTitle)
{
switch (it8->sy) {
- case SIDENT: strncpy(Buffer, it8->id, MAXID-1); break;
- case SINUM: sprintf(Buffer, "%d", it8 -> inum); break;
- case SDNUM: sprintf(Buffer, it8->DoubleFormatter, it8 -> dnum); break;
- case SSTRING: strncpy(Buffer, it8->str, MAXSTR-1); break;
+ case SIDENT: strncpy(Buffer, it8->id, max);
+ Buffer[max-1]=0;
+ break;
+ case SINUM: snprintf(Buffer, max, "%d", it8 -> inum); break;
+ case SDNUM: snprintf(Buffer, max, it8->DoubleFormatter, it8 -> dnum); break;
+ case SSTRING: strncpy(Buffer, it8->str, max);
+ Buffer[max-1] = 0;
+ break;
default:
- return SynError(it8, ErrorTitle);
- }
-
- return TRUE;
+ return SynError(it8, "%s", ErrorTitle);
+ }
+
+ Buffer[max] = 0;
+ return TRUE;
}
// ---------------------------------------------------------- Table
@@ -872,7 +1020,13 @@ static
static
LPTABLE GetTable(LPIT8 it8)
{
- return it8 ->Tab + it8 ->nTable;
+ if ((it8 -> nTable >= it8 ->TablesCount) || (it8 -> nTable < 0)) {
+
+ SynError(it8, "Table %d out of sequence", it8 -> nTable);
+ return it8 -> Tab;
+ }
+
+ return it8 ->Tab + it8 ->nTable;
}
// ---------------------------------------------------------- Memory management
@@ -896,15 +1050,15 @@ void LCMSEXPORT cmsIT8Free(LCMSHANDLE hI
for (p = it8->MemorySink; p != NULL; p = n) {
n = p->Next;
- if (p->Ptr) free(p->Ptr);
- free(p);
+ if (p->Ptr) _cmsFree(p->Ptr);
+ _cmsFree(p);
}
}
if (it8->MemoryBlock)
- free(it8->MemoryBlock);
-
- free(it8);
+ _cmsFree(it8->MemoryBlock);
+
+ _cmsFree(it8);
}
@@ -913,16 +1067,16 @@ void* AllocBigBlock(LPIT8 it8, size_t si
void* AllocBigBlock(LPIT8 it8, size_t size)
{
LPOWNEDMEM ptr1;
- void* ptr = malloc(size);
+ void* ptr = _cmsMalloc(size);
if (ptr) {
ZeroMemory(ptr, size);
- ptr1 = (LPOWNEDMEM) malloc(sizeof(OWNEDMEM));
+ ptr1 = (LPOWNEDMEM) _cmsMalloc(sizeof(OWNEDMEM));
if (ptr1 == NULL) {
- free(ptr);
+ _cmsFree(ptr);
return NULL;
}
@@ -986,8 +1140,9 @@ char *AllocString(LPIT8 it8, const char*
// Searches through linked list
static
-BOOL IsAvailableOnList(LPKEYVALUE p, const char* Key, LPKEYVALUE* LastPtr)
-{
+LCMSBOOL IsAvailableOnList(LPKEYVALUE p, const char* Key, const char* Subkey, LPKEYVALUE* LastPtr)
+{
+ if (LastPtr) *LastPtr = p;
for (; p != NULL; p = p->Next) {
@@ -996,8 +1151,22 @@ BOOL IsAvailableOnList(LPKEYVALUE p, con
if (*Key != '#') { // Comments are ignored
if (stricmp(Key, p->Keyword) == 0)
- return TRUE;
- }
+ break;
+ }
+ }
+
+ if (p == NULL)
+ return FALSE;
+
+ if (Subkey == 0)
+ return TRUE;
+
+ for (; p != NULL; p = p->NextSubkey) {
+
+ if (LastPtr) *LastPtr = p;
+
+ if (stricmp(Subkey, p->Subkey) == 0)
+ return TRUE;
}
return FALSE;
@@ -1007,35 +1176,55 @@ BOOL IsAvailableOnList(LPKEYVALUE p, con
// Add a property into a linked list
static
-BOOL AddToList(LPIT8 it8, LPKEYVALUE* Head, const char *Key, const char* xValue, WRITEMODE WriteAs)
+LPKEYVALUE AddToList(LPIT8 it8, LPKEYVALUE* Head, const char *Key, const char *Subkey, const char* xValue, WRITEMODE WriteAs)
{
LPKEYVALUE p;
- LPKEYVALUE last;
-
// Check if property is already in list (this is an error)
- if (IsAvailableOnList(*Head, Key, &last)) {
-
- // This may work for editing properties
-
- last->Value = AllocString(it8, xValue);
- last->WriteAs = WriteAs;
- return TRUE;
-
- // return SynError(it8, "duplicate key <%s>", Key);
- }
-
- // Allocate the container
+ if (IsAvailableOnList(*Head, Key, Subkey, &p)) {
+
+ // This may work for editing properties
+
+ // return SynError(it8, "duplicate key <%s>", Key);
+ }
+ else {
+ LPKEYVALUE last = p;
+
+ // Allocate the container
p = (LPKEYVALUE) AllocChunk(it8, sizeof(KEYVALUE));
if (p == NULL)
{
- return SynError(it8, "AddToList: out of memory");
+ SynError(it8, "AddToList: out of memory");
+ return NULL;
}
// Store name and value
p->Keyword = AllocString(it8, Key);
-
+ p->Subkey = (Subkey == NULL) ? NULL : AllocString(it8, Subkey);
+
+ // Keep the container in our list
+ if (*Head == NULL)
+ *Head = p;
+ else
+ {
+ if(Subkey != 0 && last != 0) {
+ last->NextSubkey = p;
+
+ // If Subkey is not null, then last is the last property with the same key,
+ // but not necessarily is the last property in the list, so we need to move
+ // to the actual list end
+ while(last->Next != 0)
+ last = last->Next;
+ }
+ last->Next = p;
+ }
+
+ p->Next = NULL;
+ p->NextSubkey = NULL;
+ }
+
+ p->WriteAs = WriteAs;
if (xValue != NULL) {
p->Value = AllocString(it8, xValue);
@@ -1044,29 +1233,20 @@ BOOL AddToList(LPIT8 it8, LPKEYVALUE* He
p->Value = NULL;
}
- p->Next = NULL;
- p->WriteAs = WriteAs;
-
- // Keep the container in our list
- if (*Head == NULL)
- *Head = p;
- else
- last->Next = p;
-
- return TRUE;
-}
-
-static
-BOOL AddAvailableProperty(LPIT8 it8, const char* Key)
-{
- return AddToList(it8, &it8->ValidKeywords, Key, NULL, WRITE_UNCOOKED);
-}
-
-
-static
-BOOL AddAvailableSampleID(LPIT8 it8, const char* Key)
-{
- return AddToList(it8, &it8->ValidSampleID, Key, NULL, WRITE_UNCOOKED);
+ return p;
+}
+
+static
+LPKEYVALUE AddAvailableProperty(LPIT8 it8, const char* Key, WRITEMODE as)
+{
+ return AddToList(it8, &it8->ValidKeywords, Key, NULL, NULL, as);
+}
+
+
+static
+LPKEYVALUE AddAvailableSampleID(LPIT8 it8, const char* Key)
+{
+ return AddToList(it8, &it8->ValidSampleID, Key, NULL, NULL, WRITE_UNCOOKED);
}
@@ -1122,8 +1302,6 @@ LCMSHANDLE LCMSEXPORT cmsIT8Alloc(void)
AllocTable(it8);
it8->MemoryBlock = NULL;
- it8->Stream[0] = NULL;
- it8->IncludeSP = 0;
it8->MemorySink = NULL;
it8 ->nTable = 0;
@@ -1141,6 +1319,8 @@ LCMSHANDLE LCMSEXPORT cmsIT8Alloc(void)
it8 -> inum = 0;
it8 -> dnum = 0.0;
+ it8->FileStack[0] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+ it8->IncludeSP = 0;
it8 -> lineno = 1;
strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
@@ -1149,7 +1329,7 @@ LCMSHANDLE LCMSEXPORT cmsIT8Alloc(void)
// Initialize predefined properties & data
for (i=0; i < NUMPREDEFINEDPROPS; i++)
- AddAvailableProperty(it8, PredefinedProperties[i]);
+ AddAvailableProperty(it8, PredefinedProperties[i].id, PredefinedProperties[i].as);
for (i=0; i < NUMPREDEFINEDSAMPLEID; i++)
AddAvailableSampleID(it8, PredefinedSampleID[i]);
@@ -1167,65 +1347,72 @@ const char* LCMSEXPORT cmsIT8GetSheetTyp
}
-BOOL LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type)
+LCMSBOOL LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type)
{
LPIT8 it8 = (LPIT8) hIT8;
strncpy(it8 ->SheetType, Type, MAXSTR-1);
+ it8 ->SheetType[MAXSTR-1] = 0;
return TRUE;
}
-BOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* Val)
{
LPIT8 it8 = (LPIT8) hIT8;
if (!Val) return FALSE;
if (!*Val) return FALSE;
- return AddToList(it8, &GetTable(it8)->HeaderList, "# ", Val, WRITE_UNCOOKED);
+ return AddToList(it8, &GetTable(it8)->HeaderList, "# ", NULL, Val, WRITE_UNCOOKED) != NULL;
}
// Sets a property
-BOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* Key, const char *Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* Key, const char *Val)
{
LPIT8 it8 = (LPIT8) hIT8;
if (!Val) return FALSE;
if (!*Val) return FALSE;
- return AddToList(it8, &GetTable(it8)->HeaderList, Key, Val, WRITE_STRINGIFY);
-}
-
-
-BOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val)
+ return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Val, WRITE_STRINGIFY) != NULL;
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val)
{
LPIT8 it8 = (LPIT8) hIT8;
char Buffer[1024];
sprintf(Buffer, it8->DoubleFormatter, Val);
- return AddToList(it8, &GetTable(it8)->HeaderList, cProp, Buffer, WRITE_UNCOOKED);
-}
-
-BOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val)
+ return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
+}
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val)
{
LPIT8 it8 = (LPIT8) hIT8;
char Buffer[1024];
sprintf(Buffer, "%d", Val);
- return AddToList(it8, &GetTable(it8)->HeaderList, cProp, Buffer, WRITE_HEXADECIMAL);
-}
-
-BOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer)
+ return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
+}
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer)
{
LPIT8 it8 = (LPIT8) hIT8;
- return AddToList(it8, &GetTable(it8)->HeaderList, Key, Buffer, WRITE_UNCOOKED);
-}
-
+ return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Buffer, WRITE_UNCOOKED) != NULL;
+}
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* Key, const char* SubKey, const char *Buffer)
+{
+ LPIT8 it8 = (LPIT8) hIT8;
+
+ return AddToList(it8, &GetTable(it8)->HeaderList, Key, SubKey, Buffer, WRITE_PAIR) != NULL;
+}
// Gets a property
const char* LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* Key)
@@ -1233,7 +1420,7 @@ const char* LCMSEXPORT cmsIT8GetProperty
LPIT8 it8 = (LPIT8) hIT8;
LPKEYVALUE p;
- if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, &p))
+ if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, NULL, &p))
{
return p -> Value;
}
@@ -1247,6 +1434,18 @@ double LCMSEXPORT cmsIT8GetPropertyDbl(L
if (v) return atof(v);
else return 0.0;
+}
+
+const char* LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* Key, const char *SubKey)
+{
+ LPIT8 it8 = (LPIT8) hIT8;
+ LPKEYVALUE p;
+
+ if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p))
+ {
+ return p -> Value;
+ }
+ return NULL;
}
// ----------------------------------------------------------------- Datasets
@@ -1287,9 +1486,16 @@ const char *GetDataFormat(LPIT8 it8, int
}
static
-BOOL SetDataFormat(LPIT8 it8, int n, const char *label)
+LCMSBOOL SetDataFormat(LPIT8 it8, int n, const char *label)
{
LPTABLE t = GetTable(it8);
+
+#ifdef STRICT_CGATS
+ if (!IsAvailableOnList(it8-> ValidSampleID, label, NULL, NULL)) {
+ SynError(it8, "Invalid data format '%s'.", label);
+ return FALSE;
+ }
+#endif
if (!t->DataFormat)
AllocateDataFormat(it8);
@@ -1308,7 +1514,7 @@ BOOL SetDataFormat(LPIT8 it8, int n, con
}
-BOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE h, int n, const char *Sample)
+LCMSBOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE h, int n, const char *Sample)
{
LPIT8 it8 = (LPIT8) h;
return SetDataFormat(it8, n, Sample);
@@ -1348,7 +1554,7 @@ char* GetData(LPIT8 it8, int nSet, int n
}
static
-BOOL SetData(LPIT8 it8, int nSet, int nField, const char *Val)
+LCMSBOOL SetData(LPIT8 it8, int nSet, int nField, const char *Val)
{
LPTABLE t = GetTable(it8);
@@ -1383,42 +1589,43 @@ void WriteStr(LPSAVESTREAM f, const char
void WriteStr(LPSAVESTREAM f, const char *str)
{
- size_t len;
-
- if (str == NULL)
- str = " ";
-
- // Lenghth to write
- len = strlen(str);
+ size_t len;
+
+ if (str == NULL)
+ str = " ";
+
+ // Lenghth to write
+ len = strlen(str);
f ->Used += len;
- if (f ->stream) { // Should I write it to a file?
-
- fwrite(str, 1, len, f->stream);
-
- }
- else { // Or to a memory block?
-
-
- if (f ->Base) { // Am I just counting the bytes?
-
- if (f ->Used > f ->Max) {
-
- cmsSignalError(LCMS_ERRC_ABORTED, "Write to memory overflows in CGATS parser");
- return;
- }
-
- CopyMemory(f ->Ptr, str, len);
- f->Ptr += len;
-
- }
-
- }
-}
-
-
-//
+ if (f ->stream) { // Should I write it to a file?
+
+ fwrite(str, 1, len, f->stream);
+
+ }
+ else { // Or to a memory block?
+
+
+ if (f ->Base) { // Am I just counting the bytes?
+
+ if (f ->Used > f ->Max) {
+
+ cmsSignalError(LCMS_ERRC_ABORTED, "Write to memory overflows in CGATS parser");
+ return;
+ }
+
+ CopyMemory(f ->Ptr, str, len);
+ f->Ptr += len;
+
+ }
+
+ }
+}
+
+
+// Write formatted
+
static
void Writef(LPSAVESTREAM f, const char* frm, ...)
{
@@ -1426,7 +1633,8 @@ void Writef(LPSAVESTREAM f, const char*
va_list args;
va_start(args, frm);
- vsprintf(Buffer, frm, args);
+ vsnprintf(Buffer, 4095, frm, args);
+ Buffer[4095] = 0;
WriteStr(f, Buffer);
va_end(args);
@@ -1450,7 +1658,7 @@ void WriteHeader(LPIT8 it8, LPSAVESTREAM
for (Pt = p ->Value; *Pt; Pt++) {
- Writef(fp, "%c", *Pt);
+ Writef(fp, "%c", *Pt);
if (*Pt == '\n') {
WriteStr(fp, "# ");
@@ -1462,7 +1670,7 @@ void WriteHeader(LPIT8 it8, LPSAVESTREAM
}
- if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL)) {
+ if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL, NULL)) {
#ifdef STRICT_CGATS
WriteStr(fp, "KEYWORD\t\"");
@@ -1470,7 +1678,7 @@ void WriteHeader(LPIT8 it8, LPSAVESTREAM
WriteStr(fp, "\"\n");
#endif
- AddAvailableProperty(it8, p->Keyword);
+ AddAvailableProperty(it8, p->Keyword, WRITE_UNCOOKED);
}
@@ -1493,6 +1701,10 @@ void WriteHeader(LPIT8 it8, LPSAVESTREAM
case WRITE_BINARY:
Writef(fp, "\t0x%B", atoi(p ->Value));
+ break;
+
+ case WRITE_PAIR:
+ Writef(fp, "\t\"%s,%s\"", p->Subkey, p->Value);
break;
default: SynError(it8, "Unknown write mode %d", p ->WriteAs);
@@ -1573,13 +1785,13 @@ void WriteData(LPSAVESTREAM fp, LPIT8 it
// Saves whole file
-BOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE hIT8, const char* cFileName)
+LCMSBOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE hIT8, const char* cFileName)
{
SAVESTREAM sd;
int i;
LPIT8 it8 = (LPIT8) hIT8;
- ZeroMemory(&sd, sizeof(SAVESTREAM));
+ ZeroMemory(&sd, sizeof(SAVESTREAM));
sd.stream = fopen(cFileName, "wt");
if (!sd.stream) return FALSE;
@@ -1594,31 +1806,31 @@ BOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHAN
WriteData(&sd, it8);
}
- fclose(sd.stream);
+ fclose(sd.stream);
return TRUE;
}
// Saves to memory
-BOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded)
+LCMSBOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded)
{
SAVESTREAM sd;
int i;
LPIT8 it8 = (LPIT8) hIT8;
- ZeroMemory(&sd, sizeof(SAVESTREAM));
+ ZeroMemory(&sd, sizeof(SAVESTREAM));
sd.stream = NULL;
- sd.Base = (LPBYTE) MemPtr;
- sd.Ptr = sd.Base;
-
- sd.Used = 0;
-
- if (sd.Base)
- sd.Max = *BytesNeeded; // Write to memory?
- else
- sd.Max = 0; // Just counting the needed bytes
+ sd.Base = (LPBYTE) MemPtr;
+ sd.Ptr = sd.Base;
+
+ sd.Used = 0;
+
+ if (sd.Base)
+ sd.Max = *BytesNeeded; // Write to memory?
+ else
+ sd.Max = 0; // Just counting the needed bytes
WriteStr(&sd, it8->SheetType);
WriteStr(&sd, "\n");
@@ -1630,12 +1842,12 @@ BOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHAND
WriteData(&sd, it8);
}
- sd.Used++; // The \0 at the very end
-
- if (sd.Base)
- sd.Ptr = 0;
-
- *BytesNeeded = sd.Used;
+ sd.Used++; // The \0 at the very end
+
+ if (sd.Base)
+ sd.Ptr = 0;
+
+ *BytesNeeded = sd.Used;
return TRUE;
}
@@ -1644,7 +1856,7 @@ BOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHAND
// -------------------------------------------------------------- Higer level parsing
static
-BOOL DataFormatSection(LPIT8 it8)
+LCMSBOOL DataFormatSection(LPIT8 it8)
{
int iField = 0;
LPTABLE t = GetTable(it8);
@@ -1685,15 +1897,18 @@ BOOL DataFormatSection(LPIT8 it8)
static
-BOOL DataSection (LPIT8 it8)
+LCMSBOOL DataSection (LPIT8 it8)
{
int iField = 0;
int iSet = 0;
- char Buffer[256];
+ char Buffer[MAXSTR];
LPTABLE t = GetTable(it8);
InSymbol(it8); // Eats "BEGIN_DATA"
CheckEOLN(it8);
+
+ if (!t->Data)
+ AllocateDataSet(it8);
while (it8->sy != SEND_DATA && it8->sy != SEOF)
{
@@ -1705,7 +1920,7 @@ BOOL DataSection (LPIT8 it8)
if (it8->sy != SEND_DATA && it8->sy != SEOF) {
- if (!GetVal(it8, Buffer, "Sample data expected"))
+ if (!GetVal(it8, Buffer, 255, "Sample data expected"))
return FALSE;
if (!SetData(it8, iSet, iField, Buffer))
@@ -1734,10 +1949,11 @@ BOOL DataSection (LPIT8 it8)
static
-BOOL HeaderSection(LPIT8 it8)
+LCMSBOOL HeaderSection(LPIT8 it8)
{
char VarName[MAXID];
char Buffer[MAXSTR];
+ LPKEYVALUE Key;
while (it8->sy != SEOF &&
it8->sy != SSYNERROR &&
@@ -1749,30 +1965,79 @@ BOOL HeaderSection(LPIT8 it8)
case SKEYWORD:
InSymbol(it8);
- if (!GetVal(it8, Buffer, "Keyword expected")) return FALSE;
- if (!AddAvailableProperty(it8, Buffer)) return FALSE;
+ if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
+ if (!AddAvailableProperty(it8, Buffer, WRITE_UNCOOKED)) return FALSE;
InSymbol(it8);
break;
+ case SDATA_FORMAT_ID:
+ InSymbol(it8);
+ if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
+ if (!AddAvailableSampleID(it8, Buffer)) return FALSE;
+ InSymbol(it8);
+ break;
+
+
case SIDENT:
strncpy(VarName, it8->id, MAXID-1);
-
- if (!IsAvailableOnList(it8-> ValidKeywords, VarName, NULL)) {
+ VarName[MAXID-1] = 0;
+
+ if (!IsAvailableOnList(it8-> ValidKeywords, VarName, NULL, &Key)) {
#ifdef STRICT_CGATS
return SynError(it8, "Undefined keyword '%s'", VarName);
#else
- if (!AddAvailableProperty(it8, VarName)) return FALSE;
+ Key = AddAvailableProperty(it8, VarName, WRITE_UNCOOKED);
+ if (Key == NULL) return FALSE;
#endif
}
InSymbol(it8);
- if (!GetVal(it8, Buffer, "Property data expected")) return FALSE;
-
-
- AddToList(it8, &GetTable(it8)->HeaderList, VarName, Buffer,
- (it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED);
+ if (!GetVal(it8, Buffer, MAXSTR-1, "Property data expected")) return FALSE;
+
+ if(Key->WriteAs != WRITE_PAIR) {
+ AddToList(it8, &GetTable(it8)->HeaderList, VarName, NULL, Buffer,
+ (it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED);
+ }
+ else {
+ const char *Subkey;
+ char *Nextkey;
+ if (it8->sy != SSTRING)
+ return SynError(it8, "Invalid value '%s' for property '%s'.", Buffer, VarName);
+
+ // chop the string as a list of "subkey, value" pairs, using ';' as a separator
+ for(Subkey = Buffer; Subkey != NULL; Subkey = Nextkey)
+ {
+ char *Value, *temp;
+
+ // identify token pair boundary
+ Nextkey = (char*) strchr(Subkey, ';');
+ if(Nextkey)
+ *Nextkey++ = '\0';
+
+ // for each pair, split the subkey and the value
+ Value = (char*) strrchr(Subkey, ',');
+ if(Value == NULL)
+ return SynError(it8, "Invalid value for property '%s'.", VarName);
+
+ // gobble the spaces before the coma, and the coma itself
+ temp = Value++;
+ do *temp-- = '\0'; while(temp >= Subkey && *temp == ' ');
+
+ // gobble any space at the right
+ temp = Value + strlen(Value) - 1;
+ while(*temp == ' ') *temp-- = '\0';
+
+ // trim the strings from the left
+ Subkey += strspn(Subkey, " ");
+ Value += strspn(Value, " ");
+
+ if(Subkey[0] == 0 || Value[0] == 0)
+ return SynError(it8, "Invalid value for property '%s'.", VarName);
+ AddToList(it8, &GetTable(it8)->HeaderList, VarName, Subkey, Value, WRITE_PAIR);
+ }
+ }
InSymbol(it8);
break;
@@ -1793,21 +2058,22 @@ BOOL HeaderSection(LPIT8 it8)
static
-BOOL ParseIT8(LPIT8 it8)
-{
- char* SheetTypePtr;
+LCMSBOOL ParseIT8(LPIT8 it8, LCMSBOOL nosheet)
+{
+ char* SheetTypePtr = it8 ->SheetType;
+
+ if (nosheet == 0) {
// First line is a very special case.
while (isseparator(it8->ch))
NextCh(it8);
- SheetTypePtr = it8 ->SheetType;
-
while (it8->ch != '\r' && it8 ->ch != '\n' && it8->ch != '\t' && it8 -> ch != -1) {
*SheetTypePtr++= (char) it8 ->ch;
NextCh(it8);
+ }
}
*SheetTypePtr = 0;
@@ -1869,6 +2135,12 @@ void CookPointers(LPIT8 it8)
for (idField = 0; idField < t -> nSamples; idField++)
{
+ if (t ->DataFormat == NULL) {
+ SynError(it8, "Undefined DATA_FORMAT");
+ return;
+
+ }
+
Fld = t->DataFormat[idField];
if (!Fld) continue;
@@ -1884,6 +2156,7 @@ void CookPointers(LPIT8 it8)
char Buffer[256];
strncpy(Buffer, Data, 255);
+ Buffer[255] = 0;
if (strlen(Buffer) <= strlen(Data))
strcpy(Data, Buffer);
@@ -1916,7 +2189,7 @@ void CookPointers(LPIT8 it8)
LPTABLE Table = it8 ->Tab + k;
LPKEYVALUE p;
- if (IsAvailableOnList(Table->HeaderList, Label, &p)) {
+ if (IsAvailableOnList(Table->HeaderList, Label, NULL, &p)) {
// Available, keep type and table
char Buffer[256];
@@ -1924,7 +2197,7 @@ void CookPointers(LPIT8 it8)
char *Type = p ->Value;
int nTable = k;
- sprintf(Buffer, "%s %d %s", Label, nTable, Type );
+ snprintf(Buffer, 255, "%s %d %s", Label, nTable, Type );
SetData(it8, i, idField, Buffer);
}
@@ -1948,8 +2221,9 @@ void CookPointers(LPIT8 it8)
// that should be something like some printable characters plus a \n
static
-BOOL IsMyBlock(LPBYTE Buffer, size_t n)
-{
+int IsMyBlock(LPBYTE Buffer, size_t n)
+{
+ int cols = 1, space = 0, quot = 0;
size_t i;
if (n < 10) return FALSE; // Too small
@@ -1959,9 +2233,26 @@ BOOL IsMyBlock(LPBYTE Buffer, size_t n)
for (i = 1; i < n; i++) {
- if (Buffer[i] == '\n' || Buffer[i] == '\r' || Buffer[i] == '\t') return TRUE;
- if (Buffer[i] < 32) return FALSE;
-
+ switch(Buffer[i])
+ {
+ case '\n':
+ case '\r':
+ return quot == 1 || cols > 2 ? 0 : cols;
+ case '\t':
+ case ' ':
+ if(!quot && !space)
+ space = 1;
+ break;
+ case '\"':
+ quot = !quot;
+ break;
+ default:
+ if (Buffer[i] < 32) return 0;
+ if (Buffer[i] > 127) return 0;
+ cols += space;
+ space = 0;
+ break;
+ }
}
return FALSE;
@@ -1970,7 +2261,7 @@ BOOL IsMyBlock(LPBYTE Buffer, size_t n)
static
-BOOL IsMyFile(const char* FileName)
+int IsMyFile(const char* FileName)
{
FILE *fp;
size_t Size;
@@ -1998,21 +2289,22 @@ LCMSHANDLE LCMSEXPORT cmsIT8LoadFromMem(
LCMSHANDLE hIT8;
LPIT8 it8;
- if (!IsMyBlock((LPBYTE) Ptr, len)) return NULL;
+ int type = IsMyBlock((LPBYTE) Ptr, len);
+ if (type == 0) return NULL;
hIT8 = cmsIT8Alloc();
if (!hIT8) return NULL;
it8 = (LPIT8) hIT8;
- it8 ->MemoryBlock = (char*) malloc(len + 1);
+ it8 ->MemoryBlock = (char*) _cmsMalloc(len + 1);
strncpy(it8 ->MemoryBlock, (const char*) Ptr, len);
it8 ->MemoryBlock[len] = 0;
- strncpy(it8->FileName, "", MAX_PATH-1);
+ strncpy(it8->FileStack[0]->FileName, "", MAX_PATH-1);
it8-> Source = it8 -> MemoryBlock;
- if (!ParseIT8(it8)) {
+ if (!ParseIT8(it8, type-1)) {
cmsIT8Free(hIT8);
return FALSE;
@@ -2021,7 +2313,7 @@ LCMSHANDLE LCMSEXPORT cmsIT8LoadFromMem(
CookPointers(it8);
it8 ->nTable = 0;
- free(it8->MemoryBlock);
+ _cmsFree(it8->MemoryBlock);
it8 -> MemoryBlock = NULL;
return hIT8;
@@ -2036,26 +2328,28 @@ LCMSHANDLE LCMSEXPORT cmsIT8LoadFromFile
LCMSHANDLE hIT8;
LPIT8 it8;
- if (!IsMyFile(cFileName)) return NULL;
+ int type = IsMyFile(cFileName);
+ if (type == 0) return NULL;
hIT8 = cmsIT8Alloc();
it8 = (LPIT8) hIT8;
if (!hIT8) return NULL;
- it8 ->Stream[0] = fopen(cFileName, "rt");
-
- if (!it8 ->Stream[0]) {
+ it8 ->FileStack[0]->Stream = fopen(cFileName, "rt");
+
+ if (!it8 ->FileStack[0]->Stream) {
cmsIT8Free(hIT8);
return NULL;
}
- strncpy(it8->FileName, cFileName, MAX_PATH-1);
-
- if (!ParseIT8(it8)) {
-
- fclose(it8 ->Stream[0]);
+ strncpy(it8->FileStack[0]->FileName, cFileName, MAX_PATH-1);
+ it8->FileStack[0]->FileName[MAX_PATH-1] = 0;
+
+ if (!ParseIT8(it8, type-1)) {
+
+ fclose(it8 ->FileStack[0]->Stream);
cmsIT8Free(hIT8);
return NULL;
}
@@ -2063,7 +2357,7 @@ LCMSHANDLE LCMSEXPORT cmsIT8LoadFromFile
CookPointers(it8);
it8 ->nTable = 0;
- fclose(it8 ->Stream[0]);
+ fclose(it8 ->FileStack[0]->Stream);
return hIT8;
}
@@ -2078,12 +2372,12 @@ int LCMSEXPORT cmsIT8EnumDataFormat(LCMS
}
-int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, char ***PropertyNames)
+int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, const char ***PropertyNames)
{
LPIT8 it8 = (LPIT8) hIT8;
LPKEYVALUE p;
int n;
- char **Props;
+ const char **Props;
LPTABLE t = GetTable(it8);
// Pass#1 - count properties
@@ -2094,7 +2388,7 @@ int LCMSEXPORT cmsIT8EnumProperties(LCMS
}
- Props = (char **) AllocChunk(it8, sizeof(char *) * n);
+ Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
// Pass#2 - Fill pointers
n = 0;
@@ -2106,6 +2400,41 @@ int LCMSEXPORT cmsIT8EnumProperties(LCMS
return n;
}
+int LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char ***SubpropertyNames)
+{
+ LPIT8 it8 = (LPIT8) hIT8;
+ LPKEYVALUE p, tmp;
+ int n;
+ const char **Props;
+ LPTABLE t = GetTable(it8);
+
+ if(!IsAvailableOnList(t->HeaderList, cProp, NULL, &p)) {
+ *SubpropertyNames = 0;
+ return 0;
+ }
+
+ // Pass#1 - count properties
+
+ n = 0;
+ for (tmp = p; tmp != NULL; tmp = tmp->NextSubkey) {
+ if(tmp->Subkey != NULL)
+ n++;
+ }
+
+
+ Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
+
+ // Pass#2 - Fill pointers
+ n = 0;
+ for (tmp = p; tmp != NULL; tmp = tmp->NextSubkey) {
+ if(tmp->Subkey != NULL)
+ Props[n++] = p ->Subkey;
+ }
+
+ *SubpropertyNames = Props;
+ return n;
+}
+
static
int LocatePatch(LPIT8 it8, const char* cPatch)
{
@@ -2201,7 +2530,7 @@ double LCMSEXPORT cmsIT8GetDataRowColDbl
}
-BOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col, const char* Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col, const char* Val)
{
LPIT8 it8 = (LPIT8) hIT8;
@@ -2209,7 +2538,7 @@ BOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMS
}
-BOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col, double Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col, double Val)
{
LPIT8 it8 = (LPIT8) hIT8;
char Buff[256];
@@ -2260,7 +2589,7 @@ double LCMSEXPORT cmsIT8GetDataDbl(LCMSH
-BOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE hIT8, const char* cPatch,
+LCMSBOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE hIT8, const char* cPatch,
const char* cSample,
const char *Val)
{
@@ -2305,18 +2634,19 @@ BOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE
}
-BOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
+LCMSBOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
const char* cSample,
double Val)
{
LPIT8 it8 = (LPIT8) hIT8;
char Buff[256];
- sprintf(Buff, it8->DoubleFormatter, Val);
+ snprintf(Buff, 255, it8->DoubleFormatter, Val);
return cmsIT8SetData(hIT8, cPatch, cSample, Buff);
}
+// Buffer should get MAXSTR at least
const char* LCMSEXPORT cmsIT8GetPatchName(LCMSHANDLE hIT8, int nPatch, char* buffer)
{
@@ -2327,8 +2657,14 @@ const char* LCMSEXPORT cmsIT8GetPatchNam
if (!Data) return NULL;
if (!buffer) return Data;
- strcpy(buffer, Data);
+ strncpy(buffer, Data, MAXSTR-1);
+ buffer[MAXSTR-1] = 0;
return buffer;
+}
+
+int LCMSEXPORT cmsIT8GetPatchByName(LCMSHANDLE hIT8, const char *cPatch)
+{
+ return LocatePatch((LPIT8)hIT8, cPatch);
}
int LCMSEXPORT cmsIT8TableCount(LCMSHANDLE hIT8)
@@ -2356,7 +2692,7 @@ int LCMSEXPORT cmsIT8SetTableByLabel(LCM
cLabelFld = cmsIT8GetData(hIT8, cSet, cField);
if (!cLabelFld) return -1;
- if (sscanf(cLabelFld, "%s %d %s", Label, &nTable, Type) != 3)
+ if (sscanf(cLabelFld, "%255s %d %255s", Label, &nTable, Type) != 3)
return -1;
if (ExpectedType != NULL && *ExpectedType == 0)
@@ -2368,6 +2704,19 @@ int LCMSEXPORT cmsIT8SetTableByLabel(LCM
}
return cmsIT8SetTable(hIT8, nTable);
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetIndexColumn(LCMSHANDLE hIT8, const char* cSample)
+{
+ LPIT8 it8 = (LPIT8) hIT8;
+
+ int pos = LocateSample(it8, cSample);
+ if(pos == -1)
+ return FALSE;
+
+ it8->Tab[it8->nTable].SampleID = pos;
+ return TRUE;
}
@@ -2380,3 +2729,4 @@ void LCMSEXPORT cmsIT8DefineDblFormat(LC
else
strcpy(it8->DoubleFormatter, Formatter);
}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -256,7 +256,7 @@ void ComputeBlackPointCompensationFactor
// Return TRUE if both m and of are empy -- "m" being identity and "of" being 0
static
-BOOL IdentityParameters(LPWMAT3 m, LPWVEC3 of)
+LCMSBOOL IdentityParameters(LPWMAT3 m, LPWVEC3 of)
{
WVEC3 wv0;
@@ -661,3 +661,6 @@ int cmsChooseCnvrt(int Absolute,
return rc;
}
+
+
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmserr.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmserr.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -57,6 +57,7 @@
// errors.
void cdecl cmsSignalError(int ErrorCode, const char *ErrorText, ...);
+
int LCMSEXPORT cmsErrorAction(int lAbort);
void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn);
@@ -96,7 +97,7 @@ void cmsSignalError(int ErrorCode, const
char Buffer[1024];
- vsprintf(Buffer, ErrorText, args);
+ vsnprintf(Buffer, 1023, ErrorText, args);
va_end(args);
if (UserErrorHandler(ErrorCode, Buffer)) {
@@ -118,8 +119,8 @@ void cmsSignalError(int ErrorCode, const
char Buffer1[1024];
char Buffer2[256];
- sprintf(Buffer1, "Error #%x; ", ErrorCode);
- vsprintf(Buffer2, ErrorText, args);
+ snprintf(Buffer1, 767, "Error #%x; ", ErrorCode);
+ vsnprintf(Buffer2, 255, ErrorText, args);
strcat(Buffer1, Buffer2);
MessageBox(NULL, Buffer1, "Little cms",
MB_OK|MB_ICONSTOP|MB_TASKMODAL);
--- a/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -63,9 +63,9 @@ LPGAMMATABLE LCMSEXPORT cmsBuildParametr
LPGAMMATABLE LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[]);
LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma);
LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma, int nPoints);
-BOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
-
-BOOL cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
+LCMSBOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
+
+LCMSBOOL cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
// Sampled curves
@@ -74,7 +74,7 @@ void cdecl cmsFreeSampledCurve
void cdecl cmsFreeSampledCurve(LPSAMPLEDCURVE p);
void cdecl cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max);
void cdecl cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max);
-BOOL cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
+LCMSBOOL cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
void cdecl cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints);
LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
@@ -84,7 +84,6 @@ double LCMSEXPORT cmsEstimateGammaEx(LPW
// ----------------------------------------------------------------------------------------
-// #define DEBUG 1
#define MAX_KNOTS 4096
typedef float vec[MAX_KNOTS+1];
@@ -144,14 +143,14 @@ LPGAMMATABLE LCMSEXPORT cmsAllocGamma(in
LPGAMMATABLE p;
size_t size;
- if (nEntries > 65530) {
- cmsSignalError(LCMS_ERRC_WARNING, "Couldn't create gammatable of more than 65530 entries; 65530 assumed");
- nEntries = 65530;
+ if (nEntries > 65530 || nEntries <= 0) {
+ cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't create gammatable of more than 65530 entries");
+ return NULL;
}
size = sizeof(GAMMATABLE) + (sizeof(WORD) * (nEntries-1));
- p = (LPGAMMATABLE) malloc(size);
+ p = (LPGAMMATABLE) _cmsMalloc(size);
if (!p) return NULL;
ZeroMemory(p, size);
@@ -164,7 +163,7 @@ LPGAMMATABLE LCMSEXPORT cmsAllocGamma(in
void LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma)
{
- if (Gamma) free(Gamma);
+ if (Gamma) _cmsFree(Gamma);
}
@@ -278,6 +277,15 @@ LPGAMMATABLE LCMSEXPORT cmsReverseGamma(
LPWORD InPtr;
LPGAMMATABLE p;
+ // Try to reverse it analytically whatever possible
+ if (InGamma -> Seed.Type > 0 && InGamma -> Seed.Type <= 5 &&
+ _cmsCrc32OfGammaTable(InGamma) == InGamma -> Seed.Crc32) {
+
+ return cmsBuildParametricGamma(nResultSamples, -(InGamma -> Seed.Type), InGamma ->Seed.Params);
+ }
+
+
+ // Nope, reverse the table
p = cmsAllocGamma(nResultSamples);
if (!p) return NULL;
@@ -528,7 +536,7 @@ void smooth2(vec w, vec y, vec z, float
// Smooths a curve sampled at regular intervals
-BOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
+LCMSBOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
{
vec w, y, z;
@@ -640,13 +648,13 @@ LPSAMPLEDCURVE cmsAllocSampledCurve(int
{
LPSAMPLEDCURVE pOut;
- pOut = (LPSAMPLEDCURVE) malloc(sizeof(SAMPLEDCURVE));
+ pOut = (LPSAMPLEDCURVE) _cmsMalloc(sizeof(SAMPLEDCURVE));
if (pOut == NULL)
return NULL;
- if((pOut->Values = (double *) malloc(nItems * sizeof(double))) == NULL)
+ if((pOut->Values = (double *) _cmsMalloc(nItems * sizeof(double))) == NULL)
{
- free(pOut);
+ _cmsFree(pOut);
return NULL;
}
@@ -659,8 +667,8 @@ LPSAMPLEDCURVE cmsAllocSampledCurve(int
void cmsFreeSampledCurve(LPSAMPLEDCURVE p)
{
- free((LPVOID) p -> Values);
- free((LPVOID) p);
+ _cmsFree((LPVOID) p -> Values);
+ _cmsFree((LPVOID) p);
}
@@ -731,7 +739,7 @@ void cmsClampSampledCurve(LPSAMPLEDCURVE
// Smooths a curve sampled at regular intervals
-BOOL cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double lambda)
+LCMSBOOL cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double lambda)
{
vec w, y, z;
int i, nItems;
@@ -915,14 +923,11 @@ LPSAMPLEDCURVE cmsConvertGammaToSampledC
// Smooth endpoints (used in Black/White compensation)
-BOOL _cmsSmoothEndpoints(LPWORD Table, int nEntries)
+LCMSBOOL _cmsSmoothEndpoints(LPWORD Table, int nEntries)
{
vec w, y, z;
int i, Zeros, Poles;
-#ifdef DEBUG
- ASAVE(Table, nEntries, "nonsmt.txt");
-#endif
if (cmsIsLinear(Table, nEntries)) return FALSE; // Nothing to do
--- a/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -66,7 +66,7 @@ to use highlights, then it will be lost.
*/
-BOOL _cmsEndPointsBySpace(icColorSpaceSignature Space, WORD **White, WORD **Black,
+LCMSBOOL _cmsEndPointsBySpace(icColorSpaceSignature Space, WORD **White, WORD **Black,
int *nOutputs)
{
// Only most common spaces
@@ -376,7 +376,6 @@ double LCMSEXPORT cmsCIE2000DeltaE(LPcms
double bs = Lab2 ->b;
double Cs = sqrt( Sqr(as) + Sqr(bs) );
-
double G = 0.5 * ( 1 - sqrt(pow((C + Cs) / 2 , 7.0) / (pow((C + Cs) / 2, 7.0) + pow(25.0, 7.0) ) ));
double a_p = (1 + G ) * a1;
@@ -390,15 +389,21 @@ double LCMSEXPORT cmsCIE2000DeltaE(LPcms
double C_ps = sqrt(Sqr(a_ps) + Sqr(b_ps));
double h_ps = atan2deg(a_ps, b_ps);
-
-
double meanC_p =(C_p + C_ps) / 2;
- double meanh_p = fabs(h_ps-h_p) <= 180 ? (h_ps + h_p)/2 : (h_ps+h_p-360)/2;
-
- double delta_h = fabs(h_p - h_ps) <= 180 ? fabs(h_p - h_ps) : 360 - fabs(h_p - h_ps);
- double delta_L = fabs(L1 - Ls);
- double delta_C = fabs(C_p - C_ps);
+ double hps_plus_hp = h_ps + h_p;
+ double hps_minus_hp = h_ps - h_p;
+
+ double meanh_p = fabs(hps_minus_hp) <= 180.000001 ? (hps_plus_hp)/2 :
+ (hps_plus_hp) < 360 ? (hps_plus_hp + 360)/2 :
+ (hps_plus_hp - 360)/2;
+
+ double delta_h = (hps_minus_hp) <= -180.000001 ? (hps_minus_hp + 360) :
+ (hps_minus_hp) > 180 ? (hps_minus_hp - 360) :
+ (hps_minus_hp);
+ double delta_L = (Ls - L1);
+ double delta_C = (C_ps - C_p );
+
double delta_H =2 * sqrt(C_ps*C_p) * sin(RADIANES(delta_h) / 2);
@@ -1065,7 +1070,7 @@ void SlopeLimiting(WORD Table[], int nEn
// Check for monotonicity.
static
-BOOL IsMonotonic(LPGAMMATABLE t)
+LCMSBOOL IsMonotonic(LPGAMMATABLE t)
{
int n = t -> nEntries;
int i, last;
@@ -1088,7 +1093,7 @@ BOOL IsMonotonic(LPGAMMATABLE t)
// Check for endpoints
static
-BOOL HasProperEndpoints(LPGAMMATABLE t)
+LCMSBOOL HasProperEndpoints(LPGAMMATABLE t)
{
if (t ->GammaTable[0] != 0) return FALSE;
if (t ->GammaTable[t ->nEntries-1] != 0xFFFF) return FALSE;
@@ -1109,7 +1114,7 @@ void _cmsComputePrelinearizationTablesFr
unsigned int t, i, v;
int j;
WORD In[MAXCHANNELS], Out[MAXCHANNELS];
- BOOL lIsSuitable;
+ LCMSBOOL lIsSuitable;
_LPcmsTRANSFORM InputXForm = (_LPcmsTRANSFORM) h[0];
_LPcmsTRANSFORM OutputXForm = (_LPcmsTRANSFORM) h[nTransforms-1];
@@ -1126,10 +1131,10 @@ void _cmsComputePrelinearizationTablesFr
}
- // Do nothing on all but RGB to RGB transforms
-
- if ((InputXForm ->EntryColorSpace != icSigRgbData) ||
- (OutputXForm->ExitColorSpace != icSigRgbData)) return;
+ // Do nothing on all but Gray/RGB to Gray/RGB transforms
+
+ if (((InputXForm ->EntryColorSpace != icSigRgbData) && (InputXForm ->EntryColorSpace != icSigGrayData)) ||
+ ((OutputXForm->ExitColorSpace != icSigRgbData) && (OutputXForm->ExitColorSpace != icSigGrayData))) return;
for (t = 0; t < Grid -> InputChan; t++)
@@ -1169,10 +1174,13 @@ void _cmsComputePrelinearizationTablesFr
if (!HasProperEndpoints(Trans[t]))
lIsSuitable = FALSE;
+ /*
// Exclude if transfer function is not smooth enough
// to be modelled as a gamma function, or the gamma is reversed
+
if (cmsEstimateGamma(Trans[t]) < 1.0)
lIsSuitable = FALSE;
+ */
}
--- a/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -282,7 +282,7 @@ void Eval8Inputs(WORD StageABC[], WORD S
// Fills optimization parameters
void cmsCalcCLUT16ParamsEx(int nSamples, int InputChan, int OutputChan,
- BOOL lUseTetrahedral, LPL16PARAMS p)
+ LCMSBOOL lUseTetrahedral, LPL16PARAMS p)
{
int clutPoints;
@@ -579,7 +579,7 @@ WORD cmsReverseLinearInterpLUT16(WORD Va
// Identify if value fall downto 0 or FFFF zone
if (Value == 0) return 0;
- if (Value == 0xFFFF) return 0xFFFF;
+ // if (Value == 0xFFFF) return 0xFFFF;
// else restrict to valid zone
@@ -631,7 +631,7 @@ WORD cmsReverseLinearInterpLUT16(WORD Va
a = (y1 - y0) / (x1 - x0);
b = y0 - a * x0;
- if (a == 0) return (WORD) x;
+ if (fabs(a) < 0.01) return (WORD) x;
f = ((Value - b) / a);
@@ -763,7 +763,7 @@ void cmsTrilinearInterp16(WORD Input[],
X0 = p -> opta3 * x0;
X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta3);
- Y0 = p -> opta2 * y0;
+ Y0 = p -> opta2 * y0;
Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta2);
Z0 = p -> opta1 * z0;
@@ -942,7 +942,7 @@ void cmsTetrahedralInterp16(WORD Input[]
X0 = p -> opta3 * x0;
X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta3);
- Y0 = p -> opta2 * y0;
+ Y0 = p -> opta2 * y0;
Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta2);
Z0 = p -> opta1 * z0;
@@ -1009,11 +1009,11 @@ void cmsTetrahedralInterp16(WORD Input[]
Rest = c1 * rx + c2 * ry + c3 * rz;
- // There is a lot of math hidden in this expression. The rest is in fixed domain
- // and the result in 0..ffff domain. So the complete expression should be
- // ROUND_FIXED_TO_INT(ToFixedDomain(Rest)) But that can be optimized as (Rest + 0x7FFF) / 0xFFFF
-
- Output[OutChan] = (WORD) (c0 + ((Rest + 0x7FFF) / 0xFFFF));
+ // There is a lot of math hidden in this expression. The rest is in fixed domain
+ // and the result in 0..ffff domain. So the complete expression should be
+ // ROUND_FIXED_TO_INT(ToFixedDomain(Rest)) But that can be optimized as (Rest + 0x7FFF) / 0xFFFF
+
+ Output[OutChan] = (WORD) (c0 + ((Rest + 0x7FFF) / 0xFFFF));
}
@@ -1131,3 +1131,4 @@ void cmsTetrahedralInterp8(WORD Input[],
}
#undef DENS
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmsio0.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsio0.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -62,7 +62,7 @@ typedef struct {
typedef struct {
LPBYTE Block; // Points to allocated memory
size_t Size; // Size of allocated memory
- int Pointer; // Points to current location
+ size_t Pointer; // Points to current location
int FreeBlockOnClose; // As title
} FILEMEM;
@@ -70,17 +70,18 @@ static
static
LPVOID MemoryOpen(LPBYTE Block, size_t Size, char Mode)
{
- FILEMEM* fm = (FILEMEM*) malloc(sizeof(FILEMEM));
+ FILEMEM* fm = (FILEMEM*) _cmsMalloc(sizeof(FILEMEM));
+ if (fm == NULL) return NULL;
+
ZeroMemory(fm, sizeof(FILEMEM));
if (Mode == 'r') {
- fm ->Block = (LPBYTE) malloc(Size);
+ fm ->Block = (LPBYTE) _cmsMalloc(Size);
if (fm ->Block == NULL) {
- free(fm);
+ _cmsFree(fm);
return NULL;
}
-
CopyMemory(fm->Block, Block, Size);
fm ->FreeBlockOnClose = TRUE;
@@ -103,13 +104,27 @@ size_t MemoryRead(LPVOID buffer, size_t
FILEMEM* ResData = (FILEMEM*) Icc ->stream;
LPBYTE Ptr;
size_t len = size * count;
-
-
- if (ResData -> Pointer + len > ResData -> Size){
+ size_t extent = ResData -> Pointer + len;
+
+ if (len == 0) {
+ return 0;
+ }
+
+ if (len / size != count) {
+ cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Integer overflow with count / size.");
+ return 0;
+ }
+
+ if (extent < len || extent < ResData -> Pointer) {
+ cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Integer overflow with len.");
+ return 0;
+ }
+
+ if (ResData -> Pointer + len > ResData -> Size) {
len = (ResData -> Size - ResData -> Pointer);
- cmsSignalError(LCMS_ERRC_WARNING, "Read from memory error. Got %d bytes, block should be of %d bytes", len * size, count * size);
-
+ cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Got %d bytes, block should be of %d bytes", len * size, count * size);
+ return 0;
}
Ptr = ResData -> Block;
@@ -123,7 +138,7 @@ size_t MemoryRead(LPVOID buffer, size_t
// SEEK_CUR is assumed
static
-BOOL MemorySeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
+LCMSBOOL MemorySeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
{
FILEMEM* ResData = (FILEMEM*) Icc ->stream;
@@ -147,18 +162,19 @@ size_t MemoryTell(struct _lcms_iccprofil
}
-// Writes data to memory, also keeps used space for further reference
-
-static
-BOOL MemoryWrite(struct _lcms_iccprofile_struct* Icc, size_t size, void *Ptr)
+// Writes data to memory, also keeps used space for further reference. NO CHECK IS PERFORMED
+
+static
+LCMSBOOL MemoryWrite(struct _lcms_iccprofile_struct* Icc, size_t size, void *Ptr)
{
FILEMEM* ResData = (FILEMEM*) Icc ->stream;
if (size == 0) return TRUE;
if (ResData != NULL)
- CopyMemory(ResData ->Block + Icc ->UsedSpace, Ptr, size);
-
+ CopyMemory(ResData ->Block + ResData ->Pointer, Ptr, size);
+
+ ResData->Pointer += size;
Icc->UsedSpace += size;
return TRUE;
@@ -166,15 +182,37 @@ BOOL MemoryWrite(struct _lcms_iccprofile
static
-BOOL MemoryClose(struct _lcms_iccprofile_struct* Icc)
+LCMSBOOL MemoryGrow(struct _lcms_iccprofile_struct* Icc, size_t size)
+{
+ FILEMEM* ResData = (FILEMEM*) Icc->stream;
+
+ void* newBlock = NULL;
+
+ /* Follow same policies as functions in lcms.h */
+ if (ResData->Size + size < 0) return NULL;
+ if (ResData->Size + size > ((size_t)1024*1024*500)) return NULL;
+
+ newBlock = realloc(ResData->Block, ResData->Size + size);
+
+ if (!newBlock) {
+ return FALSE;
+ }
+ ResData->Block = newBlock;
+ ResData->Size += size;
+ return TRUE;
+}
+
+
+static
+LCMSBOOL MemoryClose(struct _lcms_iccprofile_struct* Icc)
{
FILEMEM* ResData = (FILEMEM*) Icc ->stream;
if (ResData ->FreeBlockOnClose) {
- if (ResData ->Block) free(ResData ->Block);
- }
- free(ResData);
+ if (ResData ->Block) _cmsFree(ResData ->Block);
+ }
+ _cmsFree(ResData);
return 0;
}
@@ -192,7 +230,7 @@ size_t FileRead(void *buffer, size_t siz
{
size_t nReaded = fread(buffer, size, count, (FILE*) Icc->stream);
if (nReaded != count) {
- cmsSignalError(LCMS_ERRC_WARNING, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
+ cmsSignalError(LCMS_ERRC_ABORTED, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
return 0;
}
@@ -201,7 +239,7 @@ size_t FileRead(void *buffer, size_t siz
static
-BOOL FileSeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
+LCMSBOOL FileSeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
{
if (fseek((FILE*) Icc ->stream, (long) offset, SEEK_SET) != 0) {
@@ -223,7 +261,7 @@ size_t FileTell(struct _lcms_iccprofile_
static
-BOOL FileWrite(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr)
+LCMSBOOL FileWrite(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr)
{
if (size == 0) return TRUE;
@@ -239,7 +277,14 @@ BOOL FileWrite(struct _lcms_iccprofile_s
static
-BOOL FileClose(struct _lcms_iccprofile_struct* Icc)
+LCMSBOOL FileGrow(struct _lcms_iccprofile_struct* Icc, size_t size)
+{
+ return TRUE;
+}
+
+
+static
+LCMSBOOL FileClose(struct _lcms_iccprofile_struct* Icc)
{
return fclose((FILE*) Icc ->stream);
}
@@ -252,7 +297,7 @@ cmsHPROFILE _cmsCreateProfilePlaceholder
cmsHPROFILE _cmsCreateProfilePlaceholder(void)
{
- LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) malloc(sizeof(LCMSICCPROFILE));
+ LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) _cmsMalloc(sizeof(LCMSICCPROFILE));
if (Icc == NULL) return NULL;
// Empty values
@@ -290,7 +335,7 @@ icTagSignature LCMSEXPORT cmsGetTagSigna
// Search for a specific tag in tag dictionary
// Returns position or -1 if tag not found
-icInt32Number _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, BOOL lSignalError)
+icInt32Number _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, LCMSBOOL lSignalError)
{
icInt32Number i;
@@ -311,7 +356,7 @@ icInt32Number _cmsSearchTag(LPLCMSICCPRO
// Check existance
-BOOL LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig)
+LCMSBOOL LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
return _cmsSearchTag(Icc, sig, FALSE) >= 0;
@@ -330,7 +375,7 @@ LPVOID _cmsInitTag(LPLCMSICCPROFILE Icc,
if (i >=0) {
- if (Icc -> TagPtrs[i]) free(Icc -> TagPtrs[i]);
+ if (Icc -> TagPtrs[i]) _cmsFree(Icc -> TagPtrs[i]);
}
else {
@@ -341,11 +386,14 @@ LPVOID _cmsInitTag(LPLCMSICCPROFILE Icc,
cmsSignalError(LCMS_ERRC_ABORTED, "Too many tags (%d)", MAX_TABLE_TAG);
Icc ->TagCount = MAX_TABLE_TAG-1;
+ return NULL;
}
}
- Ptr = malloc(size);
+ Ptr = _cmsMalloc(size);
+ if (Ptr == NULL) return NULL;
+
CopyMemory(Ptr, Init, size);
Icc ->TagNames[i] = sig;
@@ -376,12 +424,15 @@ LPLCMSICCPROFILE _cmsCreateProfileFromFi
if (NewIcc == NULL) return NULL;
strncpy(NewIcc -> PhysicalFile, FileName, MAX_PATH-1);
+ NewIcc -> PhysicalFile[MAX_PATH-1] = 0;
+
NewIcc ->stream = ICCfile;
NewIcc ->Read = FileRead;
NewIcc ->Seek = FileSeek;
NewIcc ->Tell = FileTell;
NewIcc ->Close = FileClose;
+ NewIcc ->Grow = FileGrow;
NewIcc ->Write = NULL;
NewIcc ->IsWrite = FALSE;
@@ -419,7 +470,8 @@ LPLCMSICCPROFILE _cmsCreateProfileFromMe
NewIcc ->Seek = MemorySeek;
NewIcc ->Tell = MemoryTell;
NewIcc ->Close = MemoryClose;
- NewIcc ->Write = NULL;
+ NewIcc ->Grow = MemoryGrow;
+ NewIcc ->Write = MemoryWrite;
NewIcc ->IsWrite = FALSE;
@@ -476,7 +528,7 @@ void _cmsSetSaveToMemory(LPLCMSICCPROFIL
-BOOL LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
*Dest = Icc -> MediaWhitePoint;
@@ -484,14 +536,14 @@ BOOL LCMSEXPORT cmsTakeMediaWhitePoint(L
}
-BOOL LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
*Dest = Icc -> MediaBlackPoint;
return TRUE;
}
-BOOL LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
*Dest = Icc -> Illuminant;
@@ -549,7 +601,7 @@ void LCMSEXPORT cmsSetProfileID(cmsHPROF
}
-BOOL LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
CopyMemory(Dest, &Icc ->Created, sizeof(struct tm));
@@ -570,23 +622,18 @@ void LCMSEXPORT cmsSetPCS(cmsHPROFILE hP
Icc -> PCS = pcs;
}
-
-
icColorSpaceSignature LCMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
return Icc -> ColorSpace;
}
-
-
void LCMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, icColorSpaceSignature sig)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
Icc -> ColorSpace = sig;
}
-
icProfileClassSignature LCMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
@@ -598,7 +645,6 @@ DWORD LCMSEXPORT cmsGetProfileICCversion
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
return (DWORD) Icc -> Version;
}
-
void LCMSEXPORT cmsSetProfileICCversion(cmsHPROFILE hProfile, DWORD Version)
{
@@ -638,7 +684,7 @@ LPVOID DupBlock(LPLCMSICCPROFILE Icc, LP
// This is tricky, since LUT structs does have pointers
-BOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile, icTagSignature sig, const void* lut)
+LCMSBOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile, icTagSignature sig, const void* lut)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
LPLUT Orig, Stored;
@@ -666,7 +712,7 @@ BOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFIL
}
-BOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* XYZ)
+LCMSBOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* XYZ)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -675,7 +721,7 @@ BOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFIL
}
-BOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile, icTagSignature sig, const char* Text)
+LCMSBOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile, icTagSignature sig, const char* Text)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -683,7 +729,7 @@ BOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFI
return TRUE;
}
-BOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction)
+LCMSBOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -692,7 +738,7 @@ BOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROF
}
-BOOL LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm)
+LCMSBOOL LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -701,7 +747,7 @@ BOOL LCMSEXPORT _cmsAddChromaticityTag(c
}
-BOOL LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ pseq)
+LCMSBOOL LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ pseq)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -711,28 +757,40 @@ BOOL LCMSEXPORT _cmsAddSequenceDescripti
}
-BOOL LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
+LCMSBOOL LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
_cmsInitTag(Icc, sig, sizeof(cmsNAMEDCOLORLIST) + (nc ->nColors - 1) * sizeof(cmsNAMEDCOLOR), nc);
- return FALSE;
-}
-
-
-BOOL LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime)
+ return TRUE;
+}
+
+
+LCMSBOOL LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
_cmsInitTag(Icc, sig, sizeof(struct tm), DateTime);
- return FALSE;
-}
-
-
-BOOL LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
+ return TRUE;
+}
+
+
+LCMSBOOL LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
_cmsInitTag(Icc, sig, sizeof(cmsNAMEDCOLORLIST) + (nc ->nColors - 1) * sizeof(cmsNAMEDCOLOR), nc);
- return FALSE;
-}
+ return TRUE;
+}
+
+
+LCMSBOOL LCMSEXPORT _cmsAddChromaticAdaptationTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* mat)
+{
+ LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+
+ _cmsInitTag(Icc, sig, 3*sizeof(cmsCIEXYZ), mat);
+ return TRUE;
+
+}
+
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmsio1.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsio1.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -149,6 +149,7 @@ void AdjustEndianessArray16(LPWORD p, si
#endif
+
// Transports to properly encoded values - note that icc profiles does use
// big endian notation.
@@ -216,7 +217,8 @@ icTagTypeSignature ReadBase(LPLCMSICCPRO
{
icTagBase Base;
- Icc -> Read(&Base, sizeof(icTagBase), 1, Icc);
+ if (Icc -> Read(&Base, sizeof(icTagBase), 1, Icc) != 1)
+ return (icTagTypeSignature) 0;
AdjustEndianess32((LPBYTE) &Base.sig);
return Base.sig;
@@ -288,13 +290,15 @@ void EvalCHRM(LPcmsCIEXYZ Dest, LPMAT3 C
// Read profile header and validate it
static
-LPLCMSICCPROFILE ReadHeader(LPLCMSICCPROFILE Icc, BOOL lIsFromMemory)
+LPLCMSICCPROFILE ReadHeader(LPLCMSICCPROFILE Icc, LCMSBOOL lIsFromMemory)
{
icTag Tag;
icHeader Header;
icInt32Number TagCount, i;
-
- Icc -> Read(&Header, sizeof(icHeader), 1, Icc);
+ icUInt32Number extent;
+
+ if (Icc -> Read(&Header, sizeof(icHeader), 1, Icc) != 1)
+ goto ErrorCleanup;
// Convert endian
@@ -306,13 +310,12 @@ LPLCMSICCPROFILE ReadHeader(LPLCMSICCPRO
AdjustEndianess32((LPBYTE) &Header.pcs);
AdjustEndianess32((LPBYTE) &Header.magic);
AdjustEndianess32((LPBYTE) &Header.flags);
- AdjustEndianess32((LPBYTE) &Header.attributes[0]);
+ AdjustEndianess32((LPBYTE) &Header.attributes[0]);
AdjustEndianess32((LPBYTE) &Header.renderingIntent);
// Validate it
if (Header.magic != icMagicNumber) goto ErrorCleanup;
-
if (Icc ->Read(&TagCount, sizeof(icInt32Number), 1, Icc) != 1)
goto ErrorCleanup;
@@ -324,7 +327,7 @@ LPLCMSICCPROFILE ReadHeader(LPLCMSICCPRO
Icc -> PCS = Header.pcs;
Icc -> RenderingIntent = (icRenderingIntent) Header.renderingIntent;
Icc -> flags = Header.flags;
- Icc -> attributes = Header.attributes[0];
+ Icc -> attributes = Header.attributes[0];
Icc -> Illuminant.X = Convert15Fixed16(Header.illuminant.X);
Icc -> Illuminant.Y = Convert15Fixed16(Header.illuminant.Y);
Icc -> Illuminant.Z = Convert15Fixed16(Header.illuminant.Z);
@@ -348,7 +351,7 @@ LPLCMSICCPROFILE ReadHeader(LPLCMSICCPRO
// Read tag directory
- if (TagCount > MAX_TABLE_TAG) {
+ if (TagCount > MAX_TABLE_TAG || TagCount < 0) {
cmsSignalError(LCMS_ERRC_ABORTED, "Too many tags (%d)", TagCount);
goto ErrorCleanup;
@@ -357,11 +360,17 @@ LPLCMSICCPROFILE ReadHeader(LPLCMSICCPRO
Icc -> TagCount = TagCount;
for (i=0; i < TagCount; i++) {
- Icc ->Read(&Tag, sizeof(icTag), 1, Icc);
+ if (Icc ->Read(&Tag, sizeof(icTag), 1, Icc) != 1)
+ goto ErrorCleanup;
AdjustEndianess32((LPBYTE) &Tag.offset);
AdjustEndianess32((LPBYTE) &Tag.size);
AdjustEndianess32((LPBYTE) &Tag.sig); // Signature
+
+ // Perform some sanity check. Offset + size should fall inside file.
+ extent = Tag.offset + Tag.size;
+ if (extent > Header.size || extent < Tag.offset)
+ goto ErrorCleanup;
Icc -> TagNames[i] = Tag.sig;
Icc -> TagOffsets[i] = Tag.offset;
@@ -381,12 +390,9 @@ ErrorCleanup:
cmsSignalError(LCMS_ERRC_ABORTED, "Corrupted profile: '%s'", Icc->PhysicalFile);
- free(Icc);
+ _cmsFree(Icc);
return NULL;
}
-
-
-
static
unsigned int uipow(unsigned int a, unsigned int b) {
@@ -497,7 +503,7 @@ void FixLUT8bothSides(LPLUT Lut, size_t
// The infamous LUT 8
static
-void ReadLUT8(LPLCMSICCPROFILE Icc, LPLUT NewLUT, icTagSignature sig)
+LCMSBOOL ReadLUT8(LPLCMSICCPROFILE Icc, LPLUT NewLUT, icTagSignature sig)
{
icLut8 LUT8;
LPBYTE Temp;
@@ -506,7 +512,7 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
unsigned int AllLinear;
LPWORD PtrW;
- Icc ->Read(&LUT8, sizeof(icLut8) - SIZEOF_UINT8_ALIGNED, 1, Icc);
+ if (Icc ->Read(&LUT8, sizeof(icLut8) - SIZEOF_UINT8_ALIGNED, 1, Icc) != 1) return FALSE;
NewLUT -> wFlags = LUT_HASTL1|LUT_HASTL2|LUT_HAS3DGRID;
NewLUT -> cLutPoints = LUT8.clutPoints;
@@ -515,6 +521,10 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
NewLUT -> InputEntries = 256;
NewLUT -> OutputEntries = 256;
+ // Do some checking
+ if (!_cmsValidateLUT(NewLUT)) {
+ return FALSE;
+ }
AdjustEndianess32((LPBYTE) &LUT8.e00);
AdjustEndianess32((LPBYTE) &LUT8.e01);
@@ -550,13 +560,24 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
// Copy input tables
- Temp = (LPBYTE) malloc(256);
+ Temp = (LPBYTE) _cmsMalloc(256);
+ if (Temp == NULL) return FALSE;
+
AllLinear = 0;
for (i=0; i < NewLUT -> InputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * 256);
+ PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * 256);
+ if (PtrW == NULL) {
+ _cmsFree(Temp);
+ return FALSE;
+ }
+
NewLUT -> L1[i] = PtrW;
- Icc ->Read(Temp, 1, 256, Icc);
+ if (Icc ->Read(Temp, 1, 256, Icc) != 256) {
+ _cmsFree(Temp);
+ return FALSE;
+ }
+
for (j=0; j < 256; j++)
PtrW[j] = TO16_TAB(Temp[j]);
AllLinear += cmsIsLinear(NewLUT -> L1[i], NewLUT -> InputEntries);
@@ -569,7 +590,7 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
NewLUT -> wFlags &= ~LUT_HASTL1;
}
- free(Temp);
+ _cmsFree(Temp);
// Copy 3D CLUT
@@ -578,9 +599,20 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
if (nTabSize > 0) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * nTabSize);
- Temp = (LPBYTE) malloc(nTabSize);
- Icc ->Read(Temp, 1, nTabSize, Icc);
+ PtrW = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
+ if (PtrW == NULL) return FALSE;
+
+ Temp = (LPBYTE) _cmsMalloc(nTabSize);
+ if (Temp == NULL) {
+ _cmsFree(PtrW);
+ return FALSE;
+ }
+
+ if (Icc ->Read(Temp, 1, nTabSize, Icc) != nTabSize) {
+ _cmsFree(Temp);
+ _cmsFree(PtrW);
+ return FALSE;
+ }
NewLUT -> T = PtrW;
NewLUT -> Tsize = (unsigned int) (nTabSize * sizeof(WORD));
@@ -589,25 +621,37 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
*PtrW++ = TO16_TAB(Temp[i]);
}
- free(Temp);
+ _cmsFree(Temp);
}
else {
NewLUT ->T = NULL;
NewLUT ->Tsize = 0;
- NewLUT -> wFlags &= ~LUT_HAS3DGRID;
- }
-
+ NewLUT ->wFlags &= ~LUT_HAS3DGRID;
+ }
// Copy output tables
- Temp = (LPBYTE) malloc(256);
+ Temp = (LPBYTE) _cmsMalloc(256);
+ if (Temp == NULL) {
+ return FALSE;
+ }
+
AllLinear = 0;
for (i=0; i < NewLUT -> OutputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * 256);
+ PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * 256);
+ if (PtrW == NULL) {
+ _cmsFree(Temp);
+ return FALSE;
+ }
+
NewLUT -> L2[i] = PtrW;
- Icc ->Read(Temp, 1, 256, Icc);
+ if (Icc ->Read(Temp, 1, 256, Icc) != 256) {
+ _cmsFree(Temp);
+ return FALSE;
+ }
+
for (j=0; j < 256; j++)
PtrW[j] = TO16_TAB(Temp[j]);
AllLinear += cmsIsLinear(NewLUT -> L2[i], 256);
@@ -621,7 +665,7 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
}
- free(Temp);
+ _cmsFree(Temp);
cmsCalcL16Params(NewLUT -> InputEntries, &NewLUT -> In16params);
cmsCalcL16Params(NewLUT -> OutputEntries, &NewLUT -> Out16params);
@@ -646,6 +690,15 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
// some profiles does claim to do that. Poor lcms will try
// to detect such condition and fix up "on the fly".
+ switch (sig) {
+
+ case icSigBToA0Tag:
+ case icSigBToA1Tag:
+ case icSigBToA2Tag:
+ case icSigGamutTag:
+ case icSigPreview0Tag:
+ case icSigPreview1Tag:
+ case icSigPreview2Tag:
{
LPWORD WhiteLab, ExpectedWhite;
WORD WhiteFixed[MAXCHANNELS], WhiteUnfixed[MAXCHANNELS];
@@ -685,9 +738,13 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
}
}
-
- }
-
+ break;
+
+ default:;
+ }
+ }
+
+ return TRUE;
}
@@ -696,7 +753,7 @@ void ReadLUT8(LPLCMSICCPROFILE Icc, LPLU
// Case LUT 16
static
-void ReadLUT16(LPLCMSICCPROFILE Icc, LPLUT NewLUT)
+LCMSBOOL ReadLUT16(LPLCMSICCPROFILE Icc, LPLUT NewLUT)
{
icLut16 LUT16;
size_t nTabSize;
@@ -705,7 +762,8 @@ void ReadLUT16(LPLCMSICCPROFILE Icc, LPL
LPWORD PtrW;
- Icc ->Read(&LUT16, sizeof(icLut16)- SIZEOF_UINT16_ALIGNED, 1, Icc);
+ if (Icc ->Read(&LUT16, sizeof(icLut16)- SIZEOF_UINT16_ALIGNED, 1, Icc) != 1)
+ return FALSE;
NewLUT -> wFlags = LUT_HASTL1 | LUT_HASTL2 | LUT_HAS3DGRID;
NewLUT -> cLutPoints = LUT16.clutPoints;
@@ -718,6 +776,9 @@ void ReadLUT16(LPLCMSICCPROFILE Icc, LPL
NewLUT -> InputEntries = LUT16.inputEnt;
NewLUT -> OutputEntries = LUT16.outputEnt;
+ if (!_cmsValidateLUT(NewLUT)) {
+ return FALSE;
+ }
// Matrix handling
@@ -754,9 +815,14 @@ void ReadLUT16(LPLCMSICCPROFILE Icc, LPL
AllLinear = 0;
for (i=0; i < NewLUT -> InputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> InputEntries);
+ PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> InputEntries);
+ if (PtrW == NULL) return FALSE;
+
NewLUT -> L1[i] = PtrW;
- Icc ->Read(PtrW, sizeof(WORD), NewLUT -> InputEntries, Icc);
+ if (Icc ->Read(PtrW, sizeof(WORD), NewLUT -> InputEntries, Icc) != NewLUT -> InputEntries) {
+ return FALSE;
+ }
+
AdjustEndianessArray16(PtrW, NewLUT -> InputEntries);
AllLinear += cmsIsLinear(NewLUT -> L1[i], NewLUT -> InputEntries);
}
@@ -775,12 +841,17 @@ void ReadLUT16(LPLCMSICCPROFILE Icc, LPL
NewLUT->InputChan));
if (nTabSize > 0) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * nTabSize);
+ PtrW = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
+ if (PtrW == NULL)
+ return FALSE;
NewLUT -> T = PtrW;
NewLUT -> Tsize = (unsigned int) (nTabSize * sizeof(WORD));
- Icc -> Read(PtrW, sizeof(WORD), nTabSize, Icc);
+ if (Icc -> Read(PtrW, sizeof(WORD), nTabSize, Icc) != nTabSize) {
+ return FALSE;
+ }
+
AdjustEndianessArray16(NewLUT -> T, nTabSize);
}
else {
@@ -794,9 +865,16 @@ void ReadLUT16(LPLCMSICCPROFILE Icc, LPL
AllLinear = 0;
for (i=0; i < NewLUT -> OutputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> OutputEntries);
+ PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> OutputEntries);
+ if (PtrW == NULL) {
+ return FALSE;
+ }
+
NewLUT -> L2[i] = PtrW;
- Icc ->Read(PtrW, sizeof(WORD), NewLUT -> OutputEntries, Icc);
+ if (Icc ->Read(PtrW, sizeof(WORD), NewLUT -> OutputEntries, Icc) != NewLUT -> OutputEntries) {
+ return FALSE;
+ }
+
AdjustEndianessArray16(PtrW, NewLUT -> OutputEntries);
AllLinear += cmsIsLinear(NewLUT -> L2[i], NewLUT -> OutputEntries);
}
@@ -814,6 +892,8 @@ void ReadLUT16(LPLCMSICCPROFILE Icc, LPL
cmsCalcCLUT16Params(NewLUT -> cLutPoints, NewLUT -> InputChan,
NewLUT -> OutputChan,
&NewLUT -> CLut16params);
+
+ return TRUE;
}
@@ -830,16 +910,14 @@ LPGAMMATABLE ReadCurve(LPLCMSICCPROFILE
BaseType = ReadBase(Icc);
-
switch (BaseType) {
- case 0x9478ee00L: // Monaco 2 profiler is BROKEN!
+ case ((icTagTypeSignature) 0x9478ee00): // Monaco 2 profiler is BROKEN!
case icSigCurveType:
- Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
+ if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
AdjustEndianess32((LPBYTE) &Count);
-
switch (Count) {
@@ -855,7 +933,7 @@ LPGAMMATABLE ReadCurve(LPLCMSICCPROFILE
{
WORD SingleGammaFixed;
- Icc ->Read(&SingleGammaFixed, sizeof(WORD), 1, Icc);
+ if (Icc ->Read(&SingleGammaFixed, sizeof(WORD), 1, Icc) != 1) return NULL;
AdjustEndianess16((LPBYTE) &SingleGammaFixed);
return cmsBuildGamma(4096, Convert8Fixed8(SingleGammaFixed));
}
@@ -865,10 +943,9 @@ LPGAMMATABLE ReadCurve(LPLCMSICCPROFILE
NewGamma = cmsAllocGamma(Count);
if (!NewGamma) return NULL;
- Icc ->Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc);
-
+ if (Icc ->Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc) != Count)
+ return NULL;
AdjustEndianessArray16(NewGamma -> GammaTable, Count);
-
return NewGamma;
}
}
@@ -885,11 +962,11 @@ LPGAMMATABLE ReadCurve(LPLCMSICCPROFILE
icUInt16Number Type;
int i;
- Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc);
- Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc);
+ if (Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
+ if (Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
AdjustEndianess16((LPBYTE) &Type);
- if (Type > 5) {
+ if (Type > 4) {
cmsSignalError(LCMS_ERRC_ABORTED, "Unknown parametric curve type '%d' found.", Type);
return NULL;
@@ -900,7 +977,7 @@ LPGAMMATABLE ReadCurve(LPLCMSICCPROFILE
for (i=0; i < n; i++) {
Num = 0;
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
+ if (Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc) != 1) return NULL;
Params[i] = Convert15Fixed16(Num);
}
@@ -938,7 +1015,7 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
case 0x9478ee00L: // Monaco 2 profiler is BROKEN!
case icSigCurveType:
- Icc -> Read(&Count, sizeof(icUInt32Number), 1, Icc);
+ if (Icc -> Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
AdjustEndianess32((LPBYTE) &Count);
@@ -948,6 +1025,7 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
NewGamma = cmsAllocGamma(2);
if (!NewGamma) return NULL;
+
NewGamma -> GammaTable[0] = 0;
NewGamma -> GammaTable[1] = 0xFFFF;
return NewGamma;
@@ -955,7 +1033,7 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
case 1: {
WORD SingleGammaFixed;
- Icc -> Read(&SingleGammaFixed, sizeof(WORD), 1, Icc);
+ if (Icc -> Read(&SingleGammaFixed, sizeof(WORD), 1, Icc) != 1) return NULL;
AdjustEndianess16((LPBYTE) &SingleGammaFixed);
return cmsBuildGamma(4096, 1./Convert8Fixed8(SingleGammaFixed));
}
@@ -965,7 +1043,8 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
NewGamma = cmsAllocGamma(Count);
if (!NewGamma) return NULL;
- Icc -> Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc);
+ if (Icc -> Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc) != Count)
+ return NULL;
AdjustEndianessArray16(NewGamma -> GammaTable, Count);
@@ -992,11 +1071,11 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
int i;
- Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc);
- Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc);
+ if (Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
+ if (Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
AdjustEndianess16((LPBYTE) &Type);
- if (Type > 5) {
+ if (Type > 4) {
cmsSignalError(LCMS_ERRC_ABORTED, "Unknown parametric curve type '%d' found.", Type);
return NULL;
@@ -1006,7 +1085,7 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
n = ParamsByType[Type];
for (i=0; i < n; i++) {
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
+ if (Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc) != 1) return NULL;
Params[i] = Convert15Fixed16(Num);
}
@@ -1028,7 +1107,7 @@ LPGAMMATABLE ReadCurveReversed(LPLCMSICC
// V4 stuff. Read matrix for LutAtoB and LutBtoA
static
-BOOL ReadMatrixOffset(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, DWORD dwFlags)
+LCMSBOOL ReadMatrixOffset(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, DWORD dwFlags)
{
icS15Fixed16Number All[12];
@@ -1038,7 +1117,8 @@ BOOL ReadMatrixOffset(LPLCMSICCPROFILE I
if (Icc -> Seek(Icc, Offset)) return FALSE;
- Icc ->Read(All, sizeof(icS15Fixed16Number), 12, Icc);
+ if (Icc ->Read(All, sizeof(icS15Fixed16Number), 12, Icc) != 12)
+ return FALSE;
for (i=0; i < 12; i++)
AdjustEndianess32((LPBYTE) &All[i]);
@@ -1067,17 +1147,26 @@ BOOL ReadMatrixOffset(LPLCMSICCPROFILE I
// V4 stuff. Read CLUT part for LutAtoB and LutBtoA
static
-BOOL ReadCLUT(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT)
-{
-
+LCMSBOOL ReadCLUT(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT)
+{
+ unsigned int j;
icCLutStruct CLUT;
if (Icc -> Seek(Icc, Offset)) return FALSE;
- Icc ->Read(&CLUT, sizeof(icCLutStruct), 1, Icc);
-
-
- cmsAlloc3DGrid(NewLUT, CLUT.gridPoints[0], NewLUT ->InputChan,
- NewLUT ->OutputChan);
+ if (Icc ->Read(&CLUT, sizeof(icCLutStruct), 1, Icc) != 1) return FALSE;
+
+
+ for (j=1; j < NewLUT ->InputChan; j++) {
+ if (CLUT.gridPoints[0] != CLUT.gridPoints[j]) {
+ cmsSignalError(LCMS_ERRC_ABORTED, "CLUT with different granulatity is currently unsupported.");
+ return FALSE;
+ }
+
+
+ }
+
+ if (cmsAlloc3DGrid(NewLUT, CLUT.gridPoints[0], NewLUT ->InputChan,
+ NewLUT ->OutputChan) == NULL) return FALSE;
// Precission can be 1 or 2 bytes
@@ -1087,7 +1176,7 @@ BOOL ReadCLUT(LPLCMSICCPROFILE Icc, size
unsigned int i;
for (i=0; i < NewLUT->Tsize / sizeof(WORD); i++) {
- Icc ->Read(&v, sizeof(BYTE), 1, Icc);
+ if (Icc ->Read(&v, sizeof(BYTE), 1, Icc) != 1) return FALSE;
NewLUT->T[i] = TO16_TAB(v);
}
@@ -1095,10 +1184,10 @@ BOOL ReadCLUT(LPLCMSICCPROFILE Icc, size
else
if (CLUT.prec == 2) {
- Icc ->Read(NewLUT ->T, sizeof(WORD),
- NewLUT->Tsize / sizeof(WORD), Icc);
-
- AdjustEndianessArray16(NewLUT ->T, NewLUT->Tsize / sizeof(WORD));
+ size_t n = NewLUT->Tsize / sizeof(WORD);
+
+ if (Icc ->Read(NewLUT ->T, sizeof(WORD), n, Icc) != n) return FALSE;
+ AdjustEndianessArray16(NewLUT ->T, NewLUT->Tsize / sizeof(WORD));
}
else {
cmsSignalError(LCMS_ERRC_ABORTED, "Unknow precission of '%d'", CLUT.prec);
@@ -1110,6 +1199,22 @@ BOOL ReadCLUT(LPLCMSICCPROFILE Icc, size
static
+void ResampleCurves(LPGAMMATABLE Curves[], int nCurves)
+{
+ int i;
+ LPSAMPLEDCURVE sc;
+
+ for (i=0; i < nCurves; i++) {
+ sc = cmsConvertGammaToSampledCurve(Curves[i], 4096);
+ cmsFreeGamma(Curves[i]);
+ Curves[i] = cmsConvertSampledCurveToGamma(sc, 0xFFFF);
+ cmsFreeSampledCurve(sc);
+ }
+
+}
+
+
+static
void SkipAlignment(LPLCMSICCPROFILE Icc)
{
BYTE Buffer[4];
@@ -1121,7 +1226,7 @@ void SkipAlignment(LPLCMSICCPROFILE Icc)
// Read a set of curves from specific offset
static
-BOOL ReadSetOfCurves(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, int nLocation)
+LCMSBOOL ReadSetOfCurves(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, int nLocation)
{
LPGAMMATABLE Curves[MAXCHANNELS];
unsigned int i, nCurves;
@@ -1134,19 +1239,40 @@ BOOL ReadSetOfCurves(LPLCMSICCPROFILE Ic
else
nCurves = NewLUT ->OutputChan;
+ ZeroMemory(Curves, sizeof(Curves));
for (i=0; i < nCurves; i++) {
Curves[i] = ReadCurve(Icc);
+ if (Curves[i] == NULL) goto Error;
SkipAlignment(Icc);
-
+ }
+
+ // March-26'08: some V4 profiles may have different sampling
+ // rates, in this case resample all curves to maximum
+
+ for (i=1; i < nCurves; i++) {
+ if (Curves[i]->nEntries != Curves[0]->nEntries) {
+ ResampleCurves(Curves, nCurves);
+ break;
+ }
}
NewLUT = cmsAllocLinearTable(NewLUT, Curves, nLocation);
+ if (NewLUT == NULL) goto Error;
for (i=0; i < nCurves; i++)
cmsFreeGamma(Curves[i]);
return TRUE;
+
+Error:
+
+ for (i=0; i < nCurves; i++)
+ if (Curves[i])
+ cmsFreeGamma(Curves[i]);
+
+ return FALSE;
+
}
@@ -1160,21 +1286,27 @@ BOOL ReadSetOfCurves(LPLCMSICCPROFILE Ic
// L2 = B curves
static
-BOOL ReadLUT_A2B(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
+LCMSBOOL ReadLUT_A2B(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
{
icLutAtoB LUT16;
- Icc ->Read(&LUT16, sizeof(icLutAtoB), 1, Icc);
+ if (Icc ->Read(&LUT16, sizeof(icLutAtoB), 1, Icc) != 1) return FALSE;
NewLUT -> InputChan = LUT16.inputChan;
NewLUT -> OutputChan = LUT16.outputChan;
+
+ // Validate the NewLUT here to avoid excessive number of channels
+ // (leading to stack-based buffer overflow in ReadSetOfCurves).
+ // Needs revalidation after table size is filled in.
+ if (!_cmsValidateLUT(NewLUT)) {
+ return FALSE;
+ }
AdjustEndianess32((LPBYTE) &LUT16.offsetB);
AdjustEndianess32((LPBYTE) &LUT16.offsetMat);
AdjustEndianess32((LPBYTE) &LUT16.offsetM);
AdjustEndianess32((LPBYTE) &LUT16.offsetC);
AdjustEndianess32((LPBYTE) &LUT16.offsetA);
-
if (LUT16.offsetB != 0)
ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetB, NewLUT, 2);
@@ -1220,14 +1352,21 @@ BOOL ReadLUT_A2B(LPLCMSICCPROFILE Icc, L
// V4 stuff. LutBtoA type
static
-BOOL ReadLUT_B2A(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
+LCMSBOOL ReadLUT_B2A(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
{
icLutBtoA LUT16;
- Icc ->Read(&LUT16, sizeof(icLutBtoA), 1, Icc);
+ if (Icc ->Read(&LUT16, sizeof(icLutBtoA), 1, Icc) != 1) return FALSE;
NewLUT -> InputChan = LUT16.inputChan;
NewLUT -> OutputChan = LUT16.outputChan;
+
+ // Validate the NewLUT here to avoid excessive number of channels
+ // (leading to stack-based buffer overflow in ReadSetOfCurves).
+ // Needs revalidation after table size is filled in.
+ if (!_cmsValidateLUT(NewLUT)) {
+ return FALSE;
+ }
AdjustEndianess32((LPBYTE) &LUT16.offsetB);
AdjustEndianess32((LPBYTE) &LUT16.offsetMat);
@@ -1241,7 +1380,6 @@ BOOL ReadLUT_B2A(LPLCMSICCPROFILE Icc, L
if (LUT16.offsetMat != 0)
ReadMatrixOffset(Icc, BaseOffset + LUT16.offsetMat, NewLUT, LUT_HASMATRIX3);
-
if (LUT16.offsetM != 0)
ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetM, NewLUT, 3);
@@ -1294,7 +1432,7 @@ LPLUT LCMSEXPORT cmsReadICCLut(cmsHPROFI
// If is in memory, the LUT is already there, so throw a copy
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
return cmsDupLUT((LPLUT) Icc ->TagPtrs[n]);
}
@@ -1308,8 +1446,8 @@ LPLUT LCMSEXPORT cmsReadICCLut(cmsHPROFI
NewLUT = cmsAllocLUT();
- if (!NewLUT)
- {
+ if (!NewLUT) {
+
cmsSignalError(LCMS_ERRC_ABORTED, "cmsAllocLUT() failed");
return NULL;
}
@@ -1317,11 +1455,29 @@ LPLUT LCMSEXPORT cmsReadICCLut(cmsHPROFI
switch (BaseType) {
- case icSigLut8Type: ReadLUT8(Icc, NewLUT, sig); break;
- case icSigLut16Type: ReadLUT16(Icc, NewLUT); break;
-
- case icSiglutAtoBType: ReadLUT_A2B(Icc, NewLUT, offset, sig); break;
- case icSiglutBtoAType: ReadLUT_B2A(Icc, NewLUT, offset, sig); break;
+ case icSigLut8Type: if (!ReadLUT8(Icc, NewLUT, sig)) {
+ cmsFreeLUT(NewLUT);
+ return NULL;
+ }
+ break;
+
+ case icSigLut16Type: if (!ReadLUT16(Icc, NewLUT)) {
+ cmsFreeLUT(NewLUT);
+ return NULL;
+ }
+ break;
+
+ case icSiglutAtoBType: if (!ReadLUT_A2B(Icc, NewLUT, offset, sig)) {
+ cmsFreeLUT(NewLUT);
+ return NULL;
+ }
+ break;
+
+ case icSiglutBtoAType: if (!ReadLUT_B2A(Icc, NewLUT, offset, sig)) {
+ cmsFreeLUT(NewLUT);
+ return NULL;
+ }
+ break;
default: cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature %lx found.", BaseType);
cmsFreeLUT(NewLUT);
@@ -1335,16 +1491,23 @@ LPLUT LCMSEXPORT cmsReadICCLut(cmsHPROFI
// Sets the language & country preferences. Used only in ICC 4.0 profiles
-void LCMSEXPORT cmsSetLanguage(int LanguageCode, int CountryCode)
-{
- GlobalLanguageCode = LanguageCode;
- GlobalCountryCode = CountryCode;
+void LCMSEXPORT cmsSetLanguage(const char LanguageCode[4], const char CountryCode[4])
+{
+
+ int LanguageCodeInt = *(int *) LanguageCode;
+ int CountryCodeInt = *(int *) CountryCode;
+
+ AdjustEndianess32((LPBYTE) &LanguageCodeInt);
+ AdjustEndianess32((LPBYTE) &CountryCodeInt);
+
+ GlobalLanguageCode = LanguageCodeInt;
+ GlobalCountryCode = CountryCodeInt;
}
// Some tags (e.g, 'pseq') can have text tags embedded. This function
-// handles such special case.
+// handles such special case. Returns -1 on error, or the number of bytes left on success.
static
int ReadEmbeddedTextTag(LPLCMSICCPROFILE Icc, size_t size, char* Name, size_t size_max)
@@ -1353,7 +1516,6 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
BaseType = ReadBase(Icc);
-
size -= sizeof(icTagBase);
switch (BaseType) {
@@ -1365,50 +1527,54 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
icUInt16Number ScriptCodeCode, Dummy;
icUInt8Number ScriptCodeCount;
- Icc ->Read(&AsciiCount, sizeof(icUInt32Number), 1, Icc);
-
- if (size < sizeof(icUInt32Number)) return (int) size;
+ if (Icc ->Read(&AsciiCount, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+
+ if (size < sizeof(icUInt32Number)) return (int) size;
size -= sizeof(icUInt32Number);
AdjustEndianess32((LPBYTE) &AsciiCount);
Icc ->Read(Name, 1,
(AsciiCount >= size_max) ? (size_max-1) : AsciiCount, Icc);
- if (size < AsciiCount) return (int) size;
+ if (size < AsciiCount) return (int) size;
size -= AsciiCount;
// Skip Unicode code
- Icc ->Read(&UnicodeCode, sizeof(icUInt32Number), 1, Icc);
- if (size < sizeof(icUInt32Number)) return (int) size;
+ if (Icc ->Read(&UnicodeCode, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+ if (size < sizeof(icUInt32Number)) return (int) size;
size -= sizeof(icUInt32Number);
- Icc ->Read(&UnicodeCount, sizeof(icUInt32Number), 1, Icc);
- if (size < sizeof(icUInt32Number)) return (int) size;
+ if (Icc ->Read(&UnicodeCount, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+ if (size < sizeof(icUInt32Number)) return (int) size;
size -= sizeof(icUInt32Number);
AdjustEndianess32((LPBYTE) &UnicodeCount);
if (UnicodeCount > size) return (int) size;
- for (i=0; i < UnicodeCount; i++)
- Icc ->Read(&Dummy, sizeof(icUInt16Number), 1, Icc);
-
- size -= UnicodeCount * sizeof(icUInt16Number);
+ for (i=0; i < UnicodeCount; i++) {
+ size_t nread = Icc ->Read(&Dummy, sizeof(icUInt16Number), 1, Icc);
+ if (nread != 1) return (int) size;
+ size -= sizeof(icUInt16Number);
+ }
// Skip ScriptCode code
- Icc ->Read(&ScriptCodeCode, sizeof(icUInt16Number), 1, Icc);
+ if (Icc ->Read(&ScriptCodeCode, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
size -= sizeof(icUInt16Number);
- Icc ->Read(&ScriptCodeCount, sizeof(icUInt8Number), 1, Icc);
+ if (Icc ->Read(&ScriptCodeCount, sizeof(icUInt8Number), 1, Icc) != 1) return -1;
size -= sizeof(icUInt8Number);
+ // Should remain 67 bytes as filler
+
if (size < 67) return (int) size;
- for (i=0; i < 67; i++)
- Icc ->Read(&Dummy, sizeof(icUInt8Number), 1, Icc);
-
- size -= 67;
+ for (i=0; i < 67; i++) {
+ size_t nread = Icc ->Read(&Dummy, sizeof(icUInt8Number), 1, Icc);
+ if (nread != 1) return (int) size;
+ size --;
+ }
}
break;
@@ -1425,7 +1591,7 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
size = size_max - 1;
}
- Icc -> Read(Name, 1, size, Icc);
+ if (Icc -> Read(Name, 1, size, Icc) != size) return -1;
for (i=0; i < Missing; i++)
Icc -> Read(&Dummy, 1, 1, Icc);
@@ -1445,9 +1611,9 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
wchar_t* wchar = L"";
- Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
+ if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
AdjustEndianess32((LPBYTE) &Count);
- Icc ->Read(&RecLen, sizeof(icUInt32Number), 1, Icc);
+ if (Icc ->Read(&RecLen, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
AdjustEndianess32((LPBYTE) &RecLen);
if (RecLen != 12) {
@@ -1458,15 +1624,15 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
for (i=0; i < Count; i++) {
- Icc ->Read(&Language, sizeof(icUInt16Number), 1, Icc);
+ if (Icc ->Read(&Language, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
AdjustEndianess16((LPBYTE) &Language);
- Icc ->Read(&Country, sizeof(icUInt16Number), 1, Icc);
+ if (Icc ->Read(&Country, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
AdjustEndianess16((LPBYTE) &Country);
- Icc ->Read(&ThisLen, sizeof(icUInt32Number), 1, Icc);
+ if (Icc ->Read(&ThisLen, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
AdjustEndianess32((LPBYTE) &ThisLen);
- Icc ->Read(&ThisOffset, sizeof(icUInt32Number), 1, Icc);
+ if (Icc ->Read(&ThisOffset, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
AdjustEndianess32((LPBYTE) &ThisOffset);
if (Language == GlobalLanguageCode || Offset == 0) {
@@ -1492,14 +1658,18 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
for (i=0; i < Offset; i++) {
char Discard;
-
- Icc ->Read(&Discard, 1, 1, Icc);
+ if (Icc ->Read(&Discard, 1, 1, Icc) != 1) return -1;
}
- wchar = (wchar_t*) malloc(Len+2);
+
+ // Bound len
+ if (Len < 0) Len = 0;
+ if (Len > 20*1024) Len = 20 * 1024;
+
+ wchar = (wchar_t*) _cmsMalloc(Len*sizeof(wchar_t)+2);
if (!wchar) return -1;
- Icc ->Read(wchar, 1, Len, Icc);
+ if (Icc ->Read(wchar, 1, Len, Icc) != Len) return -1;
AdjustEndianessArray16((LPWORD) wchar, Len / 2);
wchar[Len / 2] = L'\0';
@@ -1509,7 +1679,7 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
Name[0] = 0; // Error
}
- free((void*) wchar);
+ _cmsFree((void*) wchar);
}
break;
@@ -1522,8 +1692,7 @@ int ReadEmbeddedTextTag(LPLCMSICCPROFILE
}
-// Take an ASCII item. Takes at most LCMS_DESC_MAX
-
+// Take an ASCII item. Takes at most size_max bytes
int LCMSEXPORT cmsReadICCTextEx(cmsHPROFILE hProfile, icTagSignature sig, char *Name, size_t size_max)
{
@@ -1535,19 +1704,27 @@ int LCMSEXPORT cmsReadICCTextEx(cmsHPROF
if (n < 0)
return -1;
- if (!Icc -> stream) {
-
- CopyMemory(Name, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
+ size = Icc -> TagSizes[n];
+
+ if (Icc -> TagPtrs[n]) {
+
+ if (size > size_max)
+ size = size_max;
+
+ CopyMemory(Name, Icc -> TagPtrs[n], size);
+
return (int) Icc -> TagSizes[n];
}
offset = Icc -> TagOffsets[n];
- size = Icc -> TagSizes[n];
+
if (Icc -> Seek(Icc, offset))
return -1;
- return ReadEmbeddedTextTag(Icc, size, Name, size_max);
+ if (ReadEmbeddedTextTag(Icc, size, Name, size_max) < 0) return -1;
+
+ return size;
}
// Keep compatibility with older versions
@@ -1561,7 +1738,7 @@ int LCMSEXPORT cmsReadICCText(cmsHPROFIL
// Take an XYZ item
static
-int ReadICCXYZ(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIEXYZ Value, BOOL lIsFatal)
+int ReadICCXYZ(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIEXYZ Value, LCMSBOOL lIsFatal)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
icTagTypeSignature BaseType;
@@ -1573,7 +1750,7 @@ int ReadICCXYZ(cmsHPROFILE hProfile, icT
if (n < 0)
return -1;
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
CopyMemory(Value, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
return (int) Icc -> TagSizes[n];
@@ -1628,7 +1805,7 @@ int ReadICCXYZArray(cmsHPROFILE hProfile
if (n < 0)
return -1; // Not found
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
CopyMemory(v, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
return (int) Icc -> TagSizes[n];
@@ -1677,7 +1854,7 @@ int ReadICCXYZArray(cmsHPROFILE hProfile
// Primaries are to be in xyY notation
-BOOL LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile)
{
if (ReadICCXYZ(hProfile, icSigRedColorantTag, &Dest -> Red, TRUE) < 0) return FALSE;
if (ReadICCXYZ(hProfile, icSigGreenColorantTag, &Dest -> Green, TRUE) < 0) return FALSE;
@@ -1687,7 +1864,7 @@ BOOL LCMSEXPORT cmsTakeColorants(LPcmsCI
}
-BOOL cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile)
+LCMSBOOL cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile)
{
cmsCIEXYZTRIPLE Primaries;
@@ -1704,7 +1881,7 @@ BOOL cmsReadICCMatrixRGB2XYZ(LPMAT3 r, c
// Always return a suitable matrix
-BOOL cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile)
+LCMSBOOL cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile)
{
if (ReadICCXYZArray(hProfile, icSigChromaticAdaptationTag, r) < 0) {
@@ -1741,7 +1918,7 @@ LPGAMMATABLE LCMSEXPORT cmsReadICCGamma(
if (n < 0)
return NULL;
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
return cmsDupGamma((LPGAMMATABLE) Icc -> TagPtrs[n]);
}
@@ -1769,7 +1946,7 @@ LPGAMMATABLE LCMSEXPORT cmsReadICCGammaR
if (n < 0)
return NULL;
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
return cmsReverseGamma(256, (LPGAMMATABLE) Icc -> TagPtrs[n]);
}
@@ -1785,7 +1962,7 @@ LPGAMMATABLE LCMSEXPORT cmsReadICCGammaR
// Check Named color header
static
-BOOL CheckHeader(LPcmsNAMEDCOLORLIST v, icNamedColor2* nc2)
+LCMSBOOL CheckHeader(LPcmsNAMEDCOLORLIST v, icNamedColor2* nc2)
{
if (v ->Prefix[0] == 0 && v ->Suffix[0] == 0 && v ->ColorantCount == 0) return TRUE;
@@ -1809,13 +1986,13 @@ int cmsReadICCnamedColorList(cmsHTRANSFO
if (n < 0)
return 0;
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
// This replaces actual named color list.
size_t size = Icc -> TagSizes[n];
if (v ->NamedColorList) cmsFreeNamedColorList(v ->NamedColorList);
- v -> NamedColorList = (LPcmsNAMEDCOLORLIST) malloc(size);
+ v -> NamedColorList = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
CopyMemory(v -> NamedColorList, Icc ->TagPtrs[n], size);
return v ->NamedColorList->nColors;
}
@@ -1844,7 +2021,7 @@ int cmsReadICCnamedColorList(cmsHTRANSFO
icNamedColor2 nc2;
unsigned int i, j;
- Icc -> Read(&nc2, sizeof(icNamedColor2) - SIZEOF_UINT8_ALIGNED, 1, Icc);
+ if (Icc -> Read(&nc2, sizeof(icNamedColor2) - SIZEOF_UINT8_ALIGNED, 1, Icc) != 1) return 0;
AdjustEndianess32((LPBYTE) &nc2.vendorFlag);
AdjustEndianess32((LPBYTE) &nc2.count);
AdjustEndianess32((LPBYTE) &nc2.nDeviceCoords);
@@ -1854,6 +2031,11 @@ int cmsReadICCnamedColorList(cmsHTRANSFO
return 0;
}
+ if (nc2.nDeviceCoords > MAXCHANNELS) {
+ cmsSignalError(LCMS_ERRC_WARNING, "Too many device coordinates.");
+ return 0;
+ }
+
strncpy(v ->NamedColorList->Prefix, (const char*) nc2.prefix, 32);
strncpy(v ->NamedColorList->Suffix, (const char*) nc2.suffix, 32);
v ->NamedColorList->Prefix[32] = v->NamedColorList->Suffix[32] = 0;
@@ -1900,7 +2082,8 @@ int cmsReadICCnamedColorList(cmsHTRANSFO
LPcmsNAMEDCOLORLIST LCMSEXPORT cmsReadColorantTable(cmsHPROFILE hProfile, icTagSignature sig)
{
- icInt32Number n, Count, i;
+ icInt32Number n;
+ icUInt32Number Count, i;
size_t offset;
icTagTypeSignature BaseType;
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -1910,10 +2093,12 @@ LPcmsNAMEDCOLORLIST LCMSEXPORT cmsReadCo
if (n < 0)
return NULL; // Not found
- if (!Icc -> stream) {
+ if (Icc -> TagPtrs[n]) {
size_t size = Icc -> TagSizes[n];
- void* v = malloc(size);
+ void* v = _cmsMalloc(size);
+
+ if (v == NULL) return NULL;
CopyMemory(v, Icc -> TagPtrs[n], size);
return (LPcmsNAMEDCOLORLIST) v;
}
@@ -1932,12 +2117,16 @@ LPcmsNAMEDCOLORLIST LCMSEXPORT cmsReadCo
}
- Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
+ if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
AdjustEndianess32((LPBYTE) &Count);
+
+ if (Count > MAXCHANNELS) {
+ cmsSignalError(LCMS_ERRC_ABORTED, "Too many colorants '%lx'", Count);
+ return NULL;
+ }
List = cmsAllocNamedColorList(Count);
for (i=0; i < Count; i++) {
-
if (!Icc ->Read(List->List[i].Name, 1, 32 , Icc)) goto Error;
if (!Icc ->Read(List->List[i].PCS, sizeof(icUInt16Number), 3, Icc)) goto Error;
@@ -1965,7 +2154,7 @@ const char* LCMSEXPORT cmsTakeManufactur
if (cmsIsTag(hProfile, icSigDeviceMfgDescTag)) {
- cmsReadICCText(hProfile, icSigDeviceMfgDescTag, Manufacturer);
+ cmsReadICCTextEx(hProfile, icSigDeviceMfgDescTag, Manufacturer, LCMS_DESC_MAX);
}
return Manufacturer;
@@ -1982,7 +2171,7 @@ const char* LCMSEXPORT cmsTakeModel(cmsH
if (cmsIsTag(hProfile, icSigDeviceModelDescTag)) {
- cmsReadICCText(hProfile, icSigDeviceModelDescTag, Model);
+ cmsReadICCTextEx(hProfile, icSigDeviceModelDescTag, Model, LCMS_DESC_MAX);
}
return Model;
@@ -1995,10 +2184,9 @@ const char* LCMSEXPORT cmsTakeCopyright(
static char Copyright[LCMS_DESC_MAX] = "";
Copyright[0] = 0;
-
if (cmsIsTag(hProfile, icSigCopyrightTag)) {
- cmsReadICCText(hProfile, icSigCopyrightTag, Copyright);
+ cmsReadICCTextEx(hProfile, icSigCopyrightTag, Copyright, LCMS_DESC_MAX);
}
return Copyright;
@@ -2009,7 +2197,7 @@ const char* LCMSEXPORT cmsTakeCopyright(
const char* LCMSEXPORT cmsTakeProductName(cmsHPROFILE hProfile)
{
- static char Name[2048];
+ static char Name[LCMS_DESC_MAX*2+4];
char Manufacturer[LCMS_DESC_MAX], Model[LCMS_DESC_MAX];
Name[0] = '\0';
@@ -2017,19 +2205,19 @@ const char* LCMSEXPORT cmsTakeProductNa
if (cmsIsTag(hProfile, icSigDeviceMfgDescTag)) {
- cmsReadICCText(hProfile, icSigDeviceMfgDescTag, Manufacturer);
+ cmsReadICCTextEx(hProfile, icSigDeviceMfgDescTag, Manufacturer, LCMS_DESC_MAX);
}
if (cmsIsTag(hProfile, icSigDeviceModelDescTag)) {
- cmsReadICCText(hProfile, icSigDeviceModelDescTag, Model);
+ cmsReadICCTextEx(hProfile, icSigDeviceModelDescTag, Model, LCMS_DESC_MAX);
}
if (!Manufacturer[0] && !Model[0]) {
if (cmsIsTag(hProfile, icSigProfileDescriptionTag)) {
- cmsReadICCText(hProfile, icSigProfileDescriptionTag, Name);
+ cmsReadICCTextEx(hProfile, icSigProfileDescriptionTag, Name, LCMS_DESC_MAX);
return Name;
}
else return "{no name}";
@@ -2129,7 +2317,7 @@ const char* LCMSEXPORT cmsTakeProductIn
// Extract the target data as a big string. Does not signal if tag is not present.
-BOOL LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len)
+LCMSBOOL LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
int n;
@@ -2142,7 +2330,11 @@ BOOL LCMSEXPORT cmsTakeCharTargetData(cm
*len = Icc -> TagSizes[n];
- *Data = (char*) malloc(*len + 1); // Plus zero marker
+
+ // Make sure that is reasonable (600K)
+ if (*len > 600*1024) *len = 600*1024;
+
+ *Data = (char*) _cmsMalloc(*len + 1); // Plus zero marker
if (!*Data) {
@@ -2162,7 +2354,7 @@ BOOL LCMSEXPORT cmsTakeCharTargetData(cm
-BOOL LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
int n;
@@ -2170,8 +2362,8 @@ BOOL LCMSEXPORT cmsTakeCalibrationDateTi
n = _cmsSearchTag(Icc, icSigCalibrationDateTimeTag, FALSE);
if (n < 0) return FALSE;
- if (!Icc ->stream)
- {
+ if (Icc ->TagPtrs[n]) {
+
CopyMemory(Dest, Icc ->TagPtrs[n], sizeof(struct tm));
}
else
@@ -2212,9 +2404,10 @@ LPcmsSEQ LCMSEXPORT cmsReadProfileSequen
size = Icc -> TagSizes[n];
if (size < 12) return NULL;
- if (!Icc -> stream) {
-
- OutSeq = (LPcmsSEQ) malloc(size);
+ if (Icc -> TagPtrs[n]) {
+
+ OutSeq = (LPcmsSEQ) _cmsMalloc(size);
+ if (OutSeq == NULL) return NULL;
CopyMemory(OutSeq, Icc ->TagPtrs[n], size);
return OutSeq;
}
@@ -2231,8 +2424,13 @@ LPcmsSEQ LCMSEXPORT cmsReadProfileSequen
Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
AdjustEndianess32((LPBYTE) &Count);
+ if (Count > 1000) {
+ return NULL;
+ }
+
size = sizeof(int) + Count * sizeof(cmsPSEQDESC);
- OutSeq = (LPcmsSEQ) malloc(size);
+ OutSeq = (LPcmsSEQ) _cmsMalloc(size);
+ if (OutSeq == NULL) return NULL;
OutSeq ->n = Count;
@@ -2268,181 +2466,11 @@ void LCMSEXPORT cmsFreeProfileSequenceDe
void LCMSEXPORT cmsFreeProfileSequenceDescription(LPcmsSEQ pseq)
{
if (pseq)
- free(pseq);
-}
-
-
-
-// Extended gamut -- an HP extension
-
-
-LPcmsGAMUTEX LCMSEXPORT cmsReadExtendedGamut(cmsHPROFILE hProfile, int index)
-{
- LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
- size_t size, offset;
- icUInt32Number off_samp, off_desc, off_vc;
- int n;
- icTagTypeSignature BaseType;
- icColorSpaceSignature CoordSig;
- icUInt16Number Method, Usage;
- icUInt32Number GamutCount, SamplesCount;
- LPcmsGAMUTEX gex;
- size_t Offsets[256];
- size_t i, Actual, Loc;
- icS15Fixed16Number Num;
- icUInt16Number Surround;
-
-
- n = _cmsSearchTag(Icc, icSigHPGamutDescTag, FALSE);
- if (n < 0) return NULL;
-
- if (!Icc ->stream) return NULL; // In memory is not supported
-
- // Read the header
-
- offset = Icc -> TagOffsets[n];
-
- if (Icc -> Seek(Icc, offset))
- return NULL;
-
- // Here is the beginning of tag
- Actual = Icc ->Tell(Icc);
-
-
- BaseType = ReadBase(Icc);
-
- if (BaseType != icSigHPGamutDescType) {
- cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature '%lx' found.", BaseType);
- return NULL;
- }
-
-
- // Read the gamut descriptors count
- Icc ->Read(&GamutCount, sizeof(icUInt32Number), 1, Icc);
- AdjustEndianess32((LPBYTE) &GamutCount);
-
-
- if (GamutCount >= 256) {
- cmsSignalError(LCMS_ERRC_ABORTED, "Too many gamut structures '%d'.", GamutCount);
- return NULL;
- }
-
- // Read the directory
-
- for (i=0; i < GamutCount; i++) {
-
- Icc ->Read(&Offsets[i], sizeof(icUInt32Number), 1, Icc);
- AdjustEndianess32((LPBYTE) &Offsets[i]);
- }
-
-
- // Is there such element?
- if (index >= (int) GamutCount) return NULL;
- Loc = Actual + Offsets[index];
-
-
- // Go to specified index
- if (Icc -> Seek(Icc, Loc))
- return NULL;
-
-
- // Read all members
- Icc ->Read(&CoordSig, sizeof(icColorSpaceSignature), 1, Icc);
- AdjustEndianess32((LPBYTE) &CoordSig);
-
- Icc ->Read(&Method, sizeof(icUInt16Number), 1, Icc);
- AdjustEndianess16((LPBYTE) &Method);
-
- Icc ->Read(&Usage, sizeof(icUInt16Number), 1, Icc);
- AdjustEndianess16((LPBYTE) &Usage);
-
- Icc ->Read(&SamplesCount, sizeof(icUInt32Number), 1, Icc);
- AdjustEndianess32((LPBYTE) &SamplesCount);
-
- Icc ->Read(&off_samp, sizeof(icUInt32Number), 1, Icc);
- AdjustEndianess32((LPBYTE) &off_samp);
-
- Icc ->Read(&off_desc, sizeof(icUInt32Number), 1, Icc);
- AdjustEndianess32((LPBYTE) &off_desc);
-
- Icc ->Read(&off_vc, sizeof(icUInt32Number), 1, Icc);
- AdjustEndianess32((LPBYTE) &off_vc);
-
-
- size = sizeof(cmsGAMUTEX) + (SamplesCount - 1) * sizeof(double);
-
- gex = (LPcmsGAMUTEX) malloc(size);
- if (gex == NULL) return NULL;
-
-
- gex ->CoordSig = CoordSig;
- gex ->Method = Method;
- gex ->Usage = Usage;
- gex ->Count = SamplesCount;
-
-
- // Read data
- if (Icc -> Seek(Icc, Loc + off_samp))
- return NULL;
-
- for (i=0; i < SamplesCount; i++) {
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Data[i] = Convert15Fixed16(Num);
- }
-
-
- // Read mluc
- if (Icc -> Seek(Icc, Loc + off_desc)) {
-
- free(gex);
- return NULL;
- }
-
- ReadEmbeddedTextTag(Icc, 256, gex ->Description, LCMS_DESC_MAX);
-
-
- // Read viewing conditions
- if (Icc -> Seek(Icc, Loc + off_vc)) {
- free(gex);
- return NULL;
- }
-
-
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Vc.whitePoint.X = Convert15Fixed16(Num);
-
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Vc.whitePoint.Y = Convert15Fixed16(Num);
-
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Vc.whitePoint.Z = Convert15Fixed16(Num);
-
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Vc.La = Convert15Fixed16(Num);
-
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Vc.Yb = Convert15Fixed16(Num);
-
- Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
- gex ->Vc.D_value = Convert15Fixed16(Num);
-
- Icc -> Read(&Surround, sizeof(icUInt16Number), 1, Icc);
- AdjustEndianess16((LPBYTE) &Surround);
- gex ->Vc.surround = Surround;
-
-
- // All OK
- return gex;
-
-}
-
-
-
-void LCMSEXPORT cmsFreeExtendedGamut(LPcmsGAMUTEX gex)
-{
- if (gex)
- free(gex);
-}
+ _cmsFree(pseq);
+}
+
+
+
// Read a few tags that are hardly required
@@ -2564,6 +2592,7 @@ cmsHPROFILE LCMSEXPORT cmsOpenProfileFro
NewIcc = (LPLCMSICCPROFILE) (LPSTR) hEmpty;
NewIcc -> IsWrite = TRUE;
strncpy(NewIcc ->PhysicalFile, lpFileName, MAX_PATH-1);
+ NewIcc ->PhysicalFile[MAX_PATH-1] = 0;
// Save LUT as 8 bit
@@ -2609,13 +2638,13 @@ cmsHPROFILE LCMSEXPORT cmsOpenProfileFro
-BOOL LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
- BOOL rc = TRUE;
+ LCMSBOOL rc = TRUE;
+ icInt32Number i;
if (!Icc) return FALSE;
-
// Was open in write mode?
if (Icc ->IsWrite) {
@@ -2624,21 +2653,15 @@ BOOL LCMSEXPORT cmsCloseProfile(cmsHPROF
rc = _cmsSaveProfile(hProfile, Icc ->PhysicalFile);
}
-
- if (Icc -> stream == NULL) { // Was a memory (i.e. not serialized) profile?
-
-
- icInt32Number i; // Yes, free tags
-
- for (i=0; i < Icc -> TagCount; i++) {
+ for (i=0; i < Icc -> TagCount; i++) {
if (Icc -> TagPtrs[i])
free(Icc -> TagPtrs[i]);
- }
-
- }
- else Icc -> Close(Icc); // No, close the stream
-
+ }
+
+ if (Icc -> stream != NULL) { // Was a memory (i.e. not serialized) profile?
+ Icc -> Close(Icc); // No, close the stream
+ }
free(Icc); // Free placeholder memory
@@ -2652,11 +2675,11 @@ BOOL LCMSEXPORT cmsCloseProfile(cmsHPROF
static
-BOOL SaveWordsTable(int nEntries, LPWORD Tab, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveWordsTable(int nEntries, LPWORD Tab, LPLCMSICCPROFILE Icc)
{
size_t nTabSize = sizeof(WORD) * nEntries;
- LPWORD PtrW = (LPWORD) malloc(nTabSize);
- BOOL rc;
+ LPWORD PtrW = (LPWORD) _cmsMalloc(nTabSize);
+ LCMSBOOL rc;
if (!PtrW) return FALSE;
CopyMemory(PtrW, Tab, nTabSize);
@@ -2672,7 +2695,7 @@ BOOL SaveWordsTable(int nEntries, LPWORD
// Saves profile header
static
-BOOL SaveHeader(LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveHeader(LPLCMSICCPROFILE Icc)
{
icHeader Header;
time_t now = time(NULL);
@@ -2727,7 +2750,7 @@ BOOL SaveHeader(LPLCMSICCPROFILE Icc)
// Setup base marker
static
-BOOL SetupBase(icTagTypeSignature sig, LPLCMSICCPROFILE Icc)
+LCMSBOOL SetupBase(icTagTypeSignature sig, LPLCMSICCPROFILE Icc)
{
icTagBase Base;
@@ -2737,10 +2760,10 @@ BOOL SetupBase(icTagTypeSignature sig, L
}
-// Store an XYZ tag
-
-static
-BOOL SaveXYZNumber(LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
+// Store a XYZ tag
+
+static
+LCMSBOOL SaveXYZNumber(LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
{
icXYZNumber XYZ;
@@ -2756,102 +2779,127 @@ BOOL SaveXYZNumber(LPcmsCIEXYZ Value, LP
}
+// Store a XYZ array.
+
+static
+LCMSBOOL SaveXYZArray(int n, LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
+{
+ int i;
+ icXYZNumber XYZ;
+
+ if (!SetupBase(icSigS15Fixed16ArrayType, Icc)) return FALSE;
+
+ for (i=0; i < n; i++) {
+
+ XYZ.X = TransportValue32(DOUBLE_TO_FIXED(Value -> X));
+ XYZ.Y = TransportValue32(DOUBLE_TO_FIXED(Value -> Y));
+ XYZ.Z = TransportValue32(DOUBLE_TO_FIXED(Value -> Z));
+
+ if (!Icc -> Write(Icc, sizeof(icXYZNumber), &XYZ)) return FALSE;
+
+ Value++;
+ }
+
+ return TRUE;
+}
+
+
// Save a gamma structure as a table
static
-BOOL SaveGammaTable(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
- icInt32Number Count;
-
- if (!SetupBase(icSigCurveType, Icc)) return FALSE;
-
- Count = TransportValue32(Gamma->nEntries);
-
- if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
-
- return SaveWordsTable(Gamma->nEntries, Gamma ->GammaTable, Icc);
+LCMSBOOL SaveGammaTable(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+{
+ icInt32Number Count;
+
+ if (!SetupBase(icSigCurveType, Icc)) return FALSE;
+
+ Count = TransportValue32(Gamma->nEntries);
+
+ if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
+
+ return SaveWordsTable(Gamma->nEntries, Gamma ->GammaTable, Icc);
}
// Save a gamma structure as a one-value
static
-BOOL SaveGammaOneValue(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
- icInt32Number Count;
- Fixed32 GammaFixed32;
- WORD GammaFixed8;
-
- if (!SetupBase(icSigCurveType, Icc)) return FALSE;
-
- Count = TransportValue32(1);
- if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
-
- GammaFixed32 = DOUBLE_TO_FIXED(Gamma ->Seed.Params[0]);
- GammaFixed8 = (WORD) ((GammaFixed32 >> 8) & 0xFFFF);
- GammaFixed8 = TransportValue16(GammaFixed8);
-
- return Icc ->Write(Icc, sizeof(icInt16Number), &GammaFixed8);
+LCMSBOOL SaveGammaOneValue(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+{
+ icInt32Number Count;
+ Fixed32 GammaFixed32;
+ WORD GammaFixed8;
+
+ if (!SetupBase(icSigCurveType, Icc)) return FALSE;
+
+ Count = TransportValue32(1);
+ if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
+
+ GammaFixed32 = DOUBLE_TO_FIXED(Gamma ->Seed.Params[0]);
+ GammaFixed8 = (WORD) ((GammaFixed32 >> 8) & 0xFFFF);
+ GammaFixed8 = TransportValue16(GammaFixed8);
+
+ return Icc ->Write(Icc, sizeof(icInt16Number), &GammaFixed8);
}
// Save a gamma structure as a parametric gamma
static
-BOOL SaveGammaParametric(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
- icUInt16Number Type, Reserved;
- int i, nParams;
- int ParamsByType[] = { 1, 3, 4, 5, 7 };
-
- if (!SetupBase(icSigParametricCurveType, Icc)) return FALSE;
-
- nParams = ParamsByType[Gamma -> Seed.Type];
-
- Type = (icUInt16Number) TransportValue16((WORD) Gamma -> Seed. Type);
- Reserved = (icUInt16Number) TransportValue16((WORD) 0);
-
- Icc -> Write(Icc, sizeof(icInt16Number), &Type);
- Icc -> Write(Icc, sizeof(icUInt16Number), &Reserved);
-
- for (i=0; i < nParams; i++) {
-
- icInt32Number val = TransportValue32(DOUBLE_TO_FIXED(Gamma -> Seed.Params[i]));
- Icc ->Write(Icc, sizeof(icInt32Number), &val);
+LCMSBOOL SaveGammaParametric(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+{
+ icUInt16Number Type, Reserved;
+ int i, nParams;
+ int ParamsByType[] = { 1, 3, 4, 5, 7 };
+
+ if (!SetupBase(icSigParametricCurveType, Icc)) return FALSE;
+
+ nParams = ParamsByType[Gamma -> Seed.Type];
+
+ Type = (icUInt16Number) TransportValue16((WORD) Gamma -> Seed. Type);
+ Reserved = (icUInt16Number) TransportValue16((WORD) 0);
+
+ Icc -> Write(Icc, sizeof(icInt16Number), &Type);
+ Icc -> Write(Icc, sizeof(icUInt16Number), &Reserved);
+
+ for (i=0; i < nParams; i++) {
+
+ icInt32Number val = TransportValue32(DOUBLE_TO_FIXED(Gamma -> Seed.Params[i]));
+ Icc ->Write(Icc, sizeof(icInt32Number), &val);
+ }
+
+
+ return TRUE;
+
+}
+
+
+// Save a gamma table
+
+static
+LCMSBOOL SaveGamma(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+{
+ // Is the gamma curve type supported by ICC format?
+
+ if (Gamma -> Seed.Type < 0 || Gamma -> Seed.Type > 5 ||
+
+ // has been modified by user?
+
+ _cmsCrc32OfGammaTable(Gamma) != Gamma -> Seed.Crc32) {
+
+ return SaveGammaTable(Gamma, Icc);
}
-
- return TRUE;
-
-}
-
-
-// Save a gamma table
-
-static
-BOOL SaveGamma(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
- // Is the gamma curve type supported by ICC format?
-
- if (Gamma -> Seed.Type < 0 || Gamma -> Seed.Type > 5 ||
-
- // has been modified by user?
-
- _cmsCrc32OfGammaTable(Gamma) != Gamma -> Seed.Crc32) {
-
- return SaveGammaTable(Gamma, Icc);
- }
-
- if (Gamma -> Seed.Type == 1) return SaveGammaOneValue(Gamma, Icc);
-
- // Only v4 profiles are allowed to hold parametric curves
-
- if (cmsGetProfileICCversion((cmsHPROFILE) Icc) >= 0x4000000)
- return SaveGammaParametric(Gamma, Icc);
-
- // Defaults to save as table
-
- return SaveGammaTable(Gamma, Icc);
+ if (Gamma -> Seed.Type == 1) return SaveGammaOneValue(Gamma, Icc);
+
+ // Only v4 profiles are allowed to hold parametric curves
+
+ if (cmsGetProfileICCversion((cmsHPROFILE) Icc) >= 0x4000000)
+ return SaveGammaParametric(Gamma, Icc);
+
+ // Defaults to save as table
+
+ return SaveGammaTable(Gamma, Icc);
}
@@ -2861,7 +2909,7 @@ BOOL SaveGamma(LPGAMMATABLE Gamma, LPLCM
// Save an DESC Tag
static
-BOOL SaveDescription(const char *Text, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveDescription(const char *Text, LPLCMSICCPROFILE Icc)
{
icUInt32Number len, Count, TotalSize, AlignedSize;
@@ -2893,6 +2941,11 @@ BOOL SaveDescription(const char *Text, L
if (!Icc ->Write(Icc, len, (LPVOID)Text)) return FALSE;
AlignedSize -= len;
+ if (AlignedSize < 0)
+ AlignedSize = 0;
+ if (AlignedSize > 255)
+ AlignedSize = 255;
+
ZeroMemory(Filler, AlignedSize);
if (!Icc ->Write(Icc, AlignedSize, Filler)) return FALSE;
@@ -2902,7 +2955,7 @@ BOOL SaveDescription(const char *Text, L
// Save an ASCII Tag
static
-BOOL SaveText(const char *Text, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveText(const char *Text, LPLCMSICCPROFILE Icc)
{
size_t len = strlen(Text) + 1;
@@ -2915,7 +2968,7 @@ BOOL SaveText(const char *Text, LPLCMSIC
// Save one of these new chromaticity values
static
-BOOL SaveOneChromaticity(double x, double y, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveOneChromaticity(double x, double y, LPLCMSICCPROFILE Icc)
{
Fixed32 xf, yf;
@@ -2932,7 +2985,7 @@ BOOL SaveOneChromaticity(double x, doubl
// New tag added in Addendum II of old spec.
static
-BOOL SaveChromaticities(LPcmsCIExyYTRIPLE chrm, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveChromaticities(LPcmsCIExyYTRIPLE chrm, LPLCMSICCPROFILE Icc)
{
WORD nChans, Table;
@@ -2952,7 +3005,7 @@ BOOL SaveChromaticities(LPcmsCIExyYTRIPL
static
-BOOL SaveSequenceDescriptionTag(LPcmsSEQ seq, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveSequenceDescriptionTag(LPcmsSEQ seq, LPLCMSICCPROFILE Icc)
{
icUInt32Number nSeqs;
icDescStruct DescStruct;
@@ -2989,7 +3042,7 @@ BOOL SaveSequenceDescriptionTag(LPcmsSEQ
// Saves a timestamp tag
static
-BOOL SaveDateTimeNumber(const struct tm *DateTime, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveDateTimeNumber(const struct tm *DateTime, LPLCMSICCPROFILE Icc)
{
icDateTimeNumber Dest;
@@ -3003,14 +3056,14 @@ BOOL SaveDateTimeNumber(const struct tm
// Saves a named color list into a named color profile
static
-BOOL SaveNamedColorList(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveNamedColorList(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
{
icUInt32Number vendorFlag; // Bottom 16 bits for IC use
icUInt32Number count; // Count of named colors
icUInt32Number nDeviceCoords; // Num of device coordinates
- icInt8Number prefix[32]; // Prefix for each color name
- icInt8Number suffix[32]; // Suffix for each color name
+ char prefix[32]; // Prefix for each color name
+ char suffix[32]; // Suffix for each color name
int i;
if (!SetupBase(icSigNamedColor2Type, Icc)) return FALSE;
@@ -3019,8 +3072,10 @@ BOOL SaveNamedColorList(LPcmsNAMEDCOLORL
count = TransportValue32(NamedColorList ->nColors);
nDeviceCoords = TransportValue32(NamedColorList ->ColorantCount);
- strncpy(prefix, (const char*) NamedColorList->Prefix, 32);
- strncpy(suffix, (const char*) NamedColorList->Suffix, 32);
+ strncpy(prefix, (const char*) NamedColorList->Prefix, 31);
+ strncpy(suffix, (const char*) NamedColorList->Suffix, 31);
+
+ suffix[31] = prefix[31] = 0;
if (!Icc ->Write(Icc, sizeof(icUInt32Number), &vendorFlag)) return FALSE;
if (!Icc ->Write(Icc, sizeof(icUInt32Number), &count)) return FALSE;
@@ -3030,15 +3085,17 @@ BOOL SaveNamedColorList(LPcmsNAMEDCOLORL
for (i=0; i < NamedColorList ->nColors; i++) {
- icUInt16Number PCS[3];
- icUInt16Number Colorant[MAXCHANNELS];
- icInt8Number root[32];
+ icUInt16Number PCS[3];
+ icUInt16Number Colorant[MAXCHANNELS];
+ char root[32];
LPcmsNAMEDCOLOR Color;
int j;
Color = NamedColorList ->List + i;
- strncpy((char*) root, Color ->Name, 32);
+ strncpy(root, Color ->Name, 32);
+ Color ->Name[32] = 0;
+
if (!Icc ->Write(Icc, 32 , root)) return FALSE;
for (j=0; j < 3; j++)
@@ -3062,7 +3119,7 @@ BOOL SaveNamedColorList(LPcmsNAMEDCOLORL
// Saves a colorant table. It is using the named color structure for simplicity sake
static
-BOOL SaveColorantTable(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveColorantTable(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
{
icUInt32Number count; // Count of named colors
int i;
@@ -3076,13 +3133,15 @@ BOOL SaveColorantTable(LPcmsNAMEDCOLORLI
for (i=0; i < NamedColorList ->nColors; i++) {
icUInt16Number PCS[3];
- icInt8Number root[32];
+ icInt8Number root[33];
LPcmsNAMEDCOLOR Color;
int j;
Color = NamedColorList ->List + i;
strncpy((char*) root, Color ->Name, 32);
+ root[32] = 0;
+
if (!Icc ->Write(Icc, 32 , root)) return FALSE;
for (j=0; j < 3; j++)
@@ -3099,7 +3158,7 @@ BOOL SaveColorantTable(LPcmsNAMEDCOLORLI
// Does serialization of LUT16 and writes it.
static
-BOOL SaveLUT(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveLUT(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
{
icLut16 LUT16;
unsigned int i;
@@ -3189,7 +3248,7 @@ BOOL SaveLUT(const LUT* NewLUT, LPLCMSIC
// Does serialization of LUT8 and writes it
static
-BOOL SaveLUT8(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveLUT8(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
{
icLut8 LUT8;
unsigned int i, j;
@@ -3323,7 +3382,7 @@ void LCMSEXPORT _cmsSetLUTdepth(cmsHPROF
// Saves Tag directory
static
-BOOL SaveTagDirectory(LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveTagDirectory(LPLCMSICCPROFILE Icc)
{
icInt32Number i;
icTag Tag;
@@ -3356,7 +3415,7 @@ BOOL SaveTagDirectory(LPLCMSICCPROFILE I
// Dump tag contents
static
-BOOL SaveTags(LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveTags(LPLCMSICCPROFILE Icc, LPLCMSICCPROFILE FileOrig)
{
LPBYTE Data;
@@ -3384,8 +3443,31 @@ BOOL SaveTags(LPLCMSICCPROFILE Icc)
Icc -> TagOffsets[i] = Begin = Icc ->UsedSpace;
Data = (LPBYTE) Icc -> TagPtrs[i];
- if (!Data)
+ if (!Data) {
+
+ // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
+ // In this case a blind copy of the block data is performed
+
+ if (Icc -> TagOffsets[i]) {
+
+ size_t TagSize = FileOrig -> TagSizes[i];
+ size_t TagOffset = FileOrig -> TagOffsets[i];
+ void* Mem;
+
+ if (FileOrig ->Seek(FileOrig, TagOffset)) return FALSE;
+
+ Mem = _cmsMalloc(TagSize);
+
+ if (FileOrig ->Read(Mem, TagSize, 1, FileOrig) != 1) return FALSE;
+ if (!Icc ->Write(Icc, TagSize, Mem)) return FALSE;
+
+ Icc -> TagSizes[i] = (Icc ->UsedSpace - Begin);
+ free(Mem);
+ }
+
continue;
+ }
+
switch (Icc -> TagNames[i]) {
@@ -3464,6 +3546,10 @@ BOOL SaveTags(LPLCMSICCPROFILE Icc)
break;
+ case icSigChromaticAdaptationTag:
+ if (!SaveXYZArray(3, (LPcmsCIEXYZ) Data, Icc)) return FALSE;
+ break;
+
default:
return FALSE;
}
@@ -3480,9 +3566,9 @@ BOOL SaveTags(LPLCMSICCPROFILE Icc)
// Add tags to profile structure
-BOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* Tag)
-{
- BOOL rc;
+LCMSBOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* Tag)
+{
+ LCMSBOOL rc;
switch (sig) {
@@ -3543,6 +3629,11 @@ BOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hP
rc = _cmsAddColorantTableTag(hProfile, sig, (LPcmsNAMEDCOLORLIST) Tag);
break;
+
+ case icSigChromaticAdaptationTag:
+ rc = _cmsAddChromaticAdaptationTag(hProfile, sig, (const cmsCIEXYZ*) Tag);
+ break;
+
default:
cmsSignalError(LCMS_ERRC_ABORTED, "cmsAddTag: Tag '%x' is unsupported", sig);
return FALSE;
@@ -3568,11 +3659,11 @@ BOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hP
// Low-level save to disk. It closes the profile on exit
-BOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName)
+LCMSBOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
LCMSICCPROFILE Keep;
- BOOL rc;
+ LCMSBOOL rc;
CopyMemory(&Keep, Icc, sizeof(LCMSICCPROFILE));
_cmsSetSaveToDisk(Icc, NULL);
@@ -3581,7 +3672,7 @@ BOOL LCMSEXPORT _cmsSaveProfile(cmsHPROF
if (!SaveHeader(Icc)) return FALSE;
if (!SaveTagDirectory(Icc)) return FALSE;
- if (!SaveTags(Icc)) return FALSE;
+ if (!SaveTags(Icc, &Keep)) return FALSE;
_cmsSetSaveToDisk(Icc, FileName);
@@ -3591,7 +3682,7 @@ BOOL LCMSEXPORT _cmsSaveProfile(cmsHPROF
if (!SaveHeader(Icc)) goto CleanUp;
if (!SaveTagDirectory(Icc)) goto CleanUp;
- if (!SaveTags(Icc)) goto CleanUp;
+ if (!SaveTags(Icc, &Keep)) goto CleanUp;
rc = (Icc ->Close(Icc) == 0);
CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
@@ -3608,7 +3699,7 @@ BOOL LCMSEXPORT _cmsSaveProfile(cmsHPROF
// Low-level save from open stream
-BOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
+LCMSBOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
size_t* BytesNeeded)
{
LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -3623,20 +3714,20 @@ BOOL LCMSEXPORT _cmsSaveProfileToMem(cms
if (!SaveHeader(Icc)) return FALSE;
if (!SaveTagDirectory(Icc)) return FALSE;
- if (!SaveTags(Icc)) return FALSE;
+ if (!SaveTags(Icc, &Keep)) return FALSE;
if (!MemPtr) {
// update BytesSaved so caller knows how many bytes are needed for MemPtr
*BytesNeeded = Icc ->UsedSpace;
- CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
+ CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
return TRUE;
}
if (*BytesNeeded < Icc ->UsedSpace) {
// need at least UsedSpace in MemPtr to continue
- CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
+ CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
return FALSE;
}
@@ -3646,7 +3737,7 @@ BOOL LCMSEXPORT _cmsSaveProfileToMem(cms
// Pass #2 does save to file into supplied stream
if (!SaveHeader(Icc)) goto CleanUp;
if (!SaveTagDirectory(Icc)) goto CleanUp;
- if (!SaveTags(Icc)) goto CleanUp;
+ if (!SaveTags(Icc, &Keep)) goto CleanUp;
// update BytesSaved so caller knows how many bytes put into stream
*BytesNeeded = Icc ->UsedSpace;
@@ -3661,3 +3752,4 @@ CleanUp:
CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
return FALSE;
}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmslut.c Thu Mar 19 13:25:35 2009 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmslut.c Tue Mar 24 19:12:02 2009 -0700
@@ -29,7 +29,7 @@
//
//
// Little cms
-// Copyright (C) 1998-2006 Marti Maria
+// Copyright (C) 1998-2007 Marti Maria
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -118,7 +118,7 @@ LPLUT LCMSEXPORT cmsAllocLUT(void)
{
LPLUT NewLUT;
- NewLUT = (LPLUT) malloc(sizeof(LUT));
+ NewLUT = (LPLUT) _cmsMalloc(sizeof(LUT));
if (NewLUT)
ZeroMemory(NewLUT, sizeof(LUT));
@@ -171,9 +171,10 @@ static
static
LPVOID DupBlockTab(LPVOID Org, size_t size)
{
- LPVOID mem = malloc(size);
-
- CopyMemory(mem, Org, size);
+ LPVOID mem = _cmsMalloc(size);
+ if (mem != NULL)
+ CopyMemory(mem, Org, size);
+
return mem;
}
@@ -210,6 +211,37 @@ unsigned int UIpow(unsigned int a, unsig
return rv;
}
+
+LCMSBOOL _cmsValidateLUT(LPLUT NewLUT)
+{
+ unsigned int calc = 1;
+ unsigned int oldCalc;
+ unsigned int power = NewLUT -> InputChan;
+
+ if (NewLUT -> cLutPoints > 100) return FALSE;
+ if (NewLUT -> InputChan > MAXCHANNELS) return FALSE;
+ if (NewLUT -> OutputChan > MAXCHANNELS) return FALSE;
+
+ if (NewLUT -> cLutPoints == 0) return TRUE;
+
+ for (; power > 0; power--) {
+
+ oldCalc = calc;
+ calc *= NewLUT -> cLutPoints;
+
+ if (calc / NewLUT -> cLutPoints != oldCalc) {
+ return FALSE;
+ }
+ }
+
+ oldCalc = calc;
+ calc *= NewLUT -> OutputChan;
+ if (NewLUT -> OutputChan && calc / NewLUT -> OutputChan != oldCalc) {
+ return FALSE;
+ }
+
+ return TRUE;
+}
LPLUT LCMSEXPORT cmsAlloc3DGrid(LPLUT NewLUT, int clutPoints, int inputChan, int outputChan)
{
@@ -220,12 +252,17 @@ LPLUT LCMSEXPORT cmsAlloc3DGrid(LPLUT Ne
NewLUT -> InputChan = inputChan;
NewLUT -> OutputChan = outputChan;
-
- nTabSize = (NewLUT -> OutputChan * UIpow(NewLUT->cLutPoints,
- NewLUT->InputChan)
- * sizeof(WORD));
-
- NewLUT -> T = (LPWORD) malloc(nTabSize);
+ if (!_cmsValidateLUT(NewLUT)) {
+ return NULL;
+ }
+
+ nTabSize = NewLUT -> OutputChan * UIpow(NewLUT->cLutPoints,
+ NewLUT->InputChan);
+
+ NewLUT -> T = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
+ nTabSize *= sizeof(WORD);
+ if (NewLUT -> T == NULL) return NULL;
+
ZeroMemory(NewLUT -> T, nTabSize);
NewLUT ->Tsize = nTabSize;
@@ -254,10 +291,12 @@ LPLUT LCMSEXPORT cmsAllocLinearTable(LPL
for (i=0; i < NewLUT -> InputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> InputEntries);
+ PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> InputEntries);
+ if (PtrW == NULL) return NULL;
+
NewLUT -> L1[i] = PtrW;
CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> InputEntries);
- CopyMemory(&NewLUT -> LCurvesSeed[0][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
+ CopyMemory(&NewLUT -> LCurvesSeed[0][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
}
@@ -268,10 +307,12 @@ LPLUT LCMSEXPORT cmsAllocLinearTable(LPL
NewLUT -> OutputEntries = Tables[0] -> nEntries;
for (i=0; i < NewLUT -> OutputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> OutputEntries);
+ PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> OutputEntries);
+ if (PtrW == NULL) return NULL;
+
NewLUT -> L2[i] = PtrW;
CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> OutputEntries);
- CopyMemory(&NewLUT -> LCurvesSeed[1][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
+ CopyMemory(&NewLUT -> LCurvesSeed[1][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
}
break;
@@ -285,10 +326,12 @@ LPLUT LCMSEXPORT cmsAllocLinearTable(LPL
for (i=0; i < NewLUT -> InputChan; i++) {
- PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> L3Entries);
+