提交 92f40df7 编写于 作者: A asaha

Merge

...@@ -536,8 +536,26 @@ d841d3fdae44f120883dab0a3a809a054cd0274b jdk8u72-b13 ...@@ -536,8 +536,26 @@ d841d3fdae44f120883dab0a3a809a054cd0274b jdk8u72-b13
f6d24d424cd2af4d2612f7737d3d9a25f58b882d jdk8u72-b14 f6d24d424cd2af4d2612f7737d3d9a25f58b882d jdk8u72-b14
f3e86cc607260bae368b52d88d7bc8883ee767e3 jdk8u72-b15 f3e86cc607260bae368b52d88d7bc8883ee767e3 jdk8u72-b15
1d4b343084874b1afa1cdd504b9b1e50bab7f121 jdk8u72-b31 1d4b343084874b1afa1cdd504b9b1e50bab7f121 jdk8u72-b31
892eb9ab179650b89b7bab6bc42f079391c98624 jdk8u73-b00
9b77d3ca0d66a117c3cc0e0a74b8059545b22f0e jdk8u73-b01
2ab13901d6f14bab0dcf4823d5e378a421fba7e2 jdk8u73-b02
9a843dc6f959f62c61014a3a71ec9aa329f1daf1 jdk8u74-b00
e829ab80dfd828803aa8837411900faeaa1254a5 jdk8u74-b01
32c49f4a16599e376e4e46bb33c7bcc486e52ff3 jdk8u74-b02
9c828e688240362b6f1b761b619cdaa070462c4e jdk8u74-b31
1d4b343084874b1afa1cdd504b9b1e50bab7f121 jdk8u72-b31
7cfd2c51c501df909833aa0fb6e40c50c61621ed jdk8u75-b00 7cfd2c51c501df909833aa0fb6e40c50c61621ed jdk8u75-b00
9e00a43602f87930c2318b2567002871ad9c59dd jdk8u75-b01 9e00a43602f87930c2318b2567002871ad9c59dd jdk8u75-b01
9de301db625bb1b462aad3ebd8347118b94bb728 jdk8u75-b02 9de301db625bb1b462aad3ebd8347118b94bb728 jdk8u75-b02
dcacefa73649a2d821267b6bff1d70aa10a06801 jdk8u75-b03 dcacefa73649a2d821267b6bff1d70aa10a06801 jdk8u75-b03
de91f05824c5398cb2d2f666ff404aaa165498de jdk8u75-b04
4138b3f27ffea524185a604c3f4f149c7e5ba780 jdk8u75-b05
32f64c19b5fba8beeae5236ca6e480bd8e99698a jdk8u75-b06
39baa472e20c13c0eb1243eb5dce589e82f78143 jdk8u76-b00
6ea3aea950d19d803475b3f4d704a2942e71b302 jdk8u76-b01
4de4cffb5988cd68959ce4bbd14c6d4547078c91 jdk8u76-b02
8bef978e2374604f449b4d1d7f90cb26618540d7 jdk8u76-b03
e057622070e5415c13b6d8511b97dce8bd2e398d jdk8u76-b04
b3128c272f8d1684303975795687fd2e9cb87ddf jdk8u76-b05
06c922a192a822b6a76516d114bfb6979fab03bf jdk8u76-b06
f6cc9dbb5db5883385c91bb71ca02081220aaf3d jdk8u81-b00 f6cc9dbb5db5883385c91bb71ca02081220aaf3d jdk8u81-b00
...@@ -229,7 +229,7 @@ define SetupJVMTIDemo ...@@ -229,7 +229,7 @@ define SetupJVMTIDemo
BUILD_DEMO_JVMTI_$1_LANG := $4 BUILD_DEMO_JVMTI_$1_LANG := $4
endif endif
ifeq (C++, $4) ifeq (C++, $4)
$1_EXTRA_CXX := $(LDFLAGS_CXX_JDK) $(LIBCXX) $1_EXTRA_CXX := $$(LDFLAGS_CXX_JDK) $(LIBCXX)
endif endif
$1_CXXFLAGS := $(CXXFLAGS_JDKLIB) -I$(JDK_TOPDIR)/src/share/demo/jvmti/$1 \ $1_CXXFLAGS := $(CXXFLAGS_JDKLIB) -I$(JDK_TOPDIR)/src/share/demo/jvmti/$1 \
...@@ -251,8 +251,8 @@ define SetupJVMTIDemo ...@@ -251,8 +251,8 @@ define SetupJVMTIDemo
LANG := $$(BUILD_DEMO_JVMTI_$1_LANG), \ LANG := $$(BUILD_DEMO_JVMTI_$1_LANG), \
OPTIMIZATION := LOW, \ OPTIMIZATION := LOW, \
CXXFLAGS := $$($1_CXXFLAGS), \ CXXFLAGS := $$($1_CXXFLAGS), \
LDFLAGS := $(filter-out -incremental:no -opt:ref, $(LDFLAGS_JDKLIB)), \ LDFLAGS := $(filter-out -incremental:no -opt:ref, $$(LDFLAGS_JDKLIB)), \
LDFLAGS_macosx := $(call SET_EXECUTABLE_ORIGIN), \ LDFLAGS_macosx := $$(call SET_EXECUTABLE_ORIGIN), \
LDFLAGS_SUFFIX := $$($1_EXTRA_CXX), \ LDFLAGS_SUFFIX := $$($1_EXTRA_CXX), \
LDFLAGS_SUFFIX_posix := $5, \ LDFLAGS_SUFFIX_posix := $5, \
LDFLAGS_SUFFIX_windows := $6, \ LDFLAGS_SUFFIX_windows := $6, \
......
...@@ -443,11 +443,6 @@ else ...@@ -443,11 +443,6 @@ else
endif endif
ifeq ($(OPENJDK_TARGET_CPU_ARCH), sparc)
UNPACKEXE_CFLAGS += -xregs=no%appl
UNPACKEXE_LDFLAGS_solaris += -xmemalign=4s
endif
UNPACKEXE_LANG := C UNPACKEXE_LANG := C
ifeq ($(OPENJDK_TARGET_OS), solaris) ifeq ($(OPENJDK_TARGET_OS), solaris)
UNPACKEXE_LANG := C++ UNPACKEXE_LANG := C++
......
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -1068,6 +1068,7 @@ JVMInit(InvocationFunctions* ifn, jlong threadStackSize, ...@@ -1068,6 +1068,7 @@ JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
void PostJVMInit(JNIEnv *env, jstring mainClass, JavaVM *vm) { void PostJVMInit(JNIEnv *env, jstring mainClass, JavaVM *vm) {
jvmInstance = vm; jvmInstance = vm;
SetMainClassForAWT(env, mainClass); SetMainClassForAWT(env, mainClass);
CHECK_EXCEPTION_RETURN();
ShowSplashScreen(); ShowSplashScreen();
} }
......
...@@ -46,6 +46,7 @@ ...@@ -46,6 +46,7 @@
-(void) deliverResize: (NSRect) rect; -(void) deliverResize: (NSRect) rect;
-(void) resetTrackingArea; -(void) resetTrackingArea;
-(void) deliverJavaKeyEventHelper: (NSEvent*) event; -(void) deliverJavaKeyEventHelper: (NSEvent*) event;
-(BOOL) isCodePointInUnicodeBlockNeedingIMEvent: (unichar) codePoint;
@end @end
// Uncomment this line to see fprintfs of each InputMethod API being called on this View // Uncomment this line to see fprintfs of each InputMethod API being called on this View
...@@ -513,6 +514,14 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -513,6 +514,14 @@ AWT_ASSERT_APPKIT_THREAD;
} }
} }
-(BOOL) isCodePointInUnicodeBlockNeedingIMEvent: (unichar) codePoint {
if ((codePoint >= 0x3000) && (codePoint <= 0x303F)) {
// Code point is in 'CJK Symbols and Punctuation' Unicode block.
return YES;
}
return NO;
}
// NSAccessibility support // NSAccessibility support
- (jobject)awtComponent:(JNIEnv*)env - (jobject)awtComponent:(JNIEnv*)env
{ {
...@@ -893,8 +902,14 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); ...@@ -893,8 +902,14 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod");
// (i.e., when the user uses the Character palette or Inkwell), or when the string to insert is a complex // (i.e., when the user uses the Character palette or Inkwell), or when the string to insert is a complex
// Unicode value. // Unicode value.
NSUInteger utf16Length = [aString lengthOfBytesUsingEncoding:NSUTF16StringEncoding]; NSUInteger utf16Length = [aString lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
NSUInteger utf8Length = [aString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
BOOL aStringIsComplex = NO;
if ((utf16Length > 2) ||
((utf8Length > 1) && [self isCodePointInUnicodeBlockNeedingIMEvent:[aString characterAtIndex:0]])) {
aStringIsComplex = YES;
}
if ([self hasMarkedText] || !fProcessingKeystroke || (utf16Length > 2)) { if ([self hasMarkedText] || !fProcessingKeystroke || aStringIsComplex) {
JNIEnv *env = [ThreadUtilities getJNIEnv]; JNIEnv *env = [ThreadUtilities getJNIEnv];
static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V"); static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V");
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
#import <JavaNativeFoundation/JavaNativeFoundation.h> #import <JavaNativeFoundation/JavaNativeFoundation.h>
#import "jni_util.h" #import "jni_util.h"
#import "ThreadUtilities.h"
#import "LWCToolkit.h" #import "LWCToolkit.h"
#import "AWT_debug.h" #import "AWT_debug.h"
...@@ -133,17 +134,20 @@ static void displaycb_handle ...@@ -133,17 +134,20 @@ static void displaycb_handle
{ {
if (flags == kCGDisplayBeginConfigurationFlag) return; if (flags == kCGDisplayBeginConfigurationFlag) return;
[ThreadUtilities performOnMainThreadWaiting:NO block:^() {
JNFPerformEnvBlock(JNFThreadDetachImmediately, ^(JNIEnv *env) { JNFPerformEnvBlock(JNFThreadDetachImmediately, ^(JNIEnv *env) {
JNFWeakJObjectWrapper *wrapper = (JNFWeakJObjectWrapper *)userInfo; JNFWeakJObjectWrapper *wrapper = (JNFWeakJObjectWrapper *)userInfo;
jobject graphicsEnv = [wrapper jObjectWithEnv:env]; jobject graphicsEnv = [wrapper jObjectWithEnv:env];
if (graphicsEnv == NULL) return; // ref already GC'd if (graphicsEnv == NULL) return; // ref already GC'd
static JNF_CLASS_CACHE(jc_CGraphicsEnvironment, "sun/awt/CGraphicsEnvironment"); static JNF_CLASS_CACHE(jc_CGraphicsEnvironment, "sun/awt/CGraphicsEnvironment");
static JNF_MEMBER_CACHE(jm_displayReconfiguration, jc_CGraphicsEnvironment, "_displayReconfiguration", "(IZ)V"); static JNF_MEMBER_CACHE(jm_displayReconfiguration,
jc_CGraphicsEnvironment, "_displayReconfiguration","(IZ)V");
JNFCallVoidMethod(env, graphicsEnv, jm_displayReconfiguration, JNFCallVoidMethod(env, graphicsEnv, jm_displayReconfiguration,
(jint) display, (jint) display, (jboolean) flags & kCGDisplayRemoveFlag);
(jboolean) flags & kCGDisplayRemoveFlag);
}); });
}];
} }
/* /*
......
...@@ -236,6 +236,7 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo ...@@ -236,6 +236,7 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
} }
NSOpenGLPixelFormatAttribute attrs[] = { NSOpenGLPixelFormatAttribute attrs[] = {
NSOpenGLPFAAllowOfflineRenderers,
NSOpenGLPFAClosestPolicy, NSOpenGLPFAClosestPolicy,
NSOpenGLPFAWindow, NSOpenGLPFAWindow,
NSOpenGLPFAPixelBuffer, NSOpenGLPFAPixelBuffer,
......
/* /*
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -459,6 +459,7 @@ JavaMain(void * _args) ...@@ -459,6 +459,7 @@ JavaMain(void * _args)
* of the application class. * of the application class.
*/ */
PostJVMInit(env, appClass, vm); PostJVMInit(env, appClass, vm);
CHECK_EXCEPTION_LEAVE(1);
/* /*
* The LoadMainClass not only loads the main class, it will also ensure * The LoadMainClass not only loads the main class, it will also ensure
* that the main method's signature is correct, therefore further checking * that the main method's signature is correct, therefore further checking
......
/* /*
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -256,6 +256,13 @@ typedef struct { ...@@ -256,6 +256,13 @@ typedef struct {
#define NULL_CHECK(NC_check_pointer) \ #define NULL_CHECK(NC_check_pointer) \
NULL_CHECK_RETURN_VALUE(NC_check_pointer, ) NULL_CHECK_RETURN_VALUE(NC_check_pointer, )
#define CHECK_EXCEPTION_RETURN() \
do { \
if ((*env)->ExceptionOccurred(env)) { \
return; \
} \
} while (JNI_FALSE)
/* /*
* For JNI calls : * For JNI calls :
* - check for thrown exceptions * - check for thrown exceptions
......
...@@ -90,6 +90,10 @@ public class JCEMapper { ...@@ -90,6 +90,10 @@ public class JCEMapper {
XMLSignature.ALGO_ID_SIGNATURE_DSA, XMLSignature.ALGO_ID_SIGNATURE_DSA,
new Algorithm("", "SHA1withDSA", "Signature") new Algorithm("", "SHA1withDSA", "Signature")
); );
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256,
new Algorithm("", "SHA256withDSA", "Signature")
);
algorithmsMap.put( algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5, XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
new Algorithm("", "MD5withRSA", "Signature") new Algorithm("", "MD5withRSA", "Signature")
......
...@@ -387,7 +387,12 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -387,7 +387,12 @@ public class SignatureAlgorithm extends Algorithm {
* This method registers the default algorithms. * This method registers the default algorithms.
*/ */
public static void registerDefaultAlgorithms() { public static void registerDefaultAlgorithms() {
algorithmHash.put(SignatureDSA.URI, SignatureDSA.class); algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256, SignatureDSA.SHA256.class
);
algorithmHash.put( algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
); );
......
...@@ -31,13 +31,15 @@ import java.security.PublicKey; ...@@ -31,13 +31,15 @@ import java.security.PublicKey;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.Signature; import java.security.Signature;
import java.security.SignatureException; import java.security.SignatureException;
import java.security.interfaces.DSAKey;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
public class SignatureDSA extends SignatureAlgorithmSpi { public class SignatureDSA extends SignatureAlgorithmSpi {
...@@ -45,19 +47,19 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -45,19 +47,19 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
private static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureDSA.class.getName()); java.util.logging.Logger.getLogger(SignatureDSA.class.getName());
/** Field URI */
public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
/** Field algorithm */ /** Field algorithm */
private java.security.Signature signatureAlgorithm = null; private java.security.Signature signatureAlgorithm = null;
/** size of Q */
private int size;
/** /**
* Method engineGetURI * Method engineGetURI
* *
* @inheritDoc * @inheritDoc
*/ */
protected String engineGetURI() { protected String engineGetURI() {
return SignatureDSA.URI; return XMLSignature.ALGO_ID_SIGNATURE_DSA;
} }
/** /**
...@@ -66,7 +68,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -66,7 +68,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public SignatureDSA() throws XMLSignatureException { public SignatureDSA() throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI); String algorithmID = JCEMapper.translateURItoJCEID(engineGetURI());
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
} }
...@@ -110,7 +112,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -110,7 +112,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature)); log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
} }
byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature); byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature,
size/8);
return this.signatureAlgorithm.verify(jcebytes); return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException ex) { } catch (SignatureException ex) {
...@@ -150,6 +153,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -150,6 +153,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
} }
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
size = ((DSAKey)publicKey).getParams().getQ().bitLength();
} }
/** /**
...@@ -159,7 +163,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -159,7 +163,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
try { try {
byte jcebytes[] = this.signatureAlgorithm.sign(); byte jcebytes[] = this.signatureAlgorithm.sign();
return SignatureDSA.convertASN1toXMLDSIG(jcebytes); return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size/8);
} catch (IOException ex) { } catch (IOException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} catch (SignatureException ex) { } catch (SignatureException ex) {
...@@ -185,6 +189,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -185,6 +189,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
size = ((DSAKey)privateKey).getParams().getQ().bitLength();
} }
/** /**
...@@ -204,6 +209,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -204,6 +209,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
size = ((DSAKey)privateKey).getParams().getQ().bitLength();
} }
/** /**
...@@ -257,100 +263,6 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -257,100 +263,6 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
return this.signatureAlgorithm.getProvider().getName(); return this.signatureAlgorithm.getProvider().getName();
} }
/**
* Converts an ASN.1 DSA value to a XML Signature DSA Value.
*
* The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param asn1Bytes
* @return the decode bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
byte rLength = asn1Bytes[3];
int i;
for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
byte sLength = asn1Bytes[5 + rLength];
int j;
for (j = sLength;
(j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
|| (asn1Bytes[2] != 2) || (i > 20)
|| (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
throw new IOException("Invalid ASN.1 format of DSA signature");
}
byte xmldsigBytes[] = new byte[40];
System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i);
System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
40 - j, j);
return xmldsigBytes;
}
/**
* Converts a XML Signature DSA Value to an ASN.1 DSA value.
*
* The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param xmldsigBytes
* @return the encoded ASN.1 bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
if (xmldsigBytes.length != 40) {
throw new IOException("Invalid XMLDSIG format of DSA signature");
}
int i;
for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--);
int j = i;
if (xmldsigBytes[20 - i] < 0) {
j += 1;
}
int k;
for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--);
int l = k;
if (xmldsigBytes[40 - k] < 0) {
l += 1;
}
byte asn1Bytes[] = new byte[6 + j + l];
asn1Bytes[0] = 48;
asn1Bytes[1] = (byte) (4 + j + l);
asn1Bytes[2] = 2;
asn1Bytes[3] = (byte) j;
System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
asn1Bytes[4 + j] = 2;
asn1Bytes[5 + j] = (byte) l;
System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k);
return asn1Bytes;
}
/** /**
* Method engineSetHMACOutputLength * Method engineSetHMACOutputLength
* *
...@@ -373,4 +285,15 @@ public class SignatureDSA extends SignatureAlgorithmSpi { ...@@ -373,4 +285,15 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
) throws XMLSignatureException { ) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA"); throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA");
} }
public static class SHA256 extends SignatureDSA {
public SHA256() throws XMLSignatureException {
super();
}
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256;
}
}
} }
...@@ -85,6 +85,10 @@ public final class XMLSignature extends SignatureElementProxy { ...@@ -85,6 +85,10 @@ public final class XMLSignature extends SignatureElementProxy {
public static final String ALGO_ID_SIGNATURE_DSA = public static final String ALGO_ID_SIGNATURE_DSA =
Constants.SignatureSpecNS + "dsa-sha1"; Constants.SignatureSpecNS + "dsa-sha1";
/** Signature - Optional DSAwithSHA256 */
public static final String ALGO_ID_SIGNATURE_DSA_SHA256 =
Constants.SignatureSpec11NS + "dsa-sha256";
/** Signature - Recommended RSAwithSHA1 */ /** Signature - Recommended RSAwithSHA1 */
public static final String ALGO_ID_SIGNATURE_RSA = public static final String ALGO_ID_SIGNATURE_RSA =
Constants.SignatureSpecNS + "rsa-sha1"; Constants.SignatureSpecNS + "rsa-sha1";
......
...@@ -151,6 +151,100 @@ public class JavaUtils { ...@@ -151,6 +151,100 @@ public class JavaUtils {
return retBytes; return retBytes;
} }
/**
* Converts an ASN.1 DSA value to a XML Signature DSA Value.
*
* The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs (see section 2.2.2 of RFC 3279); the XML Signature requires the
* core BigInteger values.
*
* @param asn1Bytes the ASN.1 encoded bytes
* @param size size of r and s in bytes
* @return the XML Signature encoded bytes
* @throws IOException if the bytes are not encoded correctly
* @see <A HREF="http://www.w3.org/TR/xmldsig-core1/#sec-DSA">6.4.1 DSA</A>
*/
public static byte[] convertDsaASN1toXMLDSIG(byte[] asn1Bytes, int size)
throws IOException
{
if (asn1Bytes[0] != 48 || asn1Bytes[1] != asn1Bytes.length - 2
|| asn1Bytes[2] != 2) {
throw new IOException("Invalid ASN.1 format of DSA signature");
}
byte rLength = asn1Bytes[3];
int i;
for (i = rLength; i > 0 && asn1Bytes[4 + rLength - i] == 0; i--);
byte sLength = asn1Bytes[5 + rLength];
int j;
for (j = sLength;
j > 0 && asn1Bytes[6 + rLength + sLength - j] == 0; j--);
if (i > size || asn1Bytes[4 + rLength] != 2 || j > size) {
throw new IOException("Invalid ASN.1 format of DSA signature");
} else {
byte[] xmldsigBytes = new byte[size * 2];
System.arraycopy(asn1Bytes, 4 + rLength - i, xmldsigBytes,
size - i, i);
System.arraycopy(asn1Bytes, 6 + rLength + sLength - j,
xmldsigBytes, size * 2 - j, j);
return xmldsigBytes;
}
}
/**
* Converts an XML Signature DSA Value to a ASN.1 DSA value.
*
* The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs (see section 2.2.2 of RFC 3279); the XML Signature requires the
* core BigInteger values.
*
* @param xmldsigBytes the XML Signature encoded bytes
* @param size size of r and s in bytes
* @return the ASN.1 encoded bytes
* @throws IOException if the bytes are not encoded correctly
* @see <A HREF="http://www.w3.org/TR/xmldsig-core1/#sec-DSA">6.4.1 DSA</A>
*/
public static byte[] convertDsaXMLDSIGtoASN1(byte[] xmldsigBytes, int size)
throws IOException
{
int totalSize = size * 2;
if (xmldsigBytes.length != totalSize) {
throw new IOException("Invalid XMLDSIG format of DSA signature");
}
int i;
for (i = size; i > 0 && xmldsigBytes[size - i] == 0; i--);
int j = i;
if (xmldsigBytes[size - i] < 0) {
j++;
}
int k;
for (k = size; k > 0 && xmldsigBytes[totalSize - k] == 0; k--);
int l = k;
if (xmldsigBytes[totalSize - k] < 0) {
l++;
}
byte[] asn1Bytes = new byte[6 + j + l];
asn1Bytes[0] = 48;
asn1Bytes[1] = (byte)(4 + j + l);
asn1Bytes[2] = 2;
asn1Bytes[3] = (byte)j;
System.arraycopy(xmldsigBytes, size - i, asn1Bytes, 4 + j - i, i);
asn1Bytes[4 + j] = 2;
asn1Bytes[5 + j] = (byte) l;
System.arraycopy(xmldsigBytes, totalSize - k, asn1Bytes,
6 + j + l - k, k);
return asn1Bytes;
}
/** /**
* Throws a {@code SecurityException} if a security manager is installed * Throws a {@code SecurityException} if a security manager is installed
* and the caller is not allowed to register an implementation of an * and the caller is not allowed to register an implementation of an
......
...@@ -934,7 +934,7 @@ public class XMLUtils { ...@@ -934,7 +934,7 @@ public class XMLUtils {
Element foundElement = null; Element foundElement = null;
String id = value.trim(); String id = value.trim();
if (id.charAt(0) == '#') { if (!id.isEmpty() && id.charAt(0) == '#') {
id = id.substring(1); id = id.substring(1);
} }
...@@ -994,7 +994,7 @@ public class XMLUtils { ...@@ -994,7 +994,7 @@ public class XMLUtils {
Node processedNode = null; Node processedNode = null;
String id = value.trim(); String id = value.trim();
if (id.charAt(0) == '#') { if (!id.isEmpty() && id.charAt(0) == '#') {
id = id.substring(1); id = id.substring(1);
} }
......
...@@ -236,6 +236,15 @@ abstract class InvokableTypeImpl extends ReferenceTypeImpl { ...@@ -236,6 +236,15 @@ abstract class InvokableTypeImpl extends ReferenceTypeImpl {
final MethodImpl method, final MethodImpl method,
final ValueImpl[] args, final ValueImpl[] args,
final int options) { final int options) {
/*
* Cache the values of args when TRACE_SENDS is enabled, for later printing.
* If not cached, printing causes a remote call while synchronized, and deadlock.
*/
if ((vm.traceFlags & VirtualMachineImpl.TRACE_SENDS) != 0) {
for (ValueImpl arg: args) {
arg.toString();
}
}
CommandSender sender = getInvokeMethodSender(thread, method, args, options); CommandSender sender = getInvokeMethodSender(thread, method, args, options);
PacketStream stream; PacketStream stream;
if ((options & ClassType.INVOKE_SINGLE_THREADED) != 0) { if ((options & ClassType.INVOKE_SINGLE_THREADED) != 0) {
......
...@@ -312,7 +312,7 @@ public abstract class Component implements ImageObserver, MenuContainer, ...@@ -312,7 +312,7 @@ public abstract class Component implements ImageObserver, MenuContainer,
* @see GraphicsConfiguration * @see GraphicsConfiguration
* @see #getGraphicsConfiguration * @see #getGraphicsConfiguration
*/ */
private transient GraphicsConfiguration graphicsConfig = null; private transient volatile GraphicsConfiguration graphicsConfig;
/** /**
* A reference to a <code>BufferStrategy</code> object * A reference to a <code>BufferStrategy</code> object
...@@ -1141,10 +1141,8 @@ public abstract class Component implements ImageObserver, MenuContainer, ...@@ -1141,10 +1141,8 @@ public abstract class Component implements ImageObserver, MenuContainer,
* @since 1.3 * @since 1.3
*/ */
public GraphicsConfiguration getGraphicsConfiguration() { public GraphicsConfiguration getGraphicsConfiguration() {
synchronized(getTreeLock()) {
return getGraphicsConfiguration_NoClientCode(); return getGraphicsConfiguration_NoClientCode();
} }
}
final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() { final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
return graphicsConfig; return graphicsConfig;
......
...@@ -348,7 +348,7 @@ public class Window extends Container implements Accessible { ...@@ -348,7 +348,7 @@ public class Window extends Container implements Accessible {
* @see #getOpacity() * @see #getOpacity()
* @since 1.7 * @since 1.7
*/ */
private float opacity = 1.0f; private volatile float opacity = 1.0f;
/** /**
* The shape assigned to this window. This field is set to {@code null} if * The shape assigned to this window. This field is set to {@code null} if
...@@ -1040,9 +1040,7 @@ public class Window extends Container implements Accessible { ...@@ -1040,9 +1040,7 @@ public class Window extends Container implements Accessible {
closeSplashScreen(); closeSplashScreen();
Dialog.checkShouldBeBlocked(this); Dialog.checkShouldBeBlocked(this);
super.show(); super.show();
synchronized (getTreeLock()) { locationByPlatform = false;
this.locationByPlatform = false;
}
for (int i = 0; i < ownedWindowList.size(); i++) { for (int i = 0; i < ownedWindowList.size(); i++) {
Window child = ownedWindowList.elementAt(i).get(); Window child = ownedWindowList.elementAt(i).get();
if ((child != null) && child.showWithParent) { if ((child != null) && child.showWithParent) {
...@@ -1115,9 +1113,7 @@ public class Window extends Container implements Accessible { ...@@ -1115,9 +1113,7 @@ public class Window extends Container implements Accessible {
modalBlocker.unblockWindow(this); modalBlocker.unblockWindow(this);
} }
super.hide(); super.hide();
synchronized (getTreeLock()) { locationByPlatform = false;
this.locationByPlatform = false;
}
} }
final void clearMostRecentFocusOwnerOnHide() { final void clearMostRecentFocusOwnerOnHide() {
...@@ -3398,7 +3394,7 @@ public class Window extends Container implements Accessible { ...@@ -3398,7 +3394,7 @@ public class Window extends Container implements Accessible {
return super.canContainFocusOwner(focusOwnerCandidate) && isFocusableWindow(); return super.canContainFocusOwner(focusOwnerCandidate) && isFocusableWindow();
} }
private boolean locationByPlatform = locationByPlatformProp; private volatile boolean locationByPlatform = locationByPlatformProp;
/** /**
...@@ -3469,10 +3465,8 @@ public class Window extends Container implements Accessible { ...@@ -3469,10 +3465,8 @@ public class Window extends Container implements Accessible {
* @since 1.5 * @since 1.5
*/ */
public boolean isLocationByPlatform() { public boolean isLocationByPlatform() {
synchronized (getTreeLock()) {
return locationByPlatform; return locationByPlatform;
} }
}
/** /**
* {@inheritDoc} * {@inheritDoc}
...@@ -3560,10 +3554,8 @@ public class Window extends Container implements Accessible { ...@@ -3560,10 +3554,8 @@ public class Window extends Container implements Accessible {
* @since 1.7 * @since 1.7
*/ */
public float getOpacity() { public float getOpacity() {
synchronized (getTreeLock()) {
return opacity; return opacity;
} }
}
/** /**
* Sets the opacity of the window. * Sets the opacity of the window.
......
...@@ -34,14 +34,16 @@ import java.lang.invoke.LambdaForm.NamedFunction; ...@@ -34,14 +34,16 @@ import java.lang.invoke.LambdaForm.NamedFunction;
import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.function.Function;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import sun.invoke.util.ValueConversions; import sun.invoke.util.ValueConversions;
import sun.invoke.util.Wrapper; import sun.invoke.util.Wrapper;
import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Type;
/** /**
* The flavor of method handle which emulates an invoke instruction * The flavor of method handle which emulates an invoke instruction
...@@ -217,7 +219,7 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -217,7 +219,7 @@ import jdk.internal.org.objectweb.asm.Type;
/*non-public*/ int fieldCount() { /*non-public*/ int fieldCount() {
return 1; return 1;
} }
/*non-public*/ static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("L", Species_L.class); /*non-public*/ static final SpeciesData SPECIES_DATA = new SpeciesData("L", Species_L.class);
/*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) { /*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) {
return new Species_L(mt, lf, argL0); return new Species_L(mt, lf, argL0);
} }
...@@ -335,7 +337,7 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -335,7 +337,7 @@ import jdk.internal.org.objectweb.asm.Type;
static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class); static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class);
private SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) { SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
this.typeChars = types; this.typeChars = types;
this.typeCodes = basicTypes(types); this.typeCodes = basicTypes(types);
this.clazz = clazz; this.clazz = clazz;
...@@ -355,26 +357,14 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -355,26 +357,14 @@ import jdk.internal.org.objectweb.asm.Type;
assert(!INIT_DONE); assert(!INIT_DONE);
if (constructor() == null) { if (constructor() == null) {
String types = typeChars; String types = typeChars;
CACHE.put(types, this);
Factory.makeCtors(clazz, types, this.constructor); Factory.makeCtors(clazz, types, this.constructor);
Factory.makeGetters(clazz, types, this.getters); Factory.makeGetters(clazz, types, this.getters);
Factory.makeNominalGetters(types, this.nominalGetters, this.getters); Factory.makeNominalGetters(types, this.nominalGetters, this.getters);
} }
} }
private SpeciesData(String typeChars) { private static final ConcurrentMap<String, SpeciesData> CACHE = new ConcurrentHashMap<>();
// Placeholder only.
this.typeChars = typeChars;
this.typeCodes = basicTypes(typeChars);
this.clazz = null;
this.constructor = null;
this.getters = null;
this.nominalGetters = null;
this.extensions = null;
}
private boolean isPlaceholder() { return clazz == null; }
private static final HashMap<String, SpeciesData> CACHE = new HashMap<>();
static { CACHE.put("", EMPTY); } // make bootstrap predictable
private static final boolean INIT_DONE; // set after <clinit> finishes... private static final boolean INIT_DONE; // set after <clinit> finishes...
SpeciesData extendWith(byte type) { SpeciesData extendWith(byte type) {
...@@ -390,62 +380,52 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -390,62 +380,52 @@ import jdk.internal.org.objectweb.asm.Type;
} }
private static SpeciesData get(String types) { private static SpeciesData get(String types) {
// Acquire cache lock for query. return CACHE.computeIfAbsent(types, new Function<String, SpeciesData>() {
SpeciesData d = lookupCache(types); @Override
if (!d.isPlaceholder()) public SpeciesData apply(String types) {
return d; Class<? extends BoundMethodHandle> bmhcl = Factory.getConcreteBMHClass(types);
synchronized (d) { // SpeciesData instantiation may throw VirtualMachineError because of
// Use synch. on the placeholder to prevent multiple instantiation of one species. // code cache overflow...
// Creating this class forces a recursive call to getForClass. SpeciesData speciesData = new SpeciesData(types, bmhcl);
if (lookupCache(types).isPlaceholder()) // CHM.computeIfAbsent ensures only one SpeciesData will be set
Factory.generateConcreteBMHClass(types); // successfully on the concrete BMH class if ever
} Factory.setSpeciesDataToConcreteBMHClass(bmhcl, speciesData);
// Reacquire cache lock. // the concrete BMH class is published via SpeciesData instance
d = lookupCache(types); // returned here only after it's SPECIES_DATA field is set
// Class loading must have upgraded the cache. return speciesData;
assert(d != null && !d.isPlaceholder());
return d;
}
static SpeciesData getForClass(String types, Class<? extends BoundMethodHandle> clazz) {
// clazz is a new class which is initializing its SPECIES_DATA field
return updateCache(types, new SpeciesData(types, clazz));
}
private static synchronized SpeciesData lookupCache(String types) {
SpeciesData d = CACHE.get(types);
if (d != null) return d;
d = new SpeciesData(types);
assert(d.isPlaceholder());
CACHE.put(types, d);
return d;
} }
private static synchronized SpeciesData updateCache(String types, SpeciesData d) { });
SpeciesData d2;
assert((d2 = CACHE.get(types)) == null || d2.isPlaceholder());
assert(!d.isPlaceholder());
CACHE.put(types, d);
return d;
} }
static { /**
// pre-fill the BMH speciesdata cache with BMH's inner classes * This is to be called when assertions are enabled. It checks whether SpeciesData for all of the statically
final Class<BoundMethodHandle> rootCls = BoundMethodHandle.class; * defined species subclasses of BoundMethodHandle has been added to the SpeciesData cache. See below in the
* static initializer for
*/
static boolean speciesDataCachePopulated() {
Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;
try { try {
for (Class<?> c : rootCls.getDeclaredClasses()) { for (Class<?> c : rootCls.getDeclaredClasses()) {
if (rootCls.isAssignableFrom(c)) { if (rootCls.isAssignableFrom(c)) {
final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class); final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh); SpeciesData d = Factory.getSpeciesDataFromConcreteBMHClass(cbmh);
assert(d != null) : cbmh.getName(); assert(d != null) : cbmh.getName();
assert(d.clazz == cbmh); assert(d.clazz == cbmh);
assert(d == lookupCache(d.typeChars)); assert(CACHE.get(d.typeChars) == d);
} }
} }
} catch (Throwable e) { } catch (Throwable e) {
throw newInternalError(e); throw newInternalError(e);
} }
return true;
for (SpeciesData d : CACHE.values()) {
d.initForBootstrap();
} }
static {
// Pre-fill the BMH species-data cache with EMPTY and all BMH's inner subclasses.
EMPTY.initForBootstrap();
Species_L.SPECIES_DATA.initForBootstrap();
// check that all static SpeciesData instances have been initialized
assert speciesDataCachePopulated();
// Note: Do not simplify this, because INIT_DONE must not be // Note: Do not simplify this, because INIT_DONE must not be
// a compile-time constant during bootstrapping. // a compile-time constant during bootstrapping.
INIT_DONE = Boolean.TRUE; INIT_DONE = Boolean.TRUE;
...@@ -479,6 +459,7 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -479,6 +459,7 @@ import jdk.internal.org.objectweb.asm.Type;
static final String BMH_SIG = "L"+BMH+";"; static final String BMH_SIG = "L"+BMH+";";
static final String SPECIES_DATA = "java/lang/invoke/BoundMethodHandle$SpeciesData"; static final String SPECIES_DATA = "java/lang/invoke/BoundMethodHandle$SpeciesData";
static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";"; static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
static final String STABLE_SIG = "Ljava/lang/invoke/Stable;";
static final String SPECIES_PREFIX_NAME = "Species_"; static final String SPECIES_PREFIX_NAME = "Species_";
static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME; static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
...@@ -493,6 +474,26 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -493,6 +474,26 @@ import jdk.internal.org.objectweb.asm.Type;
static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" }; static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
static final ConcurrentMap<String, Class<? extends BoundMethodHandle>> CLASS_CACHE = new ConcurrentHashMap<>();
/**
* Get a concrete subclass of BMH for a given combination of bound types.
*
* @param types the type signature, wherein reference types are erased to 'L'
* @return the concrete BMH class
*/
static Class<? extends BoundMethodHandle> getConcreteBMHClass(String types) {
// CHM.computeIfAbsent ensures generateConcreteBMHClass is called
// only once per key.
return CLASS_CACHE.computeIfAbsent(
types, new Function<String, Class<? extends BoundMethodHandle>>() {
@Override
public Class<? extends BoundMethodHandle> apply(String types) {
return generateConcreteBMHClass(types);
}
});
}
/** /**
* Generate a concrete subclass of BMH for a given combination of bound types. * Generate a concrete subclass of BMH for a given combination of bound types.
* *
...@@ -529,7 +530,7 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -529,7 +530,7 @@ import jdk.internal.org.objectweb.asm.Type;
* } * }
* final SpeciesData speciesData() { return SPECIES_DATA; } * final SpeciesData speciesData() { return SPECIES_DATA; }
* final int fieldCount() { return 3; } * final int fieldCount() { return 3; }
* static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LLI", Species_LLI.class); * &#64;Stable static SpeciesData SPECIES_DATA; // injected afterwards
* static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { * static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
* return new Species_LLI(mt, lf, argL0, argL1, argI2); * return new Species_LLI(mt, lf, argL0, argL1, argI2);
* } * }
...@@ -568,7 +569,9 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -568,7 +569,9 @@ import jdk.internal.org.objectweb.asm.Type;
cw.visitSource(sourceFile, null); cw.visitSource(sourceFile, null);
// emit static types and SPECIES_DATA fields // emit static types and SPECIES_DATA fields
cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null).visitEnd(); FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null);
fw.visitAnnotation(STABLE_SIG, true);
fw.visitEnd();
// emit bound argument fields // emit bound argument fields
for (int i = 0; i < types.length(); ++i) { for (int i = 0; i < types.length(); ++i) {
...@@ -694,17 +697,6 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -694,17 +697,6 @@ import jdk.internal.org.objectweb.asm.Type;
mv.visitEnd(); mv.visitEnd();
} }
// emit class initializer
mv = cw.visitMethod(NOT_ACC_PUBLIC | ACC_STATIC, "<clinit>", VOID_SIG, null, null);
mv.visitCode();
mv.visitLdcInsn(types);
mv.visitLdcInsn(Type.getObjectType(className));
mv.visitMethodInsn(INVOKESTATIC, SPECIES_DATA, "getForClass", BMHSPECIES_DATA_GFC_SIG, false);
mv.visitFieldInsn(PUTSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
cw.visitEnd(); cw.visitEnd();
// load class // load class
...@@ -715,7 +707,6 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -715,7 +707,6 @@ import jdk.internal.org.objectweb.asm.Type;
UNSAFE.defineClass(className, classFile, 0, classFile.length, UNSAFE.defineClass(className, classFile, 0, classFile.length,
BoundMethodHandle.class.getClassLoader(), null) BoundMethodHandle.class.getClassLoader(), null)
.asSubclass(BoundMethodHandle.class); .asSubclass(BoundMethodHandle.class);
UNSAFE.ensureClassInitialized(bmhClass);
return bmhClass; return bmhClass;
} }
...@@ -785,7 +776,7 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -785,7 +776,7 @@ import jdk.internal.org.objectweb.asm.Type;
// Auxiliary methods. // Auxiliary methods.
// //
static SpeciesData speciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) { static SpeciesData getSpeciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) {
try { try {
Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA"); Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
return (SpeciesData) F_SPECIES_DATA.get(null); return (SpeciesData) F_SPECIES_DATA.get(null);
...@@ -794,6 +785,16 @@ import jdk.internal.org.objectweb.asm.Type; ...@@ -794,6 +785,16 @@ import jdk.internal.org.objectweb.asm.Type;
} }
} }
static void setSpeciesDataToConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh, SpeciesData speciesData) {
try {
Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
assert F_SPECIES_DATA.getDeclaredAnnotation(Stable.class) != null;
F_SPECIES_DATA.set(null, speciesData);
} catch (ReflectiveOperationException ex) {
throw newInternalError(ex);
}
}
/** /**
* Field names in concrete BMHs adhere to this pattern: * Field names in concrete BMHs adhere to this pattern:
* arg + type + index * arg + type + index
......
...@@ -475,11 +475,6 @@ public class ProtectionDomain { ...@@ -475,11 +475,6 @@ public class ProtectionDomain {
} }
}; };
} }
@Override
public boolean getStaticPermissionsField(ProtectionDomain pd) {
return pd.staticPermissions;
}
}); });
} }
} }
...@@ -545,9 +545,8 @@ public final class HijrahChronology extends AbstractChronology implements Serial ...@@ -545,9 +545,8 @@ public final class HijrahChronology extends AbstractChronology implements Serial
@Override @Override
public boolean isLeapYear(long prolepticYear) { public boolean isLeapYear(long prolepticYear) {
checkCalendarInit(); checkCalendarInit();
int epochMonth = yearToEpochMonth((int) prolepticYear); if (prolepticYear < getMinimumYear() || prolepticYear > getMaximumYear()) {
if (epochMonth < 0 || epochMonth > maxEpochDay) { return false;
throw new DateTimeException("Hijrah date out of range");
} }
int len = getYearLength((int) prolepticYear); int len = getYearLength((int) prolepticYear);
return (len > 354); return (len > 354);
......
...@@ -304,9 +304,28 @@ public abstract class AbstractMap<K,V> implements Map<K,V> { ...@@ -304,9 +304,28 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
* Each of these fields are initialized to contain an instance of the * Each of these fields are initialized to contain an instance of the
* appropriate view the first time this view is requested. The views are * appropriate view the first time this view is requested. The views are
* stateless, so there's no reason to create more than one of each. * stateless, so there's no reason to create more than one of each.
*
* <p>Since there is no synchronization performed while accessing these fields,
* it is expected that java.util.Map view classes using these fields have
* no non-final fields (or any fields at all except for outer-this). Adhering
* to this rule would make the races on these fields benign.
*
* <p>It is also imperative that implementations read the field only once,
* as in:
*
* <pre> {@code
* public Set<K> keySet() {
* Set<K> ks = keySet; // single racy read
* if (ks == null) {
* ks = new KeySet();
* keySet = ks;
* }
* return ks;
* }
*}</pre>
*/ */
transient volatile Set<K> keySet; transient Set<K> keySet;
transient volatile Collection<V> values; transient Collection<V> values;
/** /**
* {@inheritDoc} * {@inheritDoc}
...@@ -325,8 +344,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> { ...@@ -325,8 +344,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
* method will not all return the same set. * method will not all return the same set.
*/ */
public Set<K> keySet() { public Set<K> keySet() {
if (keySet == null) { Set<K> ks = keySet;
keySet = new AbstractSet<K>() { if (ks == null) {
ks = new AbstractSet<K>() {
public Iterator<K> iterator() { public Iterator<K> iterator() {
return new Iterator<K>() { return new Iterator<K>() {
private Iterator<Entry<K,V>> i = entrySet().iterator(); private Iterator<Entry<K,V>> i = entrySet().iterator();
...@@ -361,8 +381,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> { ...@@ -361,8 +381,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
return AbstractMap.this.containsKey(k); return AbstractMap.this.containsKey(k);
} }
}; };
keySet = ks;
} }
return keySet; return ks;
} }
/** /**
...@@ -382,8 +403,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> { ...@@ -382,8 +403,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
* method will not all return the same collection. * method will not all return the same collection.
*/ */
public Collection<V> values() { public Collection<V> values() {
if (values == null) { Collection<V> vals = values;
values = new AbstractCollection<V>() { if (vals == null) {
vals = new AbstractCollection<V>() {
public Iterator<V> iterator() { public Iterator<V> iterator() {
return new Iterator<V>() { return new Iterator<V>() {
private Iterator<Entry<K,V>> i = entrySet().iterator(); private Iterator<Entry<K,V>> i = entrySet().iterator();
...@@ -418,8 +440,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> { ...@@ -418,8 +440,9 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
return AbstractMap.this.containsValue(v); return AbstractMap.this.containsValue(v);
} }
}; };
values = vals;
} }
return values; return vals;
} }
public abstract Set<Entry<K,V>> entrySet(); public abstract Set<Entry<K,V>> entrySet();
......
...@@ -380,10 +380,11 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> ...@@ -380,10 +380,11 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
*/ */
public Set<K> keySet() { public Set<K> keySet() {
Set<K> ks = keySet; Set<K> ks = keySet;
if (ks != null) if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks; return ks;
else
return keySet = new KeySet();
} }
private class KeySet extends AbstractSet<K> { private class KeySet extends AbstractSet<K> {
...@@ -418,10 +419,11 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> ...@@ -418,10 +419,11 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
*/ */
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs = values; Collection<V> vs = values;
if (vs != null) if (vs == null) {
vs = new Values();
values = vs;
}
return vs; return vs;
else
return values = new Values();
} }
private class Values extends AbstractCollection<V> { private class Values extends AbstractCollection<V> {
......
...@@ -902,8 +902,12 @@ public class HashMap<K,V> extends AbstractMap<K,V> ...@@ -902,8 +902,12 @@ public class HashMap<K,V> extends AbstractMap<K,V>
* @return a set view of the keys contained in this map * @return a set view of the keys contained in this map
*/ */
public Set<K> keySet() { public Set<K> keySet() {
Set<K> ks; Set<K> ks = keySet;
return (ks = keySet) == null ? (keySet = new KeySet()) : ks; if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
} }
final class KeySet extends AbstractSet<K> { final class KeySet extends AbstractSet<K> {
...@@ -949,8 +953,12 @@ public class HashMap<K,V> extends AbstractMap<K,V> ...@@ -949,8 +953,12 @@ public class HashMap<K,V> extends AbstractMap<K,V>
* @return a view of the values contained in this map * @return a view of the values contained in this map
*/ */
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs; Collection<V> vs = values;
return (vs = values) == null ? (values = new Values()) : vs; if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
} }
final class Values extends AbstractCollection<V> { final class Values extends AbstractCollection<V> {
......
...@@ -964,10 +964,11 @@ public class IdentityHashMap<K,V> ...@@ -964,10 +964,11 @@ public class IdentityHashMap<K,V>
*/ */
public Set<K> keySet() { public Set<K> keySet() {
Set<K> ks = keySet; Set<K> ks = keySet;
if (ks != null) if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks; return ks;
else
return keySet = new KeySet();
} }
private class KeySet extends AbstractSet<K> { private class KeySet extends AbstractSet<K> {
...@@ -1069,10 +1070,11 @@ public class IdentityHashMap<K,V> ...@@ -1069,10 +1070,11 @@ public class IdentityHashMap<K,V>
*/ */
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs = values; Collection<V> vs = values;
if (vs != null) if (vs == null) {
vs = new Values();
values = vs;
}
return vs; return vs;
else
return values = new Values();
} }
private class Values extends AbstractCollection<V> { private class Values extends AbstractCollection<V> {
......
...@@ -528,8 +528,12 @@ public class LinkedHashMap<K,V> ...@@ -528,8 +528,12 @@ public class LinkedHashMap<K,V>
* @return a set view of the keys contained in this map * @return a set view of the keys contained in this map
*/ */
public Set<K> keySet() { public Set<K> keySet() {
Set<K> ks; Set<K> ks = keySet;
return (ks = keySet) == null ? (keySet = new LinkedKeySet()) : ks; if (ks == null) {
ks = new LinkedKeySet();
keySet = ks;
}
return ks;
} }
final class LinkedKeySet extends AbstractSet<K> { final class LinkedKeySet extends AbstractSet<K> {
...@@ -577,8 +581,12 @@ public class LinkedHashMap<K,V> ...@@ -577,8 +581,12 @@ public class LinkedHashMap<K,V>
* @return a view of the values contained in this map * @return a view of the values contained in this map
*/ */
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs; Collection<V> vs = values;
return (vs = values) == null ? (values = new LinkedValues()) : vs; if (vs == null) {
vs = new LinkedValues();
values = vs;
}
return vs;
} }
final class LinkedValues extends AbstractCollection<V> { final class LinkedValues extends AbstractCollection<V> {
......
...@@ -125,7 +125,7 @@ import java.util.function.LongConsumer; ...@@ -125,7 +125,7 @@ import java.util.function.LongConsumer;
* are encountered. * are encountered.
* *
* @apiNote * @apiNote
* <p>Spliterators, like {@code Iterators}s, are for traversing the elements of * <p>Spliterators, like {@code Iterator}s, are for traversing the elements of
* a source. The {@code Spliterator} API was designed to support efficient * a source. The {@code Spliterator} API was designed to support efficient
* parallel traversal in addition to sequential traversal, by supporting * parallel traversal in addition to sequential traversal, by supporting
* decomposition as well as single-element iteration. In addition, the * decomposition as well as single-element iteration. In addition, the
......
...@@ -855,7 +855,11 @@ public class TreeMap<K,V> ...@@ -855,7 +855,11 @@ public class TreeMap<K,V>
*/ */
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs = values; Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values()); if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
} }
/** /**
......
...@@ -865,7 +865,11 @@ public class WeakHashMap<K,V> ...@@ -865,7 +865,11 @@ public class WeakHashMap<K,V>
*/ */
public Set<K> keySet() { public Set<K> keySet() {
Set<K> ks = keySet; Set<K> ks = keySet;
return (ks != null ? ks : (keySet = new KeySet())); if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
} }
private class KeySet extends AbstractSet<K> { private class KeySet extends AbstractSet<K> {
...@@ -914,7 +918,11 @@ public class WeakHashMap<K,V> ...@@ -914,7 +918,11 @@ public class WeakHashMap<K,V>
*/ */
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs = values; Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values()); if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
} }
private class Values extends AbstractCollection<V> { private class Values extends AbstractCollection<V> {
......
...@@ -34,14 +34,14 @@ ...@@ -34,14 +34,14 @@
*/ */
package java.util.concurrent.atomic; package java.util.concurrent.atomic;
import java.util.function.IntUnaryOperator;
import java.util.function.IntBinaryOperator;
import sun.misc.Unsafe;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException; import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.function.IntBinaryOperator;
import java.util.function.IntUnaryOperator;
import sun.reflect.CallerSensitive; import sun.reflect.CallerSensitive;
import sun.reflect.Reflection; import sun.reflect.Reflection;
...@@ -363,14 +363,19 @@ public abstract class AtomicIntegerFieldUpdater<T> { ...@@ -363,14 +363,19 @@ public abstract class AtomicIntegerFieldUpdater<T> {
} }
/** /**
* Standard hotspot implementation using intrinsics * Standard hotspot implementation using intrinsics.
*/ */
private static class AtomicIntegerFieldUpdaterImpl<T> private static final class AtomicIntegerFieldUpdaterImpl<T>
extends AtomicIntegerFieldUpdater<T> { extends AtomicIntegerFieldUpdater<T> {
private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
private final long offset; private final long offset;
private final Class<T> tclass; /**
* if field is protected, the subclass constructing updater, else
* the same as tclass
*/
private final Class<?> cclass; private final Class<?> cclass;
/** class holding the field */
private final Class<T> tclass;
AtomicIntegerFieldUpdaterImpl(final Class<T> tclass, AtomicIntegerFieldUpdaterImpl(final Class<T> tclass,
final String fieldName, final String fieldName,
...@@ -399,17 +404,15 @@ public abstract class AtomicIntegerFieldUpdater<T> { ...@@ -399,17 +404,15 @@ public abstract class AtomicIntegerFieldUpdater<T> {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
Class<?> fieldt = field.getType(); if (field.getType() != int.class)
if (fieldt != int.class)
throw new IllegalArgumentException("Must be integer type"); throw new IllegalArgumentException("Must be integer type");
if (!Modifier.isVolatile(modifiers)) if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type"); throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) && this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
caller != tclass) ? caller : null;
this.tclass = tclass; this.tclass = tclass;
offset = unsafe.objectFieldOffset(field); this.offset = U.objectFieldOffset(field);
} }
/** /**
...@@ -428,81 +431,87 @@ public abstract class AtomicIntegerFieldUpdater<T> { ...@@ -428,81 +431,87 @@ public abstract class AtomicIntegerFieldUpdater<T> {
return false; return false;
} }
private void fullCheck(T obj) { /**
if (!tclass.isInstance(obj)) * Checks that target argument is instance of cclass. On
* failure, throws cause.
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throwAccessCheckException(obj);
}
/**
* Throws access exception if accessCheck failed due to
* protected access, else ClassCastException.
*/
private final void throwAccessCheckException(T obj) {
if (cclass == tclass)
throw new ClassCastException(); throw new ClassCastException();
if (cclass != null) else
ensureProtectedAccess(obj); throw new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
} }
public boolean compareAndSet(T obj, int expect, int update) { public final boolean compareAndSet(T obj, int expect, int update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.compareAndSwapInt(obj, offset, expect, update); return U.compareAndSwapInt(obj, offset, expect, update);
} }
public boolean weakCompareAndSet(T obj, int expect, int update) { public final boolean weakCompareAndSet(T obj, int expect, int update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.compareAndSwapInt(obj, offset, expect, update); return U.compareAndSwapInt(obj, offset, expect, update);
} }
public void set(T obj, int newValue) { public final void set(T obj, int newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
unsafe.putIntVolatile(obj, offset, newValue); U.putIntVolatile(obj, offset, newValue);
} }
public void lazySet(T obj, int newValue) { public final void lazySet(T obj, int newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
unsafe.putOrderedInt(obj, offset, newValue); U.putOrderedInt(obj, offset, newValue);
} }
public final int get(T obj) { public final int get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.getIntVolatile(obj, offset); return U.getIntVolatile(obj, offset);
} }
public int getAndSet(T obj, int newValue) { public final int getAndSet(T obj, int newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.getAndSetInt(obj, offset, newValue); return U.getAndSetInt(obj, offset, newValue);
} }
public int getAndIncrement(T obj) { public final int getAndAdd(T obj, int delta) {
return getAndAdd(obj, 1); accessCheck(obj);
return U.getAndAddInt(obj, offset, delta);
} }
public int getAndDecrement(T obj) { public final int getAndIncrement(T obj) {
return getAndAdd(obj, -1); return getAndAdd(obj, 1);
} }
public int getAndAdd(T obj, int delta) { public final int getAndDecrement(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return getAndAdd(obj, -1);
return unsafe.getAndAddInt(obj, offset, delta);
} }
public int incrementAndGet(T obj) { public final int incrementAndGet(T obj) {
return getAndAdd(obj, 1) + 1; return getAndAdd(obj, 1) + 1;
} }
public int decrementAndGet(T obj) { public final int decrementAndGet(T obj) {
return getAndAdd(obj, -1) - 1; return getAndAdd(obj, -1) - 1;
} }
public int addAndGet(T obj, int delta) { public final int addAndGet(T obj, int delta) {
return getAndAdd(obj, delta) + delta; return getAndAdd(obj, delta) + delta;
} }
private void ensureProtectedAccess(T obj) {
if (cclass.isInstance(obj)) {
return;
}
throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()
)
);
}
} }
} }
...@@ -34,14 +34,14 @@ ...@@ -34,14 +34,14 @@
*/ */
package java.util.concurrent.atomic; package java.util.concurrent.atomic;
import java.util.function.LongUnaryOperator;
import java.util.function.LongBinaryOperator;
import sun.misc.Unsafe;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException; import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.function.LongBinaryOperator;
import java.util.function.LongUnaryOperator;
import sun.reflect.CallerSensitive; import sun.reflect.CallerSensitive;
import sun.reflect.Reflection; import sun.reflect.Reflection;
...@@ -365,11 +365,16 @@ public abstract class AtomicLongFieldUpdater<T> { ...@@ -365,11 +365,16 @@ public abstract class AtomicLongFieldUpdater<T> {
return next; return next;
} }
private static class CASUpdater<T> extends AtomicLongFieldUpdater<T> { private static final class CASUpdater<T> extends AtomicLongFieldUpdater<T> {
private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
private final long offset; private final long offset;
private final Class<T> tclass; /**
* if field is protected, the subclass constructing updater, else
* the same as tclass
*/
private final Class<?> cclass; private final Class<?> cclass;
/** class holding the field */
private final Class<T> tclass;
CASUpdater(final Class<T> tclass, final String fieldName, CASUpdater(final Class<T> tclass, final String fieldName,
final Class<?> caller) { final Class<?> caller) {
...@@ -397,103 +402,110 @@ public abstract class AtomicLongFieldUpdater<T> { ...@@ -397,103 +402,110 @@ public abstract class AtomicLongFieldUpdater<T> {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
Class<?> fieldt = field.getType(); if (field.getType() != long.class)
if (fieldt != long.class)
throw new IllegalArgumentException("Must be long type"); throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers)) if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type"); throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) && this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
caller != tclass) ? caller : null;
this.tclass = tclass; this.tclass = tclass;
offset = unsafe.objectFieldOffset(field); this.offset = U.objectFieldOffset(field);
}
/**
* Checks that target argument is instance of cclass. On
* failure, throws cause.
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throwAccessCheckException(obj);
} }
private void fullCheck(T obj) { /**
if (!tclass.isInstance(obj)) * Throws access exception if accessCheck failed due to
* protected access, else ClassCastException.
*/
private final void throwAccessCheckException(T obj) {
if (cclass == tclass)
throw new ClassCastException(); throw new ClassCastException();
if (cclass != null) else
ensureProtectedAccess(obj); throw new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
} }
public boolean compareAndSet(T obj, long expect, long update) { public final boolean compareAndSet(T obj, long expect, long update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.compareAndSwapLong(obj, offset, expect, update); return U.compareAndSwapLong(obj, offset, expect, update);
} }
public boolean weakCompareAndSet(T obj, long expect, long update) { public final boolean weakCompareAndSet(T obj, long expect, long update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.compareAndSwapLong(obj, offset, expect, update); return U.compareAndSwapLong(obj, offset, expect, update);
} }
public void set(T obj, long newValue) { public final void set(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
unsafe.putLongVolatile(obj, offset, newValue); U.putLongVolatile(obj, offset, newValue);
} }
public void lazySet(T obj, long newValue) { public final void lazySet(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
unsafe.putOrderedLong(obj, offset, newValue); U.putOrderedLong(obj, offset, newValue);
} }
public long get(T obj) { public final long get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.getLongVolatile(obj, offset); return U.getLongVolatile(obj, offset);
} }
public long getAndSet(T obj, long newValue) { public final long getAndSet(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
return unsafe.getAndSetLong(obj, offset, newValue); return U.getAndSetLong(obj, offset, newValue);
} }
public long getAndIncrement(T obj) { public final long getAndAdd(T obj, long delta) {
return getAndAdd(obj, 1); accessCheck(obj);
return U.getAndAddLong(obj, offset, delta);
} }
public long getAndDecrement(T obj) { public final long getAndIncrement(T obj) {
return getAndAdd(obj, -1); return getAndAdd(obj, 1);
} }
public long getAndAdd(T obj, long delta) { public final long getAndDecrement(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return getAndAdd(obj, -1);
return unsafe.getAndAddLong(obj, offset, delta);
} }
public long incrementAndGet(T obj) { public final long incrementAndGet(T obj) {
return getAndAdd(obj, 1) + 1; return getAndAdd(obj, 1) + 1;
} }
public long decrementAndGet(T obj) { public final long decrementAndGet(T obj) {
return getAndAdd(obj, -1) - 1; return getAndAdd(obj, -1) - 1;
} }
public long addAndGet(T obj, long delta) { public final long addAndGet(T obj, long delta) {
return getAndAdd(obj, delta) + delta; return getAndAdd(obj, delta) + delta;
} }
private void ensureProtectedAccess(T obj) {
if (cclass.isInstance(obj)) {
return;
} }
throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()
)
);
}
}
private static class LockedUpdater<T> extends AtomicLongFieldUpdater<T> { private static final class LockedUpdater<T> extends AtomicLongFieldUpdater<T> {
private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
private final long offset; private final long offset;
private final Class<T> tclass; /**
* if field is protected, the subclass constructing updater, else
* the same as tclass
*/
private final Class<?> cclass; private final Class<?> cclass;
/** class holding the field */
private final Class<T> tclass;
LockedUpdater(final Class<T> tclass, final String fieldName, LockedUpdater(final Class<T> tclass, final String fieldName,
final Class<?> caller) { final Class<?> caller) {
...@@ -521,73 +533,76 @@ public abstract class AtomicLongFieldUpdater<T> { ...@@ -521,73 +533,76 @@ public abstract class AtomicLongFieldUpdater<T> {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
Class<?> fieldt = field.getType(); if (field.getType() != long.class)
if (fieldt != long.class)
throw new IllegalArgumentException("Must be long type"); throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers)) if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type"); throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) && this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
caller != tclass) ? caller : null;
this.tclass = tclass; this.tclass = tclass;
offset = unsafe.objectFieldOffset(field); this.offset = U.objectFieldOffset(field);
} }
private void fullCheck(T obj) { /**
if (!tclass.isInstance(obj)) * Checks that target argument is instance of cclass. On
throw new ClassCastException(); * failure, throws cause.
if (cclass != null) */
ensureProtectedAccess(obj); private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throw accessCheckException(obj);
} }
public boolean compareAndSet(T obj, long expect, long update) { /**
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); * Returns access exception if accessCheck failed due to
* protected access, else ClassCastException.
*/
private final RuntimeException accessCheckException(T obj) {
if (cclass == tclass)
return new ClassCastException();
else
return new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
}
public final boolean compareAndSet(T obj, long expect, long update) {
accessCheck(obj);
synchronized (this) { synchronized (this) {
long v = unsafe.getLong(obj, offset); long v = U.getLong(obj, offset);
if (v != expect) if (v != expect)
return false; return false;
unsafe.putLong(obj, offset, update); U.putLong(obj, offset, update);
return true; return true;
} }
} }
public boolean weakCompareAndSet(T obj, long expect, long update) { public final boolean weakCompareAndSet(T obj, long expect, long update) {
return compareAndSet(obj, expect, update); return compareAndSet(obj, expect, update);
} }
public void set(T obj, long newValue) { public final void set(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
synchronized (this) { synchronized (this) {
unsafe.putLong(obj, offset, newValue); U.putLong(obj, offset, newValue);
} }
} }
public void lazySet(T obj, long newValue) { public final void lazySet(T obj, long newValue) {
set(obj, newValue); set(obj, newValue);
} }
public long get(T obj) { public final long get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); accessCheck(obj);
synchronized (this) { synchronized (this) {
return unsafe.getLong(obj, offset); return U.getLong(obj, offset);
} }
} }
private void ensureProtectedAccess(T obj) {
if (cclass.isInstance(obj)) {
return;
}
throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()
)
);
}
} }
/** /**
...@@ -595,7 +610,7 @@ public abstract class AtomicLongFieldUpdater<T> { ...@@ -595,7 +610,7 @@ public abstract class AtomicLongFieldUpdater<T> {
* classloader's delegation chain. * classloader's delegation chain.
* Equivalent to the inaccessible: first.isAncestor(second). * Equivalent to the inaccessible: first.isAncestor(second).
*/ */
private static boolean isAncestor(ClassLoader first, ClassLoader second) { static boolean isAncestor(ClassLoader first, ClassLoader second) {
ClassLoader acl = first; ClassLoader acl = first;
do { do {
acl = acl.getParent(); acl = acl.getParent();
......
...@@ -34,14 +34,14 @@ ...@@ -34,14 +34,14 @@
*/ */
package java.util.concurrent.atomic; package java.util.concurrent.atomic;
import java.util.function.UnaryOperator;
import java.util.function.BinaryOperator;
import sun.misc.Unsafe;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException; import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;
import sun.reflect.CallerSensitive; import sun.reflect.CallerSensitive;
import sun.reflect.Reflection; import sun.reflect.Reflection;
...@@ -284,11 +284,17 @@ public abstract class AtomicReferenceFieldUpdater<T,V> { ...@@ -284,11 +284,17 @@ public abstract class AtomicReferenceFieldUpdater<T,V> {
private static final class AtomicReferenceFieldUpdaterImpl<T,V> private static final class AtomicReferenceFieldUpdaterImpl<T,V>
extends AtomicReferenceFieldUpdater<T,V> { extends AtomicReferenceFieldUpdater<T,V> {
private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
private final long offset; private final long offset;
/**
* if field is protected, the subclass constructing updater, else
* the same as tclass
*/
private final Class<?> cclass;
/** class holding the field */
private final Class<T> tclass; private final Class<T> tclass;
/** field value type */
private final Class<V> vclass; private final Class<V> vclass;
private final Class<?> cclass;
/* /*
* Internal type checks within all update methods contain * Internal type checks within all update methods contain
...@@ -340,14 +346,10 @@ public abstract class AtomicReferenceFieldUpdater<T,V> { ...@@ -340,14 +346,10 @@ public abstract class AtomicReferenceFieldUpdater<T,V> {
if (!Modifier.isVolatile(modifiers)) if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type"); throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) && this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
caller != tclass) ? caller : null;
this.tclass = tclass; this.tclass = tclass;
if (vclass == Object.class)
this.vclass = null;
else
this.vclass = vclass; this.vclass = vclass;
offset = unsafe.objectFieldOffset(field); this.offset = U.objectFieldOffset(field);
} }
/** /**
...@@ -366,83 +368,78 @@ public abstract class AtomicReferenceFieldUpdater<T,V> { ...@@ -366,83 +368,78 @@ public abstract class AtomicReferenceFieldUpdater<T,V> {
return false; return false;
} }
void targetCheck(T obj) { /**
if (!tclass.isInstance(obj)) * Checks that target argument is instance of cclass. On
* failure, throws cause.
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throwAccessCheckException(obj);
}
/**
* Throws access exception if accessCheck failed due to
* protected access, else ClassCastException.
*/
private final void throwAccessCheckException(T obj) {
if (cclass == tclass)
throw new ClassCastException(); throw new ClassCastException();
if (cclass != null) else
ensureProtectedAccess(obj); throw new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
}
private final void valueCheck(V v) {
if (v != null && !(vclass.isInstance(v)))
throwCCE();
} }
void updateCheck(T obj, V update) { static void throwCCE() {
if (!tclass.isInstance(obj) ||
(update != null && vclass != null && !vclass.isInstance(update)))
throw new ClassCastException(); throw new ClassCastException();
if (cclass != null)
ensureProtectedAccess(obj);
} }
public boolean compareAndSet(T obj, V expect, V update) { public final boolean compareAndSet(T obj, V expect, V update) {
if (obj == null || obj.getClass() != tclass || cclass != null || accessCheck(obj);
(update != null && vclass != null && valueCheck(update);
vclass != update.getClass())) return U.compareAndSwapObject(obj, offset, expect, update);
updateCheck(obj, update);
return unsafe.compareAndSwapObject(obj, offset, expect, update);
} }
public boolean weakCompareAndSet(T obj, V expect, V update) { public final boolean weakCompareAndSet(T obj, V expect, V update) {
// same implementation as strong form for now // same implementation as strong form for now
if (obj == null || obj.getClass() != tclass || cclass != null || accessCheck(obj);
(update != null && vclass != null && valueCheck(update);
vclass != update.getClass())) return U.compareAndSwapObject(obj, offset, expect, update);
updateCheck(obj, update);
return unsafe.compareAndSwapObject(obj, offset, expect, update);
} }
public void set(T obj, V newValue) { public final void set(T obj, V newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null || accessCheck(obj);
(newValue != null && vclass != null && valueCheck(newValue);
vclass != newValue.getClass())) U.putObjectVolatile(obj, offset, newValue);
updateCheck(obj, newValue);
unsafe.putObjectVolatile(obj, offset, newValue);
} }
public void lazySet(T obj, V newValue) { public final void lazySet(T obj, V newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null || accessCheck(obj);
(newValue != null && vclass != null && valueCheck(newValue);
vclass != newValue.getClass())) U.putOrderedObject(obj, offset, newValue);
updateCheck(obj, newValue);
unsafe.putOrderedObject(obj, offset, newValue);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public V get(T obj) { public final V get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) accessCheck(obj);
targetCheck(obj); return (V)U.getObjectVolatile(obj, offset);
return (V)unsafe.getObjectVolatile(obj, offset);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public V getAndSet(T obj, V newValue) { public final V getAndSet(T obj, V newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null || accessCheck(obj);
(newValue != null && vclass != null && valueCheck(newValue);
vclass != newValue.getClass())) return (V)U.getAndSetObject(obj, offset, newValue);
updateCheck(obj, newValue);
return (V)unsafe.getAndSetObject(obj, offset, newValue);
}
private void ensureProtectedAccess(T obj) {
if (cclass.isInstance(obj)) {
return;
}
throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()
)
);
} }
} }
} }
...@@ -2639,7 +2639,7 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable ...@@ -2639,7 +2639,7 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable
return attributes != null ? return attributes != null ?
attributes.asList().stream() attributes.asList().stream()
.map(Attribute::getName) .map(Attribute::getName)
.collect(Collectors.joining("[", ", ", "]")) .collect(Collectors.joining(", ", "[", "]"))
: "[]"; : "[]";
} }
} }
...@@ -37,8 +37,6 @@ import java.security.Security; ...@@ -37,8 +37,6 @@ import java.security.Security;
import java.util.Set; import java.util.Set;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import sun.misc.SharedSecrets;
import sun.misc.JavaSecurityProtectionDomainAccess;
/** /**
* A {@code SubjectDomainCombiner} updates ProtectionDomains * A {@code SubjectDomainCombiner} updates ProtectionDomains
...@@ -67,9 +65,6 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner { ...@@ -67,9 +65,6 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner {
private static final boolean allowCaching = private static final boolean allowCaching =
(useJavaxPolicy && cachePolicy()); (useJavaxPolicy && cachePolicy());
private static final JavaSecurityProtectionDomainAccess pdAccess =
SharedSecrets.getJavaSecurityProtectionDomainAccess();
/** /**
* Associate the provided {@code Subject} with this * Associate the provided {@code Subject} with this
* {@code SubjectDomainCombiner}. * {@code SubjectDomainCombiner}.
...@@ -244,15 +239,10 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner { ...@@ -244,15 +239,10 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner {
subjectPd = cachedPDs.getValue(pd); subjectPd = cachedPDs.getValue(pd);
if (subjectPd == null) { if (subjectPd == null) {
if (pdAccess.getStaticPermissionsField(pd)) {
// Need to keep static ProtectionDomain objects static
subjectPd = pd;
} else {
subjectPd = new ProtectionDomain(pd.getCodeSource(), subjectPd = new ProtectionDomain(pd.getCodeSource(),
pd.getPermissions(), pd.getPermissions(),
pd.getClassLoader(), pd.getClassLoader(),
principals); principals);
}
cachedPDs.putValue(pd, subjectPd); cachedPDs.putValue(pd, subjectPd);
} else { } else {
allNew = false; allNew = false;
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
* under the License. * under the License.
*/ */
/* /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
*/ */
/* /*
* $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ * $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
...@@ -34,10 +34,12 @@ import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; ...@@ -34,10 +34,12 @@ import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec;
import java.io.IOException; import java.io.IOException;
import java.security.*; import java.security.*;
import java.security.interfaces.DSAKey;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA; import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.jcp.xml.dsig.internal.SignerOutputStream; import org.jcp.xml.dsig.internal.SignerOutputStream;
/** /**
...@@ -68,6 +70,8 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { ...@@ -68,6 +70,8 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384";
static final String ECDSA_SHA512 = static final String ECDSA_SHA512 =
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
static final String DSA_SHA256 =
"http://www.w3.org/2009/xmldsig11#dsa-sha256";
/** /**
* Creates a <code>DOMSignatureMethod</code>. * Creates a <code>DOMSignatureMethod</code>.
...@@ -119,6 +123,8 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { ...@@ -119,6 +123,8 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
return new SHA512withRSA(smElem); return new SHA512withRSA(smElem);
} else if (alg.equals(SignatureMethod.DSA_SHA1)) { } else if (alg.equals(SignatureMethod.DSA_SHA1)) {
return new SHA1withDSA(smElem); return new SHA1withDSA(smElem);
} else if (alg.equals(DSA_SHA256)) {
return new SHA256withDSA(smElem);
} else if (alg.equals(ECDSA_SHA1)) { } else if (alg.equals(ECDSA_SHA1)) {
return new SHA1withECDSA(smElem); return new SHA1withECDSA(smElem);
} else if (alg.equals(ECDSA_SHA256)) { } else if (alg.equals(ECDSA_SHA256)) {
...@@ -178,7 +184,9 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { ...@@ -178,7 +184,9 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
try { try {
Type type = getAlgorithmType(); Type type = getAlgorithmType();
if (type == Type.DSA) { if (type == Type.DSA) {
return signature.verify(convertXMLDSIGtoASN1(sig)); int size = ((DSAKey)key).getParams().getQ().bitLength();
return signature.verify(JavaUtils.convertDsaXMLDSIGtoASN1(sig,
size/8));
} else if (type == Type.ECDSA) { } else if (type == Type.ECDSA) {
return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig)); return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig));
} else { } else {
...@@ -222,7 +230,9 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { ...@@ -222,7 +230,9 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
try { try {
Type type = getAlgorithmType(); Type type = getAlgorithmType();
if (type == Type.DSA) { if (type == Type.DSA) {
return convertASN1toXMLDSIG(signature.sign()); int size = ((DSAKey)key).getParams().getQ().bitLength();
return JavaUtils.convertDsaASN1toXMLDSIG(signature.sign(),
size/8);
} else if (type == Type.ECDSA) { } else if (type == Type.ECDSA) {
return SignatureECDSA.convertASN1toXMLDSIG(signature.sign()); return SignatureECDSA.convertASN1toXMLDSIG(signature.sign());
} else { } else {
...@@ -235,101 +245,6 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { ...@@ -235,101 +245,6 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
} }
} }
/**
* Converts an ASN.1 DSA value to a XML Signature DSA Value.
*
* The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param asn1Bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
throws IOException
{
byte rLength = asn1Bytes[3];
int i;
for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
byte sLength = asn1Bytes[5 + rLength];
int j;
for (j = sLength;
(j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
|| (asn1Bytes[2] != 2) || (i > 20)
|| (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
throw new IOException("Invalid ASN.1 format of DSA signature");
} else {
byte xmldsigBytes[] = new byte[40];
System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i);
System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes,
40 - j, j);
return xmldsigBytes;
}
}
/**
* Converts a XML Signature DSA Value to an ASN.1 DSA value.
*
* The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param xmldsigBytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
throws IOException
{
if (xmldsigBytes.length != 40) {
throw new IOException("Invalid XMLDSIG format of DSA signature");
}
int i;
for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--);
int j = i;
if (xmldsigBytes[20 - i] < 0) {
j += 1;
}
int k;
for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--);
int l = k;
if (xmldsigBytes[40 - k] < 0) {
l += 1;
}
byte asn1Bytes[] = new byte[6 + j + l];
asn1Bytes[0] = 48;
asn1Bytes[1] = (byte)(4 + j + l);
asn1Bytes[2] = 2;
asn1Bytes[3] = (byte)j;
System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
asn1Bytes[4 + j] = 2;
asn1Bytes[5 + j] = (byte) l;
System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k);
return asn1Bytes;
}
static final class SHA1withRSA extends DOMSignatureMethod { static final class SHA1withRSA extends DOMSignatureMethod {
SHA1withRSA(AlgorithmParameterSpec params) SHA1withRSA(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException { throws InvalidAlgorithmParameterException {
...@@ -425,6 +340,25 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { ...@@ -425,6 +340,25 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
} }
} }
static final class SHA256withDSA extends DOMSignatureMethod {
SHA256withDSA(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
super(params);
}
SHA256withDSA(Element dmElem) throws MarshalException {
super(dmElem);
}
public String getAlgorithm() {
return DSA_SHA256;
}
String getJCAAlgorithm() {
return "SHA256withDSA";
}
Type getAlgorithmType() {
return Type.DSA;
}
}
static final class SHA1withECDSA extends DOMSignatureMethod { static final class SHA1withECDSA extends DOMSignatureMethod {
SHA1withECDSA(AlgorithmParameterSpec params) SHA1withECDSA(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException { throws InvalidAlgorithmParameterException {
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
* under the License. * under the License.
*/ */
/* /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
*/ */
/* /*
* $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
...@@ -239,6 +239,8 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { ...@@ -239,6 +239,8 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory {
return new DOMSignatureMethod.SHA512withRSA(params); return new DOMSignatureMethod.SHA512withRSA(params);
} else if (algorithm.equals(SignatureMethod.DSA_SHA1)) { } else if (algorithm.equals(SignatureMethod.DSA_SHA1)) {
return new DOMSignatureMethod.SHA1withDSA(params); return new DOMSignatureMethod.SHA1withDSA(params);
} else if (algorithm.equals(DOMSignatureMethod.DSA_SHA256)) {
return new DOMSignatureMethod.SHA256withDSA(params);
} else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) { } else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) {
return new DOMHMACSignatureMethod.SHA1(params); return new DOMHMACSignatureMethod.SHA1(params);
} else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
......
...@@ -453,6 +453,17 @@ public class FileFontStrike extends PhysicalStrike { ...@@ -453,6 +453,17 @@ public class FileFontStrike extends PhysicalStrike {
/* Only look in the cache */ /* Only look in the cache */
long getCachedGlyphPtr(int glyphCode) { long getCachedGlyphPtr(int glyphCode) {
try {
return getCachedGlyphPtrInternal(glyphCode);
} catch (Exception e) {
NullFontScaler nullScaler =
(NullFontScaler)FontScaler.getNullScaler();
long nullSC = NullFontScaler.getNullScalerContext();
return nullScaler.getGlyphImage(nullSC, glyphCode);
}
}
private long getCachedGlyphPtrInternal(int glyphCode) {
switch (glyphCacheFormat) { switch (glyphCacheFormat) {
case INTARRAY: case INTARRAY:
return intGlyphImages[glyphCode] & INTMASK; return intGlyphImages[glyphCode] & INTMASK;
...@@ -480,6 +491,27 @@ public class FileFontStrike extends PhysicalStrike { ...@@ -480,6 +491,27 @@ public class FileFontStrike extends PhysicalStrike {
} }
private synchronized long setCachedGlyphPtr(int glyphCode, long glyphPtr) { private synchronized long setCachedGlyphPtr(int glyphCode, long glyphPtr) {
try {
return setCachedGlyphPtrInternal(glyphCode, glyphPtr);
} catch (Exception e) {
switch (glyphCacheFormat) {
case INTARRAY:
case SEGINTARRAY:
StrikeCache.freeIntPointer((int)glyphPtr);
break;
case LONGARRAY:
case SEGLONGARRAY:
StrikeCache.freeLongPointer(glyphPtr);
break;
}
NullFontScaler nullScaler =
(NullFontScaler)FontScaler.getNullScaler();
long nullSC = NullFontScaler.getNullScalerContext();
return nullScaler.getGlyphImage(nullSC, glyphCode);
}
}
private long setCachedGlyphPtrInternal(int glyphCode, long glyphPtr) {
switch (glyphCacheFormat) { switch (glyphCacheFormat) {
case INTARRAY: case INTARRAY:
if (intGlyphImages[glyphCode] == 0) { if (intGlyphImages[glyphCode] == 0) {
......
...@@ -59,7 +59,11 @@ public class TrueTypeGlyphMapper extends CharToGlyphMapper { ...@@ -59,7 +59,11 @@ public class TrueTypeGlyphMapper extends CharToGlyphMapper {
} }
missingGlyph = 0; /* standard for TrueType fonts */ missingGlyph = 0; /* standard for TrueType fonts */
ByteBuffer buffer = font.getTableBuffer(TrueTypeFont.maxpTag); ByteBuffer buffer = font.getTableBuffer(TrueTypeFont.maxpTag);
if (buffer != null && buffer.capacity() >= 6) {
numGlyphs = buffer.getChar(4); // offset 4 bytes in MAXP table. numGlyphs = buffer.getChar(4); // offset 4 bytes in MAXP table.
} else {
handleBadCMAP();
}
if (FontUtilities.isSolaris && isJAlocale && font.supportsJA()) { if (FontUtilities.isSolaris && isJAlocale && font.supportsJA()) {
needsJAremapping = true; needsJAremapping = true;
if (FontUtilities.isSolaris8 && if (FontUtilities.isSolaris8 &&
......
...@@ -36,9 +36,4 @@ public interface JavaSecurityProtectionDomainAccess { ...@@ -36,9 +36,4 @@ public interface JavaSecurityProtectionDomainAccess {
* Returns the ProtectionDomainCache. * Returns the ProtectionDomainCache.
*/ */
ProtectionDomainCache getProtectionDomainCache(); ProtectionDomainCache getProtectionDomainCache();
/**
* Returns the staticPermissions field of the specified object
*/
boolean getStaticPermissionsField(ProtectionDomain pd);
} }
...@@ -291,15 +291,24 @@ public class Version { ...@@ -291,15 +291,24 @@ public class Version {
jvm_minor_version = Character.digit(cs.charAt(2), 10); jvm_minor_version = Character.digit(cs.charAt(2), 10);
jvm_micro_version = Character.digit(cs.charAt(4), 10); jvm_micro_version = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length()); cs = cs.subSequence(5, cs.length());
if (cs.charAt(0) == '_' && cs.length() >= 3 && if (cs.charAt(0) == '_' && cs.length() >= 3) {
Character.isDigit(cs.charAt(1)) && int nextChar = 0;
Character.isDigit(cs.charAt(2))) { if (Character.isDigit(cs.charAt(1)) &&
int nextChar = 3; Character.isDigit(cs.charAt(2)) &&
Character.isDigit(cs.charAt(3)))
{
nextChar = 4;
} else if (Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2)))
{
nextChar = 3;
}
try { try {
String uu = cs.subSequence(1, 3).toString(); String uu = cs.subSequence(1, nextChar).toString();
jvm_update_version = Integer.valueOf(uu).intValue(); jvm_update_version = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) { if (cs.length() >= nextChar + 1) {
char c = cs.charAt(3); char c = cs.charAt(nextChar);
if (c >= 'a' && c <= 'z') { if (c >= 'a' && c <= 'z') {
jvm_special_version = Character.toString(c); jvm_special_version = Character.toString(c);
nextChar++; nextChar++;
......
...@@ -290,8 +290,9 @@ public class PKCS10 { ...@@ -290,8 +290,9 @@ public class PKCS10 {
throw new SignatureException("Cert request was not signed"); throw new SignatureException("Cert request was not signed");
byte[] CRLF = new byte[] {'\r', '\n'};
out.println("-----BEGIN NEW CERTIFICATE REQUEST-----"); out.println("-----BEGIN NEW CERTIFICATE REQUEST-----");
out.println(Base64.getMimeEncoder().encodeToString(encoded)); out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(encoded));
out.println("-----END NEW CERTIFICATE REQUEST-----"); out.println("-----END NEW CERTIFICATE REQUEST-----");
} }
......
...@@ -28,6 +28,8 @@ package sun.security.provider; ...@@ -28,6 +28,8 @@ package sun.security.provider;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import java.security.cert.*; import java.security.cert.*;
import sun.security.util.Pem;
import sun.security.x509.X509CertImpl; import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CRLImpl; import sun.security.x509.X509CRLImpl;
import sun.security.pkcs.PKCS7; import sun.security.pkcs.PKCS7;
...@@ -633,7 +635,7 @@ public class X509Factory extends CertificateFactorySpi { ...@@ -633,7 +635,7 @@ public class X509Factory extends CertificateFactorySpi {
checkHeaderFooter(header.toString(), footer.toString()); checkHeaderFooter(header.toString(), footer.toString());
return Base64.getMimeDecoder().decode(new String(data, 0, pos)); return Pem.decode(new String(data, 0, pos));
} }
} }
......
...@@ -246,7 +246,7 @@ final class HandshakeHash { ...@@ -246,7 +246,7 @@ final class HandshakeHash {
try { try {
return cloneDigest(finMD).digest(); return cloneDigest(finMD).digest();
} catch (Exception e) { } catch (Exception e) {
throw new Error("BAD"); throw new Error("Error during hash calculation", e);
} }
} }
} }
......
...@@ -1259,8 +1259,8 @@ final class ServerHandshaker extends Handshaker { ...@@ -1259,8 +1259,8 @@ final class ServerHandshaker extends Handshaker {
} }
} }
// need EC cert signed using EC // need EC cert
if (setupPrivateKeyAndChain("EC_EC") == false) { if (setupPrivateKeyAndChain("EC") == false) {
return false; return false;
} }
if (setupEphemeralECDHKeys() == false) { if (setupEphemeralECDHKeys() == false) {
...@@ -1268,15 +1268,15 @@ final class ServerHandshaker extends Handshaker { ...@@ -1268,15 +1268,15 @@ final class ServerHandshaker extends Handshaker {
} }
break; break;
case K_ECDH_RSA: case K_ECDH_RSA:
// need EC cert signed using RSA // need EC cert
if (setupPrivateKeyAndChain("EC_RSA") == false) { if (setupPrivateKeyAndChain("EC") == false) {
return false; return false;
} }
setupStaticECDHKeys(); setupStaticECDHKeys();
break; break;
case K_ECDH_ECDSA: case K_ECDH_ECDSA:
// need EC cert signed using EC // need EC cert
if (setupPrivateKeyAndChain("EC_EC") == false) { if (setupPrivateKeyAndChain("EC") == false) {
return false; return false;
} }
setupStaticECDHKeys(); setupStaticECDHKeys();
......
/* /*
* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -28,6 +28,7 @@ package sun.security.ssl; ...@@ -28,6 +28,7 @@ package sun.security.ssl;
import java.security.AlgorithmConstraints; import java.security.AlgorithmConstraints;
import java.security.CryptoPrimitive; import java.security.CryptoPrimitive;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.Security;
import java.util.Set; import java.util.Set;
import java.util.HashSet; import java.util.HashSet;
...@@ -152,7 +153,6 @@ final class SignatureAndHashAlgorithm { ...@@ -152,7 +153,6 @@ final class SignatureAndHashAlgorithm {
getSupportedAlgorithms(AlgorithmConstraints constraints) { getSupportedAlgorithms(AlgorithmConstraints constraints) {
Collection<SignatureAndHashAlgorithm> supported = new ArrayList<>(); Collection<SignatureAndHashAlgorithm> supported = new ArrayList<>();
synchronized (priorityMap) {
for (SignatureAndHashAlgorithm sigAlg : priorityMap.values()) { for (SignatureAndHashAlgorithm sigAlg : priorityMap.values()) {
if (sigAlg.priority <= SUPPORTED_ALG_PRIORITY_MAX_NUM && if (sigAlg.priority <= SUPPORTED_ALG_PRIORITY_MAX_NUM &&
constraints.permits(SIGNATURE_PRIMITIVE_SET, constraints.permits(SIGNATURE_PRIMITIVE_SET,
...@@ -160,7 +160,6 @@ final class SignatureAndHashAlgorithm { ...@@ -160,7 +160,6 @@ final class SignatureAndHashAlgorithm {
supported.add(sigAlg); supported.add(sigAlg);
} }
} }
}
return supported; return supported;
} }
...@@ -412,10 +411,14 @@ final class SignatureAndHashAlgorithm { ...@@ -412,10 +411,14 @@ final class SignatureAndHashAlgorithm {
"SHA1withRSA", --p); "SHA1withRSA", --p);
supports(HashAlgorithm.SHA1, SignatureAlgorithm.ECDSA, supports(HashAlgorithm.SHA1, SignatureAlgorithm.ECDSA,
"SHA1withECDSA", --p); "SHA1withECDSA", --p);
if (Security.getProvider("SunMSCAPI") == null) {
supports(HashAlgorithm.SHA224, SignatureAlgorithm.RSA, supports(HashAlgorithm.SHA224, SignatureAlgorithm.RSA,
"SHA224withRSA", --p); "SHA224withRSA", --p);
supports(HashAlgorithm.SHA224, SignatureAlgorithm.ECDSA, supports(HashAlgorithm.SHA224, SignatureAlgorithm.ECDSA,
"SHA224withECDSA", --p); "SHA224withECDSA", --p);
}
supports(HashAlgorithm.SHA256, SignatureAlgorithm.RSA, supports(HashAlgorithm.SHA256, SignatureAlgorithm.RSA,
"SHA256withRSA", --p); "SHA256withRSA", --p);
supports(HashAlgorithm.SHA256, SignatureAlgorithm.ECDSA, supports(HashAlgorithm.SHA256, SignatureAlgorithm.ECDSA,
......
...@@ -79,6 +79,7 @@ import sun.security.pkcs.PKCS9Attribute; ...@@ -79,6 +79,7 @@ import sun.security.pkcs.PKCS9Attribute;
import sun.security.tools.KeyStoreUtil; import sun.security.tools.KeyStoreUtil;
import sun.security.tools.PathList; import sun.security.tools.PathList;
import sun.security.util.DerValue; import sun.security.util.DerValue;
import sun.security.util.Pem;
import sun.security.x509.*; import sun.security.x509.*;
import static java.security.KeyStore.*; import static java.security.KeyStore.*;
...@@ -99,6 +100,8 @@ import static sun.security.tools.keytool.Main.Option.*; ...@@ -99,6 +100,8 @@ import static sun.security.tools.keytool.Main.Option.*;
*/ */
public final class Main { public final class Main {
private static final byte[] CRLF = new byte[] {'\r', '\n'};
private boolean debug = false; private boolean debug = false;
private Command command = null; private Command command = null;
private String sigAlgName = null; private String sigAlgName = null;
...@@ -1205,7 +1208,7 @@ public final class Main { ...@@ -1205,7 +1208,7 @@ public final class Main {
sb.append(s); sb.append(s);
} }
} }
byte[] rawReq = Base64.getMimeDecoder().decode(new String(sb)); byte[] rawReq = Pem.decode(new String(sb));
PKCS10 req = new PKCS10(rawReq); PKCS10 req = new PKCS10(rawReq);
info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo())); info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo()));
...@@ -1282,7 +1285,7 @@ public final class Main { ...@@ -1282,7 +1285,7 @@ public final class Main {
crl.sign(privateKey, sigAlgName); crl.sign(privateKey, sigAlgName);
if (rfc) { if (rfc) {
out.println("-----BEGIN X509 CRL-----"); out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder().encodeToString(crl.getEncodedInternal())); out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(crl.getEncodedInternal()));
out.println("-----END X509 CRL-----"); out.println("-----END X509 CRL-----");
} else { } else {
out.write(crl.getEncodedInternal()); out.write(crl.getEncodedInternal());
...@@ -2251,7 +2254,7 @@ public final class Main { ...@@ -2251,7 +2254,7 @@ public final class Main {
if (rfc) { if (rfc) {
X509CRL xcrl = (X509CRL)crl; X509CRL xcrl = (X509CRL)crl;
out.println("-----BEGIN X509 CRL-----"); out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder().encodeToString(xcrl.getEncoded())); out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded()));
out.println("-----END X509 CRL-----"); out.println("-----END X509 CRL-----");
} else { } else {
out.println(crl.toString()); out.println(crl.toString());
...@@ -2278,7 +2281,7 @@ public final class Main { ...@@ -2278,7 +2281,7 @@ public final class Main {
sb.append(s); sb.append(s);
} }
} }
PKCS10 req = new PKCS10(Base64.getMimeDecoder().decode(new String(sb))); PKCS10 req = new PKCS10(Pem.decode(new String(sb)));
PublicKey pkey = req.getSubjectPublicKeyInfo(); PublicKey pkey = req.getSubjectPublicKeyInfo();
out.printf(rb.getString("PKCS.10.Certificate.Request.Version.1.0.Subject.s.Public.Key.s.format.s.key."), out.printf(rb.getString("PKCS.10.Certificate.Request.Version.1.0.Subject.s.Public.Key.s.format.s.key."),
...@@ -3059,7 +3062,7 @@ public final class Main { ...@@ -3059,7 +3062,7 @@ public final class Main {
{ {
if (rfc) { if (rfc) {
out.println(X509Factory.BEGIN_CERT); out.println(X509Factory.BEGIN_CERT);
out.println(Base64.getMimeEncoder().encodeToString(cert.getEncoded())); out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(cert.getEncoded()));
out.println(X509Factory.END_CERT); out.println(X509Factory.END_CERT);
} else { } else {
out.write(cert.getEncoded()); // binary out.write(cert.getEncoded()); // binary
......
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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 WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.util;
import java.io.IOException;
import java.util.Base64;
/**
* The Length interface defines the length of an object
*/
public class Pem {
/**
* Decodes a PEM-encoded block.
*
* @param input the input string, according to RFC 1421, can only contain
* characters in the base-64 alphabet and whitespaces.
* @return the decoded bytes
* @throws java.io.IOException if input is invalid
*/
public static byte[] decode(String input) throws IOException {
byte[] src = input.replaceAll("\\s+", "").getBytes();
try {
return Base64.getDecoder().decode(src);
} catch (IllegalArgumentException e) {
throw new IOException(e);
}
}
}
...@@ -271,7 +271,7 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { ...@@ -271,7 +271,7 @@ public class X509CertImpl extends X509Certificate implements DerEncoder {
der = new DerValue(decstream.toByteArray()); der = new DerValue(decstream.toByteArray());
break; break;
} else { } else {
decstream.write(Base64.getMimeDecoder().decode(line)); decstream.write(Pem.decode(line));
} }
} }
} catch (IOException ioe2) { } catch (IOException ioe2) {
......
/* /*
* Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -53,9 +53,7 @@ import java.util.*; ...@@ -53,9 +53,7 @@ import java.util.*;
*/ */
public abstract class CachedPainter { public abstract class CachedPainter {
// CacheMap maps from class to ImageCache. // CacheMap maps from class to ImageCache.
private static final Map<Object,ImageCache> cacheMap = private static final Map<Object,ImageCache> cacheMap = new HashMap<>();
new HashMap<Object,ImageCache>();
private static ImageCache getCache(Object key) { private static ImageCache getCache(Object key) {
synchronized(CachedPainter.class) { synchronized(CachedPainter.class) {
...@@ -96,22 +94,10 @@ public abstract class CachedPainter { ...@@ -96,22 +94,10 @@ public abstract class CachedPainter {
if (w <= 0 || h <= 0) { if (w <= 0 || h <= 0) {
return; return;
} }
if (c != null) { synchronized (CachedPainter.class) {
synchronized(c.getTreeLock()) {
synchronized(CachedPainter.class) {
// If c is non-null, synchronize on the tree lock.
// This is necessary because asking for the
// GraphicsConfiguration will grab a tree lock.
paint0(c, g, x, y, w, h, args);
}
}
}
else {
synchronized(CachedPainter.class) {
paint0(c, g, x, y, w, h, args); paint0(c, g, x, y, w, h, args);
} }
} }
}
private void paint0(Component c, Graphics g, int x, private void paint0(Component c, Graphics g, int x,
int y, int w, int h, Object... args) { int y, int w, int h, Object... args) {
......
...@@ -529,6 +529,11 @@ class_get_methodID(JNIEnv *env, ClassIndex index, MethodIndex mnum) ...@@ -529,6 +529,11 @@ class_get_methodID(JNIEnv *env, ClassIndex index, MethodIndex mnum)
info = get_info(index); info = get_info(index);
if (mnum >= info->method_count) { if (mnum >= info->method_count) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
HPROF_ERROR(JNI_TRUE,
"Could not find the java/lang/IllegalArgumentException class");
}
(*env)->ThrowNew(env, newExcCls, "Illegal mnum"); (*env)->ThrowNew(env, newExcCls, "Illegal mnum");
return NULL; return NULL;
...@@ -542,6 +547,11 @@ class_get_methodID(JNIEnv *env, ClassIndex index, MethodIndex mnum) ...@@ -542,6 +547,11 @@ class_get_methodID(JNIEnv *env, ClassIndex index, MethodIndex mnum)
name = (char *)string_get(info->method[mnum].name_index); name = (char *)string_get(info->method[mnum].name_index);
if (name==NULL) { if (name==NULL) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
HPROF_ERROR(JNI_TRUE,
"Could not find the java/lang/IllegalArgumentException class");
}
(*env)->ThrowNew(env, newExcCls, "Name not found"); (*env)->ThrowNew(env, newExcCls, "Name not found");
return NULL; return NULL;
......
...@@ -197,6 +197,11 @@ event_call(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum) ...@@ -197,6 +197,11 @@ event_call(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum)
HPROF_ASSERT(thread!=NULL); HPROF_ASSERT(thread!=NULL);
if (cnum == 0 || cnum == gdata->tracker_cnum) { if (cnum == 0 || cnum == gdata->tracker_cnum) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
HPROF_ERROR(JNI_TRUE,
"Could not find the java/lang/IllegalArgumentException class");
}
(*env)->ThrowNew(env, newExcCls, "Illegal cnum."); (*env)->ThrowNew(env, newExcCls, "Illegal cnum.");
return; return;
...@@ -258,6 +263,11 @@ event_return(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum) ...@@ -258,6 +263,11 @@ event_return(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum)
if (cnum == 0 || cnum == gdata->tracker_cnum) { if (cnum == 0 || cnum == gdata->tracker_cnum) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
HPROF_ERROR(JNI_TRUE,
"Could not find the java/lang/IllegalArgumentException class");
}
(*env)->ThrowNew(env, newExcCls, "Illegal cnum."); (*env)->ThrowNew(env, newExcCls, "Illegal cnum.");
return; return;
......
...@@ -374,7 +374,10 @@ newWeakGlobalReference(JNIEnv *env, jobject object) ...@@ -374,7 +374,10 @@ newWeakGlobalReference(JNIEnv *env, jobject object)
HPROF_ASSERT(env!=NULL); HPROF_ASSERT(env!=NULL);
HPROF_ASSERT(object!=NULL); HPROF_ASSERT(object!=NULL);
CHECK_EXCEPTIONS (env) {
gref = JNI_FUNC_PTR(env,NewWeakGlobalRef)(env, object); gref = JNI_FUNC_PTR(env,NewWeakGlobalRef)(env, object);
} END_CHECK_EXCEPTIONS;
HPROF_ASSERT(gref!=NULL); HPROF_ASSERT(gref!=NULL);
return gref; return gref;
} }
......
...@@ -52,7 +52,8 @@ JDK_GetVersionInfo0(jdk_version_info* info, size_t info_size) { ...@@ -52,7 +52,8 @@ JDK_GetVersionInfo0(jdk_version_info* info, size_t info_size) {
const char* jdk_update_string = JDK_UPDATE_VERSION; const char* jdk_update_string = JDK_UPDATE_VERSION;
unsigned int jdk_update_version = 0; unsigned int jdk_update_version = 0;
char update_ver[3]; int len_update_ver = 0;
char update_ver[5];
char jdk_special_version = '\0'; char jdk_special_version = '\0';
/* If the JDK_BUILD_NUMBER is of format bXX and XX is an integer /* If the JDK_BUILD_NUMBER is of format bXX and XX is an integer
...@@ -78,16 +79,17 @@ JDK_GetVersionInfo0(jdk_version_info* info, size_t info_size) { ...@@ -78,16 +79,17 @@ JDK_GetVersionInfo0(jdk_version_info* info, size_t info_size) {
assert(jdk_build_number >= 0 && jdk_build_number <= 255); assert(jdk_build_number >= 0 && jdk_build_number <= 255);
if (strlen(jdk_update_string) == 2 || strlen(jdk_update_string) == 3) { len_update_ver = strlen(jdk_update_string);
if (isdigit(jdk_update_string[0]) && isdigit(jdk_update_string[1])) { if (len_update_ver >= 2 && len_update_ver <= 4) {
update_ver[0] = jdk_update_string[0]; int update_digits = len_update_ver;
update_ver[1] = jdk_update_string[1];
update_ver[2] = '\0'; if (!isdigit(jdk_update_string[len_update_ver - 1])) {
jdk_update_version = (unsigned int) atoi(update_ver); jdk_special_version = jdk_update_string[len_update_ver -1];
if (strlen(jdk_update_string) == 3) { update_digits = len_update_ver - 1;
jdk_special_version = jdk_update_string[2];
}
} }
strncpy(update_ver, jdk_update_string, update_digits);
update_ver[update_digits] = '\0';
jdk_update_version = (unsigned int) atoi(update_ver);
} }
memset(info, 0, info_size); memset(info, 0, info_size);
......
...@@ -1610,6 +1610,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader ...@@ -1610,6 +1610,7 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader
int ret; int ret;
int h_samp0, h_samp1, h_samp2; int h_samp0, h_samp1, h_samp2;
int v_samp0, v_samp1, v_samp2; int v_samp0, v_samp1, v_samp2;
int cid0, cid1, cid2;
jboolean retval = JNI_FALSE; jboolean retval = JNI_FALSE;
imageIODataPtr data = (imageIODataPtr)jlong_to_ptr(ptr); imageIODataPtr data = (imageIODataPtr)jlong_to_ptr(ptr);
j_decompress_ptr cinfo; j_decompress_ptr cinfo;
...@@ -1711,17 +1712,15 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader ...@@ -1711,17 +1712,15 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader
} }
} else if (!cinfo->saw_JFIF_marker && !IS_EXIF(cinfo)) { } else if (!cinfo->saw_JFIF_marker && !IS_EXIF(cinfo)) {
/* /*
* IJG assumes all unidentified 3-channels are YCbCr. * In the absence of certain markers, IJG has interpreted
* We assume that only if the second two channels are * component id's of [1,2,3] as meaning YCbCr.We follow that
* subsampled (either horizontally or vertically). If not, * interpretation, which is additionally described in the Image
* we assume RGB. * I/O JPEG metadata spec.If that condition is not met here the
* * next step will be to examine the subsampling factors, if
* 4776576: Some digital cameras output YCbCr JPEG images * there is any difference in subsampling factors we also assume
* that do not contain a JFIF APP0 marker but are only * YCbCr, only if both horizontal and vertical subsampling
* vertically subsampled (no horizontal subsampling). * is same we assume JPEG color space as RGB.
* We should only assume this is RGB data if the subsampling * This is also described in the Image I/O JPEG metadata spec.
* factors for the second two channels are the same as the
* first (check both horizontal and vertical factors).
*/ */
h_samp0 = cinfo->comp_info[0].h_samp_factor; h_samp0 = cinfo->comp_info[0].h_samp_factor;
h_samp1 = cinfo->comp_info[1].h_samp_factor; h_samp1 = cinfo->comp_info[1].h_samp_factor;
...@@ -1731,8 +1730,13 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader ...@@ -1731,8 +1730,13 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_readImageHeader
v_samp1 = cinfo->comp_info[1].v_samp_factor; v_samp1 = cinfo->comp_info[1].v_samp_factor;
v_samp2 = cinfo->comp_info[2].v_samp_factor; v_samp2 = cinfo->comp_info[2].v_samp_factor;
if ((h_samp1 == h_samp0) && (h_samp2 == h_samp0) && cid0 = cinfo->comp_info[0].component_id;
(v_samp1 == v_samp0) && (v_samp2 == v_samp0)) cid1 = cinfo->comp_info[1].component_id;
cid2 = cinfo->comp_info[2].component_id;
if ((!(cid0 == 1 && cid1 == 2 && cid2 == 3)) &&
((h_samp1 == h_samp0) && (h_samp2 == h_samp0) &&
(v_samp1 == v_samp0) && (v_samp2 == v_samp0)))
{ {
cinfo->jpeg_color_space = JCS_RGB; cinfo->jpeg_color_space = JCS_RGB;
/* output is already RGB, so it stays the same */ /* output is already RGB, so it stays the same */
......
...@@ -52,7 +52,7 @@ Java_sun_misc_URLClassPath_knownToNotExist0(JNIEnv *env, jclass cls, jobject loa ...@@ -52,7 +52,7 @@ Java_sun_misc_URLClassPath_knownToNotExist0(JNIEnv *env, jclass cls, jobject loa
clname = getUTF(env, classname, buf, sizeof(buf)); clname = getUTF(env, classname, buf, sizeof(buf));
if (clname == NULL) { if (clname == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL); // getUTF() throws OOME before returning NULL, no need to throw OOME here
return result; return result;
} }
VerifyFixClassname(clname); VerifyFixClassname(clname);
...@@ -94,7 +94,7 @@ Java_sun_misc_URLClassPath_getLookupCacheForClassLoader(JNIEnv *env, jclass cls, ...@@ -94,7 +94,7 @@ Java_sun_misc_URLClassPath_getLookupCacheForClassLoader(JNIEnv *env, jclass cls,
resname = getUTF(env, resource_name, buf, sizeof(buf)); resname = getUTF(env, resource_name, buf, sizeof(buf));
if (resname == NULL) { if (resname == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL); // getUTF() throws OOME before returning NULL, no need to throw OOME here
return result; return result;
} }
result = JVM_GetResourceLookupCache(env, loader, resname); result = JVM_GetResourceLookupCache(env, loader, resname);
......
/* /*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -312,7 +312,7 @@ abstract class KeyStore extends KeyStoreSpi { ...@@ -312,7 +312,7 @@ abstract class KeyStore extends KeyStoreSpi {
if (alias.equals(entry.getAlias())) if (alias.equals(entry.getAlias()))
{ {
X509Certificate[] certChain = entry.getCertificateChain(); X509Certificate[] certChain = entry.getCertificateChain();
return certChain[0]; return certChain.length == 0 ? null : certChain[0];
} }
} }
...@@ -842,7 +842,7 @@ abstract class KeyStore extends KeyStoreSpi { ...@@ -842,7 +842,7 @@ abstract class KeyStore extends KeyStoreSpi {
// Obtain certificate factory // Obtain certificate factory
if (certificateFactory == null) { if (certificateFactory == null) {
certificateFactory = CertificateFactory.getInstance("X.509"); certificateFactory = CertificateFactory.getInstance("X.509", "SUN");
} }
// Generate certificate // Generate certificate
......
/* /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -508,8 +508,10 @@ D3DBlitTextureToSurface(D3DContext *d3dc, ...@@ -508,8 +508,10 @@ D3DBlitTextureToSurface(D3DContext *d3dc,
RETURN_STATUS_IF_NULL(srcOps->pResource, E_FAIL); RETURN_STATUS_IF_NULL(srcOps->pResource, E_FAIL);
RETURN_STATUS_IF_NULL(dstOps->pResource, E_FAIL); RETURN_STATUS_IF_NULL(dstOps->pResource, E_FAIL);
if ((pSrc = srcOps->pResource->GetTexture()) == NULL || pSrc = srcOps->pResource->GetTexture();
FAILED(res = d3dc->BeginScene(STATE_TEXTUREOP) || RETURN_STATUS_IF_NULL(pSrc, E_FAIL);
if (FAILED(res = d3dc->BeginScene(STATE_TEXTUREOP) ||
FAILED(res = d3dc->SetTexture(pSrc)))) FAILED(res = d3dc->SetTexture(pSrc))))
{ {
J2dRlsTraceLn(J2D_TRACE_ERROR, J2dRlsTraceLn(J2D_TRACE_ERROR,
......
/* /*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -355,7 +355,7 @@ D3DTR_UpdateCachedDestination(D3DContext *d3dc, D3DSDOps *dstOps, ...@@ -355,7 +355,7 @@ D3DTR_UpdateCachedDestination(D3DContext *d3dc, D3DSDOps *dstOps,
jint dx1, dy1, dx2, dy2; jint dx1, dy1, dx2, dy2;
D3DResource *pCachedDestTexRes; D3DResource *pCachedDestTexRes;
IDirect3DSurface9 *pCachedDestSurface, *pDst; IDirect3DSurface9 *pCachedDestSurface, *pDst;
HRESULT res; HRESULT res = S_OK;
if (isCachedDestValid && INSIDE(gx1, gy1, gx2, gy2, cachedDestBounds)) { if (isCachedDestValid && INSIDE(gx1, gy1, gx2, gy2, cachedDestBounds)) {
// glyph is already within the cached destination bounds; no need // glyph is already within the cached destination bounds; no need
......
...@@ -673,6 +673,9 @@ JNIEXPORT jlong JNICALL Java_sun_awt_shell_Win32ShellFolder2_getLinkLocation ...@@ -673,6 +673,9 @@ JNIEXPORT jlong JNICALL Java_sun_awt_shell_Win32ShellFolder2_getLinkLocation
case STRRET_WSTR : case STRRET_WSTR :
wstr = strret.pOleStr; wstr = strret.pOleStr;
break; break;
default:
return NULL;
} }
IShellLinkW* psl; IShellLinkW* psl;
......
...@@ -5200,6 +5200,8 @@ void AwtComponent::SynthesizeMouseMessage(JNIEnv *env, jobject mouseEvent) ...@@ -5200,6 +5200,8 @@ void AwtComponent::SynthesizeMouseMessage(JNIEnv *env, jobject mouseEvent)
message = WM_MBUTTONDOWN; break; message = WM_MBUTTONDOWN; break;
case java_awt_event_MouseEvent_BUTTON2: case java_awt_event_MouseEvent_BUTTON2:
message = WM_RBUTTONDOWN; break; message = WM_RBUTTONDOWN; break;
default:
return;
} }
break; break;
} }
...@@ -5211,6 +5213,8 @@ void AwtComponent::SynthesizeMouseMessage(JNIEnv *env, jobject mouseEvent) ...@@ -5211,6 +5213,8 @@ void AwtComponent::SynthesizeMouseMessage(JNIEnv *env, jobject mouseEvent)
message = WM_MBUTTONUP; break; message = WM_MBUTTONUP; break;
case java_awt_event_MouseEvent_BUTTON2: case java_awt_event_MouseEvent_BUTTON2:
message = WM_RBUTTONUP; break; message = WM_RBUTTONUP; break;
default:
return;
} }
break; break;
} }
......
/* /*
* Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -388,7 +388,7 @@ void CheckFontSmoothingSettings(HWND hWnd) { ...@@ -388,7 +388,7 @@ void CheckFontSmoothingSettings(HWND hWnd) {
} }
BOOL fontSmoothing = FALSE, settingsChanged; BOOL fontSmoothing = FALSE, settingsChanged;
UINT fontSmoothingType=0, fontSmoothingContrast=0, subPixelOrder; UINT fontSmoothingType=0, fontSmoothingContrast=0, subPixelOrder=0;
if (firstTime) { if (firstTime) {
SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &fontSmoothing, 0); SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &fontSmoothing, 0);
......
/* /*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -270,7 +270,7 @@ AwtFont* AwtFont::Create(JNIEnv *env, jobject font, jint angle, jfloat awScale) ...@@ -270,7 +270,7 @@ AwtFont* AwtFont::Create(JNIEnv *env, jobject font, jint angle, jfloat awScale)
cfnum = 0; cfnum = 0;
} }
LPCWSTR wName; LPCWSTR wName = NULL;
awtFont = new AwtFont(cfnum, env, font); awtFont = new AwtFont(cfnum, env, font);
...@@ -1168,7 +1168,7 @@ void AwtFontCache::IncRefCount(HFONT hFont){ ...@@ -1168,7 +1168,7 @@ void AwtFontCache::IncRefCount(HFONT hFont){
} }
LONG AwtFontCache::IncRefCount(Item* item){ LONG AwtFontCache::IncRefCount(Item* item){
LONG newVal; LONG newVal = 0;
if(NULL != item){ if(NULL != item){
newVal = InterlockedIncrement((long*)&item->refCount); newVal = InterlockedIncrement((long*)&item->refCount);
...@@ -1177,7 +1177,7 @@ LONG AwtFontCache::IncRefCount(Item* item){ ...@@ -1177,7 +1177,7 @@ LONG AwtFontCache::IncRefCount(Item* item){
} }
LONG AwtFontCache::DecRefCount(Item* item){ LONG AwtFontCache::DecRefCount(Item* item){
LONG newVal; LONG newVal = 0;
if(NULL != item){ if(NULL != item){
newVal = InterlockedDecrement((long*)&item->refCount); newVal = InterlockedDecrement((long*)&item->refCount);
......
...@@ -156,7 +156,7 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent) ...@@ -156,7 +156,7 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent)
PDATA pData; PDATA pData;
HWND hwndParent = NULL; HWND hwndParent = NULL;
AwtFrame* frame; AwtFrame* frame = NULL;
jclass cls = NULL; jclass cls = NULL;
jclass inputMethodWindowCls = NULL; jclass inputMethodWindowCls = NULL;
jobject target = NULL; jobject target = NULL;
...@@ -993,7 +993,9 @@ MsgRouting AwtFrame::WmActivate(UINT nState, BOOL fMinimized, HWND opposite) ...@@ -993,7 +993,9 @@ MsgRouting AwtFrame::WmActivate(UINT nState, BOOL fMinimized, HWND opposite)
AwtComponent::SetFocusedWindow(GetHWnd()); AwtComponent::SetFocusedWindow(GetHWnd());
} else { } else {
if (!::IsWindow(AwtWindow::GetModalBlocker(opposite))) { if (::IsWindow(AwtWindow::GetModalBlocker(opposite))) {
return mrConsume;
} else {
// If deactivation happens because of press on grabbing // If deactivation happens because of press on grabbing
// window - this is nonsense, since grabbing window is // window - this is nonsense, since grabbing window is
// assumed to have focus and watch for deactivation. But // assumed to have focus and watch for deactivation. But
......
/* /*
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -146,15 +146,16 @@ void AwtLabel::DoPaint(HDC hDC, RECT& r) ...@@ -146,15 +146,16 @@ void AwtLabel::DoPaint(HDC hDC, RECT& r)
jint alignment = env->GetIntField(target, AwtLabel::alignmentID); jint alignment = env->GetIntField(target, AwtLabel::alignmentID);
switch (alignment) { switch (alignment) {
case java_awt_Label_LEFT:
x = r.left + 2;
break;
case java_awt_Label_CENTER: case java_awt_Label_CENTER:
x = (r.left + r.right - size.cx) / 2; x = (r.left + r.right - size.cx) / 2;
break; break;
case java_awt_Label_RIGHT: case java_awt_Label_RIGHT:
x = r.right - 2 - size.cx; x = r.right - 2 - size.cx;
break; break;
case java_awt_Label_LEFT:
default:
x = r.left + 2;
break;
} }
/* draw string */ /* draw string */
if (isEnabled()) { if (isEnabled()) {
......
/* /*
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -1108,7 +1108,7 @@ Java_sun_awt_windows_WPrinterJob_initPrinter(JNIEnv *env, jobject self) { ...@@ -1108,7 +1108,7 @@ Java_sun_awt_windows_WPrinterJob_initPrinter(JNIEnv *env, jobject self) {
// check for collation // check for collation
HGLOBAL hDevNames = AwtPrintControl::getPrintHDName(env, self); HGLOBAL hDevNames = AwtPrintControl::getPrintHDName(env, self);
if (hDevNames != NULL) { if (hDevNames != NULL) {
DWORD dmFields; DWORD dmFields = 0;
DEVNAMES *devnames = (DEVNAMES *)::GlobalLock(hDevNames); DEVNAMES *devnames = (DEVNAMES *)::GlobalLock(hDevNames);
if (devnames != NULL) { if (devnames != NULL) {
......
/* /*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -129,6 +129,7 @@ AwtTextComponent* AwtTextComponent::Create(jobject peer, jobject parent, BOOL is ...@@ -129,6 +129,7 @@ AwtTextComponent* AwtTextComponent::Create(jobject peer, jobject parent, BOOL is
scroll_style = WS_HSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL; scroll_style = WS_HSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL;
break; break;
case java_awt_TextArea_SCROLLBARS_BOTH: case java_awt_TextArea_SCROLLBARS_BOTH:
default:
scroll_style = WS_VSCROLL | WS_HSCROLL | scroll_style = WS_VSCROLL | WS_HSCROLL |
ES_AUTOVSCROLL | ES_AUTOHSCROLL; ES_AUTOVSCROLL | ES_AUTOHSCROLL;
break; break;
......
...@@ -342,13 +342,17 @@ needs_jdk = \ ...@@ -342,13 +342,17 @@ needs_jdk = \
sun/management/jmxremote/bootstrap/JvmstatCountersTest.java \ sun/management/jmxremote/bootstrap/JvmstatCountersTest.java \
sun/management/jmxremote/bootstrap/LocalManagementTest.java \ sun/management/jmxremote/bootstrap/LocalManagementTest.java \
sun/management/jmxremote/bootstrap/CustomLauncherTest.java \ sun/management/jmxremote/bootstrap/CustomLauncherTest.java \
sun/management/jmxremote/startstop \
sun/misc/JarIndex/metaInfFilenames/Basic.java \ sun/misc/JarIndex/metaInfFilenames/Basic.java \
sun/misc/JarIndex/JarIndexMergeForClassLoaderTest.java \ sun/misc/JarIndex/JarIndexMergeForClassLoaderTest.java \
sun/reflect/CallerSensitive/CallerSensitiveFinder.java \ sun/reflect/CallerSensitive/CallerSensitiveFinder.java \
sun/reflect/CallerSensitive/MissingCallerSensitive.java \ sun/reflect/CallerSensitive/MissingCallerSensitive.java \
sun/security/util/Resources/NewNamesFormat.java \ sun/security/util/Resources/NewNamesFormat.java \
vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java \ vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java \
javax/xml/ws/clientjar/TestWsImport.java javax/xml/bind/jxc \
javax/xml/ws/8033113 \
javax/xml/ws/clientjar/TestWsImport.java \
javax/xml/ws/ebcdic
# JRE adds further tests to compact3 # JRE adds further tests to compact3
# #
...@@ -389,8 +393,10 @@ needs_jre = \ ...@@ -389,8 +393,10 @@ needs_jre = \
javax/management/mxbean/LeakTest.java \ javax/management/mxbean/LeakTest.java \
javax/management/mxbean/MXBeanTest.java \ javax/management/mxbean/MXBeanTest.java \
javax/management/mxbean/PropertyNamesTest.java \ javax/management/mxbean/PropertyNamesTest.java \
javax/xml/ws/8043129 \
jdk/lambda/vm/InterfaceAccessFlagsTest.java \ jdk/lambda/vm/InterfaceAccessFlagsTest.java \
sun/misc/URLClassPath/ClassnameCharTest.java sun/misc/URLClassPath/ClassnameCharTest.java \
sun/security/pkcs11/Provider/Login.sh
# Tests dependent on the optional charsets.jar # Tests dependent on the optional charsets.jar
# These are isolated for easy exclusions # These are isolated for easy exclusions
...@@ -538,7 +544,9 @@ needs_compact2 = \ ...@@ -538,7 +544,9 @@ needs_compact2 = \
com/sun/net/httpserver \ com/sun/net/httpserver \
java/sql \ java/sql \
javax/sql \ javax/sql \
javax/xml \ javax/xml/bind \
javax/xml/jaxp \
javax/xml/ws/xsanymixed \
jdk/lambda \ jdk/lambda \
sun/net/www/http \ sun/net/www/http \
sun/net/www/protocol/http \ sun/net/www/protocol/http \
......
...@@ -204,22 +204,6 @@ if [ ! -r c:/ ] ; then ...@@ -204,22 +204,6 @@ if [ ! -r c:/ ] ; then
clean clean
fi fi
if [ ! -r c:/ ] ; then
# Can't make a file unreadable under MKS.
echo
echo "+++++++++++++++++++++++++++++++++++"
echo "Read an unreadable file - verify the read fails."
# If the file exists, we try to read it. The
# read will fail.
mkFiles $HOME/jdb.ini
chmod a-r $HOME/jdb.ini
doit
failIfNot 1 "open: $HOME/jdb.ini"
clean
fi
echo echo
echo "+++++++++++++++++++++++++++++++++++" echo "+++++++++++++++++++++++++++++++++++"
echo "Read a directory - verify the read fails" echo "Read a directory - verify the read fails"
...@@ -239,8 +223,8 @@ echo "read $fred" > $here/jdb.ini ...@@ -239,8 +223,8 @@ echo "read $fred" > $here/jdb.ini
doit doit
failIfNot 1 "from $fred" failIfNot 1 "from $fred"
if [ ! -r c:/ ] ; then if [ "$canMakeUnreadable" = "Yes" ]
# Can't make a file unreadable under MKS then
chmod a-r $fred chmod a-r $fred
doit doit
failIfNot 1 "open: $fred" failIfNot 1 "open: $fred"
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
# questions. # questions.
# #
# @test @(#)StringConvertTest.sh 1.6 03/04/09 # @test
# @bug 4511950 4843082 # @bug 4511950 4843082
# @summary 1. jdb's expression evaluation doesn't perform string conversion properly # @summary 1. jdb's expression evaluation doesn't perform string conversion properly
# 2. TTY: run on expression evaluation # 2. TTY: run on expression evaluation
......
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Window;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* @test
* @bug 8138764
*/
public final class TreeLockDeadlock extends Frame {
@Override
public synchronized GraphicsConfiguration getGraphicsConfiguration() {
return super.getGraphicsConfiguration();
}
@Override
public synchronized void reshape(int x, int y, int width, int height) {
super.reshape(x, y, width, height);
}
@Override
public synchronized float getOpacity() {
return super.getOpacity();
}
public static void main(final String[] args) throws Exception {
final Window window = new TreeLockDeadlock();
window.setSize(300, 300);
test(window);
}
private static void test(final Window window) throws Exception {
final long start = System.nanoTime();
final long end = start + NANOSECONDS.convert(1, MINUTES);
final Runnable r1 = () -> {
while (System.nanoTime() < end) {
window.setBounds(window.getBounds());
}
};
final Runnable r2 = () -> {
while (System.nanoTime() < end) {
window.getGraphicsConfiguration();
window.getOpacity();
}
};
final Thread t1 = new Thread(r1);
final Thread t2 = new Thread(r1);
final Thread t3 = new Thread(r2);
final Thread t4 = new Thread(r2);
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
}
}
<!--
Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
or visit www.oracle.com if you need additional information or have any
questions.
-->
<html>
<body>
Verify that Chinese full stop symbol can be entered in JTextArea with Pinyin input method (IM).
This test is for OS X only. For other platforms please simply press "Pass".
1. Go to "System Preferences -> Keyboard -> Input Sources" and add "Pinyin – Traditional" or "Pinyin – Simplified" IM from Chinese language group.
2. Set current IM to "Pinyin".
3. Set focus to the text area of the test and press "dot" character on the keyboard.
4. Set current IM to the IM used before "Pinyin" was set.
5. If "。" character is displayed in the text area, press "Pass", if "." character is displayed, press "Fail".
<applet code="bug8132503.class" width=400 height=400></applet>
</body>
</html>
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 8132503
@summary [macosx] Chinese full stop symbol cannot be entered with Pinyin IM on OS X
@author Anton Litvinov
@run applet/manual=yesno bug8132503.html
*/
import javax.swing.JApplet;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class bug8132503 extends JApplet {
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTextArea textArea = new JTextArea("Text area of the test.", 40, 40);
add(new JScrollPane(textArea));
}
});
}
}
...@@ -30,6 +30,7 @@ import static java.time.temporal.ChronoField.DAY_OF_YEAR; ...@@ -30,6 +30,7 @@ import static java.time.temporal.ChronoField.DAY_OF_YEAR;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
...@@ -71,6 +72,7 @@ import org.testng.annotations.Test; ...@@ -71,6 +72,7 @@ import org.testng.annotations.Test;
/** /**
* Tests for the Umm alQura chronology and data. * Tests for the Umm alQura chronology and data.
* Note: The dates used for testing are just a sample of calendar data. * Note: The dates used for testing are just a sample of calendar data.
* @bug 8067800
*/ */
@Test @Test
public class TestUmmAlQuraChronology { public class TestUmmAlQuraChronology {
...@@ -530,6 +532,24 @@ public class TestUmmAlQuraChronology { ...@@ -530,6 +532,24 @@ public class TestUmmAlQuraChronology {
assertEquals(date.isLeapYear(), leapyear); assertEquals(date.isLeapYear(), leapyear);
} }
// Data provider to verify that a given hijrah year is outside the range of supported years
// The values are dependent on the currently configured UmmAlQura calendar data
@DataProvider(name="OutOfRangeLeapYears")
Object[][] data_invalid_leapyears() {
return new Object[][] {
{1299},
{1601},
{Integer.MAX_VALUE},
{Integer.MIN_VALUE},
};
}
@Test(dataProvider="OutOfRangeLeapYears")
public void test_notLeapYears(int y) {
assertFalse(HijrahChronology.INSTANCE.isLeapYear(y), "Out of range leap year");
}
// Date samples to convert HijrahDate to LocalDate and vice versa // Date samples to convert HijrahDate to LocalDate and vice versa
@DataProvider(name="samples") @DataProvider(name="samples")
Object[][] data_samples() { Object[][] data_samples() {
......
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8041501
* @summary Test verifies if there is no JFIF & EXIF header
* and sampling factor is same of JPEG image, then
* imageIO should not override colorspace determined
* in IJG library.
* @run main JpegImageColorSpaceTest
*/
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class JpegImageColorSpaceTest {
public static void main(String args[]) throws Exception {
String fileName = "nomarkers.jpg";
String sep = System.getProperty("file.separator");
String dir = System.getProperty("test.src", ".");
String filePath = dir+sep+fileName;
System.out.println("Test file: " + filePath);
File imageFile = new File(filePath);
BufferedImage bufferedImage = ImageIO.read(imageFile);
int imageWidth = bufferedImage.getWidth();
int imageHeight = bufferedImage.getHeight();
for (int i = 0; i < imageWidth; i++) {
for(int j = 0; j < imageHeight; j++) {
/*
* Since image is white we check individual pixel values from
* BufferedImage to verify if ImageIO.read() is done with proper
* color space or not.
*/
if (bufferedImage.getRGB(i, j) != Color.white.getRGB()) {
// color space is not proper
throw new RuntimeException("ColorSpace is not determined "
+ "properly by ImageIO");
}
}
}
}
}
/*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
public class Name implements NameMBean {
private String firstName;
private String lastName;
@Override
public String getFirstName() {
return firstName;
}
@Override
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
/*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
public interface NameMBean {
String getFirstName();
void setFirstName(String firstName);
String getLastName();
void setLastName(String lastName);
}
/*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.ServerSocket;
import java.rmi.registry.LocateRegistry;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
/**
* @test
* @bug 8147857
* @summary Tests whether RMIConnector logs attribute names correctly.
* @author Severin Gehwolf
*/
public class RMIConnectorLogAttributesTest {
private static final String ILLEGAL = ", FirstName[LastName]";
private static final Logger logger = Logger.getLogger("javax.management.remote.rmi");
private static final String ANY_NAME = "foo";
private static final TestLogHandler handler;
static {
handler = new TestLogHandler(ILLEGAL);
handler.setLevel(Level.FINEST);
logger.setLevel(Level.ALL);
logger.addHandler(handler);
}
private JMXConnectorServer startServer(int rmiPort) throws Exception {
System.out.println("DEBUG: Create RMI registry on port " + rmiPort);
LocateRegistry.createRegistry(rmiPort);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
HashMap<String,Object> env = new HashMap<String,Object>();
JMXServiceURL url =
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:" + rmiPort + "/jmxrmi");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
System.out.println("DEBUG: Started the RMI connector server");
return cs;
}
private int findPort() {
for (int i = 13333; i < 13333 + 100; i++) {
try {
ServerSocket socket = new ServerSocket(i);
socket.close();
return i;
} catch (IOException e) {
continue;
}
}
return -1;
}
private void runTest() {
int rmiPort = findPort();
if (rmiPort == -1) {
throw new RuntimeException("Test failed. No available port");
}
JMXConnectorServer server = null;
try {
server = startServer(rmiPort);
JMXConnector connector = connectToServer(server);
doTest(connector);
} catch (Exception e) {
throw new RuntimeException("Test failed unexpectedly", e);
} finally {
if (server != null) {
try {
server.stop();
} catch (IOException e) {
// ignore
}
}
}
}
private JMXConnector connectToServer(JMXConnectorServer server) throws IOException, MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, ReflectionException, MBeanException {
JMXServiceURL url = server.getAddress();
Map<String, Object> env = new HashMap<String, Object>();
JMXConnector connector = JMXConnectorFactory.connect(url, env);
System.out.println("DEBUG: Client connected to RMI at: " + url);
return connector;
}
private void doTest(JMXConnector connector) throws IOException,
MalformedObjectNameException, ReflectionException,
InstanceAlreadyExistsException, MBeanRegistrationException,
MBeanException, NotCompliantMBeanException, InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException {
MBeanServerConnection mbsc = connector.getMBeanServerConnection();
ObjectName objName = new ObjectName("com.redhat.test.jmx:type=NameMBean");
System.out.println("DEBUG: Calling createMBean");
mbsc.createMBean(Name.class.getName(), objName);
System.out.println("DEBUG: Calling setAttributes");
AttributeList attList = new AttributeList();
attList.add(new Attribute("FirstName", ANY_NAME));
attList.add(new Attribute("LastName", ANY_NAME));
mbsc.setAttributes(objName, attList);
}
public static void main(String[] args) throws Exception {
RMIConnectorLogAttributesTest test = new RMIConnectorLogAttributesTest();
test.runTest();
if (handler.testFailed()) {
throw new RuntimeException("Test failed. Logged incorrect: '" + ILLEGAL + "'");
}
System.out.println("Test passed!");
}
}
/*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class TestLogHandler extends Handler {
private final String illegal;
private boolean testFailed;
public TestLogHandler(String illegal) {
this.illegal = illegal;
this.testFailed = false;
}
@Override
public void publish(LogRecord record) {
String msg = record.getMessage();
String method = record.getSourceMethodName();
String className = record.getSourceClassName();
if (msg.contains(illegal)) {
testFailed = true;
}
if (msg.contains("attribute names=")) {
System.err.println("LOG: " + className + "." + method + ": " + msg);
}
}
@Override
public void flush() {
// nothing
}
@Override
public void close() throws SecurityException {
// nothing
}
public boolean testFailed() {
return testFailed;
}
}
...@@ -107,14 +107,14 @@ public class PrintSEUmlauts implements Printable { ...@@ -107,14 +107,14 @@ public class PrintSEUmlauts implements Printable {
System.err.println("printing content"); System.err.println("printing content");
System.err.println(content); System.err.println(content);
} }
throw new RuntimeException("Expected <e4> to represent 'ä' but not found!"); throw new RuntimeException("Expected <e4> to represent '\u00e4' but not found!");
} }
System.err.println("SUCCESS"); System.err.println("SUCCESS");
} }
public int print(Graphics g, PageFormat pf, int pg) { public int print(Graphics g, PageFormat pf, int pg) {
if (pg > 0) return NO_SUCH_PAGE; if (pg > 0) return NO_SUCH_PAGE;
g.drawString("ä", 100, 100); g.drawString("\u00e4", 100, 100);
return PAGE_EXISTS; return PAGE_EXISTS;
} }
} }
/* /*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -37,13 +37,16 @@ public class Optimize { ...@@ -37,13 +37,16 @@ public class Optimize {
ProtectionDomain pd1 = new ProtectionDomain( ProtectionDomain pd1 = new ProtectionDomain(
new CodeSource(null, (java.security.cert.Certificate[]) null), new CodeSource(null, (java.security.cert.Certificate[]) null),
new Permissions()); new Permissions(),
null, null);
ProtectionDomain pd2 = new ProtectionDomain( ProtectionDomain pd2 = new ProtectionDomain(
new CodeSource(null, (java.security.cert.Certificate[]) null), new CodeSource(null, (java.security.cert.Certificate[]) null),
new Permissions()); new Permissions(),
null, null);
ProtectionDomain pd3 = new ProtectionDomain( ProtectionDomain pd3 = new ProtectionDomain(
new CodeSource(null, (java.security.cert.Certificate[]) null), new CodeSource(null, (java.security.cert.Certificate[]) null),
new Permissions()); new Permissions(),
null, null);
ProtectionDomain[] current = new ProtectionDomain[] {pd1, pd2}; ProtectionDomain[] current = new ProtectionDomain[] {pd1, pd2};
ProtectionDomain[] assigned = new ProtectionDomain[] {pd3, pd2}; ProtectionDomain[] assigned = new ProtectionDomain[] {pd3, pd2};
......
/* /*
* 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/** /**
* @test * @test
* @bug 4635230 6283345 6303830 6824440 6867348 7094155 * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349
* @summary Basic unit tests for generating XML Signatures with JSR 105 * @summary Basic unit tests for generating XML Signatures with JSR 105
* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
* X509KeySelector.java GenerationTests.java * X509KeySelector.java GenerationTests.java
...@@ -80,9 +80,10 @@ public class GenerationTests { ...@@ -80,9 +80,10 @@ public class GenerationTests {
private static KeyInfoFactory kifac; private static KeyInfoFactory kifac;
private static DocumentBuilder db; private static DocumentBuilder db;
private static CanonicalizationMethod withoutComments; private static CanonicalizationMethod withoutComments;
private static SignatureMethod dsaSha1, rsaSha1, rsaSha256, rsaSha384, rsaSha512; private static SignatureMethod dsaSha1, dsaSha256, rsaSha1,
rsaSha256, rsaSha384, rsaSha512;
private static DigestMethod sha1, sha256, sha384, sha512; private static DigestMethod sha1, sha256, sha384, sha512;
private static KeyInfo dsa, rsa, rsa1024; private static KeyInfo dsa1024, dsa2048, rsa, rsa1024;
private static KeySelector kvks = new KeySelectors.KeyValueKeySelector(); private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();
private static KeySelector sks; private static KeySelector sks;
private static Key signingKey; private static Key signingKey;
...@@ -106,10 +107,13 @@ public class GenerationTests { ...@@ -106,10 +107,13 @@ public class GenerationTests {
"http://www.w3.org/TR/xml-stylesheet"; "http://www.w3.org/TR/xml-stylesheet";
private final static String STYLESHEET_B64 = private final static String STYLESHEET_B64 =
"http://www.w3.org/Signature/2002/04/xml-stylesheet.b64"; "http://www.w3.org/Signature/2002/04/xml-stylesheet.b64";
private final static String DSA_SHA256 =
"http://www.w3.org/2009/xmldsig11#dsa-sha256";
public static void main(String args[]) throws Exception { public static void main(String args[]) throws Exception {
setup(); setup();
test_create_signature_enveloped_dsa(); test_create_signature_enveloped_dsa(1024);
test_create_signature_enveloped_dsa(2048);
test_create_signature_enveloping_b64_dsa(); test_create_signature_enveloping_b64_dsa();
test_create_signature_enveloping_dsa(); test_create_signature_enveloping_dsa();
test_create_signature_enveloping_hmac_sha1_40(); test_create_signature_enveloping_hmac_sha1_40();
...@@ -135,6 +139,7 @@ public class GenerationTests { ...@@ -135,6 +139,7 @@ public class GenerationTests {
test_create_signature_enveloping_sha512_rsa_sha512(); test_create_signature_enveloping_sha512_rsa_sha512();
test_create_signature_reference_dependency(); test_create_signature_reference_dependency();
test_create_signature_with_attr_in_no_namespace(); test_create_signature_with_attr_in_no_namespace();
test_create_signature_with_empty_id();
} }
private static void setup() throws Exception { private static void setup() throws Exception {
...@@ -156,15 +161,18 @@ public class GenerationTests { ...@@ -156,15 +161,18 @@ public class GenerationTests {
withoutComments = fac.newCanonicalizationMethod withoutComments = fac.newCanonicalizationMethod
(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null); (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);
dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null); dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);
sha1 = fac.newDigestMethod(DigestMethod.SHA1, null); sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);
sha256 = fac.newDigestMethod(DigestMethod.SHA256, null); sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);
sha384 = fac.newDigestMethod sha384 = fac.newDigestMethod
("http://www.w3.org/2001/04/xmldsig-more#sha384", null); ("http://www.w3.org/2001/04/xmldsig-more#sha384", null);
sha512 = fac.newDigestMethod(DigestMethod.SHA512, null); sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);
dsa = kifac.newKeyInfo(Collections.singletonList dsa1024 = kifac.newKeyInfo(Collections.singletonList
(kifac.newKeyValue(validatingKey))); (kifac.newKeyValue(validatingKey)));
dsa2048 = kifac.newKeyInfo(Collections.singletonList
(kifac.newKeyValue(getPublicKey("DSA", 2048))));
rsa = kifac.newKeyInfo(Collections.singletonList rsa = kifac.newKeyInfo(Collections.singletonList
(kifac.newKeyValue(getPublicKey("RSA")))); (kifac.newKeyValue(getPublicKey("RSA", 512))));
rsa1024 = kifac.newKeyInfo(Collections.singletonList rsa1024 = kifac.newKeyInfo(Collections.singletonList
(kifac.newKeyValue(getPublicKey("RSA", 1024)))); (kifac.newKeyValue(getPublicKey("RSA", 1024))));
rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null); rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
...@@ -179,11 +187,25 @@ public class GenerationTests { ...@@ -179,11 +187,25 @@ public class GenerationTests {
httpUd = new HttpURIDereferencer(); httpUd = new HttpURIDereferencer();
} }
static void test_create_signature_enveloped_dsa() throws Exception { static void test_create_signature_enveloped_dsa(int size) throws Exception {
System.out.println("* Generating signature-enveloped-dsa.xml"); System.out.println("* Generating signature-enveloped-dsa-"
+ size + ".xml");
SignatureMethod sm = null;
KeyInfo ki = null;
Key privKey;
if (size == 1024) {
sm = dsaSha1;
ki = dsa1024;
privKey = signingKey;
} else if (size == 2048) {
sm = dsaSha256;
ki = dsa2048;
privKey = getPrivateKey("DSA", 2048);
} else throw new RuntimeException("unsupported keysize:" + size);
// create SignedInfo // create SignedInfo
SignedInfo si = fac.newSignedInfo SignedInfo si = fac.newSignedInfo
(withoutComments, dsaSha1, Collections.singletonList (withoutComments, sm, Collections.singletonList
(fac.newReference (fac.newReference
("", sha1, Collections.singletonList ("", sha1, Collections.singletonList
(fac.newTransform(Transform.ENVELOPED, (fac.newTransform(Transform.ENVELOPED,
...@@ -191,7 +213,7 @@ public class GenerationTests { ...@@ -191,7 +213,7 @@ public class GenerationTests {
null, null))); null, null)));
// create XMLSignature // create XMLSignature
XMLSignature sig = fac.newXMLSignature(si, dsa); XMLSignature sig = fac.newXMLSignature(si, ki);
Document doc = db.newDocument(); Document doc = db.newDocument();
Element envelope = doc.createElementNS Element envelope = doc.createElementNS
...@@ -200,7 +222,7 @@ public class GenerationTests { ...@@ -200,7 +222,7 @@ public class GenerationTests {
"xmlns", "http://example.org/envelope"); "xmlns", "http://example.org/envelope");
doc.appendChild(envelope); doc.appendChild(envelope);
DOMSignContext dsc = new DOMSignContext(signingKey, envelope); DOMSignContext dsc = new DOMSignContext(privKey, envelope);
sig.sign(dsc); sig.sign(dsc);
// StringWriter sw = new StringWriter(); // StringWriter sw = new StringWriter();
...@@ -225,21 +247,21 @@ public class GenerationTests { ...@@ -225,21 +247,21 @@ public class GenerationTests {
static void test_create_signature_enveloping_b64_dsa() throws Exception { static void test_create_signature_enveloping_b64_dsa() throws Exception {
System.out.println("* Generating signature-enveloping-b64-dsa.xml"); System.out.println("* Generating signature-enveloping-b64-dsa.xml");
test_create_signature_enveloping test_create_signature_enveloping
(sha1, dsaSha1, dsa, signingKey, kvks, true); (sha1, dsaSha1, dsa1024, signingKey, kvks, true);
System.out.println(); System.out.println();
} }
static void test_create_signature_enveloping_dsa() throws Exception { static void test_create_signature_enveloping_dsa() throws Exception {
System.out.println("* Generating signature-enveloping-dsa.xml"); System.out.println("* Generating signature-enveloping-dsa.xml");
test_create_signature_enveloping test_create_signature_enveloping
(sha1, dsaSha1, dsa, signingKey, kvks, false); (sha1, dsaSha1, dsa1024, signingKey, kvks, false);
System.out.println(); System.out.println();
} }
static void test_create_signature_enveloping_sha256_dsa() throws Exception { static void test_create_signature_enveloping_sha256_dsa() throws Exception {
System.out.println("* Generating signature-enveloping-sha256-dsa.xml"); System.out.println("* Generating signature-enveloping-sha256-dsa.xml");
test_create_signature_enveloping test_create_signature_enveloping
(sha256, dsaSha1, dsa, signingKey, kvks, false); (sha256, dsaSha1, dsa1024, signingKey, kvks, false);
System.out.println(); System.out.println();
} }
...@@ -292,7 +314,7 @@ public class GenerationTests { ...@@ -292,7 +314,7 @@ public class GenerationTests {
static void test_create_signature_enveloping_rsa() throws Exception { static void test_create_signature_enveloping_rsa() throws Exception {
System.out.println("* Generating signature-enveloping-rsa.xml"); System.out.println("* Generating signature-enveloping-rsa.xml");
test_create_signature_enveloping(sha1, rsaSha1, rsa, test_create_signature_enveloping(sha1, rsaSha1, rsa,
getPrivateKey("RSA"), kvks, false); getPrivateKey("RSA", 512), kvks, false);
System.out.println(); System.out.println();
} }
...@@ -300,7 +322,7 @@ public class GenerationTests { ...@@ -300,7 +322,7 @@ public class GenerationTests {
throws Exception { throws Exception {
System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml"); System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml");
test_create_signature_enveloping(sha384, rsaSha256, rsa, test_create_signature_enveloping(sha384, rsaSha256, rsa,
getPrivateKey("RSA"), kvks, false); getPrivateKey("RSA", 512), kvks, false);
System.out.println(); System.out.println();
} }
...@@ -322,13 +344,13 @@ public class GenerationTests { ...@@ -322,13 +344,13 @@ public class GenerationTests {
static void test_create_signature_external_b64_dsa() throws Exception { static void test_create_signature_external_b64_dsa() throws Exception {
System.out.println("* Generating signature-external-b64-dsa.xml"); System.out.println("* Generating signature-external-b64-dsa.xml");
test_create_signature_external(dsaSha1, dsa, signingKey, kvks, true); test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true);
System.out.println(); System.out.println();
} }
static void test_create_signature_external_dsa() throws Exception { static void test_create_signature_external_dsa() throws Exception {
System.out.println("* Generating signature-external-dsa.xml"); System.out.println("* Generating signature-external-dsa.xml");
test_create_signature_external(dsaSha1, dsa, signingKey, kvks, false); test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false);
System.out.println(); System.out.println();
} }
...@@ -440,7 +462,7 @@ public class GenerationTests { ...@@ -440,7 +462,7 @@ public class GenerationTests {
// create XMLSignature // create XMLSignature
XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null); XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null);
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc); DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
sig.sign(dsc); sig.sign(dsc);
...@@ -486,7 +508,7 @@ public class GenerationTests { ...@@ -486,7 +508,7 @@ public class GenerationTests {
XMLSignature sig = fac.newXMLSignature(si, rsa, XMLSignature sig = fac.newXMLSignature(si, rsa,
Collections.singletonList(obj), Collections.singletonList(obj),
"signature", null); "signature", null);
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc); DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
dsc.setIdAttributeNS(nc, null, "Id"); dsc.setIdAttributeNS(nc, null, "Id");
sig.sign(dsc); sig.sign(dsc);
...@@ -509,6 +531,30 @@ public class GenerationTests { ...@@ -509,6 +531,30 @@ public class GenerationTests {
System.out.println(); System.out.println();
} }
static void test_create_signature_with_empty_id() throws Exception {
System.out.println("* Generating signature-with-empty-id.xml");
// create references
List<Reference> refs = Collections.singletonList
(fac.newReference("#", sha1));
// create SignedInfo
SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
// create object with empty id
Document doc = db.newDocument();
XMLObject obj = fac.newXMLObject(Collections.singletonList
(new DOMStructure(doc.createTextNode("I am the text."))),
"", "text/plain", null);
// create XMLSignature
XMLSignature sig = fac.newXMLSignature(si, rsa,
Collections.singletonList(obj),
"signature", null);
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
sig.sign(dsc);
}
static void test_create_signature() throws Exception { static void test_create_signature() throws Exception {
System.out.println("* Generating signature.xml"); System.out.println("* Generating signature.xml");
...@@ -1091,6 +1137,16 @@ public class GenerationTests { ...@@ -1091,6 +1137,16 @@ public class GenerationTests {
"90670890367185141189796"; "90670890367185141189796";
private static final String DSA_X = private static final String DSA_X =
"0527140396812450214498055937934275626078768840117"; "0527140396812450214498055937934275626078768840117";
private static final String DSA_2048_Y =
"15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";
private static final String DSA_2048_P =
"18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";
private static final String DSA_2048_Q =
"19689526866605154788513693571065914024068069442724893395618704484701";
private static final String DSA_2048_G =
"2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";
private static final String DSA_2048_X =
"14562787764977288900757387442281559936279834964901963465277698843172";
private static final String RSA_MOD = private static final String RSA_MOD =
"010800185049102889923150759252557522305032794699952150943573164381" + "010800185049102889923150759252557522305032794699952150943573164381" +
"936603255999071981574575044810461362008102247767482738822150129277" + "936603255999071981574575044810461362008102247767482738822150129277" +
...@@ -1113,43 +1169,48 @@ public class GenerationTests { ...@@ -1113,43 +1169,48 @@ public class GenerationTests {
"204903524890556839550490384015324575598723478554854070823335021842" + "204903524890556839550490384015324575598723478554854070823335021842" +
"210112348400928769"; "210112348400928769";
private static PublicKey getPublicKey(String algo) throws Exception {
return getPublicKey(algo, 512);
}
private static PublicKey getPublicKey(String algo, int keysize) private static PublicKey getPublicKey(String algo, int keysize)
throws Exception { throws Exception {
KeyFactory kf = KeyFactory.getInstance(algo); KeyFactory kf = KeyFactory.getInstance(algo);
KeySpec kspec; KeySpec kspec;
if (algo.equalsIgnoreCase("DSA")) { if (algo.equalsIgnoreCase("DSA")) {
if (keysize == 1024) {
kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y), kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),
new BigInteger(DSA_P), new BigInteger(DSA_P),
new BigInteger(DSA_Q), new BigInteger(DSA_Q),
new BigInteger(DSA_G)); new BigInteger(DSA_G));
} else if (keysize == 2048) {
kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),
new BigInteger(DSA_2048_P),
new BigInteger(DSA_2048_Q),
new BigInteger(DSA_2048_G));
} else throw new RuntimeException("Unsupported keysize:" + keysize);
} else if (algo.equalsIgnoreCase("RSA")) { } else if (algo.equalsIgnoreCase("RSA")) {
if (keysize == 512) { if (keysize == 512) {
kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD), kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),
new BigInteger(RSA_PUB)); new BigInteger(RSA_PUB));
} else { } else if (keysize == 1024) {
kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD), kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),
new BigInteger(RSA_PUB)); new BigInteger(RSA_PUB));
} } else throw new RuntimeException("Unsupported keysize:" + keysize);
} else throw new RuntimeException("Unsupported key algorithm " + algo); } else throw new RuntimeException("Unsupported key algorithm " + algo);
return kf.generatePublic(kspec); return kf.generatePublic(kspec);
} }
private static PrivateKey getPrivateKey(String algo) throws Exception {
return getPrivateKey(algo, 512);
}
private static PrivateKey getPrivateKey(String algo, int keysize) private static PrivateKey getPrivateKey(String algo, int keysize)
throws Exception { throws Exception {
KeyFactory kf = KeyFactory.getInstance(algo); KeyFactory kf = KeyFactory.getInstance(algo);
KeySpec kspec; KeySpec kspec;
if (algo.equalsIgnoreCase("DSA")) { if (algo.equalsIgnoreCase("DSA")) {
if (keysize == 1024) {
kspec = new DSAPrivateKeySpec kspec = new DSAPrivateKeySpec
(new BigInteger(DSA_X), new BigInteger(DSA_P), (new BigInteger(DSA_X), new BigInteger(DSA_P),
new BigInteger(DSA_Q), new BigInteger(DSA_G)); new BigInteger(DSA_Q), new BigInteger(DSA_G));
} else if (keysize == 2048) {
kspec = new DSAPrivateKeySpec
(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),
new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));
} else throw new RuntimeException("Unsupported keysize:" + keysize);
} else if (algo.equalsIgnoreCase("RSA")) { } else if (algo.equalsIgnoreCase("RSA")) {
if (keysize == 512) { if (keysize == 512) {
kspec = new RSAPrivateKeySpec kspec = new RSAPrivateKeySpec
......
/* /*
* Copyright (c) 2005, 2012, 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -175,7 +175,8 @@ class KeySelectors { ...@@ -175,7 +175,8 @@ class KeySelectors {
//@@@FIXME: this should also work for key types other than DSA/RSA //@@@FIXME: this should also work for key types other than DSA/RSA
static boolean algEquals(String algURI, String algName) { static boolean algEquals(String algURI, String algName) {
if (algName.equalsIgnoreCase("DSA") && if (algName.equalsIgnoreCase("DSA") &&
algURI.equals(SignatureMethod.DSA_SHA1)) { algURI.equals(SignatureMethod.DSA_SHA1) ||
algURI.equals("http://www.w3.org/2009/xmldsig11#dsa-sha256")) {
return true; return true;
} else if (algName.equalsIgnoreCase("RSA") && } else if (algName.equalsIgnoreCase("RSA") &&
(algURI.equals(SignatureMethod.RSA_SHA1) || (algURI.equals(SignatureMethod.RSA_SHA1) ||
......
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
*/ */
/* @test /* @test
* @bug 8062518 * @bug 8062518 8133924
* @summary This class contains tests for XSLT functions * @summary This class contains tests for XSLT functions
* @compile DocumentExtFunc.java * @compile DocumentExtFunc.java
* @run testng/othervm XSLTFunctionsTest * @run testng/othervm XSLTFunctionsTest
...@@ -102,17 +102,34 @@ public class XSLTFunctionsTest { ...@@ -102,17 +102,34 @@ public class XSLTFunctionsTest {
@DataProvider(name = "document") @DataProvider(name = "document")
public static Object[][] documentTestData() { public static Object[][] documentTestData() {
return new Object[][] { return new Object[][] {
// 8062518
{documentTestXml, documentTestXsl, documentTestExternalDoc, documentTesteExpectedResult}, {documentTestXml, documentTestXsl, documentTestExternalDoc, documentTesteExpectedResult},
// 8133924
{documentTestXml, nonExistingNodeXsl, documentTestExternalDoc, nonExistNodeExpectedResult},
}; };
} }
// bug 8133924 xsl: test data to trigger the NPE when non-existing node is specified in xsl
static final String nonExistingNodeXsl = "<?xml version='1.0' encoding=\"UTF-8\"?>"
+ "<xsl:transform xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\""
+ " xmlns:set=\"http://exslt.org/sets\""
+ " exclude-result-prefixes=\"set\">"
+ " <xsl:template match=\"/\">"
+ " <xsl:copy-of select=\"set:leading(/Test, /Test/non-existing)\"/>"
+ "</xsl:template>"
+ "</xsl:transform>";
//For bug 8133924 xsl the empty transformation result is expected instead of NPE
static final String nonExistNodeExpectedResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Test>Doc</Test>";
static final String documentTestXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test>Doc</Test>"; static final String documentTestXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test>Doc</Test>";
static final String documentTestExternalDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test>External Doc</Test>"; static final String documentTestExternalDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test>External Doc</Test>";
static final String documentTestXsl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" static final String documentTestXsl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<xsl:transform version=\"1.0\"" + "<xsl:transform version=\"1.0\""
+ " xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " + " xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\""
+ " xmlns:cfunc=\"http://xml.apache.org/xalan/java/\">" + " xmlns:cfunc=\"http://xml.apache.org/xalan/java/\">"
+ "<xsl:template match=\"/\">" + "<xsl:template match=\"/\">"
+ "<xsl:element name=\"root\">" + "<xsl:element name=\"root\">"
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
/* /*
* @test * @test
* @bug 4990825 * @bug 4990825
* @run main/othervm -XX:+UsePerfData PrologSizeSanityCheck * @run main/othervm -XX:+UsePerfData -XX:PerfDataMemorySize=64k PrologSizeSanityCheck
* @summary prolog size and overflow sanity checks * @summary prolog size and overflow sanity checks
*/ */
......
...@@ -29,11 +29,13 @@ ...@@ -29,11 +29,13 @@
* @run main Version * @run main Version
*/ */
import java.util.regex.*;
import static sun.misc.Version.*; import static sun.misc.Version.*;
public class Version { public class Version {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
VersionInfo jdk = newVersionInfo(System.getProperty("java.runtime.version")); VersionInfo jdk = jdkVersionInfo(System.getProperty("java.runtime.version"));
VersionInfo v1 = new VersionInfo(jdkMajorVersion(), VersionInfo v1 = new VersionInfo(jdkMajorVersion(),
jdkMinorVersion(), jdkMinorVersion(),
jdkMicroVersion(), jdkMicroVersion(),
...@@ -44,7 +46,7 @@ public class Version { ...@@ -44,7 +46,7 @@ public class Version {
if (!jdk.equals(v1)) { if (!jdk.equals(v1)) {
throw new RuntimeException("Unmatched version: " + jdk + " vs " + v1); throw new RuntimeException("Unmatched version: " + jdk + " vs " + v1);
} }
VersionInfo jvm = newVersionInfo(System.getProperty("java.vm.version")); VersionInfo jvm = jvmVersionInfo(System.getProperty("java.vm.version"));
VersionInfo v2 = new VersionInfo(jvmMajorVersion(), VersionInfo v2 = new VersionInfo(jvmMajorVersion(),
jvmMinorVersion(), jvmMinorVersion(),
jvmMicroVersion(), jvmMicroVersion(),
...@@ -95,74 +97,73 @@ public class Version { ...@@ -95,74 +97,73 @@ public class Version {
} }
} }
private static VersionInfo newVersionInfo(String version) throws Exception { private static VersionInfo jdkVersionInfo(String version) throws Exception {
// valid format of the version string is: // valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx // <major>.<minor>[.<micro>][_uu[c]][-<identifier>]-bxx
int major = 0; int major = 0;
int minor = 0; int minor = 0;
int micro = 0; int micro = 0;
int update = 0; int update = 0;
String special = ""; String special = "";
int build = 0; int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) { String regex = "^([0-9]{1,2})"; // major
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' && regex += "\\."; // separator
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' && regex += "([0-9]{1,2})"; // minor
Character.isDigit(cs.charAt(4))) { regex += "(\\."; // separator
major = Character.digit(cs.charAt(0), 10); regex += "([0-9]{1,2})"; // micro
minor = Character.digit(cs.charAt(2), 10); regex += ")?"; // micro is optional
micro = Character.digit(cs.charAt(4), 10); regex += "(_";
cs = cs.subSequence(5, cs.length()); regex += "([0-9]{2,3})"; // update
} else if (Character.isDigit(cs.charAt(0)) && regex += "([a-z])?"; // special char (optional)
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' && regex += ")?"; // _uu[c] is optional
Character.isDigit(cs.charAt(3))) { regex += ".*"; // -<identifier>
// HSX has nn.n[n] (major.minor) version regex += "(\\-b([0-9]{1,3}$))"; // JDK -bxx
major = Integer.valueOf(version.substring(0, 2)).intValue();
if (Character.isDigit(cs.charAt(4))) { Pattern p = Pattern.compile(regex);
minor = Integer.valueOf(version.substring(3, 5)).intValue(); Matcher m = p.matcher(version);
cs = cs.subSequence(5, cs.length()); m.matches();
}
else { major = Integer.parseInt(m.group(1));
minor = Character.digit(cs.charAt(3), 10); minor = Integer.parseInt(m.group(2));
cs = cs.subSequence(4, cs.length()); micro = (m.group(4) == null) ? 0 : Integer.parseInt(m.group(4));
} update = (m.group(6) == null) ? 0 : Integer.parseInt(m.group(6));
} special = (m.group(7) == null) ? "" : m.group(7);
if (cs.charAt(0) == '_' && cs.length() >= 3 && build = Integer.parseInt(m.group(9));
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) { VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build);
int nextChar = 3; System.out.printf("jdkVersionInfo: input=%s output=%s\n", version, vi);
String uu = cs.subSequence(1, 3).toString(); return vi;
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
} }
if (cs.charAt(0) == '-') {
// skip the first character private static VersionInfo jvmVersionInfo(String version) throws Exception {
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
for (int i = res.length - 1; i >= 0; i--) {
String s = res[i];
if (s.charAt(0) == 'b') {
try { try {
build = Integer.parseInt(s.substring(1, s.length())); // valid format of the version string is:
break; // <major>.<minor>-bxx[-<identifier>][-<debug_flavor>]
} catch (NumberFormatException nfe) { int major = 0;
// ignore int minor = 0;
} int build = 0;
}
} String regex = "^([0-9]{1,2})"; // major
} regex += "\\."; // separator
} regex += "([0-9]{1,3})"; // minor
VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build); regex += "(\\-b([0-9]{1,3}))"; // JVM -bxx
System.out.printf("newVersionInfo: input=%s output=%s\n", version, vi); regex += ".*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(version);
m.matches();
major = Integer.parseInt(m.group(1));
minor = Integer.parseInt(m.group(2));
build = Integer.parseInt(m.group(4));
VersionInfo vi = new VersionInfo(major, minor, 0, 0, "", build);
System.out.printf("jvmVersionInfo: input=%s output=%s\n", version, vi);
return vi; return vi;
} catch (IllegalStateException e) {
// local builds may also follow the jdkVersionInfo format
return jdkVersionInfo(version);
}
} }
} }
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -36,17 +36,6 @@ public class AccessKeyStore { ...@@ -36,17 +36,6 @@ public class AccessKeyStore {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// Check if the provider is available
try {
Class.forName("sun.security.mscapi.SunMSCAPI");
} catch (Exception e) {
System.out.println(
"The SunMSCAPI provider is not available on this platform: " +
e);
return;
}
// Check that a security manager has been installed // Check that a security manager has been installed
if (System.getSecurityManager() == null) { if (System.getSecurityManager() == null) {
throw new Exception("A security manager has not been installed"); throw new Exception("A security manager has not been installed");
...@@ -86,8 +75,8 @@ public class AccessKeyStore { ...@@ -86,8 +75,8 @@ public class AccessKeyStore {
} }
int i = 0; int i = 0;
for (Enumeration e = keyStore.aliases(); e.hasMoreElements(); ) { for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements(); ) {
String alias = (String) e.nextElement(); String alias = e.nextElement();
displayEntry(keyStore, alias, i++); displayEntry(keyStore, alias, i++);
} }
} }
......
#!/bin/sh #!/bin/sh
# #
# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# @test # @test
# @bug 6324295 6931562 # @bug 6324295 6931562
# @requires os.family == "windows"
# @run shell AccessKeyStore.sh # @run shell AccessKeyStore.sh
# @summary Confirm that permission must be granted to access keystores. # @summary Confirm that permission must be granted to access keystores.
......
/* /*
* Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -33,16 +33,6 @@ public class IsSunMSCAPIAvailable { ...@@ -33,16 +33,6 @@ public class IsSunMSCAPIAvailable {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// Check if the provider is available
try {
Class.forName("sun.security.mscapi.SunMSCAPI");
} catch (Exception e) {
System.out.println(
"The SunMSCAPI provider is not available on this platform");
return;
}
// Dynamically register the SunMSCAPI provider // Dynamically register the SunMSCAPI provider
Security.addProvider(new sun.security.mscapi.SunMSCAPI()); Security.addProvider(new sun.security.mscapi.SunMSCAPI());
...@@ -58,7 +48,6 @@ public class IsSunMSCAPIAvailable { ...@@ -58,7 +48,6 @@ public class IsSunMSCAPIAvailable {
/* /*
* Secure Random * Secure Random
*/ */
SecureRandom random = SecureRandom.getInstance("Windows-PRNG", p); SecureRandom random = SecureRandom.getInstance("Windows-PRNG", p);
System.out.println(" Windows-PRNG is implemented by: " + System.out.println(" Windows-PRNG is implemented by: " +
random.getClass().getName()); random.getClass().getName());
......
#!/bin/sh #!/bin/sh
# #
# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# @test # @test
# @bug 6318171 6931562 # @bug 6318171 6931562
# @requires os.family == "windows"
# @run shell IsSunMSCAPIAvailable.sh # @run shell IsSunMSCAPIAvailable.sh
# @summary Basic test of the Microsoft CryptoAPI provider. # @summary Basic test of the Microsoft CryptoAPI provider.
......
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.InputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactorySpi;
import java.util.Collection;
import java.util.Enumeration;
/*
* @test
* @bug 8139436
* @summary This test validates an iteration over the Windows-ROOT certificate store
* and retrieving all certificates.
* Bug 8139436 reports an issue when 3rd party JCE providers would throw exceptions
* upon creating Certificate objects.
* This would for instance happen when using IAIK 3.15 and Elliptic Curve certificates
* are contained in the Windows-ROOT certificate store.
* The test uses a simple dummy provider which just throws Exceptions in its CertificateFactory.
* To test an external provider, you can use property sun.security.mscapi.testprovider and
* set it to the provider class name which has to be constructible by a constructor without
* arguments. The provider jar has to be added to the classpath.
* E.g. run jtreg with -javaoption:-Dsun.security.mscapi.testprovider=iaik.security.provider.IAIK and
* -cpa:<path to iaik_jce.jar>
*
* @requires os.family == "windows"
* @author Christoph Langer
* @run main IterateWindowsRootStore
*/
public class IterateWindowsRootStore {
public static class TestFactory extends CertificateFactorySpi {
@Override
public Certificate engineGenerateCertificate(InputStream inStream) throws CertificateException {
throw new CertificateException("unimplemented");
}
@Override
public Collection<? extends Certificate> engineGenerateCertificates(InputStream inStream) throws CertificateException {
throw new CertificateException("unimplemented");
}
@Override
public CRL engineGenerateCRL(InputStream inStream) throws CRLException {
throw new CRLException("unimplemented");
}
@Override
public Collection<? extends CRL> engineGenerateCRLs(InputStream inStream) throws CRLException {
throw new CRLException("unimplemented");
}
}
public static class TestProvider extends Provider {
private static final long serialVersionUID = 1L;
public TestProvider() {
super("TestProvider", 0.1, "Test provider for IterateWindowsRootStore");
/*
* Certificates
*/
this.put("CertificateFactory.X.509", "IterateWindowsRootStore$TestFactory");
this.put("Alg.Alias.CertificateFactory.X509", "X.509");
}
}
public static void main(String[] args) throws Exception {
// Try to register a JCE provider from property sun.security.mscapi.testprovider in the first slot
// otherwise register a dummy provider which would provoke the issue of bug 8139436
boolean providerPrepended = false;
String testprovider = System.getProperty("sun.security.mscapi.testprovider");
if (testprovider != null && !testprovider.isEmpty()) {
try {
System.out.println("Trying to prepend external JCE provider " + testprovider);
Class<?> providerclass = Class.forName(testprovider);
Object provider = providerclass.newInstance();
Security.insertProviderAt((Provider)provider, 1);
} catch (Exception e) {
System.out.println("Could not load JCE provider " + testprovider +". Exception is:");
e.printStackTrace(System.out);
}
providerPrepended = true;
System.out.println("Sucessfully prepended JCE provider " + testprovider);
}
if (!providerPrepended) {
System.out.println("Trying to prepend dummy JCE provider");
Security.insertProviderAt(new TestProvider(), 1);
System.out.println("Sucessfully prepended dummy JCE provider");
}
// load Windows-ROOT KeyStore
KeyStore keyStore = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
keyStore.load(null, null);
// iterate KeyStore
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
System.out.print("Reading certificate for alias: " + alias + "...");
keyStore.getCertificate(alias);
System.out.println(" done.");
}
}
}
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -38,17 +38,6 @@ public class KeyStoreCompatibilityMode { ...@@ -38,17 +38,6 @@ public class KeyStoreCompatibilityMode {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// Check if the provider is available
try {
Class.forName("sun.security.mscapi.SunMSCAPI");
} catch (Exception e) {
System.out.println(
"The SunMSCAPI provider is not available on this platform: " +
e);
return;
}
if (args.length > 0 && "-disable".equals(args[0])) { if (args.length > 0 && "-disable".equals(args[0])) {
mode = false; mode = false;
} else { } else {
......
#!/bin/sh #!/bin/sh
# #
# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -23,9 +23,9 @@ ...@@ -23,9 +23,9 @@
# questions. # questions.
# #
# @test # @test
# @bug 6324294 6931562 # @bug 6324294 6931562
# @requires os.family == "windows"
# @run shell KeyStoreCompatibilityMode.sh # @run shell KeyStoreCompatibilityMode.sh
# @summary Confirm that a null stream or password is not permitted when # @summary Confirm that a null stream or password is not permitted when
# compatibility mode is enabled (and vice versa). # compatibility mode is enabled (and vice versa).
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册