提交 715d17e7 编写于 作者: M mfang

Merge

......@@ -281,3 +281,6 @@ db30cb9eb18dacea39c35daf15a3ee5fea41fd86 jdk8u20-b07
0e717bd55bc9e3f3fa3432e545944d81ed887ab0 jdk8u20-b08
bfcdcc29c8823595a5d70b5b633bedcd5ee3ba8e jdk8u20-b09
3dd165facde7ffa240d77b33ff88b2d938fff017 jdk8u20-b10
37392f2f5d598bdecb8a12c4ea129a70a0ff8bf9 jdk8u20-b11
e323c74edabd29378819150ec000c6a0a99266ed jdk8u20-b12
4edaec5f08c09d49cc12c4e885e1180f367360a5 jdk8u20-b13
......@@ -57,7 +57,7 @@ public class AquaImageFactory {
return new IconUIResource(new AquaIcon.CachingScalingIcon(kAlertIconSize, kAlertIconSize) {
Image createImage() {
return getThisApplicationsIcon(kAlertIconSize, kAlertIconSize);
return getGenericJavaIcon();
}
});
}
......@@ -83,24 +83,6 @@ public class AquaImageFactory {
return getAppIconCompositedOn(lockIcon);
}
static Image getThisApplicationsIcon(final int width, final int height) {
final String path = getPathToThisApplication();
if (path == null) {
return getGenericJavaIcon();
}
if (path.endsWith("/Home/bin")) {
return getGenericJavaIcon();
}
if (path.startsWith("/usr/bin")) {
return getGenericJavaIcon();
}
return AquaUtils.getCImageCreator().createImageOfFile(path, height, width);
}
static Image getGenericJavaIcon() {
return java.security.AccessController.doPrivileged(new PrivilegedAction<Image>() {
public Image run() {
......@@ -144,7 +126,7 @@ public class AquaImageFactory {
final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon(
kAlertSubIconSize, kAlertSubIconSize) {
Image createImage() {
return getThisApplicationsIcon(kAlertSubIconSize, kAlertSubIconSize);
return getGenericJavaIcon();
}
};
......@@ -528,4 +510,4 @@ public class AquaImageFactory {
public static Color getSelectionInactiveForegroundColorUIResource() {
return new SystemColorProxy(LWCToolkit.getAppleColor(LWCToolkit.INACTIVE_SELECTION_FOREGROUND_COLOR));
}
}
\ No newline at end of file
}
......@@ -261,7 +261,8 @@ AWT_ASSERT_APPKIT_THREAD;
// returns id for the topmost window under mouse
+ (NSInteger) getTopmostWindowUnderMouseID {
NSInteger result = -1;
NSRect screenRect = [[NSScreen mainScreen] frame];
NSPoint nsMouseLocation = [NSEvent mouseLocation];
CGPoint cgMouseLocation = CGPointMake(nsMouseLocation.x, screenRect.size.height - nsMouseLocation.y);
......@@ -274,11 +275,13 @@ AWT_ASSERT_APPKIT_THREAD;
CGRect rect;
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[window objectForKey:(id)kCGWindowBounds], &rect);
if (CGRectContainsPoint(rect, cgMouseLocation)) {
return [[window objectForKey:(id)kCGWindowNumber] integerValue];
result = [[window objectForKey:(id)kCGWindowNumber] integerValue];
break;
}
}
}
return -1;
[windows release];
return result;
}
// checks that this window is under the mouse cursor and this point is not overlapped by others windows
......
......@@ -66,7 +66,8 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){
CFArrayAppendValue(validModes, cRef);
}
}
CFRelease(allModes);
CGDisplayModeRef currentMode = CGDisplayCopyDisplayMode(displayID);
BOOL containsCurrentMode = NO;
......@@ -81,6 +82,7 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){
if (!containsCurrentMode) {
CFArrayAppendValue(validModes, currentMode);
}
CGDisplayModeRelease(currentMode);
return validModes;
}
......@@ -235,17 +237,19 @@ Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode
{
JNF_COCOA_ENTER(env);
CFArrayRef allModes = getAllValidDisplayModes(displayID);
CGDisplayModeRef closestMatch = getBestModeForParameters(allModes, (int)w, (int)h, (int)bpp, (int)refrate);
__block CGError retCode = kCGErrorSuccess;
if (closestMatch != NULL) {
[JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
CGDisplayModeRetain(closestMatch);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
CGDisplayConfigRef config;
retCode = CGBeginDisplayConfiguration(&config);
if (retCode == kCGErrorSuccess) {
CGConfigureDisplayWithDisplayMode(config, displayID, closestMatch, NULL);
retCode = CGCompleteDisplayConfiguration(config, kCGConfigureForAppOnly);
}
CGDisplayModeRelease(closestMatch);
}];
} else {
[JNFException raise:env as:kIllegalArgumentException reason:"Invalid display mode"];
......@@ -253,8 +257,7 @@ Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode
if (retCode != kCGErrorSuccess){
[JNFException raise:env as:kIllegalArgumentException reason:"Unable to set display mode!"];
}
}
CFRelease(allModes);
JNF_COCOA_EXIT(env);
}
......
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -39,6 +39,8 @@ import javax.crypto.spec.OAEPParameterSpec;
import sun.security.rsa.*;
import sun.security.jca.Providers;
import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
import sun.security.util.KeyUtil;
/**
* RSA cipher implementation. Supports RSA en/decryption and signing/verifying
......@@ -91,8 +93,8 @@ public final class RSACipher extends CipherSpi {
// padding object
private RSAPadding padding;
// cipher parameter for OAEP padding
private OAEPParameterSpec spec = null;
// cipher parameter for OAEP padding and TLS RSA premaster secret
private AlgorithmParameterSpec spec = null;
// buffer for the data
private byte[] buffer;
......@@ -110,6 +112,9 @@ public final class RSACipher extends CipherSpi {
// hash algorithm for OAEP
private String oaepHashAlgorithm = "SHA-1";
// the source of randomness
private SecureRandom random;
public RSACipher() {
paddingType = PAD_PKCS1;
}
......@@ -175,7 +180,7 @@ public final class RSACipher extends CipherSpi {
// see JCE spec
protected AlgorithmParameters engineGetParameters() {
if (spec != null) {
if (spec != null && spec instanceof OAEPParameterSpec) {
try {
AlgorithmParameters params =
AlgorithmParameters.getInstance("OAEP",
......@@ -276,8 +281,13 @@ public final class RSACipher extends CipherSpi {
buffer = new byte[n];
} else if (paddingType == PAD_PKCS1) {
if (params != null) {
throw new InvalidAlgorithmParameterException
("Parameters not supported");
if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"Parameters not supported");
}
spec = params;
this.random = random; // for TLS RSA premaster secret
}
int blockType = (mode <= MODE_DECRYPT) ? RSAPadding.PAD_BLOCKTYPE_2
: RSAPadding.PAD_BLOCKTYPE_1;
......@@ -293,19 +303,18 @@ public final class RSACipher extends CipherSpi {
throw new InvalidKeyException
("OAEP cannot be used to sign or verify signatures");
}
OAEPParameterSpec myParams;
if (params != null) {
if (!(params instanceof OAEPParameterSpec)) {
throw new InvalidAlgorithmParameterException
("Wrong Parameters for OAEP Padding");
}
myParams = (OAEPParameterSpec) params;
spec = params;
} else {
myParams = new OAEPParameterSpec(oaepHashAlgorithm, "MGF1",
spec = new OAEPParameterSpec(oaepHashAlgorithm, "MGF1",
MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
}
padding = RSAPadding.getInstance(RSAPadding.PAD_OAEP_MGF1, n,
random, myParams);
random, (OAEPParameterSpec)spec);
if (encrypt) {
int k = padding.getMaxDataSize();
buffer = new byte[k];
......@@ -420,17 +429,40 @@ public final class RSACipher extends CipherSpi {
if (wrappedKey.length > buffer.length) {
throw new InvalidKeyException("Key is too long for unwrapping");
}
boolean isTlsRsaPremasterSecret =
algorithm.equals("TlsRsaPremasterSecret");
Exception failover = null;
byte[] encoded = null;
update(wrappedKey, 0, wrappedKey.length);
try {
byte[] encoded = doFinal();
return ConstructKeys.constructKey(encoded, algorithm, type);
encoded = doFinal();
} catch (BadPaddingException e) {
// should not occur
throw new InvalidKeyException("Unwrapping failed", e);
if (isTlsRsaPremasterSecret) {
failover = e;
} else {
throw new InvalidKeyException("Unwrapping failed", e);
}
} catch (IllegalBlockSizeException e) {
// should not occur, handled with length check above
throw new InvalidKeyException("Unwrapping failed", e);
}
if (isTlsRsaPremasterSecret) {
if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new IllegalStateException(
"No TlsRsaPremasterSecretParameterSpec specified");
}
// polish the TLS premaster secret
encoded = KeyUtil.checkTlsPreMasterSecretKey(
((TlsRsaPremasterSecretParameterSpec)spec).getClientVersion(),
((TlsRsaPremasterSecretParameterSpec)spec).getServerVersion(),
random, encoded, (failover != null));
}
return ConstructKeys.constructKey(encoded, algorithm, type);
}
// see JCE spec
......@@ -438,5 +470,4 @@ public final class RSACipher extends CipherSpi {
RSAKey rsaKey = RSAKeyFactory.toRSAKey(key);
return rsaKey.getModulus().bitLength();
}
}
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -56,7 +56,7 @@ public final class TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (params instanceof TlsRsaPremasterSecretParameterSpec == false) {
if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new InvalidAlgorithmParameterException(MSG);
}
this.spec = (TlsRsaPremasterSecretParameterSpec)params;
......@@ -67,21 +67,20 @@ public final class TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
// Only can be used in client side to generate TLS RSA premaster secret.
protected SecretKey engineGenerateKey() {
if (spec == null) {
throw new IllegalStateException(
"TlsRsaPremasterSecretGenerator must be initialized");
}
byte[] b = spec.getEncodedSecret();
if (b == null) {
if (random == null) {
random = new SecureRandom();
}
b = new byte[48];
random.nextBytes(b);
b[0] = (byte)spec.getMajorVersion();
b[1] = (byte)spec.getMinorVersion();
if (random == null) {
random = new SecureRandom();
}
byte[] b = new byte[48];
random.nextBytes(b);
b[0] = (byte)spec.getMajorVersion();
b[1] = (byte)spec.getMinorVersion();
return new SecretKeySpec(b, "TlsRsaPremasterSecret");
}
......
......@@ -35,7 +35,7 @@ import java.util.zip.ZipFile;
* @since 1.5
* @author Vincent Ryan
*/
@jdk.Exported
public interface ContentSignerParameters {
/**
......@@ -64,7 +64,9 @@ public interface ContentSignerParameters {
*
* @return The TSAPolicyID. May be null.
*/
public String getTSAPolicyID();
public default String getTSAPolicyID() {
return null;
}
/**
* Retrieves the JAR file's signature.
......
......@@ -51,6 +51,8 @@ import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
public class WindowsScrollBarUI extends BasicScrollBarUI {
private Grid thumbGrid;
private Grid highlightGrid;
private Dimension horizontalThumbSize;
private Dimension verticalThumbSize;
/**
* Creates a UI for a JScrollBar.
......@@ -65,9 +67,30 @@ public class WindowsScrollBarUI extends BasicScrollBarUI {
protected void installDefaults() {
super.installDefaults();
if (XPStyle.getXP() != null) {
XPStyle xp = XPStyle.getXP();
if (xp != null) {
scrollbar.setBorder(null);
horizontalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNHORZ);
verticalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNVERT);
} else {
horizontalThumbSize = null;
verticalThumbSize = null;
}
}
private static Dimension getSize(Component component, XPStyle xp, Part part) {
Skin skin = xp.getSkin(component, part);
return new Dimension(skin.getWidth(), skin.getHeight());
}
@Override
protected Dimension getMinimumThumbSize() {
if ((horizontalThumbSize == null) || (verticalThumbSize == null)) {
return super.getMinimumThumbSize();
}
return JScrollBar.HORIZONTAL == scrollbar.getOrientation()
? horizontalThumbSize
: verticalThumbSize;
}
public void uninstallUI(JComponent c) {
......
......@@ -162,6 +162,16 @@ public class MethodDescriptor extends FeatureDescriptor {
: null;
}
private static Method resolve(Method oldMethod, Method newMethod) {
if (oldMethod == null) {
return newMethod;
}
if (newMethod == null) {
return oldMethod;
}
return !oldMethod.isSynthetic() && newMethod.isSynthetic() ? oldMethod : newMethod;
}
/*
* Package-private constructor
* Merge two method descriptors. Where they conflict, give the
......@@ -173,8 +183,7 @@ public class MethodDescriptor extends FeatureDescriptor {
MethodDescriptor(MethodDescriptor x, MethodDescriptor y) {
super(x, y);
Method method = y.methodRef.get();
this.methodRef.set(null != method ? method : x.methodRef.get());
this.methodRef.set(resolve(x.methodRef.get(), y.methodRef.get()));
params = x.params;
if (y.params != null) {
params = y.params;
......
......@@ -752,9 +752,12 @@ public final class Files {
}
if (parent == null) {
// unable to find existing parent
if (se != null)
if (se == null) {
throw new FileSystemException(dir.toString(), null,
"Unable to determine if root directory exists");
} else {
throw se;
throw new IOException("Root directory does not exist");
}
}
// create directories
......
......@@ -118,11 +118,18 @@ public class ArrayList<E> extends AbstractList<E>
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
......@@ -141,19 +148,21 @@ public class ArrayList<E> extends AbstractList<E>
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
......@@ -166,10 +175,14 @@ public class ArrayList<E> extends AbstractList<E>
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
/**
......@@ -180,7 +193,9 @@ public class ArrayList<E> extends AbstractList<E>
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = Arrays.copyOf(elementData, size);
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
......@@ -192,11 +207,11 @@ public class ArrayList<E> extends AbstractList<E>
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != EMPTY_ELEMENTDATA)
// any size if real element table
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for empty table. It's already supposed to be
// at default size.
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
......@@ -205,7 +220,7 @@ public class ArrayList<E> extends AbstractList<E>
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
......
......@@ -2905,8 +2905,8 @@ public final class Locale implements Cloneable, Serializable {
for (int i = 1; i < subtags.length; i++) {
if (isSubtagIllFormed(subtags[i], false)) {
isIllFormed = true;
break;
}
break;
}
}
if (isIllFormed) {
......
......@@ -1400,7 +1400,7 @@ public class CopyOnWriteArrayList<E>
lock.lock();
try {
checkForComodification();
if (fromIndex < 0 || toIndex > size)
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
throw new IndexOutOfBoundsException();
return new COWSubList<E>(l, fromIndex + offset,
toIndex + offset);
......
......@@ -700,24 +700,26 @@ class ZipFile implements ZipConstants, Closeable {
}
public int read(byte b[], int off, int len) throws IOException {
if (rem == 0) {
return -1;
}
if (len <= 0) {
return 0;
}
if (len > rem) {
len = (int) rem;
}
synchronized (ZipFile.this) {
ensureOpenOrZipException();
long rem = this.rem;
long pos = this.pos;
if (rem == 0) {
return -1;
}
if (len <= 0) {
return 0;
}
if (len > rem) {
len = (int) rem;
}
ensureOpenOrZipException();
len = ZipFile.read(ZipFile.this.jzfile, jzentry, pos, b,
off, len);
}
if (len > 0) {
pos += len;
rem -= len;
if (len > 0) {
this.pos = (pos + len);
this.rem = (rem - len);
}
}
if (rem == 0) {
close();
......
......@@ -3985,6 +3985,17 @@ public abstract class JComponent extends Container implements Serializable,
* @since 1.4
*/
public AccessibleKeyBinding getAccessibleKeyBinding() {
// Try to get the linked label's mnemonic if it exists
Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
if (o instanceof Accessible){
AccessibleContext ac = ((Accessible) o).getAccessibleContext();
if (ac != null){
AccessibleComponent comp = ac.getAccessibleComponent();
if (! (comp instanceof AccessibleExtendedComponent))
return null;
return ((AccessibleExtendedComponent)comp).getAccessibleKeyBinding();
}
}
return null;
}
} // inner class AccessibleJComponent
......
......@@ -239,6 +239,13 @@ public abstract class SunDropTargetContextPeer implements DropTargetContextPeer,
if (localTransferable != null) {
return localTransferable.getTransferData(df);
} else if (df.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) {
// Workaround to JDK-8024061: Exception thrown when drag and drop
// between two components is executed quickly.
// It is expected localTransferable is not null if javaJVMLocalObjectMimeType
// is used. Executing further results in ClassCastException, so null is
// returned here as no transfer data is available in this case.
return null;
}
if (dropStatus != STATUS_ACCEPT || dropComplete) {
......
......@@ -3,22 +3,22 @@
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNUNSAFE General Public License version 2 only, as
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUNSAFET
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICUNSAFELAR PUNSAFERPOSE. See the GNUNSAFE General Public License
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNUNSAFE General Public License version
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 UNSAFESA.
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 UNSAFESA
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
......
......@@ -84,19 +84,31 @@ public final class InetAddressCachePolicy {
* Initialize
*/
static {
Integer tmp = null;
try {
tmp = new Integer(
java.security.AccessController.doPrivileged (
new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(cachePolicyProp);
}
}));
} catch (NumberFormatException e) {
// ignore
}
Integer tmp = java.security.AccessController.doPrivileged(
new PrivilegedAction<Integer>() {
public Integer run() {
try {
String tmpString = Security.getProperty(cachePolicyProp);
if (tmpString != null) {
return Integer.valueOf(tmpString);
}
} catch (NumberFormatException ignored) {
// Ignore
}
try {
String tmpString = System.getProperty(cachePolicyPropFallback);
if (tmpString != null) {
return Integer.decode(tmpString);
}
} catch (NumberFormatException ignored) {
// Ignore
}
return null;
}
});
if (tmp != null) {
cachePolicy = tmp.intValue();
if (cachePolicy < 0) {
......@@ -104,35 +116,36 @@ public final class InetAddressCachePolicy {
}
propertySet = true;
} else {
tmp = java.security.AccessController.doPrivileged
(new sun.security.action.GetIntegerAction(cachePolicyPropFallback));
if (tmp != null) {
cachePolicy = tmp.intValue();
if (cachePolicy < 0) {
cachePolicy = FOREVER;
}
propertySet = true;
} else {
/* No properties defined for positive caching. If there is no
* security manager then use the default positive cache value.
*/
if (System.getSecurityManager() == null) {
cachePolicy = DEFAULT_POSITIVE;
}
/* No properties defined for positive caching. If there is no
* security manager then use the default positive cache value.
*/
if (System.getSecurityManager() == null) {
cachePolicy = DEFAULT_POSITIVE;
}
}
tmp = java.security.AccessController.doPrivileged (
new PrivilegedAction<Integer>() {
public Integer run() {
try {
String tmpString = Security.getProperty(negativeCachePolicyProp);
if (tmpString != null) {
return Integer.valueOf(tmpString);
}
} catch (NumberFormatException ignored) {
// Ignore
}
try {
tmp = new Integer(
java.security.AccessController.doPrivileged (
new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(negativeCachePolicyProp);
}
}));
} catch (NumberFormatException e) {
// ignore
}
try {
String tmpString = System.getProperty(negativeCachePolicyPropFallback);
if (tmpString != null) {
return Integer.decode(tmpString);
}
} catch (NumberFormatException ignored) {
// Ignore
}
return null;
}
});
if (tmp != null) {
negativeCachePolicy = tmp.intValue();
......@@ -140,16 +153,6 @@ public final class InetAddressCachePolicy {
negativeCachePolicy = FOREVER;
}
propertyNegativeSet = true;
} else {
tmp = java.security.AccessController.doPrivileged
(new sun.security.action.GetIntegerAction(negativeCachePolicyPropFallback));
if (tmp != null) {
negativeCachePolicy = tmp.intValue();
if (negativeCachePolicy < 0) {
negativeCachePolicy = FOREVER;
}
propertyNegativeSet = true;
}
}
}
......
......@@ -37,90 +37,73 @@ public class IPAddressUtil {
* @param src a String representing an IPv4 address in standard format
* @return a byte array representing the IPv4 numeric address
*/
@SuppressWarnings("fallthrough")
public static byte[] textToNumericFormatV4(String src)
{
if (src.length() == 0) {
return null;
}
byte[] res = new byte[INADDR4SZ];
String[] s = src.split("\\.", -1);
long val;
try {
switch(s.length) {
case 1:
/*
* When only one part is given, the value is stored directly in
* the network address without any byte rearrangement.
*/
val = Long.parseLong(s[0]);
if (val < 0 || val > 0xffffffffL)
return null;
res[0] = (byte) ((val >> 24) & 0xff);
res[1] = (byte) (((val & 0xffffff) >> 16) & 0xff);
res[2] = (byte) (((val & 0xffff) >> 8) & 0xff);
res[3] = (byte) (val & 0xff);
break;
case 2:
/*
* When a two part address is supplied, the last part is
* interpreted as a 24-bit quantity and placed in the right
* most three bytes of the network address. This makes the
* two part address format convenient for specifying Class A
* network addresses as net.host.
*/
long tmpValue = 0;
int currByte = 0;
val = Integer.parseInt(s[0]);
if (val < 0 || val > 0xff)
return null;
res[0] = (byte) (val & 0xff);
val = Integer.parseInt(s[1]);
if (val < 0 || val > 0xffffff)
int len = src.length();
if (len == 0 || len > 15) {
return null;
}
/*
* When only one part is given, the value is stored directly in
* the network address without any byte rearrangement.
*
* When a two part address is supplied, the last part is
* interpreted as a 24-bit quantity and placed in the right
* most three bytes of the network address. This makes the
* two part address format convenient for specifying Class A
* network addresses as net.host.
*
* When a three part address is specified, the last part is
* interpreted as a 16-bit quantity and placed in the right
* most two bytes of the network address. This makes the
* three part address format convenient for specifying
* Class B net- work addresses as 128.net.host.
*
* When four parts are specified, each is interpreted as a
* byte of data and assigned, from left to right, to the
* four bytes of an IPv4 address.
*
* We determine and parse the leading parts, if any, as single
* byte values in one pass directly into the resulting byte[],
* then the remainder is treated as a 8-to-32-bit entity and
* translated into the remaining bytes in the array.
*/
for (int i = 0; i < len; i++) {
char c = src.charAt(i);
if (c == '.') {
if (tmpValue < 0 || tmpValue > 0xff || currByte == 3) {
return null;
res[1] = (byte) ((val >> 16) & 0xff);
res[2] = (byte) (((val & 0xffff) >> 8) &0xff);
res[3] = (byte) (val & 0xff);
break;
case 3:
/*
* When a three part address is specified, the last part is
* interpreted as a 16-bit quantity and placed in the right
* most two bytes of the network address. This makes the
* three part address format convenient for specifying
* Class B net- work addresses as 128.net.host.
*/
for (int i = 0; i < 2; i++) {
val = Integer.parseInt(s[i]);
if (val < 0 || val > 0xff)
return null;
res[i] = (byte) (val & 0xff);
}
val = Integer.parseInt(s[2]);
if (val < 0 || val > 0xffff)
res[currByte++] = (byte) (tmpValue & 0xff);
tmpValue = 0;
} else {
int digit = Character.digit(c, 10);
if (digit < 0) {
return null;
res[2] = (byte) ((val >> 8) & 0xff);
res[3] = (byte) (val & 0xff);
break;
case 4:
/*
* When four parts are specified, each is interpreted as a
* byte of data and assigned, from left to right, to the
* four bytes of an IPv4 address.
*/
for (int i = 0; i < 4; i++) {
val = Integer.parseInt(s[i]);
if (val < 0 || val > 0xff)
return null;
res[i] = (byte) (val & 0xff);
}
break;
default:
return null;
tmpValue *= 10;
tmpValue += digit;
}
} catch(NumberFormatException e) {
}
if (tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) {
return null;
}
switch (currByte) {
case 0:
res[0] = (byte) ((tmpValue >> 24) & 0xff);
case 1:
res[1] = (byte) ((tmpValue >> 16) & 0xff);
case 2:
res[2] = (byte) ((tmpValue >> 8) & 0xff);
case 3:
res[3] = (byte) ((tmpValue >> 0) & 0xff);
}
return res;
}
......
......@@ -665,7 +665,9 @@ public class HttpClient extends NetworkClient {
// try once more
openServer();
if (needsTunneling()) {
MessageHeader origRequests = requests;
httpuc.doTunneling();
requests = origRequests;
}
afterConnect();
writeRequests(requests, poster);
......@@ -776,7 +778,9 @@ public class HttpClient extends NetworkClient {
cachedHttpClient = false;
openServer();
if (needsTunneling()) {
MessageHeader origRequests = requests;
httpuc.doTunneling();
requests = origRequests;
}
afterConnect();
writeRequests(requests, poster);
......
......@@ -26,11 +26,11 @@
package sun.security.internal.spec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Parameters for SSL/TLS RSA Premaster secret generation.
* This class is used by SSL/TLS client to initialize KeyGenerators of the
* type "TlsRsaPremasterSecret".
* Parameters for SSL/TLS RSA premaster secret.
*
* <p>Instances of this class are immutable.
*
......@@ -43,90 +43,108 @@ import java.security.spec.AlgorithmParameterSpec;
public class TlsRsaPremasterSecretParameterSpec
implements AlgorithmParameterSpec {
private final int majorVersion;
private final int minorVersion;
private final byte[] encodedSecret;
/*
* The TLS spec says that the version in the RSA premaster secret must
* be the maximum version supported by the client (i.e. the version it
* requested in its client hello version). However, we (and other
* implementations) used to send the active negotiated version. The
* system property below allows to toggle the behavior.
*/
private final static String PROP_NAME =
"com.sun.net.ssl.rsaPreMasterSecretFix";
/*
* Default is "false" (old behavior) for compatibility reasons in
* SSLv3/TLSv1. Later protocols (TLSv1.1+) do not use this property.
*/
private final static boolean rsaPreMasterSecretFix =
AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
String value = System.getProperty(PROP_NAME);
if (value != null && value.equalsIgnoreCase("true")) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
});
private final int clientVersion;
private final int serverVersion;
/**
* Constructs a new TlsRsaPremasterSecretParameterSpec.
* <P>
* The version numbers will be placed inside the premaster secret to
* detect version rollbacks attacks as described in the TLS specification.
* Note that they do not indicate the protocol version negotiated for
* the handshake.
*
* @param majorVersion the major number of the protocol version
* @param minorVersion the minor number of the protocol version
* @param clientVersion the version of the TLS protocol by which the
* client wishes to communicate during this session
* @param serverVersion the negotiated version of the TLS protocol which
* contains the lower of that suggested by the client in the client
* hello and the highest supported by the server.
*
* @throws IllegalArgumentException if minorVersion or majorVersion are
* negative or larger than 255
* @throws IllegalArgumentException if clientVersion or serverVersion are
* negative or larger than (2^16 - 1)
*/
public TlsRsaPremasterSecretParameterSpec(int majorVersion,
int minorVersion) {
this.majorVersion =
TlsMasterSecretParameterSpec.checkVersion(majorVersion);
this.minorVersion =
TlsMasterSecretParameterSpec.checkVersion(minorVersion);
this.encodedSecret = null;
public TlsRsaPremasterSecretParameterSpec(
int clientVersion, int serverVersion) {
this.clientVersion = checkVersion(clientVersion);
this.serverVersion = checkVersion(serverVersion);
}
/**
* Constructs a new TlsRsaPremasterSecretParameterSpec.
* <P>
* The version numbers will be placed inside the premaster secret to
* detect version rollbacks attacks as described in the TLS specification.
* Note that they do not indicate the protocol version negotiated for
* the handshake.
* <P>
* Usually, the encoded secret key is a random number that acts as
* dummy pre_master_secret to avoid vulnerabilities described by
* section 7.4.7.1, RFC 5246.
*
* @param majorVersion the major number of the protocol version
* @param minorVersion the minor number of the protocol version
* @param encodedSecret the encoded secret key
* Returns the version of the TLS protocol by which the client wishes to
* communicate during this session.
*
* @throws IllegalArgumentException if minorVersion or majorVersion are
* negative or larger than 255, or encodedSecret is not exactly 48 bytes.
* @return the version of the TLS protocol in ClientHello message
*/
public TlsRsaPremasterSecretParameterSpec(int majorVersion,
int minorVersion, byte[] encodedSecret) {
this.majorVersion =
TlsMasterSecretParameterSpec.checkVersion(majorVersion);
this.minorVersion =
TlsMasterSecretParameterSpec.checkVersion(minorVersion);
if (encodedSecret == null || encodedSecret.length != 48) {
throw new IllegalArgumentException(
"Encoded secret is not exactly 48 bytes");
}
this.encodedSecret = encodedSecret.clone();
public int getClientVersion() {
return clientVersion;
}
/**
* Returns the major version.
* Returns the negotiated version of the TLS protocol which contains the
* lower of that suggested by the client in the client hello and the
* highest supported by the server.
*
* @return the major version.
* @return the negotiated version of the TLS protocol in ServerHello message
*/
public int getMajorVersion() {
return majorVersion;
public int getServerVersion() {
return serverVersion;
}
/**
* Returns the minor version.
* Returns the major version used in RSA premaster secret.
*
* @return the minor version.
* @return the major version used in RSA premaster secret.
*/
public int getMinorVersion() {
return minorVersion;
public int getMajorVersion() {
if (rsaPreMasterSecretFix || clientVersion >= 0x0302) {
// 0x0302: TLSv1.1
return (clientVersion >>> 8) & 0xFF;
}
return (serverVersion >>> 8) & 0xFF;
}
/**
* Returns the encoded secret.
* Returns the minor version used in RSA premaster secret.
*
* @return the encoded secret, may be null if no encoded secret.
* @return the minor version used in RSA premaster secret.
*/
public byte[] getEncodedSecret() {
return encodedSecret == null ? null : encodedSecret.clone();
public int getMinorVersion() {
if (rsaPreMasterSecretFix || clientVersion >= 0x0302) {
// 0x0302: TLSv1.1
return clientVersion & 0xFF;
}
return serverVersion & 0xFF;
}
private int checkVersion(int version) {
if ((version < 0) || (version > 0xFFFF)) {
throw new IllegalArgumentException(
"Version must be between 0 and 65,535");
}
return version;
}
}
......@@ -37,6 +37,8 @@ import javax.crypto.spec.*;
import static sun.security.pkcs11.TemplateManager.*;
import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
import sun.security.util.KeyUtil;
/**
* RSA Cipher implementation class. We currently only support
......@@ -102,6 +104,12 @@ final class P11RSACipher extends CipherSpi {
// maximum output size. this is the length of the key
private int outputSize;
// cipher parameter for TLS RSA premaster secret
private AlgorithmParameterSpec spec = null;
// the source of randomness
private SecureRandom random;
P11RSACipher(Token token, String algorithm, long mechanism)
throws PKCS11Exception {
super();
......@@ -165,8 +173,12 @@ final class P11RSACipher extends CipherSpi {
AlgorithmParameterSpec params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (params != null) {
throw new InvalidAlgorithmParameterException
("Parameters not supported");
if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"Parameters not supported");
}
spec = params;
this.random = random; // for TLS RSA premaster secret
}
implInit(opmode, key);
}
......@@ -176,8 +188,8 @@ final class P11RSACipher extends CipherSpi {
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (params != null) {
throw new InvalidAlgorithmParameterException
("Parameters not supported");
throw new InvalidAlgorithmParameterException(
"Parameters not supported");
}
implInit(opmode, key);
}
......@@ -452,21 +464,101 @@ final class P11RSACipher extends CipherSpi {
protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
int type) throws InvalidKeyException, NoSuchAlgorithmException {
// XXX implement unwrap using C_Unwrap() for all keys
implInit(Cipher.DECRYPT_MODE, p11Key);
if (wrappedKey.length > maxInputSize) {
throw new InvalidKeyException("Key is too long for unwrapping");
boolean isTlsRsaPremasterSecret =
algorithm.equals("TlsRsaPremasterSecret");
Exception failover = null;
SecureRandom secureRandom = random;
if (secureRandom == null && isTlsRsaPremasterSecret) {
secureRandom = new SecureRandom();
}
implUpdate(wrappedKey, 0, wrappedKey.length);
try {
byte[] encoded = doFinal();
// Should C_Unwrap be preferred for non-TLS RSA premaster secret?
if (token.supportsRawSecretKeyImport()) {
// XXX implement unwrap using C_Unwrap() for all keys
implInit(Cipher.DECRYPT_MODE, p11Key);
if (wrappedKey.length > maxInputSize) {
throw new InvalidKeyException("Key is too long for unwrapping");
}
byte[] encoded = null;
implUpdate(wrappedKey, 0, wrappedKey.length);
try {
encoded = doFinal();
} catch (BadPaddingException e) {
if (isTlsRsaPremasterSecret) {
failover = e;
} else {
throw new InvalidKeyException("Unwrapping failed", e);
}
} catch (IllegalBlockSizeException e) {
// should not occur, handled with length check above
throw new InvalidKeyException("Unwrapping failed", e);
}
if (isTlsRsaPremasterSecret) {
if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new IllegalStateException(
"No TlsRsaPremasterSecretParameterSpec specified");
}
// polish the TLS premaster secret
TlsRsaPremasterSecretParameterSpec psps =
(TlsRsaPremasterSecretParameterSpec)spec;
encoded = KeyUtil.checkTlsPreMasterSecretKey(
psps.getClientVersion(), psps.getServerVersion(),
secureRandom, encoded, (failover != null));
}
return ConstructKeys.constructKey(encoded, algorithm, type);
} catch (BadPaddingException e) {
// should not occur
throw new InvalidKeyException("Unwrapping failed", e);
} catch (IllegalBlockSizeException e) {
// should not occur, handled with length check above
throw new InvalidKeyException("Unwrapping failed", e);
} else {
Session s = null;
SecretKey secretKey = null;
try {
try {
s = token.getObjSession();
long keyType = CKK_GENERIC_SECRET;
CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] {
new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
new CK_ATTRIBUTE(CKA_KEY_TYPE, keyType),
};
attributes = token.getAttributes(
O_IMPORT, CKO_SECRET_KEY, keyType, attributes);
long keyID = token.p11.C_UnwrapKey(s.id(),
new CK_MECHANISM(mechanism), p11Key.keyID,
wrappedKey, attributes);
secretKey = P11Key.secretKey(s, keyID,
algorithm, 48 << 3, attributes);
} catch (PKCS11Exception e) {
if (isTlsRsaPremasterSecret) {
failover = e;
} else {
throw new InvalidKeyException("unwrap() failed", e);
}
}
if (isTlsRsaPremasterSecret) {
byte[] replacer = new byte[48];
if (failover == null) {
// Does smart compiler dispose this operation?
secureRandom.nextBytes(replacer);
}
TlsRsaPremasterSecretParameterSpec psps =
(TlsRsaPremasterSecretParameterSpec)spec;
// Please use the tricky failover and replacer byte array
// as the parameters so that smart compiler won't dispose
// the unused variable .
secretKey = polishPreMasterSecretKey(token, s,
failover, replacer, secretKey,
psps.getClientVersion(), psps.getServerVersion());
}
return secretKey;
} finally {
token.releaseSession(s);
}
}
}
......@@ -475,6 +567,34 @@ final class P11RSACipher extends CipherSpi {
int n = P11KeyFactory.convertKey(token, key, algorithm).length();
return n;
}
private static SecretKey polishPreMasterSecretKey(
Token token, Session session,
Exception failover, byte[] replacer, SecretKey secretKey,
int clientVersion, int serverVersion) {
if (failover != null) {
CK_VERSION version = new CK_VERSION(
(clientVersion >>> 8) & 0xFF, clientVersion & 0xFF);
try {
CK_ATTRIBUTE[] attributes = token.getAttributes(
O_GENERATE, CKO_SECRET_KEY,
CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
long keyID = token.p11.C_GenerateKey(session.id(),
// new CK_MECHANISM(CKM_TLS_PRE_MASTER_KEY_GEN, version),
new CK_MECHANISM(CKM_SSL3_PRE_MASTER_KEY_GEN, version),
attributes);
return P11Key.secretKey(session,
keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
} catch (PKCS11Exception e) {
throw new ProviderException(
"Could not generate premaster secret", e);
}
}
return secretKey;
}
}
final class ConstructKeys {
......
......@@ -73,7 +73,7 @@ final class P11TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (params instanceof TlsRsaPremasterSecretParameterSpec == false) {
if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new InvalidAlgorithmParameterException(MSG);
}
this.spec = (TlsRsaPremasterSecretParameterSpec)params;
......@@ -83,38 +83,32 @@ final class P11TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
// Only can be used in client side to generate TLS RSA premaster secret.
protected SecretKey engineGenerateKey() {
if (spec == null) {
throw new IllegalStateException
("TlsRsaPremasterSecretGenerator must be initialized");
}
byte[] b = spec.getEncodedSecret();
if (b == null) {
CK_VERSION version = new CK_VERSION(
CK_VERSION version = new CK_VERSION(
spec.getMajorVersion(), spec.getMinorVersion());
Session session = null;
try {
session = token.getObjSession();
CK_ATTRIBUTE[] attributes = token.getAttributes(
O_GENERATE, CKO_SECRET_KEY,
CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
long keyID = token.p11.C_GenerateKey(session.id(),
new CK_MECHANISM(mechanism, version), attributes);
SecretKey key = P11Key.secretKey(session,
keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
return key;
} catch (PKCS11Exception e) {
throw new ProviderException(
"Could not generate premaster secret", e);
} finally {
token.releaseSession(session);
}
Session session = null;
try {
session = token.getObjSession();
CK_ATTRIBUTE[] attributes = token.getAttributes(
O_GENERATE, CKO_SECRET_KEY,
CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
long keyID = token.p11.C_GenerateKey(session.id(),
new CK_MECHANISM(mechanism, version), attributes);
SecretKey key = P11Key.secretKey(session,
keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
return key;
} catch (PKCS11Exception e) {
throw new ProviderException(
"Could not generate premaster secret", e);
} finally {
token.releaseSession(session);
}
// Won't worry, the TlsRsaPremasterSecret will be soon converted to
// TlsMasterSecret.
return new SecretKeySpec(b, "TlsRsaPremasterSecret");
}
}
......@@ -36,6 +36,7 @@ import javax.security.auth.login.LoginException;
import sun.security.jca.JCAUtil;
import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.TemplateManager.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
/**
......@@ -122,6 +123,9 @@ class Token implements Serializable {
private final static CK_MECHANISM_INFO INVALID_MECH =
new CK_MECHANISM_INFO(0, 0, 0);
// flag indicating whether the token supports raw secret key material import
private Boolean supportsRawSecretKeyImport;
Token(SunPKCS11 provider) throws PKCS11Exception {
this.provider = provider;
this.removable = provider.removable;
......@@ -160,6 +164,36 @@ class Token implements Serializable {
return writeProtected;
}
// return whether the token supports raw secret key material import
boolean supportsRawSecretKeyImport() {
if (supportsRawSecretKeyImport == null) {
SecureRandom random = JCAUtil.getSecureRandom();
byte[] encoded = new byte[48];
random.nextBytes(encoded);
CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[3];
attributes[0] = new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);
attributes[1] = new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_GENERIC_SECRET);
attributes[2] = new CK_ATTRIBUTE(CKA_VALUE, encoded);
Session session = null;
try {
attributes = getAttributes(O_IMPORT,
CKO_SECRET_KEY, CKK_GENERIC_SECRET, attributes);
session = getObjSession();
long keyID = p11.C_CreateObject(session.id(), attributes);
supportsRawSecretKeyImport = Boolean.TRUE;
} catch (PKCS11Exception e) {
supportsRawSecretKeyImport = Boolean.FALSE;
} finally {
releaseSession(session);
}
}
return supportsRawSecretKeyImport;
}
// return whether we are logged in
// uses cached result if current. session is optional and may be null
boolean isLoggedIn(Session session) throws PKCS11Exception {
......
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -60,7 +60,8 @@ class ByteBufferInputStream extends InputStream {
if (bb.remaining() == 0) {
return -1;
}
return bb.get();
return (bb.get() & 0xFF); // need to be in the range 0 to 255
}
/**
......
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -109,14 +109,8 @@ final class EngineInputRecord extends InputRecord {
ProtocolVersion recordVersion =
ProtocolVersion.valueOf(buf.get(pos + 1), buf.get(pos + 2));
// Check if too old (currently not possible)
// or if the major version does not match.
// The actual version negotiation is in the handshaker classes
if ((recordVersion.v < ProtocolVersion.MIN.v)
|| (recordVersion.major > ProtocolVersion.MAX.major)) {
throw new SSLException(
"Unsupported record version " + recordVersion);
}
// check the record version
checkRecordVersion(recordVersion, false);
/*
* Reasonably sure this is a V3, disable further checks.
......@@ -147,18 +141,8 @@ final class EngineInputRecord extends InputRecord {
ProtocolVersion recordVersion =
ProtocolVersion.valueOf(buf.get(pos + 3), buf.get(pos + 4));
// Check if too old (currently not possible)
// or if the major version does not match.
// The actual version negotiation is in the handshaker classes
if ((recordVersion.v < ProtocolVersion.MIN.v)
|| (recordVersion.major > ProtocolVersion.MAX.major)) {
// if it's not SSLv2, we're out of here.
if (recordVersion.v != ProtocolVersion.SSL20Hello.v) {
throw new SSLException(
"Unsupported record version " + recordVersion);
}
}
// check the record version
checkRecordVersion(recordVersion, true);
/*
* Client or Server Hello
......@@ -406,14 +390,9 @@ final class EngineInputRecord extends InputRecord {
ProtocolVersion recordVersion = ProtocolVersion.valueOf(
srcBB.get(srcPos + 1), srcBB.get(srcPos + 2));
// Check if too old (currently not possible)
// or if the major version does not match.
// The actual version negotiation is in the handshaker classes
if ((recordVersion.v < ProtocolVersion.MIN.v)
|| (recordVersion.major > ProtocolVersion.MAX.major)) {
throw new SSLException(
"Unsupported record version " + recordVersion);
}
// check the record version
checkRecordVersion(recordVersion, false);
/*
* It's really application data. How much to consume?
......
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -533,20 +533,36 @@ class InputRecord extends ByteArrayInputStream implements Record {
}
}
/**
* Return true if the specified record protocol version is out of the
* range of the possible supported versions.
*/
static void checkRecordVersion(ProtocolVersion version,
boolean allowSSL20Hello) throws SSLException {
// Check if the record version is too old (currently not possible)
// or if the major version does not match.
//
// The actual version negotiation is in the handshaker classes
if ((version.v < ProtocolVersion.MIN.v) ||
((version.major & 0xFF) > (ProtocolVersion.MAX.major & 0xFF))) {
// if it's not SSLv2, we're out of here.
if (!allowSSL20Hello ||
(version.v != ProtocolVersion.SSL20Hello.v)) {
throw new SSLException("Unsupported record version " + version);
}
}
}
/**
* Read a SSL/TLS record. Throw an IOException if the format is invalid.
*/
private void readV3Record(InputStream s, OutputStream o)
throws IOException {
ProtocolVersion recordVersion = ProtocolVersion.valueOf(buf[1], buf[2]);
// Check if too old (currently not possible)
// or if the major version does not match.
// The actual version negotiation is in the handshaker classes
if ((recordVersion.v < ProtocolVersion.MIN.v)
|| (recordVersion.major > ProtocolVersion.MAX.major)) {
throw new SSLException(
"Unsupported record version " + recordVersion);
}
// check the record version
checkRecordVersion(recordVersion, false);
/*
* Get and check length, then the data.
......
/*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -101,7 +101,7 @@ public final class ProtocolVersion implements Comparable<ProtocolVersion> {
this.v = v;
this.name = name;
major = (byte)(v >>> 8);
minor = (byte)(v & 0xff);
minor = (byte)(v & 0xFF);
}
// private
......@@ -117,8 +117,8 @@ public final class ProtocolVersion implements Comparable<ProtocolVersion> {
} else if (v == SSL20Hello.v) {
return SSL20Hello;
} else {
int major = (v >>> 8) & 0xff;
int minor = v & 0xff;
int major = (v >>> 8) & 0xFF;
int minor = v & 0xFF;
return new ProtocolVersion(v, "Unknown-" + major + "." + minor);
}
}
......@@ -128,10 +128,7 @@ public final class ProtocolVersion implements Comparable<ProtocolVersion> {
* numbers. Never throws exceptions.
*/
public static ProtocolVersion valueOf(int major, int minor) {
major &= 0xff;
minor &= 0xff;
int v = (major << 8) | minor;
return valueOf(v);
return valueOf(((major & 0xFF) << 8) | (minor & 0xFF));
}
/**
......
......@@ -48,23 +48,6 @@ import sun.security.util.KeyUtil;
*/
final class RSAClientKeyExchange extends HandshakeMessage {
/**
* The TLS spec says that the version in the RSA premaster secret must
* be the maximum version supported by the client (i.e. the version it
* requested in its client hello version). However, we (and other
* implementations) used to send the active negotiated version. The
* system property below allows to toggle the behavior.
*/
private final static String PROP_NAME =
"com.sun.net.ssl.rsaPreMasterSecretFix";
/*
* Default is "false" (old behavior) for compatibility reasons in
* SSLv3/TLSv1. Later protocols (TLSv1.1+) do not use this property.
*/
private final static boolean rsaPreMasterSecretFix =
Debug.getBooleanProperty(PROP_NAME, false);
/*
* The following field values were encrypted with the server's public
* key (or temp key from server key exchange msg) and are presented
......@@ -88,22 +71,12 @@ final class RSAClientKeyExchange extends HandshakeMessage {
}
this.protocolVersion = protocolVersion;
int major, minor;
if (rsaPreMasterSecretFix || maxVersion.v >= ProtocolVersion.TLS11.v) {
major = maxVersion.major;
minor = maxVersion.minor;
} else {
major = protocolVersion.major;
minor = protocolVersion.minor;
}
try {
String s = ((protocolVersion.v >= ProtocolVersion.TLS12.v) ?
"SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
KeyGenerator kg = JsseJce.getKeyGenerator(s);
kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor),
generator);
kg.init(new TlsRsaPremasterSecretParameterSpec(
maxVersion.v, protocolVersion.v), generator);
preMaster = kg.generateKey();
Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
......@@ -138,18 +111,16 @@ final class RSAClientKeyExchange extends HandshakeMessage {
}
}
Exception failover = null;
byte[] encoded = null;
try {
Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
// Cannot generate key here, please don't use Cipher.UNWRAP_MODE!
cipher.init(Cipher.DECRYPT_MODE, privateKey);
encoded = cipher.doFinal(encrypted);
} catch (BadPaddingException bpe) {
failover = bpe;
encoded = null;
} catch (IllegalBlockSizeException ibse) {
// the message it too big to process with RSA
cipher.init(Cipher.UNWRAP_MODE, privateKey,
new TlsRsaPremasterSecretParameterSpec(
maxVersion.v, currentVersion.v),
generator);
preMaster = (SecretKey)cipher.unwrap(encrypted,
"TlsRsaPremasterSecret", Cipher.SECRET_KEY);
} catch (InvalidKeyException ibk) {
// the message is too big to process with RSA
throw new SSLProtocolException(
"Unable to process PreMasterSecret, may be too big");
} catch (Exception e) {
......@@ -160,124 +131,6 @@ final class RSAClientKeyExchange extends HandshakeMessage {
}
throw new RuntimeException("Could not generate dummy secret", e);
}
// polish the premaster secret
preMaster = polishPreMasterSecretKey(
currentVersion, maxVersion, generator, encoded, failover);
}
/**
* To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
* treating incorrectly formatted message blocks and/or mismatched
* version numbers in a manner indistinguishable from correctly
* formatted RSA blocks.
*
* RFC 5246 describes the approach as :
*
* 1. Generate a string R of 48 random bytes
*
* 2. Decrypt the message to recover the plaintext M
*
* 3. If the PKCS#1 padding is not correct, or the length of message
* M is not exactly 48 bytes:
* pre_master_secret = R
* else If ClientHello.client_version <= TLS 1.0, and version
* number check is explicitly disabled:
* premaster secret = M
* else If M[0..1] != ClientHello.client_version:
* premaster secret = R
* else:
* premaster secret = M
*
* Note that #2 has completed before the call of this method.
*/
private SecretKey polishPreMasterSecretKey(ProtocolVersion currentVersion,
ProtocolVersion clientHelloVersion, SecureRandom generator,
byte[] encoded, Exception failoverException) {
this.protocolVersion = clientHelloVersion;
if (generator == null) {
generator = new SecureRandom();
}
byte[] random = new byte[48];
generator.nextBytes(random);
if (failoverException == null && encoded != null) {
// check the length
if (encoded.length != 48) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println(
"incorrect length of premaster secret: " +
encoded.length);
}
return generatePreMasterSecret(
clientHelloVersion, random, generator);
}
if (clientHelloVersion.major != encoded[0] ||
clientHelloVersion.minor != encoded[1]) {
if (clientHelloVersion.v <= ProtocolVersion.TLS10.v &&
currentVersion.major == encoded[0] &&
currentVersion.minor == encoded[1]) {
/*
* For compatibility, we maintain the behavior that the
* version in pre_master_secret can be the negotiated
* version for TLS v1.0 and SSL v3.0.
*/
this.protocolVersion = currentVersion;
} else {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Mismatching Protocol Versions, " +
"ClientHello.client_version is " +
clientHelloVersion +
", while PreMasterSecret.client_version is " +
ProtocolVersion.valueOf(encoded[0], encoded[1]));
}
encoded = random;
}
}
return generatePreMasterSecret(
clientHelloVersion, encoded, generator);
}
if (debug != null && Debug.isOn("handshake") &&
failoverException != null) {
System.out.println("Error decrypting premaster secret:");
failoverException.printStackTrace(System.out);
}
return generatePreMasterSecret(clientHelloVersion, random, generator);
}
// generate a premaster secret with the specified version number
private static SecretKey generatePreMasterSecret(
ProtocolVersion version, byte[] encodedSecret,
SecureRandom generator) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Generating a random fake premaster secret");
}
try {
String s = ((version.v >= ProtocolVersion.TLS12.v) ?
"SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
KeyGenerator kg = JsseJce.getKeyGenerator(s);
kg.init(new TlsRsaPremasterSecretParameterSpec(
version.major, version.minor, encodedSecret), generator);
return kg.generateKey();
} catch (InvalidAlgorithmParameterException |
NoSuchAlgorithmException iae) {
// unlikely to happen, otherwise, must be a provider exception
if (debug != null && Debug.isOn("handshake")) {
System.out.println("RSA premaster secret generation error:");
iae.printStackTrace(System.out);
}
throw new RuntimeException("Could not generate dummy secret", iae);
}
}
@Override
......
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -32,6 +32,7 @@ import java.security.InvalidKeyException;
import java.security.interfaces.ECKey;
import java.security.interfaces.RSAKey;
import java.security.interfaces.DSAKey;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHKey;
......@@ -156,6 +157,79 @@ public final class KeyUtil {
providerName.startsWith("SunPKCS11"));
}
/**
* Check the format of TLS PreMasterSecret.
* <P>
* To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
* treating incorrectly formatted message blocks and/or mismatched
* version numbers in a manner indistinguishable from correctly
* formatted RSA blocks.
*
* RFC 5246 describes the approach as :
*
* 1. Generate a string R of 48 random bytes
*
* 2. Decrypt the message to recover the plaintext M
*
* 3. If the PKCS#1 padding is not correct, or the length of message
* M is not exactly 48 bytes:
* pre_master_secret = R
* else If ClientHello.client_version <= TLS 1.0, and version
* number check is explicitly disabled:
* premaster secret = M
* else If M[0..1] != ClientHello.client_version:
* premaster secret = R
* else:
* premaster secret = M
*
* Note that #2 should have completed before the call to this method.
*
* @param clientVersion the version of the TLS protocol by which the
* client wishes to communicate during this session
* @param serverVersion the negotiated version of the TLS protocol which
* contains the lower of that suggested by the client in the client
* hello and the highest supported by the server.
* @param encoded the encoded key in its "RAW" encoding format
* @param isFailover whether or not the previous decryption of the
* encrypted PreMasterSecret message run into problem
* @return the polished PreMasterSecret key in its "RAW" encoding format
*/
public static byte[] checkTlsPreMasterSecretKey(
int clientVersion, int serverVersion, SecureRandom random,
byte[] encoded, boolean isFailOver) {
if (random == null) {
random = new SecureRandom();
}
byte[] replacer = new byte[48];
random.nextBytes(replacer);
if (!isFailOver && (encoded != null)) {
// check the length
if (encoded.length != 48) {
// private, don't need to clone the byte array.
return replacer;
}
int encodedVersion =
((encoded[0] & 0xFF) << 8) | (encoded[1] & 0xFF);
if (clientVersion != encodedVersion) {
if (clientVersion > 0x0301 || // 0x0301: TLSv1
serverVersion != encodedVersion) {
encoded = replacer;
} // Otherwise, For compatibility, we maintain the behavior
// that the version in pre_master_secret can be the
// negotiated version for TLS v1.0 and SSL v3.0.
}
// private, don't need to clone the byte array.
return encoded;
}
// private, don't need to clone the byte array.
return replacer;
}
/**
* Returns whether the Diffie-Hellman public key is valid or not.
*
......
/*
* Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -69,17 +69,14 @@ Java_sun_awt_image_BufImgSurfaceData_initIDs
}
clsICMCD = (*env)->NewWeakGlobalRef(env, cd);
initICMCDmID = (*env)->GetMethodID(env, cd, "<init>", "(J)V");
pDataID = (*env)->GetFieldID(env, cd, "pData", "J");
rgbID = (*env)->GetFieldID(env, icm, "rgb", "[I");
allGrayID = (*env)->GetFieldID(env, icm, "allgrayopaque", "Z");
mapSizeID = (*env)->GetFieldID(env, icm, "map_size", "I");
colorDataID = (*env)->GetFieldID(env, icm, "colorData",
"Lsun/awt/image/BufImgSurfaceData$ICMColorData;");
if (allGrayID == 0 || rgbID == 0 || mapSizeID == 0 || pDataID == 0|| colorDataID == 0 || initICMCDmID == 0) {
JNU_ThrowInternalError(env, "Could not get field IDs");
}
JNU_CHECK_EXCEPTION(env);
CHECK_NULL(initICMCDmID = (*env)->GetMethodID(env, cd, "<init>", "(J)V"));
CHECK_NULL(pDataID = (*env)->GetFieldID(env, cd, "pData", "J"));
CHECK_NULL(rgbID = (*env)->GetFieldID(env, icm, "rgb", "[I"));
CHECK_NULL(allGrayID = (*env)->GetFieldID(env, icm, "allgrayopaque", "Z"));
CHECK_NULL(mapSizeID = (*env)->GetFieldID(env, icm, "map_size", "I"));
CHECK_NULL(colorDataID = (*env)->GetFieldID(env, icm, "colorData",
"Lsun/awt/image/BufImgSurfaceData$ICMColorData;"));
}
/*
......@@ -120,6 +117,7 @@ Java_sun_awt_image_BufImgSurfaceData_initRaster(JNIEnv *env, jobject bisd,
bisdo->sdOps.Unlock = NULL;
bisdo->sdOps.Dispose = BufImg_Dispose;
bisdo->array = (*env)->NewWeakGlobalRef(env, array);
JNU_CHECK_EXCEPTION(env);
bisdo->offset = offset;
bisdo->bitoffset = bitoffset;
bisdo->scanStr = scanStr;
......@@ -131,6 +129,7 @@ Java_sun_awt_image_BufImgSurfaceData_initRaster(JNIEnv *env, jobject bisd,
} else {
jobject lutarray = (*env)->GetObjectField(env, icm, rgbID);
bisdo->lutarray = (*env)->NewWeakGlobalRef(env, lutarray);
JNU_CHECK_EXCEPTION(env);
bisdo->lutsize = (*env)->GetIntField(env, icm, mapSizeID);
bisdo->icm = (*env)->NewWeakGlobalRef(env, icm);
}
......@@ -174,8 +173,8 @@ static jint BufImg_Lock(JNIEnv *env,
{
bipriv->cData = BufImg_SetupICM(env, bisdo);
if (bipriv->cData == NULL) {
JNU_ThrowNullPointerException(env, "Could not initialize "
"inverse tables");
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "Could not initialize inverse tables");
return SD_FAILURE;
}
} else {
......@@ -201,6 +200,7 @@ static void BufImg_GetRasInfo(JNIEnv *env,
if ((bipriv->lockFlags & (SD_LOCK_RD_WR)) != 0) {
bipriv->base =
(*env)->GetPrimitiveArrayCritical(env, bisdo->array, NULL);
CHECK_NULL(bipriv->base);
}
if ((bipriv->lockFlags & (SD_LOCK_LUT)) != 0) {
bipriv->lutbase =
......@@ -291,6 +291,7 @@ static ColorData *BufImg_SetupICM(JNIEnv *env,
= (*env)->GetBooleanField(env, bisdo->icm, allGrayID);
int *pRgb = (int *)
((*env)->GetPrimitiveArrayCritical(env, bisdo->lutarray, NULL));
CHECK_NULL_RETURN(pRgb, (ColorData*)NULL);
cData->img_clr_tbl = initCubemap(pRgb, bisdo->lutsize, 32);
if (allGray == JNI_TRUE) {
initInverseGrayLut(pRgb, bisdo->lutsize, cData);
......@@ -303,6 +304,7 @@ static ColorData *BufImg_SetupICM(JNIEnv *env,
if (JNU_IsNull(env, colorData)) {
jlong pData = ptr_to_jlong(cData);
colorData = (*env)->NewObjectA(env, clsICMCD, initICMCDmID, (jvalue *)&pData);
JNU_CHECK_EXCEPTION_RETURN(env, (ColorData*)NULL);
(*env)->SetObjectField(env, bisdo->icm, colorDataID, colorData);
}
}
......
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -74,6 +74,7 @@ Java_sun_awt_image_DataBufferNative_getElem(JNIEnv *env, jobject dbn,
SurfaceDataOps *ops;
ops = SurfaceData_GetOps(env, sd);
JNU_CHECK_EXCEPTION_RETURN(env, -1);
if (!(pixelPtr = DBN_GetPixelPointer(env, x, y, &lockInfo,
ops, SD_LOCK_READ)))
......@@ -115,6 +116,7 @@ Java_sun_awt_image_DataBufferNative_setElem(JNIEnv *env, jobject dbn,
ops = SurfaceData_GetOps(env, sd);
JNU_CHECK_EXCEPTION(env);
if (!(pixelPtr = DBN_GetPixelPointer(env, x, y, &lockInfo,
ops, SD_LOCK_WRITE)))
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -97,9 +97,9 @@ static jfieldID s_JsrcLUTtransIndexID;
JNIEXPORT void JNICALL
Java_sun_awt_image_ImageRepresentation_initIDs(JNIEnv *env, jclass cls) {
s_JnumSrcLUTID = (*env)->GetFieldID(env, cls, "numSrcLUT", "I");
s_JsrcLUTtransIndexID = (*env)->GetFieldID(env, cls, "srcLUTtransIndex",
"I");
CHECK_NULL(s_JnumSrcLUTID = (*env)->GetFieldID(env, cls, "numSrcLUT", "I"));
CHECK_NULL(s_JsrcLUTtransIndexID = (*env)->GetFieldID(env, cls,
"srcLUTtransIndex", "I"));
}
/*
......@@ -166,6 +166,7 @@ Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls,
cOffs = (int *) (*env)->GetPrimitiveArrayCritical(env, joffs, NULL);
if (cOffs == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "Null channel offset array");
return JNI_FALSE;
}
......@@ -190,6 +191,7 @@ Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls,
srcLUT = (int *) (*env)->GetPrimitiveArrayCritical(env, jlut, NULL);
if (srcLUT == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "Null IndexColorModel LUT");
return JNI_FALSE;
}
......@@ -198,6 +200,7 @@ Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls,
NULL);
if (srcData == NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jlut, srcLUT, JNI_ABORT);
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "Null data array");
return JNI_FALSE;
}
......@@ -206,6 +209,7 @@ Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls,
if (dstData == NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jlut, srcLUT, JNI_ABORT);
(*env)->ReleasePrimitiveArrayCritical(env, jpix, srcData, JNI_ABORT);
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "Null tile data array");
return JNI_FALSE;
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -182,6 +182,11 @@ static int checkChannelOffsets(RasterS_t *rasterP, int dataArrayLength) {
int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
jobject joffs = NULL;
/* int status;*/
jclass singlePixelPackedSampleModelClass = NULL;
jclass integerComponentRasterClass = NULL;
jclass byteComponentRasterClass = NULL;
jclass shortComponentRasterClass = NULL;
jclass bytePackedRasterClass = NULL;
if (JNU_IsNull(env, jraster)) {
JNU_ThrowNullPointerException(env, "null Raster object");
......@@ -226,8 +231,11 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
rasterP->sppsm.isUsed = 0;
singlePixelPackedSampleModelClass = (*env)->FindClass(env,
"java/awt/image/SinglePixelPackedSampleModel");
CHECK_NULL_RETURN(singlePixelPackedSampleModelClass, -1);
if ((*env)->IsInstanceOf(env, rasterP->jsampleModel,
(*env)->FindClass(env,"java/awt/image/SinglePixelPackedSampleModel"))) {
singlePixelPackedSampleModelClass)) {
jobject jmask, joffs, jnbits;
rasterP->sppsm.isUsed = 1;
......@@ -261,8 +269,15 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
rasterP->jsampleModel,
g_SMHeightID);
if ((*env)->IsInstanceOf(env, jraster,
(*env)->FindClass(env, "sun/awt/image/IntegerComponentRaster"))){
integerComponentRasterClass = (*env)->FindClass(env, "sun/awt/image/IntegerComponentRaster");
CHECK_NULL_RETURN(integerComponentRasterClass, -1);
byteComponentRasterClass = (*env)->FindClass(env, "sun/awt/image/ByteComponentRaster");
CHECK_NULL_RETURN(byteComponentRasterClass, -1);
shortComponentRasterClass = (*env)->FindClass(env,"sun/awt/image/ShortComponentRaster");
CHECK_NULL_RETURN(shortComponentRasterClass, -1);
bytePackedRasterClass = (*env)->FindClass(env, "sun/awt/image/BytePackedRaster");
CHECK_NULL_RETURN(bytePackedRasterClass, -1);
if ((*env)->IsInstanceOf(env, jraster, integerComponentRasterClass)){
rasterP->jdata = (*env)->GetObjectField(env, jraster, g_ICRdataID);
rasterP->dataType = INT_DATA_TYPE;
rasterP->dataSize = 4;
......@@ -273,8 +288,7 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
rasterP->pixelStride = (*env)->GetIntField(env, jraster, g_ICRpixstrID);
joffs = (*env)->GetObjectField(env, jraster, g_ICRdataOffsetsID);
}
else if ((*env)->IsInstanceOf(env, jraster,
(*env)->FindClass(env, "sun/awt/image/ByteComponentRaster"))){
else if ((*env)->IsInstanceOf(env, jraster, byteComponentRasterClass)){
rasterP->jdata = (*env)->GetObjectField(env, jraster, g_BCRdataID);
rasterP->dataType = BYTE_DATA_TYPE;
rasterP->dataSize = 1;
......@@ -285,8 +299,7 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
rasterP->pixelStride = (*env)->GetIntField(env, jraster, g_BCRpixstrID);
joffs = (*env)->GetObjectField(env, jraster, g_BCRdataOffsetsID);
}
else if ((*env)->IsInstanceOf(env, jraster,
(*env)->FindClass(env, "sun/awt/image/ShortComponentRaster"))){
else if ((*env)->IsInstanceOf(env, jraster, shortComponentRasterClass)){
rasterP->jdata = (*env)->GetObjectField(env, jraster, g_SCRdataID);
rasterP->dataType = SHORT_DATA_TYPE;
rasterP->dataSize = 2;
......@@ -297,8 +310,7 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
rasterP->pixelStride = (*env)->GetIntField(env, jraster, g_SCRpixstrID);
joffs = (*env)->GetObjectField(env, jraster, g_SCRdataOffsetsID);
}
else if ((*env)->IsInstanceOf(env, jraster,
(*env)->FindClass(env, "sun/awt/image/BytePackedRaster"))){
else if ((*env)->IsInstanceOf(env, jraster, bytePackedRasterClass)){
rasterP->rasterType = PACKED_RASTER_TYPE;
rasterP->dataType = BYTE_DATA_TYPE;
rasterP->dataSize = 1;
......@@ -397,30 +409,41 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
}
static int getColorModelType(JNIEnv *env, jobject jcmodel) {
int type = UNKNOWN_CM_TYPE;
jclass colorModelClass;
if ((*env)->IsInstanceOf(env, jcmodel,
(*env)->FindClass(env, "java/awt/image/IndexColorModel")))
colorModelClass = (*env)->FindClass(env,
"java/awt/image/IndexColorModel");
CHECK_NULL_RETURN(colorModelClass, UNKNOWN_CM_TYPE);
if ((*env)->IsInstanceOf(env, jcmodel, colorModelClass))
{
type = INDEX_CM_TYPE;
} else if ((*env)->IsInstanceOf(env, jcmodel,
(*env)->FindClass(env, "java/awt/image/PackedColorModel")))
return INDEX_CM_TYPE;
}
colorModelClass = (*env)->FindClass(env,
"java/awt/image/PackedColorModel");
CHECK_NULL_RETURN(colorModelClass, UNKNOWN_CM_TYPE);
if ((*env)->IsInstanceOf(env, jcmodel, colorModelClass))
{
if ((*env)->IsInstanceOf(env, jcmodel,
(*env)->FindClass(env, "java/awt/image/DirectColorModel"))) {
type = DIRECT_CM_TYPE;
colorModelClass = (*env)->FindClass(env,
"java/awt/image/DirectColorModel");
CHECK_NULL_RETURN(colorModelClass, UNKNOWN_CM_TYPE);
if ((*env)->IsInstanceOf(env, jcmodel, colorModelClass)) {
return DIRECT_CM_TYPE;
}
else {
type = PACKED_CM_TYPE;
return PACKED_CM_TYPE;
}
}
else if ((*env)->IsInstanceOf(env, jcmodel,
(*env)->FindClass(env, "java/awt/image/ComponentColorModel")))
colorModelClass = (*env)->FindClass(env,
"java/awt/image/ComponentColorModel");
CHECK_NULL_RETURN(colorModelClass, UNKNOWN_CM_TYPE);
if ((*env)->IsInstanceOf(env, jcmodel, colorModelClass))
{
type = COMPONENT_CM_TYPE;
return COMPONENT_CM_TYPE;
}
return type;
return UNKNOWN_CM_TYPE;
}
int awt_parseColorModel (JNIEnv *env, jobject jcmodel, int imageType,
......@@ -506,12 +529,13 @@ int awt_parseColorModel (JNIEnv *env, jobject jcmodel, int imageType,
if (s_jdefCM == NULL) {
jobject defCM;
jclass jcm = (*env)->FindClass(env, "java/awt/image/ColorModel");
CHECK_NULL_RETURN(jcm, -1);
defCM = (*env)->CallStaticObjectMethod(env, jcm,
g_CMgetRGBdefaultMID, NULL);
s_jdefCM = (*env)->NewGlobalRef(env, defCM);
if (defCM == NULL || s_jdefCM == NULL) {
JNU_ThrowNullPointerException(env,
"Unable to find default CM");
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "Unable to find default CM");
return -1;
}
}
......@@ -931,6 +955,7 @@ int awt_getPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP) {
jdata = (*env)->NewIntArray(env, maxSamples);
if (JNU_IsNull(env, jdata)) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
......@@ -1028,6 +1053,7 @@ int awt_setPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP) {
jdata = (*env)->NewIntArray(env, maxSamples);
if (JNU_IsNull(env, jdata)) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
......
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -104,12 +104,12 @@ static jfieldID outCodeID;
JNIEXPORT void JNICALL
Java_sun_awt_image_GifImageDecoder_initIDs(JNIEnv *env, jclass this)
{
readID = (*env)->GetMethodID(env, this, "readBytes", "([BII)I");
sendID = (*env)->GetMethodID(env, this, "sendPixels",
"(IIII[BLjava/awt/image/ColorModel;)I");
prefixID = (*env)->GetFieldID(env, this, "prefix", "[S");
suffixID = (*env)->GetFieldID(env, this, "suffix", "[B");
outCodeID = (*env)->GetFieldID(env, this, "outCode", "[B");
CHECK_NULL(readID = (*env)->GetMethodID(env, this, "readBytes", "([BII)I"));
CHECK_NULL(sendID = (*env)->GetMethodID(env, this, "sendPixels",
"(IIII[BLjava/awt/image/ColorModel;)I"));
CHECK_NULL(prefixID = (*env)->GetFieldID(env, this, "prefix", "[S"));
CHECK_NULL(suffixID = (*env)->GetFieldID(env, this, "suffix", "[B"));
CHECK_NULL(outCodeID = (*env)->GetFieldID(env, this, "outCode", "[B"));
}
JNIEXPORT jboolean JNICALL
......@@ -292,8 +292,10 @@ Java_sun_awt_image_GifImageDecoder_parseImage(JNIEnv *env,
* reads the immediately subsequent code as uncompressed data.
*/
if (verbose) {
RELEASE_ARRAYS();
fprintf(stdout, ".");
fflush(stdout);
GET_ARRAYS();
}
/* Note that freeCode is one less than it is supposed to be,
......@@ -319,10 +321,10 @@ Java_sun_awt_image_GifImageDecoder_parseImage(JNIEnv *env,
/* make sure we read the whole block of pixels. */
flushit:
while (!blockEnd) {
RELEASE_ARRAYS();
if (verbose) {
fprintf(stdout, "flushing %d bytes\n", blockLength);
}
RELEASE_ARRAYS();
if ((*env)->CallIntMethod(env, this, readID,
blockh, 0, blockLength + 1) != 0
|| (*env)->ExceptionOccurred(env))
......
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -29,211 +29,139 @@
JNIEXPORT void JNICALL
Java_java_awt_image_BufferedImage_initIDs(JNIEnv *env, jclass cls) {
g_BImgRasterID = (*env)->GetFieldID(env, cls, "raster",
"Ljava/awt/image/WritableRaster;");
g_BImgTypeID = (*env)->GetFieldID(env, cls, "imageType", "I");
g_BImgCMID = (*env)->GetFieldID(env, cls, "colorModel",
"Ljava/awt/image/ColorModel;");
g_BImgGetRGBMID = (*env)->GetMethodID(env, cls, "getRGB",
"(IIII[III)[I");
g_BImgSetRGBMID = (*env)->GetMethodID(env, cls, "setRGB",
"(IIII[III)V");
if (g_BImgRasterID == NULL || g_BImgTypeID == NULL || g_BImgCMID == NULL
|| g_BImgGetRGBMID == NULL) {
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_BImgRasterID = (*env)->GetFieldID(env, cls, "raster",
"Ljava/awt/image/WritableRaster;"));
CHECK_NULL(g_BImgTypeID = (*env)->GetFieldID(env, cls, "imageType", "I"));
CHECK_NULL(g_BImgCMID = (*env)->GetFieldID(env, cls, "colorModel",
"Ljava/awt/image/ColorModel;"));
CHECK_NULL(g_BImgGetRGBMID = (*env)->GetMethodID(env, cls, "getRGB",
"(IIII[III)[I"));
CHECK_NULL(g_BImgSetRGBMID = (*env)->GetMethodID(env, cls, "setRGB",
"(IIII[III)V"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_Raster_initIDs(JNIEnv *env, jclass cls) {
g_RasterWidthID = (*env)->GetFieldID(env, cls, "width", "I");
g_RasterHeightID = (*env)->GetFieldID(env, cls, "height", "I");
g_RasterNumBandsID = (*env)->GetFieldID(env, cls, "numBands", "I");
g_RasterGetDataMID = (*env)->GetMethodID(env, cls, "getDataElements",
"(IIIILjava/lang/Object;)Ljava/lang/Object;");
g_RasterMinXID = (*env)->GetFieldID(env, cls, "minX", "I");
g_RasterMinYID = (*env)->GetFieldID(env, cls, "minY", "I");
g_RasterBaseOriginXID = (*env)->GetFieldID(env, cls,
"sampleModelTranslateX", "I");
g_RasterBaseOriginYID = (*env)->GetFieldID(env, cls,
"sampleModelTranslateY", "I");
g_RasterSampleModelID = (*env)->GetFieldID(env, cls,
"sampleModel","Ljava/awt/image/SampleModel;");
g_RasterNumDataElementsID = (*env)->GetFieldID(env, cls, "numDataElements",
"I");
g_RasterNumBandsID = (*env)->GetFieldID(env, cls, "numBands", "I");
g_RasterDataBufferID = (*env)->GetFieldID(env, cls, "dataBuffer",
"Ljava/awt/image/DataBuffer;");
if (g_RasterWidthID == NULL || g_RasterHeightID == NULL
|| g_RasterNumBandsID == NULL || g_RasterGetDataMID == NULL
|| g_RasterMinXID == NULL || g_RasterMinYID == NULL
|| g_RasterBaseOriginXID == NULL || g_RasterBaseOriginYID == NULL
|| g_RasterSampleModelID == NULL || g_RasterNumDataElementsID == NULL
|| g_RasterNumBandsID == NULL || g_RasterDataBufferID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_RasterWidthID = (*env)->GetFieldID(env, cls, "width", "I"));
CHECK_NULL(g_RasterHeightID = (*env)->GetFieldID(env, cls, "height", "I"));
CHECK_NULL(g_RasterNumBandsID = (*env)->GetFieldID(env, cls, "numBands", "I"));
CHECK_NULL(g_RasterGetDataMID = (*env)->GetMethodID(env, cls, "getDataElements",
"(IIIILjava/lang/Object;)Ljava/lang/Object;"));
CHECK_NULL(g_RasterMinXID = (*env)->GetFieldID(env, cls, "minX", "I"));
CHECK_NULL(g_RasterMinYID = (*env)->GetFieldID(env, cls, "minY", "I"));
CHECK_NULL(g_RasterBaseOriginXID = (*env)->GetFieldID(env, cls,
"sampleModelTranslateX", "I"));
CHECK_NULL(g_RasterBaseOriginYID = (*env)->GetFieldID(env, cls,
"sampleModelTranslateY", "I"));
CHECK_NULL(g_RasterSampleModelID = (*env)->GetFieldID(env, cls,
"sampleModel","Ljava/awt/image/SampleModel;"));
CHECK_NULL(g_RasterNumDataElementsID = (*env)->GetFieldID(env, cls,
"numDataElements", "I"));
CHECK_NULL(g_RasterNumBandsID = (*env)->GetFieldID(env, cls, "numBands", "I"));
CHECK_NULL(g_RasterDataBufferID = (*env)->GetFieldID(env, cls, "dataBuffer",
"Ljava/awt/image/DataBuffer;"));
}
JNIEXPORT void JNICALL
Java_sun_awt_image_ByteComponentRaster_initIDs(JNIEnv *env, jclass cls) {
g_BCRdataID = (*env)->GetFieldID(env, cls, "data", "[B");
g_BCRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I");
g_BCRpixstrID = (*env)->GetFieldID(env, cls, "pixelStride", "I");
g_BCRbandoffsID = (*env)->GetFieldID(env, cls, "bandOffset", "I");
g_BCRdataOffsetsID = (*env)->GetFieldID(env, cls, "dataOffsets", "[I");
g_BCRtypeID = (*env)->GetFieldID(env, cls, "type", "I");
if (g_BCRdataID == NULL || g_BCRscanstrID == NULL ||
g_BCRpixstrID == NULL || g_BCRbandoffsID == NULL ||
g_BCRtypeID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_BCRdataID = (*env)->GetFieldID(env, cls, "data", "[B"));
CHECK_NULL(g_BCRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I"));
CHECK_NULL(g_BCRpixstrID = (*env)->GetFieldID(env, cls, "pixelStride", "I"));
CHECK_NULL(g_BCRbandoffsID = (*env)->GetFieldID(env, cls, "bandOffset", "I"));
CHECK_NULL(g_BCRdataOffsetsID = (*env)->GetFieldID(env, cls, "dataOffsets", "[I"));
CHECK_NULL(g_BCRtypeID = (*env)->GetFieldID(env, cls, "type", "I"));
}
JNIEXPORT void JNICALL
Java_sun_awt_image_BytePackedRaster_initIDs(JNIEnv *env, jclass cls) {
g_BPRdataID = (*env)->GetFieldID(env, cls, "data", "[B");
g_BPRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I");
g_BPRpixstrID = (*env)->GetFieldID(env, cls, "pixelBitStride", "I");
g_BPRtypeID = (*env)->GetFieldID(env, cls, "type", "I");
g_BPRdataBitOffsetID = (*env)->GetFieldID(env, cls, "dataBitOffset", "I");
if (g_BPRdataID == NULL || g_BPRscanstrID == NULL ||
g_BPRpixstrID == NULL || g_BPRtypeID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_BPRdataID = (*env)->GetFieldID(env, cls, "data", "[B"));
CHECK_NULL(g_BPRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I"));
CHECK_NULL(g_BPRpixstrID = (*env)->GetFieldID(env, cls, "pixelBitStride", "I"));
CHECK_NULL(g_BPRtypeID = (*env)->GetFieldID(env, cls, "type", "I"));
CHECK_NULL(g_BPRdataBitOffsetID = (*env)->GetFieldID(env, cls, "dataBitOffset", "I"));
}
JNIEXPORT void JNICALL
Java_sun_awt_image_ShortComponentRaster_initIDs(JNIEnv *env, jclass cls) {
g_SCRdataID = (*env)->GetFieldID(env, cls, "data", "[S");
g_SCRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I");
g_SCRpixstrID = (*env)->GetFieldID(env, cls, "pixelStride", "I");
g_SCRbandoffsID = (*env)->GetFieldID(env, cls, "bandOffset", "I");
g_SCRdataOffsetsID = (*env)->GetFieldID(env, cls, "dataOffsets", "[I");
g_SCRtypeID = (*env)->GetFieldID(env, cls, "type", "I");
if (g_SCRdataID == NULL || g_SCRscanstrID == NULL ||
g_SCRpixstrID == NULL || g_SCRbandoffsID == NULL ||
g_SCRdataOffsetsID == NULL || g_SCRtypeID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_SCRdataID = (*env)->GetFieldID(env, cls, "data", "[S"));
CHECK_NULL(g_SCRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I"));
CHECK_NULL(g_SCRpixstrID = (*env)->GetFieldID(env, cls, "pixelStride", "I"));
CHECK_NULL(g_SCRbandoffsID = (*env)->GetFieldID(env, cls, "bandOffset", "I"));
CHECK_NULL(g_SCRdataOffsetsID = (*env)->GetFieldID(env, cls, "dataOffsets", "[I"));
CHECK_NULL(g_SCRtypeID = (*env)->GetFieldID(env, cls, "type", "I"));
}
JNIEXPORT void JNICALL
Java_sun_awt_image_IntegerComponentRaster_initIDs(JNIEnv *env, jclass cls) {
g_ICRdataID = (*env)->GetFieldID(env, cls, "data", "[I");
g_ICRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I");
g_ICRpixstrID = (*env)->GetFieldID(env, cls, "pixelStride", "I");
g_ICRdataOffsetsID = (*env)->GetFieldID(env, cls, "dataOffsets", "[I");
g_ICRbandoffsID = (*env)->GetFieldID(env, cls, "bandOffset", "I");
g_ICRputDataMID = (*env)->GetMethodID(env, cls, "setDataElements",
"(IIIILjava/lang/Object;)V");
g_ICRtypeID = (*env)->GetFieldID(env, cls, "type", "I");
if (g_ICRdataID == NULL || g_ICRscanstrID == NULL
|| g_ICRpixstrID == NULL || g_ICRbandoffsID == NULL
|| g_ICRputDataMID == NULL || g_ICRdataOffsetsID == NULL || g_ICRtypeID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_ICRdataID = (*env)->GetFieldID(env, cls, "data", "[I"));
CHECK_NULL(g_ICRscanstrID = (*env)->GetFieldID(env, cls, "scanlineStride", "I"));
CHECK_NULL(g_ICRpixstrID = (*env)->GetFieldID(env, cls, "pixelStride", "I"));
CHECK_NULL(g_ICRdataOffsetsID = (*env)->GetFieldID(env, cls, "dataOffsets", "[I"));
CHECK_NULL(g_ICRbandoffsID = (*env)->GetFieldID(env, cls, "bandOffset", "I"));
CHECK_NULL(g_ICRputDataMID = (*env)->GetMethodID(env, cls, "setDataElements",
"(IIIILjava/lang/Object;)V"));
CHECK_NULL(g_ICRtypeID = (*env)->GetFieldID(env, cls, "type", "I"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_SinglePixelPackedSampleModel_initIDs(JNIEnv *env,
jclass cls) {
g_SPPSMmaskArrID = (*env)->GetFieldID(env, cls, "bitMasks", "[I");
g_SPPSMmaskOffID = (*env)->GetFieldID(env, cls, "bitOffsets", "[I");
g_SPPSMnBitsID = (*env)->GetFieldID(env, cls, "bitSizes", "[I");
g_SPPSMmaxBitID = (*env)->GetFieldID(env, cls, "maxBitSize", "I");
if (g_SPPSMmaskArrID == NULL || g_SPPSMmaskOffID == NULL ||
g_SPPSMnBitsID == NULL || g_SPPSMmaxBitID == NULL) {
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
Java_java_awt_image_SinglePixelPackedSampleModel_initIDs(JNIEnv *env, jclass cls) {
CHECK_NULL(g_SPPSMmaskArrID = (*env)->GetFieldID(env, cls, "bitMasks", "[I"));
CHECK_NULL(g_SPPSMmaskOffID = (*env)->GetFieldID(env, cls, "bitOffsets", "[I"));
CHECK_NULL(g_SPPSMnBitsID = (*env)->GetFieldID(env, cls, "bitSizes", "[I"));
CHECK_NULL(g_SPPSMmaxBitID = (*env)->GetFieldID(env, cls, "maxBitSize", "I"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_ColorModel_initIDs(JNIEnv *env, jclass cls) {
g_CMpDataID = (*env)->GetFieldID (env, cls, "pData", "J");
g_CMnBitsID = (*env)->GetFieldID(env, cls, "nBits", "[I");
g_CMcspaceID = (*env)->GetFieldID(env, cls, "colorSpace",
"Ljava/awt/color/ColorSpace;");
g_CMnumComponentsID = (*env)->GetFieldID(env, cls, "numComponents", "I");
g_CMsuppAlphaID = (*env)->GetFieldID(env, cls, "supportsAlpha", "Z");
g_CMisAlphaPreID = (*env)->GetFieldID(env, cls, "isAlphaPremultiplied",
"Z");
g_CMtransparencyID = (*env)->GetFieldID(env, cls, "transparency", "I");
g_CMgetRGBMID = (*env)->GetMethodID(env, cls, "getRGB",
"(Ljava/lang/Object;)I");
g_CMcsTypeID = (*env)->GetFieldID(env, cls, "colorSpaceType", "I");
g_CMis_sRGBID = (*env)->GetFieldID(env, cls, "is_sRGB", "Z");
g_CMgetRGBdefaultMID = (*env)->GetStaticMethodID(env, cls,
CHECK_NULL(g_CMpDataID = (*env)->GetFieldID (env, cls, "pData", "J"));
CHECK_NULL(g_CMnBitsID = (*env)->GetFieldID(env, cls, "nBits", "[I"));
CHECK_NULL(g_CMcspaceID = (*env)->GetFieldID(env, cls, "colorSpace",
"Ljava/awt/color/ColorSpace;"));
CHECK_NULL(g_CMnumComponentsID = (*env)->GetFieldID(env, cls, "numComponents", "I"));
CHECK_NULL(g_CMsuppAlphaID = (*env)->GetFieldID(env, cls, "supportsAlpha", "Z"));
CHECK_NULL(g_CMisAlphaPreID = (*env)->GetFieldID(env, cls, "isAlphaPremultiplied",
"Z"));
CHECK_NULL(g_CMtransparencyID = (*env)->GetFieldID(env, cls, "transparency", "I"));
CHECK_NULL(g_CMgetRGBMID = (*env)->GetMethodID(env, cls, "getRGB",
"(Ljava/lang/Object;)I"));
CHECK_NULL(g_CMcsTypeID = (*env)->GetFieldID(env, cls, "colorSpaceType", "I"));
CHECK_NULL(g_CMis_sRGBID = (*env)->GetFieldID(env, cls, "is_sRGB", "Z"));
CHECK_NULL(g_CMgetRGBdefaultMID = (*env)->GetStaticMethodID(env, cls,
"getRGBdefault",
"()Ljava/awt/image/ColorModel;");
if (g_CMnBitsID == NULL || g_CMcspaceID == NULL
|| g_CMnumComponentsID == NULL || g_CMsuppAlphaID == NULL
|| g_CMisAlphaPreID == NULL || g_CMtransparencyID == NULL
|| g_CMgetRGBMID == NULL || g_CMgetRGBMID == NULL
|| g_CMis_sRGBID == NULL || g_CMgetRGBdefaultMID == NULL
|| g_CMpDataID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
"()Ljava/awt/image/ColorModel;"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_IndexColorModel_initIDs(JNIEnv *env, jclass cls) {
g_ICMtransIdxID = (*env)->GetFieldID(env, cls, "transparent_index", "I");
g_ICMmapSizeID = (*env)->GetFieldID(env, cls, "map_size", "I");
g_ICMrgbID = (*env)->GetFieldID(env, cls, "rgb", "[I");
if (g_ICMtransIdxID == NULL || g_ICMmapSizeID == NULL
|| g_ICMrgbID == NULL) {
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_ICMtransIdxID = (*env)->GetFieldID(env, cls, "transparent_index", "I"));
CHECK_NULL(g_ICMmapSizeID = (*env)->GetFieldID(env, cls, "map_size", "I"));
CHECK_NULL(g_ICMrgbID = (*env)->GetFieldID(env, cls, "rgb", "[I"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_SampleModel_initIDs(JNIEnv *env, jclass cls) {
g_SMWidthID = (*env)->GetFieldID(env, cls, "width","I");
g_SMHeightID = (*env)->GetFieldID(env, cls, "height","I");
g_SMGetPixelsMID = (*env)->GetMethodID(env, cls, "getPixels",
"(IIII[ILjava/awt/image/DataBuffer;)[I");
g_SMSetPixelsMID = (*env)->GetMethodID(env, cls, "setPixels",
"(IIII[ILjava/awt/image/DataBuffer;)V");
if (g_SMWidthID == NULL || g_SMHeightID == NULL || g_SMGetPixelsMID == NULL
|| g_SMSetPixelsMID == NULL) {
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_SMWidthID = (*env)->GetFieldID(env, cls, "width","I"));
CHECK_NULL(g_SMHeightID = (*env)->GetFieldID(env, cls, "height","I"));
CHECK_NULL(g_SMGetPixelsMID = (*env)->GetMethodID(env, cls, "getPixels",
"(IIII[ILjava/awt/image/DataBuffer;)[I"));
CHECK_NULL(g_SMSetPixelsMID = (*env)->GetMethodID(env, cls, "setPixels",
"(IIII[ILjava/awt/image/DataBuffer;)V"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_ComponentSampleModel_initIDs(JNIEnv *env, jclass cls) {
g_CSMPixStrideID = (*env)->GetFieldID(env, cls, "pixelStride", "I");
g_CSMScanStrideID = (*env)->GetFieldID(env, cls, "scanlineStride", "I");
g_CSMBandOffsetsID = (*env)->GetFieldID(env, cls, "bandOffsets", "[I");
if (g_CSMPixStrideID == NULL || g_CSMScanStrideID == NULL ||
g_CSMBandOffsetsID == NULL) {
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_CSMPixStrideID = (*env)->GetFieldID(env, cls, "pixelStride", "I"));
CHECK_NULL(g_CSMScanStrideID = (*env)->GetFieldID(env, cls, "scanlineStride", "I"));
CHECK_NULL(g_CSMBandOffsetsID = (*env)->GetFieldID(env, cls, "bandOffsets", "[I"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_Kernel_initIDs(JNIEnv *env, jclass cls) {
g_KernelWidthID = (*env)->GetFieldID(env, cls, "width", "I");
g_KernelHeightID = (*env)->GetFieldID(env, cls, "height", "I");
g_KernelDataID = (*env)->GetFieldID(env, cls, "data", "[F");
if (g_KernelWidthID == NULL || g_KernelHeightID == NULL
|| g_KernelDataID == NULL)
{
JNU_ThrowNullPointerException(env, "Unable to grab field ids");
}
CHECK_NULL(g_KernelWidthID = (*env)->GetFieldID(env, cls, "width", "I"));
CHECK_NULL(g_KernelHeightID = (*env)->GetFieldID(env, cls, "height", "I"));
CHECK_NULL(g_KernelDataID = (*env)->GetFieldID(env, cls, "data", "[F"));
}
JNIEXPORT void JNICALL
Java_java_awt_image_DataBufferInt_initIDs(JNIEnv *env, jclass cls) {
g_DataBufferIntPdataID = (*env)->GetFieldID(env, cls, "pData", "J");
if (g_DataBufferIntPdataID == NULL) {
JNU_ThrowNullPointerException(env, "Unable to grab DataBufferInt.pData");
return;
}
CHECK_NULL(g_DataBufferIntPdataID = (*env)->GetFieldID(env, cls, "pData", "J"));
}
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -153,6 +153,7 @@ static int initStreamBuffer(JNIEnv *env, streamBufferPtr sb) {
/* Initialize a new buffer */
jbyteArray hInputBuffer = (*env)->NewByteArray(env, STREAMBUF_SIZE);
if (hInputBuffer == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowByName( env,
"java/lang/OutOfMemoryError",
"Initializing Reader");
......@@ -557,6 +558,7 @@ sun_jpeg_output_message (j_common_ptr cinfo)
// Create a new java string from the message
string = (*env)->NewStringUTF(env, buffer);
CHECK_NULL(string);
theObject = data->imageIOobj;
......@@ -591,12 +593,7 @@ static void imageio_set_stream(JNIEnv *env,
/* Now we need a new weak global reference for the I/O provider */
if (io != NULL) { // Fix for 4411955
sb->ioRef = (*env)->NewWeakGlobalRef(env, io);
if (sb->ioRef == NULL) {
JNU_ThrowByName(env,
"java/lang/OutOfMemoryError",
"Setting I/O provider");
return;
}
CHECK_NULL(sb->ioRef);
}
/* And finally reset state */
......@@ -693,6 +690,7 @@ static int setQTables(JNIEnv *env,
}
for (i = 0; i < qlen; i++) {
table = (*env)->GetObjectArrayElement(env, qtables, i);
CHECK_NULL_RETURN(table, 0);
qdata = (*env)->GetObjectField(env, table, JPEGQTable_tableID);
qdataBody = (*env)->GetPrimitiveArrayCritical(env, qdata, NULL);
......@@ -724,7 +722,7 @@ static int setQTables(JNIEnv *env,
return qlen;
}
static void setHuffTable(JNIEnv *env,
static boolean setHuffTable(JNIEnv *env,
JHUFF_TBL *huff_ptr,
jobject table) {
......@@ -742,6 +740,8 @@ static void setHuffTable(JNIEnv *env,
hlensBody = (*env)->GetShortArrayElements(env,
huffLens,
NULL);
CHECK_NULL_RETURN(hlensBody, FALSE);
if (hlensLen > 16) {
/* Ignore extra elements of bits array. Only 16 elements can be
stored. 0-th element is not used. (see jpeglib.h, line 107) */
......@@ -762,6 +762,7 @@ static void setHuffTable(JNIEnv *env,
hvalsBody = (*env)->GetShortArrayElements(env,
huffValues,
NULL);
CHECK_NULL_RETURN(hvalsBody, FALSE);
if (hvalsLen > 256) {
/* Ignore extra elements of hufval array. Only 256 elements
......@@ -775,6 +776,7 @@ static void setHuffTable(JNIEnv *env,
huffValues,
hvalsBody,
JNI_ABORT);
return TRUE;
}
static int setHTables(JNIEnv *env,
......@@ -810,7 +812,9 @@ static int setHTables(JNIEnv *env,
huff_ptr = comp->dc_huff_tbl_ptrs[i];
}
table = (*env)->GetObjectArrayElement(env, DCHuffmanTables, i);
setHuffTable(env, huff_ptr, table);
if (table == NULL || !setHuffTable(env, huff_ptr, table)) {
return 0;
}
huff_ptr->sent_table = !write;
}
hlen = (*env)->GetArrayLength(env, ACHuffmanTables);
......@@ -835,7 +839,9 @@ static int setHTables(JNIEnv *env,
huff_ptr = comp->ac_huff_tbl_ptrs[i];
}
table = (*env)->GetObjectArrayElement(env, ACHuffmanTables, i);
setHuffTable(env, huff_ptr, table);
if(table == NULL || !setHuffTable(env, huff_ptr, table)) {
return 0;
}
huff_ptr->sent_table = !write;
}
return hlen;
......@@ -1409,57 +1415,57 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_initReaderIDs
jclass qTableClass,
jclass huffClass) {
JPEGImageReader_readInputDataID = (*env)->GetMethodID(env,
CHECK_NULL(JPEGImageReader_readInputDataID = (*env)->GetMethodID(env,
cls,
"readInputData",
"([BII)I");
JPEGImageReader_skipInputBytesID = (*env)->GetMethodID(env,
"([BII)I"));
CHECK_NULL(JPEGImageReader_skipInputBytesID = (*env)->GetMethodID(env,
cls,
"skipInputBytes",
"(J)J");
JPEGImageReader_warningOccurredID = (*env)->GetMethodID(env,
"(J)J"));
CHECK_NULL(JPEGImageReader_warningOccurredID = (*env)->GetMethodID(env,
cls,
"warningOccurred",
"(I)V");
JPEGImageReader_warningWithMessageID =
"(I)V"));
CHECK_NULL(JPEGImageReader_warningWithMessageID =
(*env)->GetMethodID(env,
cls,
"warningWithMessage",
"(Ljava/lang/String;)V");
JPEGImageReader_setImageDataID = (*env)->GetMethodID(env,
"(Ljava/lang/String;)V"));
CHECK_NULL(JPEGImageReader_setImageDataID = (*env)->GetMethodID(env,
cls,
"setImageData",
"(IIIII[B)V");
JPEGImageReader_acceptPixelsID = (*env)->GetMethodID(env,
"(IIIII[B)V"));
CHECK_NULL(JPEGImageReader_acceptPixelsID = (*env)->GetMethodID(env,
cls,
"acceptPixels",
"(IZ)V");
JPEGImageReader_passStartedID = (*env)->GetMethodID(env,
"(IZ)V"));
CHECK_NULL(JPEGImageReader_passStartedID = (*env)->GetMethodID(env,
cls,
"passStarted",
"(I)V");
JPEGImageReader_passCompleteID = (*env)->GetMethodID(env,
"(I)V"));
CHECK_NULL(JPEGImageReader_passCompleteID = (*env)->GetMethodID(env,
cls,
"passComplete",
"()V");
JPEGImageReader_pushBackID = (*env)->GetMethodID(env,
"()V"));
CHECK_NULL(JPEGImageReader_pushBackID = (*env)->GetMethodID(env,
cls,
"pushBack",
"(I)V");
JPEGQTable_tableID = (*env)->GetFieldID(env,
"(I)V"));
CHECK_NULL(JPEGQTable_tableID = (*env)->GetFieldID(env,
qTableClass,
"qTable",
"[I");
"[I"));
JPEGHuffmanTable_lengthsID = (*env)->GetFieldID(env,
CHECK_NULL(JPEGHuffmanTable_lengthsID = (*env)->GetFieldID(env,
huffClass,
"lengths",
"[S");
"[S"));
JPEGHuffmanTable_valuesID = (*env)->GetFieldID(env,
CHECK_NULL(JPEGHuffmanTable_valuesID = (*env)->GetFieldID(env,
huffClass,
"values",
"[S");
"[S"));
}
JNIEXPORT jlong JNICALL
......@@ -1540,9 +1546,9 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_initJPEGImageReader
/* set up the association to persist for future calls */
ret = initImageioData(env, (j_common_ptr) cinfo, this);
if (ret == NULL) {
JNU_ThrowByName( env,
"java/lang/OutOfMemoryError",
"Initializing Reader");
(*env)->ExceptionClear(env);
JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
"Initializing Reader");
imageio_dispose((j_common_ptr)cinfo);
return 0;
}
......@@ -1637,6 +1643,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader
#endif
if (GET_ARRAYS(env, data, &src->next_input_byte) == NOT_OK) {
(*env)->ExceptionClear(env);
JNU_ThrowByName(env,
"javax/imageio/IIOException",
"Array pin failed");
......@@ -1900,6 +1907,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImage
body = (*env)->GetIntArrayElements(env, srcBands, NULL);
if (body == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowByName( env,
"java/lang/OutOfMemoryError",
"Initializing Read");
......@@ -1958,6 +1966,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImage
}
if (GET_ARRAYS(env, data, &src->next_input_byte) == NOT_OK) {
(*env)->ExceptionClear(env);
JNU_ThrowByName(env,
"javax/imageio/IIOException",
"Array pin failed");
......@@ -2403,44 +2412,39 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_initWriterIDs
jclass qTableClass,
jclass huffClass) {
JPEGImageWriter_writeOutputDataID = (*env)->GetMethodID(env,
CHECK_NULL(JPEGImageWriter_writeOutputDataID = (*env)->GetMethodID(env,
cls,
"writeOutputData",
"([BII)V");
JPEGImageWriter_warningOccurredID = (*env)->GetMethodID(env,
"([BII)V"));
CHECK_NULL(JPEGImageWriter_warningOccurredID = (*env)->GetMethodID(env,
cls,
"warningOccurred",
"(I)V");
JPEGImageWriter_warningWithMessageID =
(*env)->GetMethodID(env,
cls,
"warningWithMessage",
"(Ljava/lang/String;)V");
JPEGImageWriter_writeMetadataID = (*env)->GetMethodID(env,
"(I)V"));
CHECK_NULL(JPEGImageWriter_warningWithMessageID =
(*env)->GetMethodID(env,
cls,
"warningWithMessage",
"(Ljava/lang/String;)V"));
CHECK_NULL(JPEGImageWriter_writeMetadataID = (*env)->GetMethodID(env,
cls,
"writeMetadata",
"()V");
JPEGImageWriter_grabPixelsID = (*env)->GetMethodID(env,
"()V"));
CHECK_NULL(JPEGImageWriter_grabPixelsID = (*env)->GetMethodID(env,
cls,
"grabPixels",
"(I)V");
JPEGQTable_tableID = (*env)->GetFieldID(env,
"(I)V"));
CHECK_NULL(JPEGQTable_tableID = (*env)->GetFieldID(env,
qTableClass,
"qTable",
"[I");
JPEGHuffmanTable_lengthsID = (*env)->GetFieldID(env,
"[I"));
CHECK_NULL(JPEGHuffmanTable_lengthsID = (*env)->GetFieldID(env,
huffClass,
"lengths",
"[S");
JPEGHuffmanTable_valuesID = (*env)->GetFieldID(env,
"[S"));
CHECK_NULL(JPEGHuffmanTable_valuesID = (*env)->GetFieldID(env,
huffClass,
"values",
"[S");
"[S"));
}
JNIEXPORT jlong JNICALL
......@@ -2516,6 +2520,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_initJPEGImageWriter
/* set up the association to persist for future calls */
ret = initImageioData(env, (j_common_ptr) cinfo, this);
if (ret == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowByName( env,
"java/lang/OutOfMemoryError",
"Initializing Writer");
......@@ -2593,6 +2598,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeTables
if (GET_ARRAYS(env, data,
(const JOCTET **)(&dest->next_output_byte)) == NOT_OK) {
(*env)->ExceptionClear(env);
JNU_ThrowByName(env,
"javax/imageio/IIOException",
"Array pin failed");
......@@ -2664,6 +2670,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
imageIODataPtr data = (imageIODataPtr)jlong_to_ptr(ptr);
j_compress_ptr cinfo;
UINT8** scale = NULL;
boolean success = TRUE;
/* verify the inputs */
......@@ -2708,13 +2715,14 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
}
bandSize = (*env)->GetIntArrayElements(env, bandSizes, NULL);
CHECK_NULL_RETURN(bandSize, JNI_FALSE);
for (i = 0; i < numBands; i++) {
if (bandSize[i] <= 0 || bandSize[i] > JPEG_BAND_SIZE) {
(*env)->ReleaseIntArrayElements(env, bandSizes,
bandSize, JNI_ABORT);
JNU_ThrowByName(env, "javax/imageio/IIOException", "Invalid Image");
return JNI_FALSE;;
return JNI_FALSE;
}
}
......@@ -2825,30 +2833,30 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
vfactors = (*env)->GetIntArrayElements(env, VsamplingFactors, NULL);
qsels = (*env)->GetIntArrayElements(env, QtableSelectors, NULL);
if ((ids == NULL) ||
(hfactors == NULL) || (vfactors == NULL) ||
(qsels == NULL)) {
JNU_ThrowByName( env,
"java/lang/OutOfMemoryError",
"Writing JPEG");
return JNI_FALSE;
if (ids && hfactors && vfactors && qsels) {
for (i = 0; i < numBands; i++) {
cinfo->comp_info[i].component_id = ids[i];
cinfo->comp_info[i].h_samp_factor = hfactors[i];
cinfo->comp_info[i].v_samp_factor = vfactors[i];
cinfo->comp_info[i].quant_tbl_no = qsels[i];
}
} else {
success = FALSE;
}
for (i = 0; i < numBands; i++) {
cinfo->comp_info[i].component_id = ids[i];
cinfo->comp_info[i].h_samp_factor = hfactors[i];
cinfo->comp_info[i].v_samp_factor = vfactors[i];
cinfo->comp_info[i].quant_tbl_no = qsels[i];
if (ids) {
(*env)->ReleaseIntArrayElements(env, componentIds, ids, JNI_ABORT);
}
(*env)->ReleaseIntArrayElements(env, componentIds,
ids, JNI_ABORT);
(*env)->ReleaseIntArrayElements(env, HsamplingFactors,
hfactors, JNI_ABORT);
(*env)->ReleaseIntArrayElements(env, VsamplingFactors,
vfactors, JNI_ABORT);
(*env)->ReleaseIntArrayElements(env, QtableSelectors,
qsels, JNI_ABORT);
if (hfactors) {
(*env)->ReleaseIntArrayElements(env, HsamplingFactors, hfactors, JNI_ABORT);
}
if (vfactors) {
(*env)->ReleaseIntArrayElements(env, VsamplingFactors, vfactors, JNI_ABORT);
}
if (qsels) {
(*env)->ReleaseIntArrayElements(env, QtableSelectors, qsels, JNI_ABORT);
}
if (!success) return data->abortFlag;
jpeg_suppress_tables(cinfo, TRUE); // Disable writing any current
......@@ -2865,6 +2873,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
if (GET_ARRAYS(env, data,
(const JOCTET **)(&dest->next_output_byte)) == NOT_OK) {
(*env)->ExceptionClear(env);
JNU_ThrowByName(env,
"javax/imageio/IIOException",
"Array pin failed");
......@@ -2899,6 +2908,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
cinfo->scan_info = cinfo->script_space;
scanptr = (int *) cinfo->script_space;
scanData = (*env)->GetIntArrayElements(env, scanInfo, NULL);
CHECK_NULL_RETURN(scanData, data->abortFlag);
// number of jints per scan is 9
// We avoid a memcpy to handle different size ints
for (i = 0; i < numScans*9; i++) {
......
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -465,14 +465,14 @@ JNIEXPORT void JNICALL
Java_sun_awt_image_JPEGImageDecoder_initIDs(JNIEnv *env, jclass cls,
jclass InputStreamClass)
{
sendHeaderInfoID = (*env)->GetMethodID(env, cls, "sendHeaderInfo",
"(IIZZZ)Z");
sendPixelsByteID = (*env)->GetMethodID(env, cls, "sendPixels", "([BI)Z");
sendPixelsIntID = (*env)->GetMethodID(env, cls, "sendPixels", "([II)Z");
InputStream_readID = (*env)->GetMethodID(env, InputStreamClass,
"read", "([BII)I");
InputStream_availableID = (*env)->GetMethodID(env, InputStreamClass,
"available", "()I");
CHECK_NULL(sendHeaderInfoID = (*env)->GetMethodID(env, cls, "sendHeaderInfo",
"(IIZZZ)Z"));
CHECK_NULL(sendPixelsByteID = (*env)->GetMethodID(env, cls, "sendPixels", "([BI)Z"));
CHECK_NULL(sendPixelsIntID = (*env)->GetMethodID(env, cls, "sendPixels", "([II)Z"));
CHECK_NULL(InputStream_readID = (*env)->GetMethodID(env, InputStreamClass,
"read", "([BII)I"));
CHECK_NULL(InputStream_availableID = (*env)->GetMethodID(env, InputStreamClass,
"available", "()I"));
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -1151,6 +1151,7 @@ fprintf(stderr,"Flags : %d\n",dst->flags);
if (ddata == NULL) {
/* Need to store it back into the array */
if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
(*env)->ExceptionClear(env); // Could not store the array, try another way
retStatus = setPixelsFormMlibImage(env, dstRasterP, dst);
}
}
......@@ -2062,6 +2063,7 @@ cvtCustomToDefault(JNIEnv *env, BufImageS_t *imageP, int component,
jpixels = (*env)->NewIntArray(env, nbytes);
if (JNU_IsNull(env, jpixels)) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
......@@ -2127,6 +2129,7 @@ cvtDefaultToCustom(JNIEnv *env, BufImageS_t *imageP, int component,
jpixels = (*env)->NewIntArray(env, nbytes);
if (JNU_IsNull(env, jpixels)) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
......@@ -2823,21 +2826,14 @@ static int expandICM(JNIEnv *env, BufImageS_t *imageP, unsigned int *mDataP)
/* Need to grab the lookup tables. Right now only bytes */
rgb = (int *) (*env)->GetPrimitiveArrayCritical(env, cmP->jrgb, NULL);
CHECK_NULL_RETURN(rgb, -1);
/* Interleaved with shared data */
dataP = (void *) (*env)->GetPrimitiveArrayCritical(env,
rasterP->jdata, NULL);
if (rgb == NULL || dataP == NULL) {
if (dataP == NULL) {
/* Release the lookup tables */
if (rgb) {
(*env)->ReleasePrimitiveArrayCritical(env, cmP->jrgb, rgb,
JNI_ABORT);
}
if (dataP) {
(*env)->ReleasePrimitiveArrayCritical(env,
rasterP->jdata, dataP,
JNI_ABORT);
}
(*env)->ReleasePrimitiveArrayCritical(env, cmP->jrgb, rgb, JNI_ABORT);
return -1;
}
......
......@@ -25,10 +25,23 @@
package java.lang;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.security.AccessController;
import static java.security.AccessController.doPrivileged;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
/* java.lang.Process subclass in the UNIX environment.
*
......@@ -108,14 +121,15 @@ final class UNIXProcess extends Process {
* - fork(2) and exec(2)
* - posix_spawn(2)
*
* @param std_fds array of file descriptors. Indexes 0, 1, and
* 2 correspond to standard input, standard output and
* standard error, respectively. On input, a value of -1
* means to create a pipe to connect child and parent
* processes. On output, a value which is not -1 is the
* parent pipe fd corresponding to the pipe which has
* been created. An element of this array is -1 on input
* if and only if it is <em>not</em> -1 on output.
* @param fds an array of three file descriptors.
* Indexes 0, 1, and 2 correspond to standard input,
* standard output and standard error, respectively. On
* input, a value of -1 means to create a pipe to connect
* child and parent processes. On output, a value which
* is not -1 is the parent pipe fd corresponding to the
* pipe which has been created. An element of this array
* is -1 on input if and only if it is <em>not</em> -1 on
* output.
* @return the pid of the subprocess
*/
private native int forkAndExec(int mode, byte[] helperpath,
......@@ -123,15 +137,51 @@ final class UNIXProcess extends Process {
byte[] argBlock, int argc,
byte[] envBlock, int envc,
byte[] dir,
int[] std_fds,
int[] fds,
boolean redirectErrorStream)
throws IOException;
/**
* The thread factory used to create "process reaper" daemon threads.
*/
private static class ProcessReaperThreadFactory implements ThreadFactory {
private final static ThreadGroup group = getRootThreadGroup();
private static ThreadGroup getRootThreadGroup() {
return doPrivileged(new PrivilegedAction<ThreadGroup> () {
public ThreadGroup run() {
ThreadGroup root = Thread.currentThread().getThreadGroup();
while (root.getParent() != null)
root = root.getParent();
return root;
}});
}
public Thread newThread(Runnable grimReaper) {
// Our thread stack requirement is quite modest.
Thread t = new Thread(group, grimReaper, "process reaper", 32768);
t.setDaemon(true);
// A small attempt (probably futile) to avoid priority inversion
t.setPriority(Thread.MAX_PRIORITY);
return t;
}
}
/**
* The thread pool of "process reaper" daemon threads.
*/
private static final Executor processReaperExecutor =
doPrivileged(new PrivilegedAction<Executor>() {
public Executor run() {
return Executors.newCachedThreadPool
(new ProcessReaperThreadFactory());
}});
UNIXProcess(final byte[] prog,
final byte[] argBlock, int argc,
final byte[] envBlock, int envc,
final byte[] dir,
final int[] std_fds,
final int[] fds,
final boolean redirectErrorStream)
throws IOException {
pid = forkAndExec(launchMechanism.value,
......@@ -140,63 +190,62 @@ final class UNIXProcess extends Process {
argBlock, argc,
envBlock, envc,
dir,
std_fds,
fds,
redirectErrorStream);
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() { public Void run() {
if (std_fds[0] == -1)
stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE;
else {
FileDescriptor stdin_fd = new FileDescriptor();
fdAccess.set(stdin_fd, std_fds[0]);
stdin_stream = new BufferedOutputStream(
new FileOutputStream(stdin_fd));
}
try {
doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException {
initStreams(fds);
return null;
}
});
} catch (PrivilegedActionException ex) {
throw (IOException) ex.getException();
}
}
if (std_fds[1] == -1)
stdout_stream = ProcessBuilder.NullInputStream.INSTANCE;
else {
FileDescriptor stdout_fd = new FileDescriptor();
fdAccess.set(stdout_fd, std_fds[1]);
stdout_inner_stream = new DeferredCloseInputStream(stdout_fd);
stdout_stream = new BufferedInputStream(stdout_inner_stream);
}
void initStreams(int[] fds) throws IOException {
if (fds[0] == -1)
stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE;
else {
FileDescriptor stdin_fd = new FileDescriptor();
fdAccess.set(stdin_fd, fds[0]);
stdin_stream = new BufferedOutputStream(
new FileOutputStream(stdin_fd));
}
if (std_fds[2] == -1)
stderr_stream = ProcessBuilder.NullInputStream.INSTANCE;
else {
FileDescriptor stderr_fd = new FileDescriptor();
fdAccess.set(stderr_fd, std_fds[2]);
stderr_stream = new DeferredCloseInputStream(stderr_fd);
}
if (fds[1] == -1)
stdout_stream = ProcessBuilder.NullInputStream.INSTANCE;
else {
FileDescriptor stdout_fd = new FileDescriptor();
fdAccess.set(stdout_fd, fds[1]);
stdout_inner_stream = new DeferredCloseInputStream(stdout_fd);
stdout_stream = new BufferedInputStream(stdout_inner_stream);
}
return null; }});
/*
* For each subprocess forked a corresponding reaper thread
* is started. That thread is the only thread which waits
* for the subprocess to terminate and it doesn't hold any
* locks while doing so. This design allows waitFor() and
* exitStatus() to be safely executed in parallel (and they
* need no native code).
*/
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() { public Void run() {
Thread t = new Thread("process reaper") {
public void run() {
int res = waitForProcessExit(pid);
synchronized (UNIXProcess.this) {
hasExited = true;
exitcode = res;
UNIXProcess.this.notifyAll();
}
}
};
t.setDaemon(true);
t.start();
return null; }});
if (fds[2] == -1)
stderr_stream = ProcessBuilder.NullInputStream.INSTANCE;
else {
FileDescriptor stderr_fd = new FileDescriptor();
fdAccess.set(stderr_fd, fds[2]);
stderr_stream = new DeferredCloseInputStream(stderr_fd);
}
processReaperExecutor.execute(new Runnable() {
public void run() {
int exitcode = waitForProcessExit(pid);
UNIXProcess.this.processExited(exitcode);
}});
}
void processExited(int exitcode) {
synchronized (this) {
this.exitcode = exitcode;
hasExited = true;
notifyAll();
}
}
public OutputStream getOutputStream() {
......
......@@ -375,11 +375,12 @@ public abstract class UnixFileSystemProvider
UnixPath dir = UnixPath.toUnixPath(obj);
dir.checkWrite();
int mode = UnixFileModeAttribute
.toUnixMode(UnixFileModeAttribute.ALL_PERMISSIONS, attrs);
int mode = UnixFileModeAttribute.toUnixMode(UnixFileModeAttribute.ALL_PERMISSIONS, attrs);
try {
mkdir(dir, mode);
} catch (UnixException x) {
if (x.errno() == EISDIR)
throw new FileAlreadyExistsException(dir.toString());
x.rethrowAsIOException(dir);
}
}
......
......@@ -482,7 +482,7 @@ class UnixPath
@Override
public Path normalize() {
final int count = getNameCount();
if (count == 0)
if (count == 0 || isEmpty())
return this;
boolean[] ignore = new boolean[count]; // true => ignore name
......
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -213,6 +213,8 @@ Java_sun_print_CUPSPrinter_getMedia(JNIEnv *env,
name = (*env)->GetStringUTFChars(env, printer, NULL);
if (name == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not create printer name");
return NULL;
}
......@@ -220,12 +222,10 @@ Java_sun_print_CUPSPrinter_getMedia(JNIEnv *env,
// unlink() must be caled to remove the file when finished using it.
filename = j2d_cupsGetPPD(name);
(*env)->ReleaseStringUTFChars(env, printer, name);
CHECK_NULL_RETURN(filename, NULL);
cls = (*env)->FindClass(env, "java/lang/String");
if (filename == NULL) {
return NULL;
}
CHECK_NULL_RETURN(cls, NULL);
if ((ppd = j2d_ppdOpenFile(filename)) == NULL) {
unlink(filename);
......@@ -249,6 +249,7 @@ Java_sun_print_CUPSPrinter_getMedia(JNIEnv *env,
unlink(filename);
j2d_ppdClose(ppd);
DPRINTF("CUPSfuncs::bad alloc new array\n", "")
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
return NULL;
}
......@@ -323,6 +324,11 @@ Java_sun_print_CUPSPrinter_getPageSizes(JNIEnv *env,
ppd_size_t *size;
const char *name = (*env)->GetStringUTFChars(env, printer, NULL);
if (name == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not create printer name");
return NULL;
}
const char *filename;
int i;
jobjectArray sizeArray = NULL;
......@@ -332,9 +338,7 @@ Java_sun_print_CUPSPrinter_getPageSizes(JNIEnv *env,
// unlink() must be called to remove the file after using it.
filename = j2d_cupsGetPPD(name);
(*env)->ReleaseStringUTFChars(env, printer, name);
if (filename == NULL) {
return NULL;
}
CHECK_NULL_RETURN(filename, NULL);
if ((ppd = j2d_ppdOpenFile(filename)) == NULL) {
unlink(filename);
DPRINTF("unable to open PPD %s\n", filename)
......@@ -350,11 +354,19 @@ Java_sun_print_CUPSPrinter_getPageSizes(JNIEnv *env,
unlink(filename);
j2d_ppdClose(ppd);
DPRINTF("CUPSfuncs::bad alloc new float array\n", "")
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
return NULL;
}
dims = (*env)->GetFloatArrayElements(env, sizeArray, NULL);
if (dims == NULL) {
unlink(filename);
j2d_ppdClose(ppd);
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not create printer name");
return NULL;
}
for (i = 0; i<option->num_choices; i++) {
choice = (option->choices)+i;
size = j2d_ppdPageSize(ppd, choice->choice);
......
/*
* Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -892,11 +892,10 @@ jobject getColorSpace(JNIEnv* env, jint csID) {
jmethodID mid;
clazz = (*env)->FindClass(env,"java/awt/color/ColorSpace");
CHECK_NULL_RETURN(clazz, NULL);
mid = (*env)->GetStaticMethodID(env, clazz, "getInstance",
"(I)Ljava/awt/color/ColorSpace;");
if (mid == NULL) {
return NULL;
}
CHECK_NULL_RETURN(mid, NULL);
/* SECURITY: This is safe, because static methods cannot
* be overridden, and this method does not invoke
......@@ -919,6 +918,11 @@ jobject awtJNI_GetColorModel(JNIEnv *env, AwtGraphicsConfigDataPtr aData)
(aData->awt_depth >= 15))
{
clazz = (*env)->FindClass(env,"java/awt/image/DirectColorModel");
if (clazz == NULL) {
(*env)->PopLocalFrame(env, 0);
return NULL;
}
if (!aData->isTranslucencySupported) {
mid = (*env)->GetMethodID(env,clazz,"<init>","(IIIII)V");
......@@ -1005,6 +1009,10 @@ jobject awtJNI_GetColorModel(JNIEnv *env, AwtGraphicsConfigDataPtr aData)
}
clazz = (*env)->FindClass(env,"java/awt/image/ComponentColorModel");
if (clazz == NULL) {
(*env)->PopLocalFrame(env, 0);
return NULL;
}
mid = (*env)->GetMethodID(env,clazz,"<init>",
"(Ljava/awt/color/ColorSpace;[IZZII)V");
......@@ -1253,6 +1261,7 @@ int awtJNI_GetColorForVis (JNIEnv *env,jobject this, AwtGraphicsConfigDataPtr aw
if (!JNU_IsNull(env,this))
{
SYSCLR_class = (*env)->FindClass(env, "java/awt/SystemColor");
CHECK_NULL_RETURN(SYSCLR_class, 0);
if ((*env)->IsInstanceOf(env, this, SYSCLR_class)) {
/* SECURITY: This is safe, because there is no way
......@@ -1264,6 +1273,7 @@ int awtJNI_GetColorForVis (JNIEnv *env,jobject this, AwtGraphicsConfigDataPtr aw
,this
,"getRGB"
,"()I").i;
JNU_CHECK_EXCEPTION_RETURN(env, 0);
} else {
col = (int)(*env)->GetIntField(env,this,colorValueID);
}
......@@ -1370,6 +1380,8 @@ awtJNI_CreateColorData(JNIEnv *env, AwtGraphicsConfigDataPtr adata,
AWT_UNLOCK ();
}
sysColors = (*env)->FindClass (env, "java/awt/SystemColor");
CHECK_NULL(sysColors);
if (lock) {
AWT_LOCK ();
}
......@@ -1377,6 +1389,13 @@ awtJNI_CreateColorData(JNIEnv *env, AwtGraphicsConfigDataPtr adata,
"systemColors",
"[I");
if (colorID == NULL) {
if (lock) {
AWT_UNLOCK();
}
return;
}
colors = (jintArray) (*env)->GetStaticObjectField
(env, sysColors, colorID);
......
/*
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -77,8 +77,22 @@ extern void awt_output_flush();
#define AWT_LOCK_IMPL() \
(*env)->CallStaticVoidMethod(env, tkClass, awtLockMID)
#define AWT_NOFLUSH_UNLOCK_IMPL() \
(*env)->CallStaticVoidMethod(env, tkClass, awtUnlockMID)
do { \
jthrowable pendingException; \
if ((pendingException = (*env)->ExceptionOccurred(env)) != NULL) { \
(*env)->ExceptionClear(env); \
} \
(*env)->CallStaticVoidMethod(env, tkClass, awtUnlockMID); \
if (pendingException) { \
if ((*env)->ExceptionCheck(env)) { \
(*env)->ExceptionDescribe(env); \
(*env)->ExceptionClear(env); \
} \
(*env)->Throw(env, pendingException); \
} \
} while (0)
#define AWT_WAIT_IMPL(tm) \
(*env)->CallStaticVoidMethod(env, tkClass, awtWaitMID, (jlong)(tm))
#define AWT_NOTIFY_IMPL() \
......
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -49,22 +49,22 @@ struct KeyEventIDs keyEventIDs;
JNIEXPORT void JNICALL
Java_java_awt_AWTEvent_initIDs(JNIEnv *env, jclass cls)
{
awtEventIDs.bdata = (*env)->GetFieldID(env, cls, "bdata", "[B");
awtEventIDs.consumed = (*env)->GetFieldID(env, cls, "consumed", "Z");
awtEventIDs.id = (*env)->GetFieldID(env, cls, "id", "I");
CHECK_NULL(awtEventIDs.bdata = (*env)->GetFieldID(env, cls, "bdata", "[B"));
CHECK_NULL(awtEventIDs.consumed = (*env)->GetFieldID(env, cls, "consumed", "Z"));
CHECK_NULL(awtEventIDs.id = (*env)->GetFieldID(env, cls, "id", "I"));
}
JNIEXPORT void JNICALL
Java_java_awt_event_InputEvent_initIDs(JNIEnv *env, jclass cls)
{
inputEventIDs.modifiers = (*env)->GetFieldID(env, cls, "modifiers", "I");
CHECK_NULL(inputEventIDs.modifiers = (*env)->GetFieldID(env, cls, "modifiers", "I"));
}
JNIEXPORT void JNICALL
Java_java_awt_event_KeyEvent_initIDs(JNIEnv *env, jclass cls)
{
keyEventIDs.keyCode = (*env)->GetFieldID(env, cls, "keyCode", "I");
keyEventIDs.keyChar = (*env)->GetFieldID(env, cls, "keyChar", "C");
CHECK_NULL(keyEventIDs.keyCode = (*env)->GetFieldID(env, cls, "keyCode", "I"));
CHECK_NULL(keyEventIDs.keyChar = (*env)->GetFieldID(env, cls, "keyChar", "C"));
}
JNIEXPORT void JNICALL
......
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -78,6 +78,8 @@ JNIEXPORT jint JNICALL awt_DrawingSurface_Lock(JAWT_DrawingSurface* ds)
/* Make sure the target is a java.awt.Component */
componentClass = (*env)->FindClass(env, "java/awt/Component");
CHECK_NULL_RETURN(componentClass, (jint)JAWT_LOCK_ERROR);
if (!(*env)->IsInstanceOf(env, target, componentClass)) {
#ifdef DEBUG
fprintf(stderr, "Target is not a component\n");
......@@ -126,6 +128,8 @@ JNIEXPORT int32_t JNICALL
/* Make sure the target is a java.awt.Component */
componentClass = (*env)->FindClass(env, "java/awt/Component");
CHECK_NULL_RETURN(componentClass, (int32_t) 0);
if (!(*env)->IsInstanceOf(env, target, componentClass)) {
#ifdef DEBUG
fprintf(stderr, "DrawingSurface target must be a component\n");
......@@ -195,6 +199,8 @@ awt_DrawingSurface_GetDrawingSurfaceInfo(JAWT_DrawingSurface* ds)
/* Make sure the target is a java.awt.Component */
componentClass = (*env)->FindClass(env, "java/awt/Component");
CHECK_NULL_RETURN(componentClass, NULL);
if (!(*env)->IsInstanceOf(env, target, componentClass)) {
#ifdef DEBUG
fprintf(stderr, "DrawingSurface target must be a component\n");
......@@ -292,6 +298,8 @@ JNIEXPORT JAWT_DrawingSurface* JNICALL
/* Make sure the target component is a java.awt.Component */
componentClass = (*env)->FindClass(env, "java/awt/Component");
CHECK_NULL_RETURN(componentClass, NULL);
if (!(*env)->IsInstanceOf(env, target, componentClass)) {
#ifdef DEBUG
fprintf(stderr,
......@@ -354,6 +362,10 @@ JNIEXPORT jobject JNICALL
if (window != None) {
peer = JNU_CallStaticMethodByName(env, NULL, "sun/awt/X11/XToolkit",
"windowToXWindow", "(J)Lsun/awt/X11/XBaseWindow;", (jlong)window).l;
if ((*env)->ExceptionCheck(env)) {
AWT_UNLOCK();
return (jobject)NULL;
}
}
if ((peer != NULL) &&
(JNU_IsInstanceOfByName(env, peer, "sun/awt/X11/XWindow") == 1)) {
......@@ -361,6 +373,7 @@ JNIEXPORT jobject JNICALL
}
if (target == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowNullPointerException(env, "NullPointerException");
AWT_UNLOCK();
return (jobject)NULL;
......
/*
* Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -86,14 +86,13 @@ Java_java_awt_Font_initIDs
#ifndef HEADLESS
/** We call "NoClientCode" methods because they won't invoke client
code on the privileged toolkit thread **/
fontIDs.pData = (*env)->GetFieldID(env, cls, "pData", "J");
fontIDs.style = (*env)->GetFieldID(env, cls, "style", "I");
fontIDs.size = (*env)->GetFieldID(env, cls, "size", "I");
fontIDs.getPeer = (*env)->GetMethodID(env, cls, "getPeer_NoClientCode",
"()Ljava/awt/peer/FontPeer;");
fontIDs.getFamily =
(*env)->GetMethodID(env, cls, "getFamily_NoClientCode",
"()Ljava/lang/String;");
CHECK_NULL(fontIDs.pData = (*env)->GetFieldID(env, cls, "pData", "J"));
CHECK_NULL(fontIDs.style = (*env)->GetFieldID(env, cls, "style", "I"));
CHECK_NULL(fontIDs.size = (*env)->GetFieldID(env, cls, "size", "I"));
CHECK_NULL(fontIDs.getPeer = (*env)->GetMethodID(env, cls, "getPeer_NoClientCode",
"()Ljava/awt/peer/FontPeer;"));
CHECK_NULL(fontIDs.getFamily = (*env)->GetMethodID(env, cls, "getFamily_NoClientCode",
"()Ljava/lang/String;"));
#endif /* !HEADLESS */
}
......@@ -120,12 +119,10 @@ Java_sun_awt_FontDescriptor_initIDs
(JNIEnv *env, jclass cls)
{
#ifndef HEADLESS
fontDescriptorIDs.nativeName =
(*env)->GetFieldID(env, cls, "nativeName",
"Ljava/lang/String;");
fontDescriptorIDs.charsetName =
(*env)->GetFieldID(env, cls, "charsetName",
"Ljava/lang/String;");
CHECK_NULL(fontDescriptorIDs.nativeName =
(*env)->GetFieldID(env, cls, "nativeName", "Ljava/lang/String;"));
CHECK_NULL(fontDescriptorIDs.charsetName =
(*env)->GetFieldID(env, cls, "charsetName", "Ljava/lang/String;"));
#endif /* !HEADLESS */
}
......@@ -144,20 +141,18 @@ Java_sun_awt_PlatformFont_initIDs
(JNIEnv *env, jclass cls)
{
#ifndef HEADLESS
platformFontIDs.componentFonts =
(*env)->GetFieldID(env, cls, "componentFonts",
"[Lsun/awt/FontDescriptor;");
platformFontIDs.fontConfig =
(*env)->GetFieldID(env,cls, "fontConfig",
"Lsun/awt/FontConfiguration;");
platformFontIDs.makeConvertedMultiFontString =
(*env)->GetMethodID(env, cls, "makeConvertedMultiFontString",
"(Ljava/lang/String;)[Ljava/lang/Object;");
platformFontIDs.makeConvertedMultiFontChars =
(*env)->GetMethodID(env, cls, "makeConvertedMultiFontChars",
"([CII)[Ljava/lang/Object;");
CHECK_NULL(platformFontIDs.componentFonts =
(*env)->GetFieldID(env, cls, "componentFonts",
"[Lsun/awt/FontDescriptor;"));
CHECK_NULL(platformFontIDs.fontConfig =
(*env)->GetFieldID(env,cls, "fontConfig",
"Lsun/awt/FontConfiguration;"));
CHECK_NULL(platformFontIDs.makeConvertedMultiFontString =
(*env)->GetMethodID(env, cls, "makeConvertedMultiFontString",
"(Ljava/lang/String;)[Ljava/lang/Object;"));
CHECK_NULL(platformFontIDs.makeConvertedMultiFontChars =
(*env)->GetMethodID(env, cls, "makeConvertedMultiFontChars",
"([CII)[Ljava/lang/Object;"));
#endif /* !HEADLESS */
}
......@@ -385,6 +380,11 @@ awtJNI_FontName(JNIEnv * env, jstring name, char **foundry, char **facename, cha
return 0;
}
cname = (char *) JNU_GetStringPlatformChars(env, name, NULL);
if (cname == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not create font name");
return 0;
}
/* additional default font names */
if (strcmp(cname, "serif") == 0) {
......@@ -448,6 +448,8 @@ awtJNI_GetFontData(JNIEnv * env, jobject font, char **errmsg)
}
if (!JNU_IsNull(env, font) && awtJNI_IsMultiFont(env, font)) {
JNU_CHECK_EXCEPTION_RETURN(env, NULL);
struct FontData *fdata = NULL;
int32_t i, size;
char *fontsetname = NULL;
......@@ -513,6 +515,11 @@ awtJNI_GetFontData(JNIEnv * env, jobject font, char **errmsg)
fdata->flist[i].charset_name = (char *)
JNU_GetStringPlatformChars(env, charsetName, NULL);
if (fdata->flist[i].charset_name == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not create charset name");
return NULL;
}
/* We are done with the objects. */
(*env)->DeleteLocalRef(env, fontDescriptor);
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -152,8 +152,11 @@ Java_sun_awt_X11GraphicsConfig_initIDs (JNIEnv *env, jclass cls)
x11GraphicsConfigIDs.screen = NULL;
x11GraphicsConfigIDs.aData = (*env)->GetFieldID (env, cls, "aData", "J");
CHECK_NULL(x11GraphicsConfigIDs.aData);
x11GraphicsConfigIDs.bitsPerPixel = (*env)->GetFieldID (env, cls, "bitsPerPixel", "I");
CHECK_NULL(x11GraphicsConfigIDs.bitsPerPixel);
x11GraphicsConfigIDs.screen = (*env)->GetFieldID (env, cls, "screen", "Lsun/awt/X11GraphicsDevice;");
CHECK_NULL(x11GraphicsConfigIDs.screen);
if (x11GraphicsConfigIDs.aData == NULL ||
x11GraphicsConfigIDs.bitsPerPixel == NULL ||
......@@ -1346,7 +1349,6 @@ JNIEnv *env, jobject this)
/* Make Color Model object for this GraphicsConfiguration */
colorModel = awtJNI_GetColorModel (env, adata);
AWT_UNLOCK ();
return colorModel;
......@@ -1374,6 +1376,7 @@ Java_sun_awt_X11GraphicsConfig_pGetBounds(JNIEnv *env, jobject this, jint screen
JNU_GetLongFieldAsPtr(env, this, x11GraphicsConfigIDs.aData);
clazz = (*env)->FindClass(env, "java/awt/Rectangle");
CHECK_NULL_RETURN(clazz, NULL);
mid = (*env)->GetMethodID(env, clazz, "<init>", "(IIII)V");
if (mid != NULL) {
if (usingXinerama) {
......@@ -1543,7 +1546,7 @@ Java_sun_awt_X11GraphicsDevice_getDoubleBufferVisuals(JNIEnv *env,
clazz = (*env)->GetObjectClass(env, this);
midAddVisual = (*env)->GetMethodID(env, clazz, "addDoubleBufferVisual",
"(I)V");
CHECK_NULL(midAddVisual);
AWT_LOCK();
rootWindow = RootWindow(awt_display, xinawareScreen);
visScreenInfo = XdbeGetVisualInfo(awt_display, &rootWindow, &n);
......@@ -1739,6 +1742,7 @@ X11GD_CreateDisplayMode(JNIEnv *env, jint width, jint height,
jint validRefreshRate = refreshRate;
displayModeClass = (*env)->FindClass(env, "java/awt/DisplayMode");
CHECK_NULL_RETURN(displayModeClass, NULL);
if (JNU_IsNull(env, displayModeClass)) {
JNU_ThrowInternalError(env,
"Could not get display mode class");
......@@ -1746,6 +1750,7 @@ X11GD_CreateDisplayMode(JNIEnv *env, jint width, jint height,
}
cid = (*env)->GetMethodID(env, displayModeClass, "<init>", "(IIII)V");
CHECK_NULL_RETURN(cid, NULL);
if (cid == NULL) {
JNU_ThrowInternalError(env,
"Could not get display mode constructor");
......@@ -1779,6 +1784,7 @@ X11GD_AddDisplayMode(JNIEnv *env, jobject arrayList,
}
mid = (*env)->GetMethodID(env, arrayListClass, "add",
"(Ljava/lang/Object;)Z");
CHECK_NULL(mid);
if (mid == NULL) {
JNU_ThrowInternalError(env,
"Could not get method java.util.ArrayList.add()");
......@@ -1955,6 +1961,9 @@ Java_sun_awt_X11GraphicsDevice_enumDisplayModes
size.height,
BIT_DEPTH_MULTI,
rates[j]);
if ((*env)->ExceptionCheck(env)) {
break;
}
}
}
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -319,6 +319,7 @@ static X11InputMethodData * getX11InputMethodData(JNIEnv * env, jobject imInstan
JNU_CallMethodByName(env, NULL, pX11IMData->x11inputmethod,
"flushText",
"()V");
JNU_CHECK_EXCEPTION_RETURN(env, NULL);
/* IMPORTANT:
The order of the following calls is critical since "imInstance" may
point to the global reference itself, if "freeX11InputMethodData" is called
......@@ -1120,6 +1121,9 @@ PreeditDrawCallback(XIC ic, XPointer client_data,
if (text->string.multi_byte != NULL) {
if (pre_draw->text->encoding_is_wchar == False) {
javastr = JNU_NewStringPlatform(env, (const char *)text->string.multi_byte);
if (javastr == NULL) {
goto finally;
}
} else {
char *mbstr = wcstombsdmp(text->string.wide_char, text->length);
if (mbstr == NULL) {
......@@ -1127,6 +1131,9 @@ PreeditDrawCallback(XIC ic, XPointer client_data,
}
javastr = JNU_NewStringPlatform(env, (const char *)mbstr);
free(mbstr);
if (javastr == NULL) {
goto finally;
}
}
}
if (text->feedback != NULL) {
......@@ -1135,6 +1142,7 @@ PreeditDrawCallback(XIC ic, XPointer client_data,
style = (*env)->NewIntArray(env, text->length);
if (JNU_IsNull(env, style)) {
(*env)->ExceptionClear(env);
THROW_OUT_OF_MEMORY_ERROR();
goto finally;
}
......@@ -1395,14 +1403,17 @@ Java_sun_awt_X11_XInputMethod_createXICNative(JNIEnv *env,
pX11IMData->lookup_buf = 0;
pX11IMData->lookup_buf_len = 0;
if (createXIC(env, pX11IMData, (Window)window)
== False) {
if (createXIC(env, pX11IMData, (Window)window) == False) {
destroyX11InputMethodData((JNIEnv *) NULL, pX11IMData);
pX11IMData = (X11InputMethodData *) NULL;
if ((*env)->ExceptionCheck(env)) {
goto finally;
}
}
setX11InputMethodData(env, this, pX11IMData);
finally:
AWT_UNLOCK();
return (pX11IMData != NULL);
}
......
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -34,8 +34,8 @@ struct InsetsIDs insetsIDs;
JNIEXPORT void JNICALL
Java_java_awt_Insets_initIDs(JNIEnv *env, jclass cls)
{
insetsIDs.top = (*env)->GetFieldID(env, cls, "top", "I");
insetsIDs.bottom = (*env)->GetFieldID(env, cls, "bottom", "I");
insetsIDs.left = (*env)->GetFieldID(env, cls, "left", "I");
insetsIDs.right = (*env)->GetFieldID(env, cls, "right", "I");
CHECK_NULL(insetsIDs.top = (*env)->GetFieldID(env, cls, "top", "I"));
CHECK_NULL(insetsIDs.bottom = (*env)->GetFieldID(env, cls, "bottom", "I"));
CHECK_NULL(insetsIDs.left = (*env)->GetFieldID(env, cls, "left", "I"));
CHECK_NULL(insetsIDs.right = (*env)->GetFieldID(env, cls, "right", "I"));
}
......@@ -77,11 +77,16 @@ JNIEXPORT jboolean JNICALL AWTIsHeadless() {
return isHeadless;
}
#define CHECK_EXCEPTION_FATAL(env, message) \
if ((*env)->ExceptionCheck(env)) { \
(*env)->ExceptionClear(env); \
(*env)->FatalError(env, message); \
}
/*
* Pathnames to the various awt toolkits
*/
#ifdef MACOSX
#define LWAWT_PATH "/libawt_lwawt.dylib"
#define DEFAULT_PATH LWAWT_PATH
......@@ -125,6 +130,8 @@ AWT_OnLoad(JavaVM *vm, void *reserved)
*/
fmProp = (*env)->NewStringUTF(env, "sun.font.fontmanager");
CHECK_EXCEPTION_FATAL(env, "Could not allocate font manager property");
#ifdef MACOSX
fmanager = (*env)->NewStringUTF(env, "sun.font.CFontManager");
tk = LWAWT_PATH;
......@@ -132,10 +139,13 @@ AWT_OnLoad(JavaVM *vm, void *reserved)
fmanager = (*env)->NewStringUTF(env, "sun.awt.X11FontManager");
tk = XAWT_PATH;
#endif
CHECK_EXCEPTION_FATAL(env, "Could not allocate font manager name");
if (fmanager && fmProp) {
JNU_CallStaticMethodByName(env, NULL, "java/lang/System", "setProperty",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
fmProp, fmanager);
CHECK_EXCEPTION_FATAL(env, "Could not allocate set properties");
}
#ifndef MACOSX
......@@ -154,9 +164,11 @@ AWT_OnLoad(JavaVM *vm, void *reserved)
(*env)->DeleteLocalRef(env, fmanager);
}
jstring jbuf = JNU_NewStringPlatform(env, buf);
CHECK_EXCEPTION_FATAL(env, "Could not allocate library name");
JNU_CallStaticMethodByName(env, NULL, "java/lang/System", "load",
"(Ljava/lang/String;)V",
JNU_NewStringPlatform(env, buf));
jbuf);
awtHandle = dlopen(buf, RTLD_LAZY | RTLD_GLOBAL);
......
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -175,10 +175,13 @@ Java_sun_awt_X11_XRobotPeer_setup (JNIEnv * env, jclass cls, jint numberOfButton
num_buttons = numberOfButtons;
tmp = (*env)->GetIntArrayElements(env, buttonDownMasks, JNI_FALSE);
CHECK_NULL(tmp);
masks = (jint *)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), num_buttons);
if (masks == (jint *) NULL) {
JNU_ThrowOutOfMemoryError((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2), NULL);
(*env)->ExceptionClear(env);
(*env)->ReleaseIntArrayElements(env, buttonDownMasks, tmp, 0);
JNU_ThrowOutOfMemoryError((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2), NULL);
return;
}
for (i = 0; i < num_buttons; i++) {
......
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -98,6 +98,7 @@ jboolean _icon_upcall(JNIEnv *env, jobject this, GdkPixbuf *pixbuf)
(*env)->GetObjectClass(env, this));
icon_upcall_method = (*env)->GetMethodID(env, this_class,
"loadIconCallback", "([BIIIIIZ)V");
CHECK_NULL_RETURN(icon_upcall_method, JNI_FALSE);
}
if (pixbuf != NULL)
......@@ -112,6 +113,8 @@ jboolean _icon_upcall(JNIEnv *env, jobject this, GdkPixbuf *pixbuf)
/* Copy the data array into a Java structure so we can pass it back. */
jbyteArray data = (*env)->NewByteArray(env, (row_stride * height));
JNU_CHECK_EXCEPTION_RETURN(env, JNI_FALSE);
(*env)->SetByteArrayRegion(env, data, 0, (row_stride * height),
(jbyte *)pixbuf_data);
......
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -62,7 +62,7 @@ static Atom decor_list[9];
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
void
jboolean
awtJNI_ThreadYield(JNIEnv *env) {
static jclass threadClass = NULL;
......@@ -76,6 +76,7 @@ awtJNI_ThreadYield(JNIEnv *env) {
Boolean err = FALSE;
if (threadClass == NULL) {
jclass tc = (*env)->FindClass(env, "java/lang/Thread");
CHECK_NULL_RETURN(tc, JNI_FALSE);
threadClass = (*env)->NewGlobalRef(env, tc);
(*env)->DeleteLocalRef(env, tc);
if (threadClass != NULL) {
......@@ -91,10 +92,11 @@ awtJNI_ThreadYield(JNIEnv *env) {
err = TRUE;
}
if (err) {
return;
return JNI_FALSE;
}
} /* threadClass == NULL*/
(*env)->CallStaticVoidMethod(env, threadClass, yieldMethodID);
DASSERT(!((*env)->ExceptionOccurred(env)));
return JNI_TRUE;
} /* awtJNI_ThreadYield() */
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -78,7 +78,7 @@ struct DPos {
int32_t echoC;
};
extern void awtJNI_ThreadYield(JNIEnv *env);
extern jboolean awtJNI_ThreadYield(JNIEnv *env);
/*
* Functions for accessing fields by name and signature
......
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -161,17 +161,22 @@ jboolean isDisplayLocal(JNIEnv *env) {
if (! isLocalSet) {
jclass geCls = (*env)->FindClass(env, "java/awt/GraphicsEnvironment");
CHECK_NULL_RETURN(geCls, JNI_FALSE);
jmethodID getLocalGE = (*env)->GetStaticMethodID(env, geCls,
"getLocalGraphicsEnvironment",
"()Ljava/awt/GraphicsEnvironment;");
CHECK_NULL_RETURN(getLocalGE, JNI_FALSE);
jobject ge = (*env)->CallStaticObjectMethod(env, geCls, getLocalGE);
JNU_CHECK_EXCEPTION_RETURN(env, JNI_FALSE);
jclass sgeCls = (*env)->FindClass(env,
"sun/java2d/SunGraphicsEnvironment");
CHECK_NULL_RETURN(sgeCls, JNI_FALSE);
if ((*env)->IsInstanceOf(env, ge, sgeCls)) {
jmethodID isDisplayLocal = (*env)->GetMethodID(env, sgeCls,
"isDisplayLocal",
"()Z");
JNU_CHECK_EXCEPTION_RETURN(env, JNI_FALSE);
isLocal = (*env)->CallBooleanMethod(env, ge, isDisplayLocal);
} else {
isLocal = True;
......@@ -1005,50 +1010,38 @@ Java_sun_font_FontConfigManager_getFontConfig
jmethodID fcFontCons;
char* debugMinGlyphsStr = getenv("J2D_DEBUG_MIN_GLYPHS");
CHECK_NULL(fcInfoObj);
CHECK_NULL(fcCompFontArray);
jclass fcInfoClass =
(*env)->FindClass(env, "sun/font/FontConfigManager$FontConfigInfo");
CHECK_NULL(fcInfoClass);
jclass fcCompFontClass =
(*env)->FindClass(env, "sun/font/FontConfigManager$FcCompFont");
CHECK_NULL(fcCompFontClass);
jclass fcFontClass =
(*env)->FindClass(env, "sun/font/FontConfigManager$FontConfigFont");
if (fcInfoObj == NULL || fcCompFontArray == NULL || fcInfoClass == NULL ||
fcCompFontClass == NULL || fcFontClass == NULL) {
return;
}
fcVersionID = (*env)->GetFieldID(env, fcInfoClass, "fcVersion", "I");
fcCacheDirsID = (*env)->GetFieldID(env, fcInfoClass, "cacheDirs",
"[Ljava/lang/String;");
fcNameID = (*env)->GetFieldID(env, fcCompFontClass,
"fcName", "Ljava/lang/String;");
fcFirstFontID =
(*env)->GetFieldID(env, fcCompFontClass, "firstFont",
"Lsun/font/FontConfigManager$FontConfigFont;");
fcAllFontsID =
(*env)->GetFieldID(env, fcCompFontClass, "allFonts",
"[Lsun/font/FontConfigManager$FontConfigFont;");
fcFontCons = (*env)->GetMethodID(env, fcFontClass, "<init>", "()V");
familyNameID = (*env)->GetFieldID(env, fcFontClass,
"familyName", "Ljava/lang/String;");
styleNameID = (*env)->GetFieldID(env, fcFontClass,
"styleStr", "Ljava/lang/String;");
fullNameID = (*env)->GetFieldID(env, fcFontClass,
"fullName", "Ljava/lang/String;");
fontFileID = (*env)->GetFieldID(env, fcFontClass,
"fontFile", "Ljava/lang/String;");
if (fcVersionID == NULL || fcCacheDirsID == NULL || fcNameID == NULL ||
fcFirstFontID == NULL || fcAllFontsID == NULL || fcFontCons == NULL ||
familyNameID == NULL || styleNameID == NULL || fullNameID == NULL ||
fontFileID == NULL) {
return;
}
CHECK_NULL(fcFontClass);
CHECK_NULL(fcVersionID = (*env)->GetFieldID(env, fcInfoClass, "fcVersion", "I"));
CHECK_NULL(fcCacheDirsID = (*env)->GetFieldID(env, fcInfoClass, "cacheDirs",
"[Ljava/lang/String;"));
CHECK_NULL(fcNameID = (*env)->GetFieldID(env, fcCompFontClass,
"fcName", "Ljava/lang/String;"));
CHECK_NULL(fcFirstFontID = (*env)->GetFieldID(env, fcCompFontClass, "firstFont",
"Lsun/font/FontConfigManager$FontConfigFont;"));
CHECK_NULL(fcAllFontsID = (*env)->GetFieldID(env, fcCompFontClass, "allFonts",
"[Lsun/font/FontConfigManager$FontConfigFont;"));
CHECK_NULL(fcFontCons = (*env)->GetMethodID(env, fcFontClass, "<init>", "()V"));
CHECK_NULL(familyNameID = (*env)->GetFieldID(env, fcFontClass,
"familyName", "Ljava/lang/String;"));
CHECK_NULL(styleNameID = (*env)->GetFieldID(env, fcFontClass,
"styleStr", "Ljava/lang/String;"));
CHECK_NULL(fullNameID = (*env)->GetFieldID(env, fcFontClass,
"fullName", "Ljava/lang/String;"));
CHECK_NULL(fontFileID = (*env)->GetFieldID(env, fcFontClass,
"fontFile", "Ljava/lang/String;"));
if ((libfontconfig = openFontConfig()) == NULL) {
return;
......@@ -1129,6 +1122,8 @@ Java_sun_font_FontConfigManager_getFontConfig
if (cacheDirs != NULL) {
while ((cnt < max) && (cacheDir = (*FcStrListNext)(cacheDirs))) {
jstr = (*env)->NewStringUTF(env, (const char*)cacheDir);
JNU_CHECK_EXCEPTION(env);
(*env)->SetObjectArrayElement(env, cacheDirArray, cnt++, jstr);
}
(*FcStrListDone)(cacheDirs);
......@@ -1136,6 +1131,11 @@ Java_sun_font_FontConfigManager_getFontConfig
}
locale = (*env)->GetStringUTFChars(env, localeStr, 0);
if (locale == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not create locale");
return;
}
arrlen = (*env)->GetArrayLength(env, fcCompFontArray);
for (i=0; i<arrlen; i++) {
......
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -47,9 +47,6 @@ Java_java_awt_Color_initIDs
(JNIEnv *env, jclass clazz)
{
colorValueID = (*env)->GetFieldID(env, clazz, "value", "I");
if(colorValueID == NULL)
JNU_ThrowNullPointerException (env, "Can't get java/awt/Color.value fieldID");
}
JNIEXPORT void JNICALL
......
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -74,7 +74,7 @@ awtJNI_GetFontDescriptorNumber(JNIEnv * env
jobject temp = NULL;
jboolean validRet = JNI_FALSE;
if ((*env)->EnsureLocalCapacity(env, 2) < 0)
if ((*env)->EnsureLocalCapacity(env, 2) < 0 || (*env)->ExceptionCheck(env))
goto done;
peer = (*env)->CallObjectMethod(env,font,fontIDs.getPeer);
......@@ -162,7 +162,7 @@ awtJNI_IsMultiFontMetrics(JNIEnv * env, jobject this)
font = JNU_CallMethodByName(env, NULL, this, "getFont_NoClientCode",
"()Ljava/awt/Font;").l;
if (JNU_IsNull(env, font)) {
if (JNU_IsNull(env, font) || (*env)->ExceptionCheck(env)) {
return JNI_FALSE;
}
......@@ -318,6 +318,10 @@ awtJNI_GetMFStringWidth(JNIEnv * env, jcharArray s, int offset, int sLength, job
}
fdata = awtJNI_GetFontData(env, font, &err);
if ((*env)->ExceptionCheck(env)) {
(*env)->DeleteLocalRef(env, dataArray);
return 0;
}
stringCount = (*env)->GetArrayLength(env, dataArray);
......@@ -336,6 +340,11 @@ awtJNI_GetMFStringWidth(JNIEnv * env, jcharArray s, int offset, int sLength, job
}
j = awtJNI_GetFontDescriptorNumber(env, font, fontDescriptor);
if ((*env)->ExceptionCheck(env)) {
(*env)->DeleteLocalRef(env, fontDescriptor);
(*env)->DeleteLocalRef(env, data);
break;
}
if (fdata->flist[j].load == 0) {
xf = loadFont(awt_display,
......@@ -356,6 +365,14 @@ awtJNI_GetMFStringWidth(JNIEnv * env, jcharArray s, int offset, int sLength, job
stringData =
(unsigned char *)(*env)->GetPrimitiveArrayCritical(env, data,NULL);
if (stringData == NULL) {
(*env)->DeleteLocalRef(env, fontDescriptor);
(*env)->DeleteLocalRef(env, data);
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not get string data");
break;
}
length = (stringData[0] << 24) | (stringData[1] << 16) |
(stringData[2] << 8) | stringData[3];
offsetStringData = (char *)(stringData + (4 * sizeof(char)));
......
/*
* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -45,10 +45,12 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs
filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx,
"filenameFilterCallback", "(Ljava/lang/String;)Z");
DASSERT(filenameFilterCallbackMethodID != NULL);
CHECK_NULL(filenameFilterCallbackMethodID);
setFileInternalMethodID = (*env)->GetMethodID(env, cx,
"setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V");
DASSERT(setFileInternalMethodID != NULL);
CHECK_NULL(setFileInternalMethodID);
widgetFieldID = (*env)->GetFieldID(env, cx, "widget", "J");
DASSERT(widgetFieldID != NULL);
......@@ -63,6 +65,7 @@ static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gp
env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2);
filename = (*env)->NewStringUTF(env, filter_info->filename);
JNU_CHECK_EXCEPTION_RETURN(env, FALSE);
return (*env)->CallBooleanMethod(env, obj, filenameFilterCallbackMethodID,
filename);
......@@ -173,13 +176,14 @@ static jobjectArray toFilenamesArray(JNIEnv *env, GSList* list)
stringCls = (*env)->FindClass(env, "java/lang/String");
if (stringCls == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowInternalError(env, "Could not get java.lang.String class");
return NULL;
}
array = (*env)->NewObjectArray(env, fp_gtk_g_slist_length(list), stringCls,
NULL);
array = (*env)->NewObjectArray(env, fp_gtk_g_slist_length(list), stringCls, NULL);
if (array == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowInternalError(env, "Could not instantiate array files array");
return NULL;
}
......@@ -189,7 +193,9 @@ static jobjectArray toFilenamesArray(JNIEnv *env, GSList* list)
entry = (char*) iterator->data;
entry = strrchr(entry, '/') + 1;
str = (*env)->NewStringUTF(env, entry);
(*env)->SetObjectArrayElement(env, array, i, str);
if (str && !(*env)->ExceptionCheck(env)) {
(*env)->SetObjectArrayElement(env, array, i, str);
}
i++;
}
......@@ -215,13 +221,14 @@ static jobjectArray toPathAndFilenamesArray(JNIEnv *env, GSList* list)
stringCls = (*env)->FindClass(env, "java/lang/String");
if (stringCls == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowInternalError(env, "Could not get java.lang.String class");
return NULL;
}
array = (*env)->NewObjectArray(env, fp_gtk_g_slist_length(list), stringCls,
NULL);
array = (*env)->NewObjectArray(env, fp_gtk_g_slist_length(list), stringCls, NULL);
if (array == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowInternalError(env, "Could not instantiate array files array");
return NULL;
}
......@@ -236,7 +243,9 @@ static jobjectArray toPathAndFilenamesArray(JNIEnv *env, GSList* list)
}
str = (*env)->NewStringUTF(env, entry);
(*env)->SetObjectArrayElement(env, array, i, str);
if (str && !(*env)->ExceptionCheck(env)) {
(*env)->SetObjectArrayElement(env, array, i, str);
}
i++;
}
......@@ -268,16 +277,17 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj)
if (full_path_names) {
//This is a hack for use with "Recent Folders" in gtk where each
//file could have its own directory.
jcurrent_folder = (*env)->NewStringUTF(env, "/");
jfilenames = toPathAndFilenamesArray(env, filenames);
jcurrent_folder = (*env)->NewStringUTF(env, "/");
} else {
jcurrent_folder = (*env)->NewStringUTF(env, current_folder);
jfilenames = toFilenamesArray(env, filenames);
jcurrent_folder = (*env)->NewStringUTF(env, current_folder);
}
if (!(*env)->ExceptionCheck(env)) {
(*env)->CallVoidMethod(env, obj, setFileInternalMethodID,
jcurrent_folder, jfilenames);
}
(*env)->CallVoidMethod(env, obj, setFileInternalMethodID, jcurrent_folder,
jfilenames);
fp_g_free(current_folder);
quit(env, (jobject)obj, TRUE);
}
......@@ -296,11 +306,17 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer,
if (jvm == NULL) {
(*env)->GetJavaVM(env, &jvm);
JNU_CHECK_EXCEPTION(env);
}
fp_gdk_threads_enter();
const char *title = jtitle == NULL? "": (*env)->GetStringUTFChars(env, jtitle, 0);
if (title == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not get title");
return;
}
if (mode == java_awt_FileDialog_SAVE) {
/* Save action */
......@@ -328,6 +344,11 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer,
/* Set the directory */
if (jdir != NULL) {
const char *dir = (*env)->GetStringUTFChars(env, jdir, 0);
if (dir == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not get dir");
return;
}
fp_gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), dir);
(*env)->ReleaseStringUTFChars(env, jdir, dir);
}
......@@ -335,6 +356,11 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer,
/* Set the filename */
if (jfile != NULL) {
const char *filename = (*env)->GetStringUTFChars(env, jfile, 0);
if (filename == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowOutOfMemoryError(env, "Could not get filename");
return;
}
if (mode == java_awt_FileDialog_SAVE) {
fp_gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), filename);
} else {
......
/*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -40,6 +40,7 @@
#include "awt_Component.h"
#include "awt_MenuComponent.h"
#include "awt_Font.h"
#include "awt_util.h"
#include "sun_awt_X11_XToolkit.h"
#include "java_awt_SystemColor.h"
......@@ -76,6 +77,8 @@ struct MenuComponentIDs menuComponentIDs;
#ifndef HEADLESS
extern Display* awt_init_Display(JNIEnv *env, jobject this);
extern void freeNativeStringArray(char **array, long length);
extern char** stringArrayToNative(JNIEnv *env, jobjectArray array, jsize * ret_length);
struct XFontPeerIDs xFontPeerIDs;
......@@ -103,9 +106,11 @@ Java_sun_awt_X11_XToolkit_initIDs
(JNIEnv *env, jclass clazz)
{
jfieldID fid = (*env)->GetStaticFieldID(env, clazz, "numLockMask", "I");
CHECK_NULL(fid);
awt_NumLockMask = (*env)->GetStaticIntField(env, clazz, fid);
DTRACE_PRINTLN1("awt_NumLockMask = %u", awt_NumLockMask);
fid = (*env)->GetStaticFieldID(env, clazz, "modLockIsShiftLock", "I");
CHECK_NULL(fid);
awt_ModLockIsShiftLock = (*env)->GetStaticIntField(env, clazz, fid) != 0 ? True : False;
}
......@@ -173,21 +178,31 @@ Java_java_awt_Component_initIDs
componentIDs.x = (*env)->GetFieldID(env, cls, "x", "I");
CHECK_NULL(componentIDs.x);
componentIDs.y = (*env)->GetFieldID(env, cls, "y", "I");
CHECK_NULL(componentIDs.y);
componentIDs.width = (*env)->GetFieldID(env, cls, "width", "I");
CHECK_NULL(componentIDs.width);
componentIDs.height = (*env)->GetFieldID(env, cls, "height", "I");
CHECK_NULL(componentIDs.height);
componentIDs.isPacked = (*env)->GetFieldID(env, cls, "isPacked", "Z");
CHECK_NULL(componentIDs.isPacked);
componentIDs.peer =
(*env)->GetFieldID(env, cls, "peer", "Ljava/awt/peer/ComponentPeer;");
CHECK_NULL(componentIDs.peer);
componentIDs.background =
(*env)->GetFieldID(env, cls, "background", "Ljava/awt/Color;");
CHECK_NULL(componentIDs.background);
componentIDs.foreground =
(*env)->GetFieldID(env, cls, "foreground", "Ljava/awt/Color;");
CHECK_NULL(componentIDs.foreground);
componentIDs.graphicsConfig =
(*env)->GetFieldID(env, cls, "graphicsConfig",
"Ljava/awt/GraphicsConfiguration;");
CHECK_NULL(componentIDs.graphicsConfig);
componentIDs.name =
(*env)->GetFieldID(env, cls, "name", "Ljava/lang/String;");
CHECK_NULL(componentIDs.name);
/* Use _NoClientCode() methods for trusted methods, so that we
* know that we are not invoking client code on trusted threads
......@@ -195,19 +210,20 @@ Java_java_awt_Component_initIDs
componentIDs.getParent =
(*env)->GetMethodID(env, cls, "getParent_NoClientCode",
"()Ljava/awt/Container;");
CHECK_NULL(componentIDs.getParent);
componentIDs.getLocationOnScreen =
(*env)->GetMethodID(env, cls, "getLocationOnScreen_NoTreeLock",
"()Ljava/awt/Point;");
CHECK_NULL(componentIDs.getLocationOnScreen);
keyclass = (*env)->FindClass(env, "java/awt/event/KeyEvent");
if (JNU_IsNull(env, keyclass)) {
return;
}
CHECK_NULL(keyclass);
componentIDs.isProxyActive =
(*env)->GetFieldID(env, keyclass, "isProxyActive",
"Z");
CHECK_NULL(componentIDs.isProxyActive);
componentIDs.appContext =
(*env)->GetFieldID(env, cls, "appContext",
......@@ -339,7 +355,7 @@ JNIEXPORT void JNICALL Java_java_awt_Dialog_initIDs (JNIEnv *env, jclass cls)
static void waitForEvents(JNIEnv *, jlong);
static void awt_pipe_init();
static void processOneEvent(XtInputMask iMask);
static void performPoll(JNIEnv *, jlong);
static Boolean performPoll(JNIEnv *, jlong);
static void wakeUp();
static void update_poll_timeout(int timeout_control);
static uint32_t get_poll_timeout(jlong nextTaskTime);
......@@ -608,11 +624,13 @@ static uint32_t get_poll_timeout(jlong nextTaskTime)
*/
void
waitForEvents(JNIEnv *env, jlong nextTaskTime) {
performPoll(env, nextTaskTime);
if ((awt_next_flush_time > 0) && (awtJNI_TimeMillis() >= awt_next_flush_time)) {
XFlush(awt_display);
awt_last_flush_time = awt_next_flush_time;
awt_next_flush_time = 0LL;
if (performPoll(env, nextTaskTime)
&& (awt_next_flush_time > 0)
&& (awtJNI_TimeMillis() >= awt_next_flush_time)) {
XFlush(awt_display);
awt_last_flush_time = awt_next_flush_time;
awt_next_flush_time = 0LL;
}
} /* waitForEvents() */
......@@ -646,7 +664,7 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_XToolkit_wakeup_1poll (JNIEnv *env, jcla
*
* The fdAWTPipe will be empty when this returns.
*/
static void
static Boolean
performPoll(JNIEnv *env, jlong nextTaskTime) {
static Bool pollFdsInited = False;
static char read_buf[AWT_POLL_BUFSIZE + 1]; /* dummy buf to empty pipe */
......@@ -673,7 +691,9 @@ performPoll(JNIEnv *env, jlong nextTaskTime) {
/* ACTUALLY DO THE POLL() */
if (timeout == 0) {
// be sure other threads get a chance
awtJNI_ThreadYield(env);
if (!awtJNI_ThreadYield(env)) {
return FALSE;
}
}
if (tracing) poll_sleep_time = awtJNI_TimeMillis();
......@@ -701,7 +721,7 @@ performPoll(JNIEnv *env, jlong nextTaskTime) {
update_poll_timeout(TIMEOUT_EVENTS);
PRINT2("performPoll(): TIMEOUT_EVENTS curPollTimeout = %ld \n", curPollTimeout);
}
return;
return TRUE;
} /* performPoll() */
......@@ -856,23 +876,25 @@ Java_sun_awt_motif_XsessionWMcommand(JNIEnv *env, jobject this,
xawt_root_window = get_xawt_root_shell(env);
if ( xawt_root_window == None ) {
JNU_ThrowNullPointerException(env, "AWT root shell is unrealized");
AWT_UNLOCK();
JNU_ThrowNullPointerException(env, "AWT root shell is unrealized");
return;
}
command = (char *) JNU_GetStringPlatformChars(env, jcommand, NULL);
c[0] = (char *)command;
status = XmbTextListToTextProperty(awt_display, c, 1,
XStdICCTextStyle, &text_prop);
if (status == Success || status > 0) {
XSetTextProperty(awt_display, xawt_root_window,
&text_prop, XA_WM_COMMAND);
if (text_prop.value != NULL)
XFree(text_prop.value);
if (command != NULL) {
c[0] = (char *)command;
status = XmbTextListToTextProperty(awt_display, c, 1,
XStdICCTextStyle, &text_prop);
if (status == Success || status > 0) {
XSetTextProperty(awt_display, xawt_root_window,
&text_prop, XA_WM_COMMAND);
if (text_prop.value != NULL)
XFree(text_prop.value);
}
JNU_ReleaseStringPlatformChars(env, jcommand, command);
}
JNU_ReleaseStringPlatformChars(env, jcommand, command);
AWT_UNLOCK();
}
......@@ -886,96 +908,56 @@ Java_sun_awt_motif_XsessionWMcommand(JNIEnv *env, jobject this,
* name. It's not! It's just a plain function.
*/
JNIEXPORT void JNICALL
Java_sun_awt_motif_XsessionWMcommand_New(JNIEnv *env, jobjectArray jargv)
Java_sun_awt_motif_XsessionWMcommand_New(JNIEnv *env, jobjectArray jarray)
{
static const char empty[] = "";
int argc;
const char **cargv;
jsize length;
char ** array;
XTextProperty text_prop;
int status;
int i;
Window xawt_root_window;
AWT_LOCK();
xawt_root_window = get_xawt_root_shell(env);
if (xawt_root_window == None) {
JNU_ThrowNullPointerException(env, "AWT root shell is unrealized");
AWT_UNLOCK();
JNU_ThrowNullPointerException(env, "AWT root shell is unrealized");
return;
}
argc = (int)(*env)->GetArrayLength(env, jargv);
if (argc == 0) {
AWT_UNLOCK();
return;
}
/* array of C strings */
cargv = (const char **)calloc(argc, sizeof(char *));
if (cargv == NULL) {
JNU_ThrowOutOfMemoryError(env, "Unable to allocate cargv");
AWT_UNLOCK();
return;
}
array = stringArrayToNative(env, jarray, &length);
/* fill C array with platform chars of java strings */
for (i = 0; i < argc; ++i) {
jstring js;
const char *cs;
cs = NULL;
js = (*env)->GetObjectArrayElement(env, jargv, i);
if (js != NULL) {
cs = JNU_GetStringPlatformChars(env, js, NULL);
}
if (cs == NULL) {
cs = empty;
}
cargv[i] = cs;
(*env)->DeleteLocalRef(env, js);
}
/* grr, X prototype doesn't declare cargv as const, thought it really is */
status = XmbTextListToTextProperty(awt_display, (char **)cargv, argc,
XStdICCTextStyle, &text_prop);
if (status < 0) {
switch (status) {
case XNoMemory:
JNU_ThrowOutOfMemoryError(env,
"XmbTextListToTextProperty: XNoMemory");
break;
case XLocaleNotSupported:
JNU_ThrowInternalError(env,
"XmbTextListToTextProperty: XLocaleNotSupported");
break;
case XConverterNotFound:
JNU_ThrowNullPointerException(env,
"XmbTextListToTextProperty: XConverterNotFound");
break;
default:
JNU_ThrowInternalError(env,
"XmbTextListToTextProperty: unknown error");
if (array != NULL) {
status = XmbTextListToTextProperty(awt_display, array, length,
XStdICCTextStyle, &text_prop);
if (status < 0) {
switch (status) {
case XNoMemory:
JNU_ThrowOutOfMemoryError(env,
"XmbTextListToTextProperty: XNoMemory");
break;
case XLocaleNotSupported:
JNU_ThrowInternalError(env,
"XmbTextListToTextProperty: XLocaleNotSupported");
break;
case XConverterNotFound:
JNU_ThrowNullPointerException(env,
"XmbTextListToTextProperty: XConverterNotFound");
break;
default:
JNU_ThrowInternalError(env,
"XmbTextListToTextProperty: unknown error");
}
} else {
XSetTextProperty(awt_display, xawt_root_window,
&text_prop, XA_WM_COMMAND);
}
} else {
XSetTextProperty(awt_display, xawt_root_window,
&text_prop, XA_WM_COMMAND);
}
for (i = 0; i < argc; ++i) {
jstring js;
if (cargv[i] == empty)
continue;
if (text_prop.value != NULL)
XFree(text_prop.value);
js = (*env)->GetObjectArrayElement(env, jargv, i);
JNU_ReleaseStringPlatformChars(env, js, cargv[i]);
(*env)->DeleteLocalRef(env, js);
freeNativeStringArray(array, length);
}
if (text_prop.value != NULL)
XFree(text_prop.value);
AWT_UNLOCK();
}
......
/*
* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -1242,9 +1242,13 @@ Java_sun_awt_X11_XWindow_initIDs
{
char *ptr = NULL;
windowID = (*env)->GetFieldID(env, clazz, "window", "J");
CHECK_NULL(windowID);
targetID = (*env)->GetFieldID(env, clazz, "target", "Ljava/awt/Component;");
CHECK_NULL(targetID);
graphicsConfigID = (*env)->GetFieldID(env, clazz, "graphicsConfig", "Lsun/awt/X11GraphicsConfig;");
CHECK_NULL(graphicsConfigID);
drawStateID = (*env)->GetFieldID(env, clazz, "drawState", "I");
CHECK_NULL(drawStateID);
ptr = getenv("_AWT_USE_TYPE4_PATCH");
if( ptr != NULL && ptr[0] != 0 ) {
if( strncmp("true", ptr, 4) == 0 ) {
......
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -23,6 +23,7 @@
* questions.
*/
#include "jni_util.h"
#include "gtk2_interface.h"
#include "gnome_interface.h"
......@@ -65,6 +66,12 @@ JNIEXPORT jboolean JNICALL Java_sun_awt_X11_XDesktopPeer_gnome_1url_1show
const gchar* url_c;
url_c = (char*)(*env)->GetByteArrayElements(env, url_j, NULL);
if (url_c == NULL) {
if (!(*env)->ExceptionCheck(env)) {
JNU_ThrowOutOfMemoryError(env, 0);
}
return JNI_FALSE;
}
if (gtk_has_been_loaded) {
fp_gdk_threads_enter();
......
......@@ -493,6 +493,14 @@ public class WindowsFileSystemProvider
try {
CreateDirectory(dir.getPathForWin32Calls(), sd.address());
} catch (WindowsException x) {
// convert ERROR_ACCESS_DENIED to FileAlreadyExistsException if we can
// verify that the directory exists
if (x.lastError() == ERROR_ACCESS_DENIED) {
try {
if (WindowsFileAttributes.get(dir, false).isDirectory())
throw new FileAlreadyExistsException(dir.toString());
} catch (WindowsException ignore) { }
}
x.rethrowAsIOException(dir);
} finally {
sd.release();
......
......@@ -35,6 +35,8 @@ import javax.crypto.*;
import javax.crypto.spec.*;
import sun.security.rsa.RSAKeyFactory;
import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
import sun.security.util.KeyUtil;
/**
* RSA cipher implementation using the Microsoft Crypto API.
......@@ -92,9 +94,16 @@ public final class RSACipher extends CipherSpi {
// the public key, if we were initialized using a public key
private sun.security.mscapi.Key publicKey;
// the private key, if we were initialized using a private key
private sun.security.mscapi.Key privateKey;
// cipher parameter for TLS RSA premaster secret
private AlgorithmParameterSpec spec = null;
// the source of randomness
private SecureRandom random;
public RSACipher() {
paddingType = PAD_PKCS1;
}
......@@ -155,8 +164,12 @@ public final class RSACipher extends CipherSpi {
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (params != null) {
throw new InvalidAlgorithmParameterException
("Parameters not supported");
if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"Parameters not supported");
}
spec = params;
this.random = random; // for TLS RSA premaster secret
}
init(opmode, key);
}
......@@ -356,39 +369,47 @@ public final class RSACipher extends CipherSpi {
}
// see JCE spec
protected java.security.Key engineUnwrap(byte[] wrappedKey, String algorithm,
protected java.security.Key engineUnwrap(byte[] wrappedKey,
String algorithm,
int type) throws InvalidKeyException, NoSuchAlgorithmException {
if (wrappedKey.length > buffer.length) {
throw new InvalidKeyException("Key is too long for unwrapping");
}
update(wrappedKey, 0, wrappedKey.length);
try {
byte[] encoding = doFinal();
switch (type) {
case Cipher.PUBLIC_KEY:
return constructPublicKey(encoding, algorithm);
case Cipher.PRIVATE_KEY:
return constructPrivateKey(encoding, algorithm);
case Cipher.SECRET_KEY:
return constructSecretKey(encoding, algorithm);
default:
throw new InvalidKeyException("Unknown key type " + type);
}
boolean isTlsRsaPremasterSecret =
algorithm.equals("TlsRsaPremasterSecret");
Exception failover = null;
byte[] encoded = null;
update(wrappedKey, 0, wrappedKey.length);
try {
encoded = doFinal();
} catch (BadPaddingException e) {
// should not occur
throw new InvalidKeyException("Unwrapping failed", e);
if (isTlsRsaPremasterSecret) {
failover = e;
} else {
throw new InvalidKeyException("Unwrapping failed", e);
}
} catch (IllegalBlockSizeException e) {
// should not occur, handled with length check above
throw new InvalidKeyException("Unwrapping failed", e);
}
if (isTlsRsaPremasterSecret) {
if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
throw new IllegalStateException(
"No TlsRsaPremasterSecretParameterSpec specified");
}
// polish the TLS premaster secret
encoded = KeyUtil.checkTlsPreMasterSecretKey(
((TlsRsaPremasterSecretParameterSpec)spec).getClientVersion(),
((TlsRsaPremasterSecretParameterSpec)spec).getServerVersion(),
random, encoded, (failover != null));
}
return constructKey(encoded, algorithm, type);
}
// see JCE spec
......@@ -452,6 +473,22 @@ public final class RSACipher extends CipherSpi {
return new SecretKeySpec(encodedKey, encodedKeyAlgorithm);
}
private static Key constructKey(byte[] encodedKey,
String encodedKeyAlgorithm,
int keyType) throws InvalidKeyException, NoSuchAlgorithmException {
switch (keyType) {
case Cipher.PUBLIC_KEY:
return constructPublicKey(encodedKey, encodedKeyAlgorithm);
case Cipher.PRIVATE_KEY:
return constructPrivateKey(encodedKey, encodedKeyAlgorithm);
case Cipher.SECRET_KEY:
return constructSecretKey(encodedKey, encodedKeyAlgorithm);
default:
throw new InvalidKeyException("Unknown key type " + keyType);
}
}
/*
* Encrypt/decrypt a data buffer using Microsoft Crypto API with HCRYPTKEY.
* It expects and returns ciphertext data in big-endian form.
......
......@@ -23,6 +23,7 @@
* questions.
*/
#include "jni_util.h"
#include "awt.h"
#include "sun_java2d_windows_GDIRenderer.h"
#include "java_awt_geom_PathIterator.h"
......@@ -387,13 +388,20 @@ Java_sun_java2d_windows_GDIRenderer_doDrawPoly
return;
}
POINT tmpPts[POLYTEMPSIZE], *pPoints;
POINT tmpPts[POLYTEMPSIZE], *pPoints = NULL;
jint *xpoints = (jint *) env->GetPrimitiveArrayCritical(xpointsarray, NULL);
jint *ypoints = (jint *) env->GetPrimitiveArrayCritical(ypointsarray, NULL);
pPoints = TransformPoly(xpoints, ypoints, transx, transy,
tmpPts, &npoints, isclosed, TRUE);
env->ReleasePrimitiveArrayCritical(xpointsarray, xpoints, JNI_ABORT);
env->ReleasePrimitiveArrayCritical(ypointsarray, ypoints, JNI_ABORT);
if (xpoints != NULL) {
jint *ypoints = (jint *) env->GetPrimitiveArrayCritical(ypointsarray, NULL);
if (ypoints != NULL) {
pPoints = TransformPoly(xpoints, ypoints, transx, transy,
tmpPts, &npoints, isclosed, TRUE);
env->ReleasePrimitiveArrayCritical(ypointsarray, ypoints, JNI_ABORT);
}
env->ReleasePrimitiveArrayCritical(xpointsarray, xpoints, JNI_ABORT);
}
if (pPoints == NULL) {
return;
}
......@@ -654,13 +662,19 @@ Java_sun_java2d_windows_GDIRenderer_doFillPoly
return;
}
POINT tmpPts[POLYTEMPSIZE], *pPoints;
POINT tmpPts[POLYTEMPSIZE], *pPoints = NULL;
jint *xpoints = (jint *) env->GetPrimitiveArrayCritical(xpointsarray, NULL);
jint *ypoints = (jint *) env->GetPrimitiveArrayCritical(ypointsarray, NULL);
pPoints = TransformPoly(xpoints, ypoints, transx, transy,
tmpPts, &npoints, FALSE, FALSE);
env->ReleasePrimitiveArrayCritical(xpointsarray, xpoints, JNI_ABORT);
env->ReleasePrimitiveArrayCritical(ypointsarray, ypoints, JNI_ABORT);
if (xpoints != NULL) {
jint *ypoints = (jint *) env->GetPrimitiveArrayCritical(ypointsarray, NULL);
if (ypoints != NULL) {
pPoints = TransformPoly(xpoints, ypoints, transx, transy,
tmpPts, &npoints, FALSE, FALSE);
env->ReleasePrimitiveArrayCritical(ypointsarray, xpoints, JNI_ABORT);
}
env->ReleasePrimitiveArrayCritical(xpointsarray, xpoints, JNI_ABORT);
}
if (pPoints == NULL) {
return;
}
......@@ -720,13 +734,26 @@ Java_sun_java2d_windows_GDIRenderer_doShape
if (hdc == NULL) {
return;
}
::SetPolyFillMode(hdc, (rule == java_awt_geom_PathIterator_WIND_NON_ZERO
? WINDING : ALTERNATE));
::BeginPath(hdc);
jbyte *types = (jbyte *) env->GetPrimitiveArrayCritical(typesarray,
NULL);
if (types == NULL) {
wsdo->ReleaseDC(env, wsdo, hdc);
return;
}
jfloat *coords = (jfloat *) env->GetPrimitiveArrayCritical(coordsarray,
NULL);
if (coords == NULL) {
env->ReleasePrimitiveArrayCritical(typesarray, types, JNI_ABORT);
wsdo->ReleaseDC(env, wsdo, hdc);
return;
}
::SetPolyFillMode(hdc, (rule == java_awt_geom_PathIterator_WIND_NON_ZERO
? WINDING : ALTERNATE));
::BeginPath(hdc);
int index = 0;
BOOL ok = TRUE;
BOOL isempty = TRUE;
......
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -47,12 +47,15 @@ void SetIDs(JNIEnv *env, jclass wFlagsClass)
{
wFlagsClassID = (jclass)env->NewGlobalRef(wFlagsClass);
d3dEnabledID = env->GetStaticFieldID(wFlagsClass, "d3dEnabled", "Z");
CHECK_NULL(d3dEnabledID);
d3dSetID = env->GetStaticFieldID(wFlagsClass, "d3dSet", "Z");
CHECK_NULL(d3dSetID);
}
BOOL GetStaticBoolean(JNIEnv *env, jclass wfClass, const char *fieldName)
{
jfieldID fieldID = env->GetStaticFieldID(wfClass, fieldName, "Z");
CHECK_NULL_RETURN(fieldID, FALSE);
return env->GetStaticBooleanField(wfClass, fieldID);
}
......@@ -60,6 +63,7 @@ jobject GetStaticObject(JNIEnv *env, jclass wfClass, const char *fieldName,
const char *signature)
{
jfieldID fieldID = env->GetStaticFieldID(wfClass, fieldName, signature);
CHECK_NULL_RETURN(fieldID, NULL);
return env->GetStaticObjectField(wfClass, fieldID);
}
......@@ -90,15 +94,17 @@ void GetFlagValues(JNIEnv *env, jclass wFlagsClass)
forceD3DUsage = d3dSet;
g_offscreenSharing = GetStaticBoolean(env, wFlagsClass,
"offscreenSharingEnabled");
JNU_CHECK_EXCEPTION(env);
accelReset = GetStaticBoolean(env, wFlagsClass, "accelReset");
JNU_CHECK_EXCEPTION(env);
checkRegistry = GetStaticBoolean(env, wFlagsClass, "checkRegistry");
JNU_CHECK_EXCEPTION(env);
disableRegistry = GetStaticBoolean(env, wFlagsClass, "disableRegistry");
jstring javaVersionString = (jstring)GetStaticObject(env, wFlagsClass,
"javaVersion",
"Ljava/lang/String;");
JNU_CHECK_EXCEPTION(env);
setHighDPIAware =
(IS_WINVISTA && GetStaticBoolean(env, wFlagsClass, "setHighDPIAware"));
JNU_CHECK_EXCEPTION(env);
J2dTraceLn(J2D_TRACE_INFO, "WindowsFlags (native):");
J2dTraceLn1(J2D_TRACE_INFO, " d3dEnabled = %s",
......@@ -166,6 +172,7 @@ Java_sun_java2d_windows_WindowsFlags_initNativeFlags(JNIEnv *env,
jclass wFlagsClass)
{
SetIDs(env, wFlagsClass);
JNU_CHECK_EXCEPTION(env);
GetFlagValues(env, wFlagsClass);
}
......
/*
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -63,6 +63,10 @@ AwtCanvas* AwtCanvas::Create(jobject self, jobject hParent)
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
jobject target = NULL;
jobject graphicsConfig = NULL;
jclass canvasClass = NULL;
jclass win32cls = NULL;
AwtCanvas *canvas = NULL;
try {
......@@ -100,16 +104,24 @@ AwtCanvas* AwtCanvas::Create(jobject self, jobject hParent)
// Set the pixel format of the HWND if a GraphicsConfiguration
// was provided to the Canvas constructor.
jclass canvasClass = env->FindClass("java/awt/Canvas");
canvasClass = env->FindClass("java/awt/Canvas");
DASSERT(canvasClass != NULL);
if (!canvasClass) {
throw std::bad_alloc();
}
if ( env->IsInstanceOf( target, canvasClass ) ) {
// Get GraphicsConfig from our target
jobject graphicsConfig = env->GetObjectField(target,
graphicsConfig = env->GetObjectField(target,
AwtComponent::graphicsConfigID);
if (graphicsConfig != NULL) {
jclass win32cls = env->FindClass("sun/awt/Win32GraphicsConfig");
win32cls = env->FindClass("sun/awt/Win32GraphicsConfig");
DASSERT (win32cls != NULL);
if (!win32cls) {
throw std::bad_alloc();
}
if ( env->IsInstanceOf( graphicsConfig, win32cls ) ) {
// Get the visual ID member from our GC
......@@ -131,8 +143,7 @@ AwtCanvas* AwtCanvas::Create(jobject self, jobject hParent)
env->ExceptionClear();
env->ThrowNew(excCls,
"\nUnable to set Pixel format on Canvas");
env->DeleteLocalRef(target);
return canvas;
env->DeleteLocalRef(excCls);
}
}
}
......@@ -141,11 +152,20 @@ AwtCanvas* AwtCanvas::Create(jobject self, jobject hParent)
}
} catch (...) {
env->DeleteLocalRef(target);
env->DeleteLocalRef(graphicsConfig);
env->DeleteLocalRef(canvasClass);
env->DeleteLocalRef(win32cls);
env->DeleteGlobalRef(self);
env->DeleteGlobalRef(hParent);
throw;
}
done:
env->DeleteLocalRef(target);
env->DeleteLocalRef(graphicsConfig);
env->DeleteLocalRef(canvasClass);
env->DeleteLocalRef(win32cls);
return canvas;
CATCH_BAD_ALLOC_RET(0);
}
......
......@@ -157,6 +157,7 @@ AwtChoice* AwtChoice::Create(jobject peer, jobject parent) {
"preferredSize",
"()Ljava/awt/Dimension;").l;
DASSERT(!safe_ExceptionOccurred(env));
if (env->ExceptionCheck()) goto done;
if (dimension != NULL && width == 0) {
width = env->GetIntField(dimension, AwtDimension::widthID);
......@@ -337,9 +338,8 @@ jobject AwtChoice::PreferredItemSize(JNIEnv *env)
"preferredSize",
"()Ljava/awt/Dimension;").l;
DASSERT(!safe_ExceptionOccurred(env));
if (dimension == NULL) {
return NULL;
}
CHECK_NULL_RETURN(dimension, NULL);
/* This size is window size of choice and it's too big for each
* drop down item height.
*/
......@@ -605,7 +605,8 @@ void AwtChoice::_AddItems(void *param)
for (i = 0; i < itemCount; i++)
{
jstring item = (jstring)env->GetObjectArrayElement(items, i);
JNI_CHECK_NULL_GOTO(item, "null item", next_elem);
if (env->ExceptionCheck()) goto done;
if (item == NULL) goto next_elem;
c->SendMessage(CB_INSERTSTRING, index + i, JavaStringBuffer(env, item));
env->DeleteLocalRef(item);
next_elem:
......
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -23,6 +23,7 @@
* questions.
*/
#include "jni_util.h"
#include "awt.h"
#include <jni.h>
#include <shellapi.h>
......@@ -41,7 +42,12 @@ JNIEXPORT jstring JNICALL Java_sun_awt_windows_WDesktopPeer_ShellExecute
(JNIEnv *env, jclass cls, jstring fileOrUri_j, jstring verb_j)
{
LPCWSTR fileOrUri_c = JNU_GetStringPlatformChars(env, fileOrUri_j, JNI_FALSE);
CHECK_NULL_RETURN(fileOrUri_c, NULL);
LPCWSTR verb_c = JNU_GetStringPlatformChars(env, verb_j, JNI_FALSE);
if (verb_c == NULL) {
JNU_ReleaseStringPlatformChars(env, fileOrUri_j, fileOrUri_c);
return NULL;
}
// 6457572: ShellExecute possibly changes FPU control word - saving it here
unsigned oldcontrol87 = _control87(0, 0);
......
/*
* Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -23,6 +23,7 @@
* questions.
*/
#include "jni_util.h"
#include "awt_Toolkit.h"
#include "awt_Dialog.h"
#include "awt_Window.h"
......@@ -457,18 +458,25 @@ void AwtDialog::ModalActivateNextWindow(HWND dialogHWnd,
{
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
jclass wwindowPeerCls = env->FindClass("sun/awt/windows/WWindowPeer");
jmethodID getActiveWindowsMID = env->GetStaticMethodID(wwindowPeerCls,
"getActiveWindowHandles", "()[J");
DASSERT(getActiveWindowsMID != NULL);
jlongArray windows = (jlongArray)(env->CallStaticObjectMethod(wwindowPeerCls,
getActiveWindowsMID));
jboolean exc;
jlongArray windows = (jlongArray) JNU_CallStaticMethodByName
(env,
&exc,
"sun/awt/windows/WWindowPeer",
"getActiveWindowHandles",
"()[J").l;
if (exc == JNI_TRUE) {
throw std::bad_alloc();
}
if (windows == NULL) {
return;
}
jboolean isCopy;
jlong *ws = env->GetLongArrayElements(windows, &isCopy);
if (ws == NULL) {
throw std::bad_alloc();
}
int windowsCount = env->GetArrayLength(windows);
for (int i = windowsCount - 1; i >= 0; i--) {
HWND w = (HWND)ws[i];
......@@ -744,11 +752,13 @@ Java_java_awt_Dialog_initIDs(JNIEnv *env, jclass cls)
/* java.awt.Dialog fields and methods */
AwtDialog::titleID
= env->GetFieldID(cls, "title", "Ljava/lang/String;");
DASSERT(AwtDialog::titleID != NULL);
CHECK_NULL(AwtDialog::titleID);
AwtDialog::undecoratedID
= env->GetFieldID(cls,"undecorated","Z");
DASSERT(AwtDialog::undecoratedID != NULL);
DASSERT(AwtDialog::titleID != NULL);
CHECK_NULL(AwtDialog::undecoratedID);
CATCH_BAD_ALLOC;
}
......
......@@ -614,7 +614,8 @@ void AwtList::_AddItems(void *param)
{
LPTSTR itemPtr = NULL;
jstring item = (jstring)env->GetObjectArrayElement(items, i);
JNI_CHECK_NULL_GOTO(item, "null item", next_item);
if (env->ExceptionCheck()) goto ret;
if (item == NULL) goto next_item;
itemPtr = (LPTSTR)JNU_GetStringPlatformChars(env, item, 0);
if (itemPtr == NULL)
{
......@@ -1017,8 +1018,8 @@ Java_sun_awt_windows_WListPeer_isSelected(JNIEnv *env, jobject self,
ses->list = env->NewGlobalRef(self);
ses->index = index;
return (jboolean)AwtToolkit::GetInstance().SyncCall(
(void *(*)(void *))AwtList::_IsSelected, ses);
return JNI_IS_TRUE(AwtToolkit::GetInstance().SyncCall(
(void *(*)(void *))AwtList::_IsSelected, ses));
// global ref and ses are deleted in _IsSelected
CATCH_BAD_ALLOC_RET(FALSE);
......
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -268,9 +268,11 @@ Java_java_awt_MenuBar_initIDs(JNIEnv *env, jclass cls)
TRY;
AwtMenuBar::getMenuCountMID = env->GetMethodID(cls, "getMenuCountImpl", "()I");
DASSERT(AwtMenuBar::getMenuCountMID != NULL);
CHECK_NULL(AwtMenuBar::getMenuCountMID);
AwtMenuBar::getMenuMID = env->GetMethodID(cls, "getMenuImpl",
"(I)Ljava/awt/Menu;");
DASSERT(AwtMenuBar::getMenuCountMID != NULL);
DASSERT(AwtMenuBar::getMenuMID != NULL);
CATCH_BAD_ALLOC;
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册