From e55eebc5ed578e1bf8558f68dd35297d8189810b Mon Sep 17 00:00:00 2001
From: Anthony Scarpino
Date: Mon, 14 Apr 2014 21:02:31 +0000
Subject: [PATCH 01/82] 8037846: Ensure streaming of input cipher streams
Reviewed-by: xuelei, valeriep
---
.../share/classes/javax/crypto/CipherInputStream.java | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
diff --git a/jdk/src/java.base/share/classes/javax/crypto/CipherInputStream.java b/jdk/src/java.base/share/classes/javax/crypto/CipherInputStream.java
index f9be4611d83..0930f9d6426 100644
--- a/jdk/src/java.base/share/classes/javax/crypto/CipherInputStream.java
+++ b/jdk/src/java.base/share/classes/javax/crypto/CipherInputStream.java
@@ -107,9 +107,10 @@ public class CipherInputStream extends FilterInputStream {
done = true;
try {
obuffer = cipher.doFinal();
+ } catch (IllegalBlockSizeException | BadPaddingException e) {
+ obuffer = null;
+ throw new IOException(e);
}
- catch (IllegalBlockSizeException e) {obuffer = null;}
- catch (BadPaddingException e) {obuffer = null;}
if (obuffer == null)
return -1;
else {
@@ -120,7 +121,10 @@ public class CipherInputStream extends FilterInputStream {
}
try {
obuffer = cipher.update(ibuffer, 0, readin);
- } catch (IllegalStateException e) {obuffer = null;};
+ } catch (IllegalStateException e) {
+ obuffer = null;
+ throw e;
+ }
ostart = 0;
if (obuffer == null)
ofinish = 0;
@@ -302,6 +306,7 @@ public class CipherInputStream extends FilterInputStream {
}
}
catch (BadPaddingException | IllegalBlockSizeException ex) {
+ throw new IOException(ex);
}
ostart = 0;
ofinish = 0;
From 1d8cb90952f7a6f9ccdaa7f77dc10eaa1c46f3a2 Mon Sep 17 00:00:00 2001
From: Naoto Sato
Date: Mon, 21 Apr 2014 11:08:30 -0700
Subject: [PATCH 02/82] 8036936: Use local locales
Made sure cache key is cleare on GC invocation
Reviewed-by: okutsu
---
.../classes/sun/util/locale/BaseLocale.java | 90 ++++++++++---------
.../sun/util/locale/LocaleObjectCache.java | 4 +-
2 files changed, 53 insertions(+), 41 deletions(-)
diff --git a/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java b/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java
index 137fd82f7dd..2f4da3d5960 100644
--- a/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java
+++ b/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java
@@ -31,6 +31,7 @@
*/
package sun.util.locale;
+import java.lang.ref.SoftReference;
import java.util.StringJoiner;
@@ -151,11 +152,11 @@ public final class BaseLocale {
return h;
}
- private static final class Key implements Comparable {
- private final String lang;
- private final String scrt;
- private final String regn;
- private final String vart;
+ private static final class Key {
+ private final SoftReference lang;
+ private final SoftReference scrt;
+ private final SoftReference regn;
+ private final SoftReference vart;
private final boolean normalized;
private final int hash;
@@ -167,10 +168,10 @@ public final class BaseLocale {
assert language.intern() == language
&& region.intern() == region;
- lang = language;
- scrt = "";
- regn = region;
- vart = "";
+ lang = new SoftReference<>(language);
+ scrt = new SoftReference<>("");
+ regn = new SoftReference<>(region);
+ vart = new SoftReference<>("");
this.normalized = true;
int h = language.hashCode();
@@ -191,40 +192,40 @@ public final class BaseLocale {
String variant, boolean normalized) {
int h = 0;
if (language != null) {
- lang = language;
+ lang = new SoftReference<>(language);
int len = language.length();
for (int i = 0; i < len; i++) {
h = 31*h + LocaleUtils.toLower(language.charAt(i));
}
} else {
- lang = "";
+ lang = new SoftReference<>("");
}
if (script != null) {
- scrt = script;
+ scrt = new SoftReference<>(script);
int len = script.length();
for (int i = 0; i < len; i++) {
h = 31*h + LocaleUtils.toLower(script.charAt(i));
}
} else {
- scrt = "";
+ scrt = new SoftReference<>("");
}
if (region != null) {
- regn = region;
+ regn = new SoftReference<>(region);
int len = region.length();
for (int i = 0; i < len; i++) {
h = 31*h + LocaleUtils.toLower(region.charAt(i));
}
} else {
- regn = "";
+ regn = new SoftReference<>("");
}
if (variant != null) {
- vart = variant;
+ vart = new SoftReference<>(variant);
int len = variant.length();
for (int i = 0; i < len; i++) {
h = 31*h + variant.charAt(i);
}
} else {
- vart = "";
+ vart = new SoftReference<>("");
}
hash = h;
this.normalized = normalized;
@@ -232,28 +233,31 @@ public final class BaseLocale {
@Override
public boolean equals(Object obj) {
- return (this == obj) ||
- (obj instanceof Key)
- && this.hash == ((Key)obj).hash
- && LocaleUtils.caseIgnoreMatch(((Key)obj).lang, this.lang)
- && LocaleUtils.caseIgnoreMatch(((Key)obj).scrt, this.scrt)
- && LocaleUtils.caseIgnoreMatch(((Key)obj).regn, this.regn)
- && ((Key)obj).vart.equals(vart); // variant is case sensitive in JDK!
- }
+ if (this == obj) {
+ return true;
+ }
- @Override
- public int compareTo(Key other) {
- int res = LocaleUtils.caseIgnoreCompare(this.lang, other.lang);
- if (res == 0) {
- res = LocaleUtils.caseIgnoreCompare(this.scrt, other.scrt);
- if (res == 0) {
- res = LocaleUtils.caseIgnoreCompare(this.regn, other.regn);
- if (res == 0) {
- res = this.vart.compareTo(other.vart);
+ if (obj instanceof Key && this.hash == ((Key)obj).hash) {
+ String tl = this.lang.get();
+ String ol = ((Key)obj).lang.get();
+ if (tl != null && ol != null &&
+ LocaleUtils.caseIgnoreMatch(ol, tl)) {
+ String ts = this.scrt.get();
+ String os = ((Key)obj).scrt.get();
+ if (ts != null && os != null &&
+ LocaleUtils.caseIgnoreMatch(os, ts)) {
+ String tr = this.regn.get();
+ String or = ((Key)obj).regn.get();
+ if (tr != null && or != null &&
+ LocaleUtils.caseIgnoreMatch(or, tr)) {
+ String tv = this.vart.get();
+ String ov = ((Key)obj).vart.get();
+ return (ov != null && ov.equals(tv));
+ }
}
}
}
- return res;
+ return false;
}
@Override
@@ -266,10 +270,10 @@ public final class BaseLocale {
return key;
}
- String lang = LocaleUtils.toLowerString(key.lang).intern();
- String scrt = LocaleUtils.toTitleString(key.scrt).intern();
- String regn = LocaleUtils.toUpperString(key.regn).intern();
- String vart = key.vart.intern(); // preserve upper/lower cases
+ String lang = LocaleUtils.toLowerString(key.lang.get()).intern();
+ String scrt = LocaleUtils.toTitleString(key.scrt.get()).intern();
+ String regn = LocaleUtils.toUpperString(key.regn.get()).intern();
+ String vart = key.vart.get().intern(); // preserve upper/lower cases
return new Key(lang, scrt, regn, vart, true);
}
@@ -282,12 +286,18 @@ public final class BaseLocale {
@Override
protected Key normalizeKey(Key key) {
+ assert key.lang.get() != null &&
+ key.scrt.get() != null &&
+ key.regn.get() != null &&
+ key.vart.get() != null;
+
return Key.normalize(key);
}
@Override
protected BaseLocale createObject(Key key) {
- return new BaseLocale(key.lang, key.scrt, key.regn, key.vart);
+ return new BaseLocale(key.lang.get(), key.scrt.get(),
+ key.regn.get(), key.vart.get());
}
}
}
diff --git a/jdk/src/java.base/share/classes/sun/util/locale/LocaleObjectCache.java b/jdk/src/java.base/share/classes/sun/util/locale/LocaleObjectCache.java
index 88920aaf50c..eae1480882b 100644
--- a/jdk/src/java.base/share/classes/sun/util/locale/LocaleObjectCache.java
+++ b/jdk/src/java.base/share/classes/sun/util/locale/LocaleObjectCache.java
@@ -57,8 +57,10 @@ public abstract class LocaleObjectCache {
value = entry.get();
}
if (value == null) {
- key = normalizeKey(key);
V newVal = createObject(key);
+ // make sure key is normalized *after* the object creation
+ // so that newVal is assured to be created from a valid key.
+ key = normalizeKey(key);
if (key == null || newVal == null) {
// subclass must return non-null key/value object
return null;
From 9cba51fbc5aba121d8809e5d91a7b185832197d0 Mon Sep 17 00:00:00 2001
From: Xue-Lei Andrew Fan
Date: Tue, 22 Apr 2014 00:43:56 +0000
Subject: [PATCH 03/82] 8037066: Secure transport layer
Reviewed-by: weijun, ahgross, asmotrak, mbankal
---
.../sun/security/ssl/ClientHandshaker.java | 193 +++++++++++++++++-
.../classes/sun/security/ssl/Handshaker.java | 13 +-
.../sun/security/ssl/SSLSessionImpl.java | 26 ++-
3 files changed, 223 insertions(+), 9 deletions(-)
diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java
index 5c3abbcdab5..5108528f283 100644
--- a/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -36,6 +36,8 @@ import java.security.spec.ECParameterSpec;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
+import java.security.cert.CertificateParsingException;
+import javax.security.auth.x500.X500Principal;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
@@ -89,11 +91,65 @@ final class ClientHandshaker extends Handshaker {
private final static boolean enableSNIExtension =
Debug.getBooleanProperty("jsse.enableSNIExtension", true);
+ /*
+ * Allow unsafe server certificate change?
+ *
+ * Server certificate change during SSL/TLS renegotiation may be considered
+ * unsafe, as described in the Triple Handshake attacks:
+ *
+ * https://secure-resumption.com/tlsauth.pdf
+ *
+ * Endpoint identification (See
+ * SSLParameters.getEndpointIdentificationAlgorithm()) is a pretty nice
+ * guarantee that the server certificate change in renegotiation is legal.
+ * However, endpoing identification is only enabled for HTTPS and LDAP
+ * over SSL/TLS by default. It is not enough to protect SSL/TLS
+ * connections other than HTTPS and LDAP.
+ *
+ * The renegotiation indication extension (See RFC 5764) is a pretty
+ * strong guarantee that the endpoints on both client and server sides
+ * are identical on the same connection. However, the Triple Handshake
+ * attacks can bypass this guarantee if there is a session-resumption
+ * handshake between the initial full handshake and the renegotiation
+ * full handshake.
+ *
+ * Server certificate change may be unsafe and should be restricted if
+ * endpoint identification is not enabled and the previous handshake is
+ * a session-resumption abbreviated initial handshake, unless the
+ * identities represented by both certificates can be regraded as the
+ * same (See isIdentityEquivalent()).
+ *
+ * Considering the compatibility impact and the actual requirements to
+ * support server certificate change in practice, the system property,
+ * jdk.tls.allowUnsafeServerCertChange, is used to define whether unsafe
+ * server certificate change in renegotiation is allowed or not. The
+ * default value of the system property is "false". To mitigate the
+ * compactibility impact, applications may want to set the system
+ * property to "true" at their own risk.
+ *
+ * If the value of the system property is "false", server certificate
+ * change in renegotiation after a session-resumption abbreviated initial
+ * handshake is restricted (See isIdentityEquivalent()).
+ *
+ * If the system property is set to "true" explicitly, the restriction on
+ * server certificate change in renegotiation is disabled.
+ */
+ private final static boolean allowUnsafeServerCertChange =
+ Debug.getBooleanProperty("jdk.tls.allowUnsafeServerCertChange", false);
+
private List requestedServerNames =
Collections.emptyList();
private boolean serverNamesAccepted = false;
+ /*
+ * the reserved server certificate chain in previous handshaking
+ *
+ * The server certificate chain is only reserved if the previous
+ * handshake is a session-resumption abbreviated initial handshake.
+ */
+ private X509Certificate[] reservedServerCerts = null;
+
/*
* Constructors
*/
@@ -555,14 +611,19 @@ final class ClientHandshaker extends Handshaker {
// we wanted to resume, but the server refused
session = null;
if (!enableNewSession) {
- throw new SSLException
- ("New session creation is disabled");
+ throw new SSLException("New session creation is disabled");
}
}
}
if (resumingSession && session != null) {
setHandshakeSessionSE(session);
+ // Reserve the handshake state if this is a session-resumption
+ // abbreviated initial handshake.
+ if (isInitialHandshake) {
+ session.setAsSessionResumption(true);
+ }
+
return;
}
@@ -1063,6 +1124,13 @@ final class ClientHandshaker extends Handshaker {
serverVerifyData = mesg.getVerifyData();
}
+ /*
+ * Reset the handshake state if this is not an initial handshake.
+ */
+ if (!isInitialHandshake) {
+ session.setAsSessionResumption(false);
+ }
+
/*
* OK, it verified. If we're doing the fast handshake, add that
* "Finished" message to the hash of handshake messages, then send
@@ -1161,8 +1229,23 @@ final class ClientHandshaker extends Handshaker {
System.out.println("%% No cached client session");
}
}
- if ((session != null) && (session.isRejoinable() == false)) {
- session = null;
+ if (session != null) {
+ // If unsafe server certificate change is not allowed, reserve
+ // current server certificates if the previous handshake is a
+ // session-resumption abbreviated initial handshake.
+ if (!allowUnsafeServerCertChange && session.isSessionResumption()) {
+ try {
+ // If existing, peer certificate chain cannot be null.
+ reservedServerCerts =
+ (X509Certificate[])session.getPeerCertificates();
+ } catch (SSLPeerUnverifiedException puve) {
+ // Maybe not certificate-based, ignore the exception.
+ }
+ }
+
+ if (!session.isRejoinable()) {
+ session = null;
+ }
}
if (session != null) {
@@ -1331,9 +1414,28 @@ final class ClientHandshaker extends Handshaker {
}
X509Certificate[] peerCerts = mesg.getCertificateChain();
if (peerCerts.length == 0) {
- fatalSE(Alerts.alert_bad_certificate,
- "empty certificate chain");
+ fatalSE(Alerts.alert_bad_certificate, "empty certificate chain");
}
+
+ // Allow server certificate change in client side during renegotiation
+ // after a session-resumption abbreviated initial handshake?
+ //
+ // DO NOT need to check allowUnsafeServerCertChange here. We only
+ // reserve server certificates when allowUnsafeServerCertChange is
+ // flase.
+ if (reservedServerCerts != null) {
+ // It is not necessary to check the certificate update if endpoint
+ // identification is enabled.
+ String identityAlg = getEndpointIdentificationAlgorithmSE();
+ if ((identityAlg == null || identityAlg.length() == 0) &&
+ !isIdentityEquivalent(peerCerts[0], reservedServerCerts[0])) {
+
+ fatalSE(Alerts.alert_bad_certificate,
+ "server certificate change is restricted " +
+ "during renegotiation");
+ }
+ }
+
// ask the trust manager to verify the chain
X509TrustManager tm = sslContext.getX509TrustManager();
try {
@@ -1370,4 +1472,81 @@ final class ClientHandshaker extends Handshaker {
}
session.setPeerCertificates(peerCerts);
}
+
+ /*
+ * Whether the certificates can represent the same identity?
+ *
+ * The certificates can be used to represent the same identity:
+ * 1. If the subject alternative names of IP address are present in
+ * both certificates, they should be identical; otherwise,
+ * 2. if the subject alternative names of DNS name are present in
+ * both certificates, they should be identical; otherwise,
+ * 3. if the subject fields are present in both certificates, the
+ * certificate subjects and issuers should be identical.
+ */
+ private static boolean isIdentityEquivalent(X509Certificate thisCert,
+ X509Certificate prevCert) {
+ if (thisCert.equals(prevCert)) {
+ return true;
+ }
+
+ // check the iPAddress field in subjectAltName extension
+ Object thisIPAddress = getSubjectAltName(thisCert, 7); // 7: iPAddress
+ Object prevIPAddress = getSubjectAltName(prevCert, 7);
+ if (thisIPAddress != null && prevIPAddress!= null) {
+ // only allow the exactly match
+ return Objects.equals(thisIPAddress, prevIPAddress);
+ }
+
+ // check the dNSName field in subjectAltName extension
+ Object thisDNSName = getSubjectAltName(thisCert, 2); // 2: dNSName
+ Object prevDNSName = getSubjectAltName(prevCert, 2);
+ if (thisDNSName != null && prevDNSName!= null) {
+ // only allow the exactly match
+ return Objects.equals(thisDNSName, prevDNSName);
+ }
+
+ // check the certificate subject and issuer
+ X500Principal thisSubject = thisCert.getSubjectX500Principal();
+ X500Principal prevSubject = prevCert.getSubjectX500Principal();
+ X500Principal thisIssuer = thisCert.getIssuerX500Principal();
+ X500Principal prevIssuer = prevCert.getIssuerX500Principal();
+ if (!thisSubject.getName().isEmpty() &&
+ !prevSubject.getName().isEmpty() &&
+ thisSubject.equals(prevSubject) &&
+ thisIssuer.equals(prevIssuer)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /*
+ * Returns the subject alternative name of the specified type in the
+ * subjectAltNames extension of a certificate.
+ */
+ private static Object getSubjectAltName(X509Certificate cert, int type) {
+ Collection> subjectAltNames;
+
+ try {
+ subjectAltNames = cert.getSubjectAlternativeNames();
+ } catch (CertificateParsingException cpe) {
+ if (debug != null && Debug.isOn("handshake")) {
+ System.out.println(
+ "Attempt to obtain subjectAltNames extension failed!");
+ }
+ return null;
+ }
+
+ if (subjectAltNames != null) {
+ for (List> subjectAltName : subjectAltNames) {
+ int subjectAltNameType = (Integer)subjectAltName.get(0);
+ if (subjectAltNameType == type) {
+ return subjectAltName.get(1);
+ }
+ }
+ }
+
+ return null;
+ }
}
diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java
index bea8608e6ff..80c2a518c1b 100644
--- a/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -359,6 +359,17 @@ abstract class Handshaker {
}
}
+ String getEndpointIdentificationAlgorithmSE() {
+ SSLParameters paras;
+ if (conn != null) {
+ paras = conn.getSSLParameters();
+ } else {
+ paras = engine.getSSLParameters();
+ }
+
+ return paras.getEndpointIdentificationAlgorithm();
+ }
+
private void setVersionSE(ProtocolVersion protocolVersion) {
if (conn != null) {
conn.setVersion(protocolVersion);
diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java
index 6cb4170d34f..b5f304b6b97 100644
--- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -114,6 +114,14 @@ final class SSLSessionImpl extends ExtendedSSLSession {
private Principal peerPrincipal;
private Principal localPrincipal;
+ /*
+ * Is the session currently re-established with a session-resumption
+ * abbreviated initial handshake?
+ *
+ * Note that currently we only set this variable in client side.
+ */
+ private boolean isSessionResumption = false;
+
/*
* We count session creations, eventually for statistical data but
* also since counters make shorter debugging IDs than the big ones
@@ -324,6 +332,22 @@ final class SSLSessionImpl extends ExtendedSSLSession {
}
}
+ /**
+ * Return true if the session is currently re-established with a
+ * session-resumption abbreviated initial handshake.
+ */
+ boolean isSessionResumption() {
+ return isSessionResumption;
+ }
+
+ /**
+ * Resets whether the session is re-established with a session-resumption
+ * abbreviated initial handshake.
+ */
+ void setAsSessionResumption(boolean flag) {
+ isSessionResumption = flag;
+ }
+
/**
* Returns the name of the cipher suite in use on this session
*/
From 62383e4a21c4eb80b11675523d86194b4a546abe Mon Sep 17 00:00:00 2001
From: Joe Darcy
Date: Tue, 22 Apr 2014 14:07:45 -0700
Subject: [PATCH 04/82] 8035781: Improve equality for annotations
Reviewed-by: jfranck, abuckley, ahgross, dmeetry
---
.../AnnotationInvocationHandler.java | 113 ++++++++++++++++--
1 file changed, 104 insertions(+), 9 deletions(-)
diff --git a/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java b/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java
index 6e73de70d52..120fe7aac16 100644
--- a/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java
+++ b/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,7 +29,6 @@ import java.lang.annotation.*;
import java.lang.reflect.*;
import java.io.Serializable;
import java.util.*;
-import java.lang.annotation.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -45,6 +44,11 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
private final Map memberValues;
AnnotationInvocationHandler(Class extends Annotation> type, Map memberValues) {
+ Class>[] superInterfaces = type.getInterfaces();
+ if (!type.isAnnotation() ||
+ superInterfaces.length != 1 ||
+ superInterfaces[0] != java.lang.annotation.Annotation.class)
+ throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type.");
this.type = type;
this.memberValues = memberValues;
}
@@ -57,13 +61,17 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
if (member.equals("equals") && paramTypes.length == 1 &&
paramTypes[0] == Object.class)
return equalsImpl(args[0]);
- assert paramTypes.length == 0;
- if (member.equals("toString"))
+ if (paramTypes.length != 0)
+ throw new AssertionError("Too many parameters for an annotation method");
+
+ switch(member) {
+ case "toString":
return toStringImpl();
- if (member.equals("hashCode"))
+ case "hashCode":
return hashCodeImpl();
- if (member.equals("annotationType"))
+ case "annotationType":
return type;
+ }
// Handle annotation member accessors
Object result = memberValues.get(member);
@@ -129,7 +137,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
* Implementation of dynamicProxy.toString()
*/
private String toStringImpl() {
- StringBuffer result = new StringBuffer(128);
+ StringBuilder result = new StringBuilder(128);
result.append('@');
result.append(type.getName());
result.append('(');
@@ -277,6 +285,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
new PrivilegedAction() {
public Method[] run() {
final Method[] mm = type.getDeclaredMethods();
+ validateAnnotationMethods(mm);
AccessibleObject.setAccessible(mm, true);
return mm;
}
@@ -286,6 +295,94 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
}
private transient volatile Method[] memberMethods = null;
+ /**
+ * Validates that a method is structurally appropriate for an
+ * annotation type. As of Java SE 8, annotation types cannot
+ * contain static methods and the declared methods of an
+ * annotation type must take zero arguments and there are
+ * restrictions on the return type.
+ */
+ private void validateAnnotationMethods(Method[] memberMethods) {
+ /*
+ * Specification citations below are from JLS
+ * 9.6.1. Annotation Type Elements
+ */
+ boolean valid = true;
+ for(Method method : memberMethods) {
+ /*
+ * "By virtue of the AnnotationTypeElementDeclaration
+ * production, a method declaration in an annotation type
+ * declaration cannot have formal parameters, type
+ * parameters, or a throws clause.
+ *
+ * "By virtue of the AnnotationTypeElementModifier
+ * production, a method declaration in an annotation type
+ * declaration cannot be default or static."
+ */
+ if (method.getModifiers() != (Modifier.PUBLIC | Modifier.ABSTRACT) ||
+ method.isDefault() ||
+ method.getParameterCount() != 0 ||
+ method.getExceptionTypes().length != 0) {
+ valid = false;
+ break;
+ }
+
+ /*
+ * "It is a compile-time error if the return type of a
+ * method declared in an annotation type is not one of the
+ * following: a primitive type, String, Class, any
+ * parameterized invocation of Class, an enum type
+ * (section 8.9), an annotation type, or an array type
+ * (chapter 10) whose element type is one of the preceding
+ * types."
+ */
+ Class> returnType = method.getReturnType();
+ if (returnType.isArray()) {
+ returnType = returnType.getComponentType();
+ if (returnType.isArray()) { // Only single dimensional arrays
+ valid = false;
+ break;
+ }
+ }
+
+ if (!((returnType.isPrimitive() && returnType != void.class) ||
+ returnType == java.lang.String.class ||
+ returnType == java.lang.Class.class ||
+ returnType.isEnum() ||
+ returnType.isAnnotation())) {
+ valid = false;
+ break;
+ }
+
+ /*
+ * "It is a compile-time error if any method declared in an
+ * annotation type has a signature that is
+ * override-equivalent to that of any public or protected
+ * method declared in class Object or in the interface
+ * java.lang.annotation.Annotation."
+ *
+ * The methods in Object or Annotation meeting the other
+ * criteria (no arguments, contrained return type, etc.)
+ * above are:
+ *
+ * String toString()
+ * int hashCode()
+ * Class extends Annotation> annotationType()
+ */
+ String methodName = method.getName();
+ if ((methodName.equals("toString") && returnType == java.lang.String.class) ||
+ (methodName.equals("hashCode") && returnType == int.class) ||
+ (methodName.equals("annotationType") && returnType == java.lang.Class.class)) {
+ valid = false;
+ break;
+ }
+ }
+ if (valid)
+ return;
+ else
+ throw new AnnotationFormatError("Malformed method on an annotation type");
+ }
+
/**
* Implementation of dynamicProxy.hashCode()
*/
@@ -330,7 +427,6 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
-
// Check to make sure that types have not evolved incompatibly
AnnotationType annotationType = null;
@@ -343,7 +439,6 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
Map> memberTypes = annotationType.memberTypes();
-
// If there are annotation members without values, that
// situation is handled by the invoke method.
for (Map.Entry memberValue : memberValues.entrySet()) {
From 5ce941b14301dfda807965e95fb501c4eb9eea42 Mon Sep 17 00:00:00 2001
From: Vladimir Ivanov
Date: Wed, 23 Apr 2014 09:06:22 -1000
Subject: [PATCH 05/82] 8037326: VerifyAccess.isMemberAccessible() has
incorrect access check
Reviewed-by: jrose, twisti, ahgross
---
.../classes/sun/invoke/util/VerifyAccess.java | 16 +++++++++++-----
1 file changed, 11 insertions(+), 5 deletions(-)
diff --git a/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java b/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java
index a95aefbafb1..fc870fc9403 100644
--- a/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java
+++ b/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java
@@ -102,19 +102,24 @@ public class VerifyAccess {
case PUBLIC:
return true; // already checked above
case PROTECTED:
+ assert !defc.isInterface(); // protected members aren't allowed in interfaces
if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
isSamePackage(defc, lookupClass))
return true;
if ((allowedModes & PROTECTED) == 0)
return false;
+ // Protected members are accessible by subclasses, which does not include interfaces.
+ // Interfaces are types, not classes. They should not have access to
+ // protected members in j.l.Object, even though it is their superclass.
if ((mods & STATIC) != 0 &&
!isRelatedClass(refc, lookupClass))
return false;
if ((allowedModes & PROTECTED) != 0 &&
- isSuperClass(defc, lookupClass))
+ isSubClass(lookupClass, defc))
return true;
return false;
case PACKAGE_ONLY: // That is, zero. Unmarked member is package-only access.
+ assert !defc.isInterface(); // package-private members aren't allowed in interfaces
return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
isSamePackage(defc, lookupClass));
case PRIVATE:
@@ -129,12 +134,13 @@ public class VerifyAccess {
static boolean isRelatedClass(Class> refc, Class> lookupClass) {
return (refc == lookupClass ||
- refc.isAssignableFrom(lookupClass) ||
- lookupClass.isAssignableFrom(refc));
+ isSubClass(refc, lookupClass) ||
+ isSubClass(lookupClass, refc));
}
- static boolean isSuperClass(Class> defc, Class> lookupClass) {
- return defc.isAssignableFrom(lookupClass);
+ static boolean isSubClass(Class> lookupClass, Class> defc) {
+ return defc.isAssignableFrom(lookupClass) &&
+ !lookupClass.isInterface(); // interfaces are types, not classes.
}
static int getClassModifiers(Class> c) {
From d124a839cec2e8247eec1353324e138fe029f186 Mon Sep 17 00:00:00 2001
From: Vladimir Kozlov
Date: Thu, 2 Oct 2014 11:36:44 -0700
Subject: [PATCH 06/82] 8059299: assert(adr_type != NULL) failed: expecting
TypeKlassPtr
Use top() for dead paths when initializing Phi node of exceptions klasses in Parse::catch_inline_exceptions().
Reviewed-by: jrose, vlivanov
---
hotspot/src/share/vm/opto/doCall.cpp | 14 +++-
hotspot/test/TEST.groups | 2 +-
.../exceptions/CatchInlineExceptions.java | 81 +++++++++++++++++++
3 files changed, 92 insertions(+), 5 deletions(-)
create mode 100644 hotspot/test/compiler/exceptions/CatchInlineExceptions.java
diff --git a/hotspot/src/share/vm/opto/doCall.cpp b/hotspot/src/share/vm/opto/doCall.cpp
index 62eb88460f1..813d9450fc3 100644
--- a/hotspot/src/share/vm/opto/doCall.cpp
+++ b/hotspot/src/share/vm/opto/doCall.cpp
@@ -802,10 +802,16 @@ void Parse::catch_inline_exceptions(SafePointNode* ex_map) {
// each arm of the Phi. If I know something clever about the exceptions
// I'm loading the class from, I can replace the LoadKlass with the
// klass constant for the exception oop.
- if( ex_node->is_Phi() ) {
- ex_klass_node = new PhiNode( ex_node->in(0), TypeKlassPtr::OBJECT );
- for( uint i = 1; i < ex_node->req(); i++ ) {
- Node* p = basic_plus_adr( ex_node->in(i), ex_node->in(i), oopDesc::klass_offset_in_bytes() );
+ if (ex_node->is_Phi()) {
+ ex_klass_node = new PhiNode(ex_node->in(0), TypeKlassPtr::OBJECT);
+ for (uint i = 1; i < ex_node->req(); i++) {
+ Node* ex_in = ex_node->in(i);
+ if (ex_in == top() || ex_in == NULL) {
+ // This path was not taken.
+ ex_klass_node->init_req(i, top());
+ continue;
+ }
+ Node* p = basic_plus_adr(ex_in, ex_in, oopDesc::klass_offset_in_bytes());
Node* k = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT) );
ex_klass_node->init_req( i, k );
}
diff --git a/hotspot/test/TEST.groups b/hotspot/test/TEST.groups
index 6ad554b58d8..a73ae8e5f5a 100644
--- a/hotspot/test/TEST.groups
+++ b/hotspot/test/TEST.groups
@@ -440,7 +440,7 @@ hotspot_compiler_3 = \
compiler/codegen/ \
compiler/cpuflags/RestoreMXCSR.java \
compiler/EscapeAnalysis/ \
- compiler/exceptions/TestRecursiveReplacedException.java \
+ compiler/exceptions/ \
compiler/floatingpoint/ModNaN.java \
compiler/gcbarriers/G1CrashTest.java \
compiler/inlining/ \
diff --git a/hotspot/test/compiler/exceptions/CatchInlineExceptions.java b/hotspot/test/compiler/exceptions/CatchInlineExceptions.java
new file mode 100644
index 00000000000..01be927cf7b
--- /dev/null
+++ b/hotspot/test/compiler/exceptions/CatchInlineExceptions.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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 8059299
+ * @summary assert(adr_type != NULL) failed: expecting TypeKlassPtr
+ * @run main/othervm -Xbatch CatchInlineExceptions
+ */
+
+class Exception1 extends Exception {};
+class Exception2 extends Exception {};
+
+public class CatchInlineExceptions {
+ private static int counter0;
+ private static int counter1;
+ private static int counter2;
+ private static int counter;
+
+ static void foo(int i) throws Exception {
+ if ((i & 1023) == 2) {
+ counter0++;
+ throw new Exception2();
+ }
+ }
+
+ static void test(int i) throws Exception {
+ try {
+ foo(i);
+ }
+ catch (Exception e) {
+ if (e instanceof Exception1) {
+ counter1++;
+ } else if (e instanceof Exception2) {
+ counter2++;
+ }
+ counter++;
+ throw e;
+ }
+ }
+
+ public static void main(String[] args) throws Throwable {
+ for (int i = 0; i < 15000; i++) {
+ try {
+ test(i);
+ } catch (Exception e) {
+ // expected
+ }
+ }
+ if (counter1 != 0) {
+ throw new RuntimeException("Failed: counter1(" + counter1 + ") != 0");
+ }
+ if (counter2 != counter) {
+ throw new RuntimeException("Failed: counter2(" + counter2 + ") != counter0(" + counter0 + ")");
+ }
+ if (counter2 != counter) {
+ throw new RuntimeException("Failed: counter2(" + counter2 + ") != counter(" + counter + ")");
+ }
+ System.out.println("TEST PASSED");
+ }
+}
From 3263a62bb4fbb74af2731c20cc0d84bedd6cff92 Mon Sep 17 00:00:00 2001
From: Goetz Lindenmaier
Date: Thu, 2 Oct 2014 09:32:53 +0200
Subject: [PATCH 07/82] 8059592: Recent bugfixes in ppc64 port
Reviewed-by: kvn
---
hotspot/make/aix/makefiles/fastdebug.make | 1 -
hotspot/src/cpu/ppc/vm/assembler_ppc.hpp | 117 +++++++++++++++++-
.../src/cpu/ppc/vm/assembler_ppc.inline.hpp | 52 ++++++++
.../src/cpu/ppc/vm/globalDefinitions_ppc.hpp | 2 +
hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp | 1 -
hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp | 1 -
hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp | 14 +--
hotspot/src/cpu/ppc/vm/ppc.ad | 58 +++++----
hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp | 6 +-
.../src/cpu/ppc/vm/templateTable_ppc_64.cpp | 4 -
.../vm/prefetch_linux_ppc.inline.hpp | 2 +-
11 files changed, 207 insertions(+), 51 deletions(-)
diff --git a/hotspot/make/aix/makefiles/fastdebug.make b/hotspot/make/aix/makefiles/fastdebug.make
index 40d792002e6..33bf50940b9 100644
--- a/hotspot/make/aix/makefiles/fastdebug.make
+++ b/hotspot/make/aix/makefiles/fastdebug.make
@@ -67,7 +67,6 @@ MAPFILE = $(GAMMADIR)/make/aix/makefiles/mapfile-vers-debug
# not justified.
LFLAGS_QIPA=
-G_SUFFIX = _g
VERSION = optimized
SYSDEFS += -DASSERT -DFASTDEBUG
PICFLAGS = DEFAULT
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
index 0c8cf435aea..7d9aecb310f 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
@@ -268,8 +268,35 @@ class Assembler : public AbstractAssembler {
ISEL_OPCODE = (31u << OPCODE_SHIFT | 15u << 1),
- MTLR_OPCODE = (31u << OPCODE_SHIFT | 467u << 1 | 8 << SPR_0_4_SHIFT),
- MFLR_OPCODE = (31u << OPCODE_SHIFT | 339u << 1 | 8 << SPR_0_4_SHIFT),
+ // Special purpose registers
+ MTSPR_OPCODE = (31u << OPCODE_SHIFT | 467u << 1),
+ MFSPR_OPCODE = (31u << OPCODE_SHIFT | 339u << 1),
+
+ MTXER_OPCODE = (MTSPR_OPCODE | 1 << SPR_0_4_SHIFT),
+ MFXER_OPCODE = (MFSPR_OPCODE | 1 << SPR_0_4_SHIFT),
+
+ MTDSCR_OPCODE = (MTSPR_OPCODE | 3 << SPR_0_4_SHIFT),
+ MFDSCR_OPCODE = (MFSPR_OPCODE | 3 << SPR_0_4_SHIFT),
+
+ MTLR_OPCODE = (MTSPR_OPCODE | 8 << SPR_0_4_SHIFT),
+ MFLR_OPCODE = (MFSPR_OPCODE | 8 << SPR_0_4_SHIFT),
+
+ MTCTR_OPCODE = (MTSPR_OPCODE | 9 << SPR_0_4_SHIFT),
+ MFCTR_OPCODE = (MFSPR_OPCODE | 9 << SPR_0_4_SHIFT),
+
+ MTTFHAR_OPCODE = (MTSPR_OPCODE | 128 << SPR_0_4_SHIFT),
+ MFTFHAR_OPCODE = (MFSPR_OPCODE | 128 << SPR_0_4_SHIFT),
+ MTTFIAR_OPCODE = (MTSPR_OPCODE | 129 << SPR_0_4_SHIFT),
+ MFTFIAR_OPCODE = (MFSPR_OPCODE | 129 << SPR_0_4_SHIFT),
+ MTTEXASR_OPCODE = (MTSPR_OPCODE | 130 << SPR_0_4_SHIFT),
+ MFTEXASR_OPCODE = (MFSPR_OPCODE | 130 << SPR_0_4_SHIFT),
+ MTTEXASRU_OPCODE = (MTSPR_OPCODE | 131 << SPR_0_4_SHIFT),
+ MFTEXASRU_OPCODE = (MFSPR_OPCODE | 131 << SPR_0_4_SHIFT),
+
+ MTVRSAVE_OPCODE = (MTSPR_OPCODE | 256 << SPR_0_4_SHIFT),
+ MFVRSAVE_OPCODE = (MFSPR_OPCODE | 256 << SPR_0_4_SHIFT),
+
+ MFTB_OPCODE = (MFSPR_OPCODE | 268 << SPR_0_4_SHIFT),
MTCRF_OPCODE = (31u << OPCODE_SHIFT | 144u << 1),
MFCR_OPCODE = (31u << OPCODE_SHIFT | 19u << 1),
@@ -291,9 +318,6 @@ class Assembler : public AbstractAssembler {
// CTR-related opcodes
BCCTR_OPCODE = (19u << OPCODE_SHIFT | 528u << 1),
- MTCTR_OPCODE = (31u << OPCODE_SHIFT | 467u << 1 | 9 << SPR_0_4_SHIFT),
- MFCTR_OPCODE = (31u << OPCODE_SHIFT | 339u << 1 | 9 << SPR_0_4_SHIFT),
-
LWZ_OPCODE = (32u << OPCODE_SHIFT),
LWZX_OPCODE = (31u << OPCODE_SHIFT | 23u << 1),
@@ -585,6 +609,37 @@ class Assembler : public AbstractAssembler {
MTVSCR_OPCODE = (4u << OPCODE_SHIFT | 1604u ),
MFVSCR_OPCODE = (4u << OPCODE_SHIFT | 1540u ),
+ // AES (introduced with Power 8)
+ VCIPHER_OPCODE = (4u << OPCODE_SHIFT | 1288u),
+ VCIPHERLAST_OPCODE = (4u << OPCODE_SHIFT | 1289u),
+ VNCIPHER_OPCODE = (4u << OPCODE_SHIFT | 1352u),
+ VNCIPHERLAST_OPCODE = (4u << OPCODE_SHIFT | 1353u),
+ VSBOX_OPCODE = (4u << OPCODE_SHIFT | 1480u),
+
+ // SHA (introduced with Power 8)
+ VSHASIGMAD_OPCODE = (4u << OPCODE_SHIFT | 1730u),
+ VSHASIGMAW_OPCODE = (4u << OPCODE_SHIFT | 1666u),
+
+ // Vector Binary Polynomial Multiplication (introduced with Power 8)
+ VPMSUMB_OPCODE = (4u << OPCODE_SHIFT | 1032u),
+ VPMSUMD_OPCODE = (4u << OPCODE_SHIFT | 1224u),
+ VPMSUMH_OPCODE = (4u << OPCODE_SHIFT | 1096u),
+ VPMSUMW_OPCODE = (4u << OPCODE_SHIFT | 1160u),
+
+ // Vector Permute and Xor (introduced with Power 8)
+ VPERMXOR_OPCODE = (4u << OPCODE_SHIFT | 45u),
+
+ // Transactional Memory instructions (introduced with Power 8)
+ TBEGIN_OPCODE = (31u << OPCODE_SHIFT | 654u << 1),
+ TEND_OPCODE = (31u << OPCODE_SHIFT | 686u << 1),
+ TABORT_OPCODE = (31u << OPCODE_SHIFT | 910u << 1),
+ TABORTWC_OPCODE = (31u << OPCODE_SHIFT | 782u << 1),
+ TABORTWCI_OPCODE = (31u << OPCODE_SHIFT | 846u << 1),
+ TABORTDC_OPCODE = (31u << OPCODE_SHIFT | 814u << 1),
+ TABORTDCI_OPCODE = (31u << OPCODE_SHIFT | 878u << 1),
+ TSR_OPCODE = (31u << OPCODE_SHIFT | 750u << 1),
+ TCHECK_OPCODE = (31u << OPCODE_SHIFT | 718u << 1),
+
// Icache and dcache related instructions
DCBA_OPCODE = (31u << OPCODE_SHIFT | 758u << 1),
DCBZ_OPCODE = (31u << OPCODE_SHIFT | 1014u << 1),
@@ -1420,6 +1475,25 @@ class Assembler : public AbstractAssembler {
inline void mcrf( ConditionRegister crd, ConditionRegister cra);
inline void mtcr( Register s);
+ // Special purpose registers
+ // Exception Register
+ inline void mtxer(Register s1);
+ inline void mfxer(Register d);
+ // Vector Register Save Register
+ inline void mtvrsave(Register s1);
+ inline void mfvrsave(Register d);
+ // Timebase
+ inline void mftb(Register d);
+ // Introduced with Power 8:
+ // Data Stream Control Register
+ inline void mtdscr(Register s1);
+ inline void mfdscr(Register d );
+ // Transactional Memory Registers
+ inline void mftfhar(Register d);
+ inline void mftfiar(Register d);
+ inline void mftexasr(Register d);
+ inline void mftexasru(Register d);
+
// PPC 1, section 2.4.1 Branch Instructions
inline void b( address a, relocInfo::relocType rt = relocInfo::none);
inline void b( Label& L);
@@ -1860,6 +1934,39 @@ class Assembler : public AbstractAssembler {
inline void mtvscr( VectorRegister b);
inline void mfvscr( VectorRegister d);
+ // AES (introduced with Power 8)
+ inline void vcipher( VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vcipherlast( VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vncipher( VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vncipherlast(VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vsbox( VectorRegister d, VectorRegister a);
+
+ // SHA (introduced with Power 8)
+ // Not yet implemented.
+
+ // Vector Binary Polynomial Multiplication (introduced with Power 8)
+ inline void vpmsumb( VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vpmsumd( VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vpmsumh( VectorRegister d, VectorRegister a, VectorRegister b);
+ inline void vpmsumw( VectorRegister d, VectorRegister a, VectorRegister b);
+
+ // Vector Permute and Xor (introduced with Power 8)
+ inline void vpermxor( VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c);
+
+ // Transactional Memory instructions (introduced with Power 8)
+ inline void tbegin_(); // R=0
+ inline void tbeginrot_(); // R=1 Rollback-Only Transaction
+ inline void tend_(); // A=0
+ inline void tendall_(); // A=1
+ inline void tabort_(Register a);
+ inline void tabortwc_(int t, Register a, Register b);
+ inline void tabortwci_(int t, Register a, int si);
+ inline void tabortdc_(int t, Register a, Register b);
+ inline void tabortdci_(int t, Register a, int si);
+ inline void tsuspend_(); // tsr with L=0
+ inline void tresume_(); // tsr with L=1
+ inline void tcheck(int f);
+
// The following encoders use r0 as second operand. These instructions
// read r0 as '0'.
inline void lwzx( Register d, Register s2);
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
index 87db4bff89d..b4a7370994d 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
@@ -312,6 +312,25 @@ inline void Assembler::mcrf( ConditionRegister crd, ConditionRegister cra)
{ emit_int32(MCRF_OPCODE | bf(crd) | bfa(cra)); }
inline void Assembler::mtcr( Register s) { Assembler::mtcrf(0xff, s); }
+// Special purpose registers
+// Exception Register
+inline void Assembler::mtxer(Register s1) { emit_int32(MTXER_OPCODE | rs(s1)); }
+inline void Assembler::mfxer(Register d ) { emit_int32(MFXER_OPCODE | rt(d)); }
+// Vector Register Save Register
+inline void Assembler::mtvrsave(Register s1) { emit_int32(MTVRSAVE_OPCODE | rs(s1)); }
+inline void Assembler::mfvrsave(Register d ) { emit_int32(MFVRSAVE_OPCODE | rt(d)); }
+// Timebase
+inline void Assembler::mftb(Register d ) { emit_int32(MFTB_OPCODE | rt(d)); }
+// Introduced with Power 8:
+// Data Stream Control Register
+inline void Assembler::mtdscr(Register s1) { emit_int32(MTDSCR_OPCODE | rs(s1)); }
+inline void Assembler::mfdscr(Register d ) { emit_int32(MFDSCR_OPCODE | rt(d)); }
+// Transactional Memory Registers
+inline void Assembler::mftfhar(Register d ) { emit_int32(MFTFHAR_OPCODE | rt(d)); }
+inline void Assembler::mftfiar(Register d ) { emit_int32(MFTFIAR_OPCODE | rt(d)); }
+inline void Assembler::mftexasr(Register d ) { emit_int32(MFTEXASR_OPCODE | rt(d)); }
+inline void Assembler::mftexasru(Register d ) { emit_int32(MFTEXASRU_OPCODE | rt(d)); }
+
// SAP JVM 2006-02-13 PPC branch instruction.
// PPC 1, section 2.4.1 Branch Instructions
inline void Assembler::b( address a, relocInfo::relocType rt) { emit_data(BXX_OPCODE| li(disp( intptr_t(a), intptr_t(pc()))) |aa(0)|lk(0), rt); }
@@ -735,6 +754,39 @@ inline void Assembler::vsrah( VectorRegister d, VectorRegister a, VectorRegist
inline void Assembler::mtvscr( VectorRegister b) { emit_int32( MTVSCR_OPCODE | vrb(b)); }
inline void Assembler::mfvscr( VectorRegister d) { emit_int32( MFVSCR_OPCODE | vrt(d)); }
+// AES (introduced with Power 8)
+inline void Assembler::vcipher( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VCIPHER_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vcipherlast( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VCIPHERLAST_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vncipher( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VNCIPHER_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vncipherlast(VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VNCIPHERLAST_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vsbox( VectorRegister d, VectorRegister a) { emit_int32( VSBOX_OPCODE | vrt(d) | vra(a) ); }
+
+// SHA (introduced with Power 8)
+// Not yet implemented.
+
+// Vector Binary Polynomial Multiplication (introduced with Power 8)
+inline void Assembler::vpmsumb( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMB_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vpmsumd( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMD_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vpmsumh( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMH_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vpmsumw( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMW_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+
+// Vector Permute and Xor (introduced with Power 8)
+inline void Assembler::vpermxor( VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c) { emit_int32( VPMSUMW_OPCODE | vrt(d) | vra(a) | vrb(b) | vrc(c)); }
+
+// Transactional Memory instructions (introduced with Power 8)
+inline void Assembler::tbegin_() { emit_int32( TBEGIN_OPCODE | rc(1)); }
+inline void Assembler::tbeginrot_() { emit_int32( TBEGIN_OPCODE | /*R=1*/ 1u << (31-10) | rc(1)); }
+inline void Assembler::tend_() { emit_int32( TEND_OPCODE | rc(1)); }
+inline void Assembler::tendall_() { emit_int32( TEND_OPCODE | /*A=1*/ 1u << (31-6) | rc(1)); }
+inline void Assembler::tabort_(Register a) { emit_int32( TABORT_OPCODE | ra(a) | rc(1)); }
+inline void Assembler::tabortwc_(int t, Register a, Register b) { emit_int32( TABORTWC_OPCODE | to(t) | ra(a) | rb(b) | rc(1)); }
+inline void Assembler::tabortwci_(int t, Register a, int si) { emit_int32( TABORTWCI_OPCODE | to(t) | ra(a) | sh1620(si) | rc(1)); }
+inline void Assembler::tabortdc_(int t, Register a, Register b) { emit_int32( TABORTDC_OPCODE | to(t) | ra(a) | rb(b) | rc(1)); }
+inline void Assembler::tabortdci_(int t, Register a, int si) { emit_int32( TABORTDCI_OPCODE | to(t) | ra(a) | sh1620(si) | rc(1)); }
+inline void Assembler::tsuspend_() { emit_int32( TSR_OPCODE | rc(1)); }
+inline void Assembler::tresume_() { emit_int32( TSR_OPCODE | /*L=1*/ 1u << (31-10) | rc(1)); }
+inline void Assembler::tcheck(int f) { emit_int32( TCHECK_OPCODE | bf(f)); }
+
// ra0 version
inline void Assembler::lwzx( Register d, Register s2) { emit_int32( LWZX_OPCODE | rt(d) | rb(s2));}
inline void Assembler::lwz( Register d, int si16 ) { emit_int32( LWZ_OPCODE | rt(d) | d1(si16));}
diff --git a/hotspot/src/cpu/ppc/vm/globalDefinitions_ppc.hpp b/hotspot/src/cpu/ppc/vm/globalDefinitions_ppc.hpp
index 4cd5efdd4c3..bd8bef477da 100644
--- a/hotspot/src/cpu/ppc/vm/globalDefinitions_ppc.hpp
+++ b/hotspot/src/cpu/ppc/vm/globalDefinitions_ppc.hpp
@@ -37,6 +37,8 @@ const int StackAlignmentInBytes = 16;
// signatures accordingly.
const bool CCallingConventionRequiresIntsAsLongs = true;
+#define SUPPORTS_NATIVE_CX8
+
// The PPC CPUs are NOT multiple-copy-atomic.
#define CPU_NOT_MULTIPLE_COPY_ATOMIC
diff --git a/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp b/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp
index 91decd076e7..6c89a18c03b 100644
--- a/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp
+++ b/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp
@@ -25,7 +25,6 @@
#include "precompiled.hpp"
-#include "asm/assembler.hpp"
#include "asm/macroAssembler.inline.hpp"
#include "interp_masm_ppc_64.hpp"
#include "interpreter/interpreterRuntime.hpp"
diff --git a/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp b/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp
index d64da8ea17a..be85db68c82 100644
--- a/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp
@@ -24,7 +24,6 @@
*/
#include "precompiled.hpp"
-#include "asm/assembler.hpp"
#include "asm/macroAssembler.inline.hpp"
#include "interpreter/bytecodeHistogram.hpp"
#include "interpreter/interpreter.hpp"
diff --git a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp
index 4366af19626..1b98de177dc 100644
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp
@@ -2366,7 +2366,7 @@ void MacroAssembler::g1_write_barrier_post(Register Rstore_addr, Register Rnew_v
#endif // INCLUDE_ALL_GCS
// Values for last_Java_pc, and last_Java_sp must comply to the rules
-// in frame_ppc64.hpp.
+// in frame_ppc.hpp.
void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc) {
// Always set last_Java_pc and flags first because once last_Java_sp
// is visible has_last_Java_frame is true and users will look at the
@@ -2493,6 +2493,7 @@ int MacroAssembler::instr_size_for_decode_klass_not_null() {
}
void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
+ assert(dst != R0, "Dst reg may not be R0, as R0 is used here.");
if (src == noreg) src = dst;
Register shifted_src = src;
if (Universe::narrow_klass_shift() != 0 ||
@@ -2527,14 +2528,11 @@ void MacroAssembler::load_klass_with_trap_null_check(Register dst, Register src)
void MacroAssembler::reinit_heapbase(Register d, Register tmp) {
if (Universe::heap() != NULL) {
- if (Universe::narrow_oop_base() == NULL) {
- Assembler::xorr(R30, R30, R30);
- } else {
- load_const(R30, Universe::narrow_ptrs_base(), tmp);
- }
+ load_const_optimized(R30, Universe::narrow_ptrs_base(), tmp);
} else {
- load_const(R30, Universe::narrow_ptrs_base_addr(), tmp);
- ld(R30, 0, R30);
+ // Heap not yet allocated. Load indirectly.
+ int simm16_offset = load_const_optimized(R30, Universe::narrow_ptrs_base_addr(), tmp, true);
+ ld(R30, simm16_offset, R30);
}
}
diff --git a/hotspot/src/cpu/ppc/vm/ppc.ad b/hotspot/src/cpu/ppc/vm/ppc.ad
index ab2d535bbc9..d68749c8ca1 100644
--- a/hotspot/src/cpu/ppc/vm/ppc.ad
+++ b/hotspot/src/cpu/ppc/vm/ppc.ad
@@ -1249,6 +1249,7 @@ EmitCallOffsets emit_call_with_trampoline_stub(MacroAssembler &_masm, address en
// Emit the trampoline stub which will be related to the branch-and-link below.
CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, offsets.insts_call_instruction_offset);
+ if (Compile::current()->env()->failing()) { return offsets; } // Code cache may be full.
__ relocate(rtype);
}
@@ -1410,7 +1411,7 @@ void MachPrologNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
while (bang_offset <= bang_end) {
// Need at least one stack bang at end of shadow zone.
- // Again I had to copy code, this time from assembler_ppc64.cpp,
+ // Again I had to copy code, this time from assembler_ppc.cpp,
// bang_stack_with_offset - see there for comments.
// Stack grows down, caller passes positive offset.
@@ -2000,7 +2001,7 @@ void MachUEPNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
// Inline_cache contains a klass.
Register ic_klass = as_Register(Matcher::inline_cache_reg_encode());
- Register receiver_klass = R0; // tmp
+ Register receiver_klass = R12_scratch2; // tmp
assert_different_registers(ic_klass, receiver_klass, R11_scratch1, R3_ARG1);
assert(R11_scratch1 == R11, "need prologue scratch register");
@@ -3484,6 +3485,7 @@ encode %{
// Emit the trampoline stub which will be related to the branch-and-link below.
CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, start_offset);
+ if (Compile::current()->env()->failing()) { return; } // Code cache may be full.
__ relocate(_optimized_virtual ?
relocInfo::opt_virtual_call_type : relocInfo::static_call_type);
}
@@ -3527,6 +3529,7 @@ encode %{
// Emit the trampoline stub which will be related to the branch-and-link below.
CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, start_offset);
+ if (ra_->C->env()->failing()) { return; } // Code cache may be full.
assert(_optimized_virtual, "methodHandle call should be a virtual call");
__ relocate(relocInfo::opt_virtual_call_type);
}
@@ -3577,9 +3580,7 @@ encode %{
const address entry_point_const = __ address_constant(entry_point, RelocationHolder::none);
const int entry_point_const_toc_offset = __ offset_to_method_toc(entry_point_const);
CallStubImpl::emit_trampoline_stub(_masm, entry_point_const_toc_offset, __ offset());
-
- if (ra_->C->env()->failing())
- return;
+ if (ra_->C->env()->failing()) { return; } // Code cache may be full.
// Build relocation at call site with ic position as data.
assert((_load_ic_hi_node != NULL && _load_ic_node == NULL) ||
@@ -5638,19 +5639,6 @@ instruct loadNKlass(iRegNdst dst, memory mem) %{
ins_pipe(pipe_class_memory);
%}
-//// Load compressed klass and decode it if narrow_klass_shift == 0.
-//// TODO: will narrow_klass_shift ever be 0?
-//instruct decodeNKlass2Klass(iRegPdst dst, memory mem) %{
-// match(Set dst (DecodeNKlass (LoadNKlass mem)));
-// predicate(false /* TODO: PPC port Universe::narrow_klass_shift() == 0*);
-// ins_cost(MEMORY_REF_COST);
-//
-// format %{ "LWZ $dst, $mem \t// DecodeNKlass (unscaled)" %}
-// size(4);
-// ins_encode( enc_lwz(dst, mem) );
-// ins_pipe(pipe_class_memory);
-//%}
-
// Load Klass Pointer
instruct loadKlass(iRegPdst dst, memoryAlg4 mem) %{
match(Set dst (LoadKlass mem));
@@ -6070,11 +6058,15 @@ instruct loadConN_Ex(iRegNdst dst, immN src) %{
%}
%}
-instruct loadConNKlass_hi(iRegNdst dst, immNKlass src) %{
+// We have seen a safepoint between the hi and lo parts, and this node was handled
+// as an oop. Therefore this needs a match rule so that build_oop_map knows this is
+// not a narrow oop.
+instruct loadConNKlass_hi(iRegNdst dst, immNKlass_NM src) %{
+ match(Set dst src);
effect(DEF dst, USE src);
ins_cost(DEFAULT_COST);
- format %{ "LIS $dst, $src \t// narrow oop hi" %}
+ format %{ "LIS $dst, $src \t// narrow klass hi" %}
size(4);
ins_encode %{
// TODO: PPC port $archOpcode(ppc64Opcode_addis);
@@ -6084,6 +6076,21 @@ instruct loadConNKlass_hi(iRegNdst dst, immNKlass src) %{
ins_pipe(pipe_class_default);
%}
+// As loadConNKlass_hi this must be recognized as narrow klass, not oop!
+instruct loadConNKlass_mask(iRegNdst dst, immNKlass_NM src1, iRegNsrc src2) %{
+ match(Set dst src1);
+ effect(TEMP src2);
+ ins_cost(DEFAULT_COST);
+
+ format %{ "MASK $dst, $src2, 0xFFFFFFFF" %} // mask
+ size(4);
+ ins_encode %{
+ // TODO: PPC port $archOpcode(ppc64Opcode_rldicl);
+ __ clrldi($dst$$Register, $src2$$Register, 0x20);
+ %}
+ ins_pipe(pipe_class_default);
+%}
+
// This needs a match rule so that build_oop_map knows this is
// not a narrow oop.
instruct loadConNKlass_lo(iRegNdst dst, immNKlass_NM src1, iRegNsrc src2) %{
@@ -6091,10 +6098,10 @@ instruct loadConNKlass_lo(iRegNdst dst, immNKlass_NM src1, iRegNsrc src2) %{
effect(TEMP src2);
ins_cost(DEFAULT_COST);
- format %{ "ADDI $dst, $src1, $src2 \t// narrow oop lo" %}
+ format %{ "ORI $dst, $src1, $src2 \t// narrow klass lo" %}
size(4);
ins_encode %{
- // TODO: PPC port $archOpcode(ppc64Opcode_addi);
+ // TODO: PPC port $archOpcode(ppc64Opcode_ori);
intptr_t Csrc = Klass::encode_klass((Klass *)$src1$$constant);
assert(__ oop_recorder() != NULL, "this assembler needs an OopRecorder");
int klass_index = __ oop_recorder()->find_index((Klass *)$src1$$constant);
@@ -6125,10 +6132,11 @@ instruct loadConNKlass_Ex(iRegNdst dst, immNKlass src) %{
MachNode *m2 = m1;
if (!Assembler::is_uimm((jlong)Klass::encode_klass((Klass *)op_src->constant()), 31)) {
// Value might be 1-extended. Mask out these bits.
- m2 = new clearMs32bNode();
+ m2 = new loadConNKlass_maskNode();
m2->add_req(NULL, m1);
m2->_opnds[0] = op_dst;
- m2->_opnds[1] = op_dst;
+ m2->_opnds[1] = op_src;
+ m2->_opnds[2] = op_dst;
ra_->set_pair(m2->_idx, ra_->get_reg_second(this), ra_->get_reg_first(this));
nodes->push(m2);
}
@@ -6973,7 +6981,7 @@ instruct encodePKlass_32GAligned(iRegNdst dst, iRegPsrc src) %{
size(4);
ins_encode %{
// TODO: PPC port $archOpcode(ppc64Opcode_rldicl);
- __ rldicl($dst$$Register, $src$$Register, 64-Universe::narrow_oop_shift(), 32);
+ __ rldicl($dst$$Register, $src$$Register, 64-Universe::narrow_klass_shift(), 32);
%}
ins_pipe(pipe_class_default);
%}
diff --git a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
index 290a4be01b0..0f8c752cacc 100644
--- a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
@@ -24,7 +24,6 @@
*/
#include "precompiled.hpp"
-#include "asm/assembler.hpp"
#include "asm/macroAssembler.inline.hpp"
#include "interpreter/interpreter.hpp"
#include "nativeInst_ppc.hpp"
@@ -39,9 +38,6 @@
#include "runtime/stubCodeGenerator.hpp"
#include "runtime/stubRoutines.hpp"
#include "utilities/top.hpp"
-#ifdef COMPILER2
-#include "opto/runtime.hpp"
-#endif
#include "runtime/thread.inline.hpp"
#define __ _masm->
@@ -216,7 +212,7 @@ class StubGenerator: public StubCodeGenerator {
{
BLOCK_COMMENT("Call frame manager or native entry.");
// Call frame manager or native entry.
- Register r_new_arg_entry = R14; // PPC_state;
+ Register r_new_arg_entry = R14;
assert_different_registers(r_new_arg_entry, r_top_of_arguments_addr,
r_arg_method, r_arg_thread);
diff --git a/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp b/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp
index 663c5744095..f0c7097abbd 100644
--- a/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp
+++ b/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp
@@ -353,7 +353,6 @@ void TemplateTable::ldc(bool wide) {
__ sldi(Rscratch1, Rscratch1, LogBytesPerWord);
__ cmpdi(CCR0, Rscratch2, JVM_CONSTANT_Integer);
__ bne(CCR0, notInt);
- __ isync(); // Order load of constant wrt. tags.
__ lwax(R17_tos, Rcpool, Rscratch1);
__ push(itos);
__ b(exit);
@@ -365,7 +364,6 @@ void TemplateTable::ldc(bool wide) {
__ cmpdi(CCR0, Rscratch2, JVM_CONSTANT_Float);
__ asm_assert_eq("unexpected type", 0x8765);
#endif
- __ isync(); // Order load of constant wrt. tags.
__ lfsx(F15_ftos, Rcpool, Rscratch1);
__ push(ftos);
@@ -424,13 +422,11 @@ void TemplateTable::ldc2_w() {
// Check out Conversions.java for an example.
// Also ConstantPool::header_size() is 20, which makes it very difficult
// to double-align double on the constant pool. SG, 11/7/97
- __ isync(); // Order load of constant wrt. tags.
__ lfdx(F15_ftos, Rcpool, Rindex);
__ push(dtos);
__ b(Lexit);
__ bind(Llong);
- __ isync(); // Order load of constant wrt. tags.
__ ldx(R17_tos, Rcpool, Rindex);
__ push(ltos);
diff --git a/hotspot/src/os_cpu/linux_ppc/vm/prefetch_linux_ppc.inline.hpp b/hotspot/src/os_cpu/linux_ppc/vm/prefetch_linux_ppc.inline.hpp
index c14df6ef9d3..c3b880f87ac 100644
--- a/hotspot/src/os_cpu/linux_ppc/vm/prefetch_linux_ppc.inline.hpp
+++ b/hotspot/src/os_cpu/linux_ppc/vm/prefetch_linux_ppc.inline.hpp
@@ -47,4 +47,4 @@ inline void Prefetch::write(void *loc, intx interval) {
);
}
-#endif // OS_CPU_LINUX_PPC_VM_PREFETCH_LINUX_OJDKPPC_HPP
+#endif // OS_CPU_LINUX_PPC_VM_PREFETCH_LINUX_PPC_INLINE_HPP
From 0ba49695491589e57839eb44852e1941b3f32bd5 Mon Sep 17 00:00:00 2001
From: Aleksey Shipilev
Date: Thu, 2 Oct 2014 17:13:31 +0400
Subject: [PATCH 08/82] 8059595: Verifier::verify is wasting time before
is_eligible_for_verification check
Do the check earlier.
Reviewed-by: hseigel, kamg
---
hotspot/src/share/vm/classfile/verifier.cpp | 73 +++++++++++----------
1 file changed, 38 insertions(+), 35 deletions(-)
diff --git a/hotspot/src/share/vm/classfile/verifier.cpp b/hotspot/src/share/vm/classfile/verifier.cpp
index 36ec76d6e5d..877eebd0e0b 100644
--- a/hotspot/src/share/vm/classfile/verifier.cpp
+++ b/hotspot/src/share/vm/classfile/verifier.cpp
@@ -98,6 +98,14 @@ bool Verifier::verify(instanceKlassHandle klass, Verifier::Mode mode, bool shoul
HandleMark hm;
ResourceMark rm(THREAD);
+ if (!is_eligible_for_verification(klass, should_verify_class)) {
+ return true;
+ }
+
+ // If the class should be verified, first see if we can use the split
+ // verifier. If not, or if verification fails and FailOverToOldVerifier
+ // is set, then call the inference verifier.
+
Symbol* exception_name = NULL;
const size_t message_buffer_len = klass->name()->utf8_length() + 1024;
char* message_buffer = NEW_RESOURCE_ARRAY(char, message_buffer_len);
@@ -105,47 +113,42 @@ bool Verifier::verify(instanceKlassHandle klass, Verifier::Mode mode, bool shoul
const char* klassName = klass->external_name();
bool can_failover = FailOverToOldVerifier &&
- klass->major_version() < NOFAILOVER_MAJOR_VERSION;
+ klass->major_version() < NOFAILOVER_MAJOR_VERSION;
- // If the class should be verified, first see if we can use the split
- // verifier. If not, or if verification fails and FailOverToOldVerifier
- // is set, then call the inference verifier.
- if (is_eligible_for_verification(klass, should_verify_class)) {
- if (TraceClassInitialization) {
- tty->print_cr("Start class verification for: %s", klassName);
- }
- if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
- ClassVerifier split_verifier(klass, THREAD);
- split_verifier.verify_class(THREAD);
- exception_name = split_verifier.result();
- if (can_failover && !HAS_PENDING_EXCEPTION &&
- (exception_name == vmSymbols::java_lang_VerifyError() ||
- exception_name == vmSymbols::java_lang_ClassFormatError())) {
- if (TraceClassInitialization || VerboseVerification) {
- tty->print_cr(
- "Fail over class verification to old verifier for: %s", klassName);
- }
- exception_name = inference_verify(
- klass, message_buffer, message_buffer_len, THREAD);
+ if (TraceClassInitialization) {
+ tty->print_cr("Start class verification for: %s", klassName);
+ }
+ if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
+ ClassVerifier split_verifier(klass, THREAD);
+ split_verifier.verify_class(THREAD);
+ exception_name = split_verifier.result();
+ if (can_failover && !HAS_PENDING_EXCEPTION &&
+ (exception_name == vmSymbols::java_lang_VerifyError() ||
+ exception_name == vmSymbols::java_lang_ClassFormatError())) {
+ if (TraceClassInitialization || VerboseVerification) {
+ tty->print_cr(
+ "Fail over class verification to old verifier for: %s", klassName);
}
- if (exception_name != NULL) {
- exception_message = split_verifier.exception_message();
- }
- } else {
exception_name = inference_verify(
- klass, message_buffer, message_buffer_len, THREAD);
+ klass, message_buffer, message_buffer_len, THREAD);
}
+ if (exception_name != NULL) {
+ exception_message = split_verifier.exception_message();
+ }
+ } else {
+ exception_name = inference_verify(
+ klass, message_buffer, message_buffer_len, THREAD);
+ }
- if (TraceClassInitialization || VerboseVerification) {
- if (HAS_PENDING_EXCEPTION) {
- tty->print("Verification for %s has", klassName);
- tty->print_cr(" exception pending %s ",
- InstanceKlass::cast(PENDING_EXCEPTION->klass())->external_name());
- } else if (exception_name != NULL) {
- tty->print_cr("Verification for %s failed", klassName);
- }
- tty->print_cr("End class verification for: %s", klassName);
+ if (TraceClassInitialization || VerboseVerification) {
+ if (HAS_PENDING_EXCEPTION) {
+ tty->print("Verification for %s has", klassName);
+ tty->print_cr(" exception pending %s ",
+ InstanceKlass::cast(PENDING_EXCEPTION->klass())->external_name());
+ } else if (exception_name != NULL) {
+ tty->print_cr("Verification for %s failed", klassName);
}
+ tty->print_cr("End class verification for: %s", klassName);
}
if (HAS_PENDING_EXCEPTION) {
From 90200446c1fc1fea38479a9381ef7dbf676a0a6f Mon Sep 17 00:00:00 2001
From: Coleen Phillimore
Date: Thu, 2 Oct 2014 16:31:44 -0400
Subject: [PATCH 09/82] 8047736: Remove JVM_GetClassLoader as no longer used
Remove this function from hotspot. It's already removed from the JDK.
Reviewed-by: mchung, fparain, ctornqvi
---
hotspot/make/aix/makefiles/mapfile-vers-debug | 1 -
hotspot/make/aix/makefiles/mapfile-vers-product | 1 -
hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug | 1 -
.../make/bsd/makefiles/mapfile-vers-darwin-product | 1 -
hotspot/make/bsd/makefiles/mapfile-vers-debug | 1 -
hotspot/make/bsd/makefiles/mapfile-vers-product | 1 -
hotspot/make/linux/makefiles/mapfile-vers-debug | 1 -
hotspot/make/linux/makefiles/mapfile-vers-product | 1 -
hotspot/make/solaris/makefiles/mapfile-vers | 1 -
hotspot/src/share/vm/prims/jvm.cpp | 11 -----------
hotspot/src/share/vm/prims/jvm.h | 3 ---
11 files changed, 23 deletions(-)
diff --git a/hotspot/make/aix/makefiles/mapfile-vers-debug b/hotspot/make/aix/makefiles/mapfile-vers-debug
index 613e26bd880..49beedda9ed 100644
--- a/hotspot/make/aix/makefiles/mapfile-vers-debug
+++ b/hotspot/make/aix/makefiles/mapfile-vers-debug
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/make/aix/makefiles/mapfile-vers-product b/hotspot/make/aix/makefiles/mapfile-vers-product
index 0b8a040c74a..8adbf613849 100644
--- a/hotspot/make/aix/makefiles/mapfile-vers-product
+++ b/hotspot/make/aix/makefiles/mapfile-vers-product
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug
index 7f7f00036fe..adf6616885a 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug
@@ -115,7 +115,6 @@
_JVM_GetClassDeclaredMethods
_JVM_GetClassFieldsCount
_JVM_GetClassInterfaces
- _JVM_GetClassLoader
_JVM_GetClassMethodsCount
_JVM_GetClassModifiers
_JVM_GetClassName
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product
index 7f7f00036fe..adf6616885a 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product
@@ -115,7 +115,6 @@
_JVM_GetClassDeclaredMethods
_JVM_GetClassFieldsCount
_JVM_GetClassInterfaces
- _JVM_GetClassLoader
_JVM_GetClassMethodsCount
_JVM_GetClassModifiers
_JVM_GetClassName
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-debug b/hotspot/make/bsd/makefiles/mapfile-vers-debug
index f7d88125ab5..6c79e8b9b75 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-debug
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-product b/hotspot/make/bsd/makefiles/mapfile-vers-product
index f7d88125ab5..6c79e8b9b75 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-product
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-product
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/make/linux/makefiles/mapfile-vers-debug b/hotspot/make/linux/makefiles/mapfile-vers-debug
index f7d88125ab5..6c79e8b9b75 100644
--- a/hotspot/make/linux/makefiles/mapfile-vers-debug
+++ b/hotspot/make/linux/makefiles/mapfile-vers-debug
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/make/linux/makefiles/mapfile-vers-product b/hotspot/make/linux/makefiles/mapfile-vers-product
index f7d88125ab5..6c79e8b9b75 100644
--- a/hotspot/make/linux/makefiles/mapfile-vers-product
+++ b/hotspot/make/linux/makefiles/mapfile-vers-product
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/make/solaris/makefiles/mapfile-vers b/hotspot/make/solaris/makefiles/mapfile-vers
index 9bf34ff8305..51cb3f9657b 100644
--- a/hotspot/make/solaris/makefiles/mapfile-vers
+++ b/hotspot/make/solaris/makefiles/mapfile-vers
@@ -117,7 +117,6 @@ SUNWprivate_1.1 {
JVM_GetClassDeclaredMethods;
JVM_GetClassFieldsCount;
JVM_GetClassInterfaces;
- JVM_GetClassLoader;
JVM_GetClassMethodsCount;
JVM_GetClassModifiers;
JVM_GetClassName;
diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp
index 1a51e80e00e..fa02d67b4a7 100644
--- a/hotspot/src/share/vm/prims/jvm.cpp
+++ b/hotspot/src/share/vm/prims/jvm.cpp
@@ -1073,17 +1073,6 @@ JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
JVM_END
-JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))
- JVMWrapper("JVM_GetClassLoader");
- if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
- return NULL;
- }
- Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
- oop loader = k->class_loader();
- return JNIHandles::make_local(env, loader);
-JVM_END
-
-
JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
JVMWrapper("JVM_IsInterface");
oop mirror = JNIHandles::resolve_non_null(cls);
diff --git a/hotspot/src/share/vm/prims/jvm.h b/hotspot/src/share/vm/prims/jvm.h
index 72278843ab2..c1aa8080cd3 100644
--- a/hotspot/src/share/vm/prims/jvm.h
+++ b/hotspot/src/share/vm/prims/jvm.h
@@ -462,9 +462,6 @@ JVM_GetClassName(JNIEnv *env, jclass cls);
JNIEXPORT jobjectArray JNICALL
JVM_GetClassInterfaces(JNIEnv *env, jclass cls);
-JNIEXPORT jobject JNICALL
-JVM_GetClassLoader(JNIEnv *env, jclass cls);
-
JNIEXPORT jboolean JNICALL
JVM_IsInterface(JNIEnv *env, jclass cls);
From c39454ae56e4bf02589612944e7862e4779a9912 Mon Sep 17 00:00:00 2001
From: Igor Veresov
Date: Fri, 3 Oct 2014 13:34:46 -0700
Subject: [PATCH 10/82] 8059621: JVM crashes with "unexpected index type"
assert in LIRGenerator::do_UnsafeGetRaw
Get types from LIR instructions instead of HIR
Reviewed-by: kvn
---
hotspot/src/share/vm/c1/c1_LIRGenerator.cpp | 20 ++++++++++----------
1 file changed, 10 insertions(+), 10 deletions(-)
diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
index 3515a322477..2beb72a60f1 100644
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
@@ -2069,14 +2069,14 @@ void LIRGenerator::do_UnsafeGetRaw(UnsafeGetRaw* x) {
LIR_Opr base_op = base.result();
LIR_Opr index_op = idx.result();
#ifndef _LP64
- if (x->base()->type()->tag() == longTag) {
+ if (base_op->type() == T_LONG) {
base_op = new_register(T_INT);
__ convert(Bytecodes::_l2i, base.result(), base_op);
}
if (x->has_index()) {
- if (x->index()->type()->tag() == longTag) {
+ if (index_op->type() == T_LONG) {
LIR_Opr long_index_op = index_op;
- if (x->index()->type()->is_constant()) {
+ if (index_op->is_constant()) {
long_index_op = new_register(T_LONG);
__ move(index_op, long_index_op);
}
@@ -2091,14 +2091,14 @@ void LIRGenerator::do_UnsafeGetRaw(UnsafeGetRaw* x) {
assert(!x->has_index() || index_op->type() == T_INT, "index should be an int");
#else
if (x->has_index()) {
- if (x->index()->type()->tag() == intTag) {
- if (!x->index()->type()->is_constant()) {
+ if (index_op->type() == T_INT) {
+ if (!index_op->is_constant()) {
index_op = new_register(T_LONG);
__ convert(Bytecodes::_i2l, idx.result(), index_op);
}
} else {
- assert(x->index()->type()->tag() == longTag, "must be");
- if (x->index()->type()->is_constant()) {
+ assert(index_op->type() == T_LONG, "must be");
+ if (index_op->is_constant()) {
index_op = new_register(T_LONG);
__ move(idx.result(), index_op);
}
@@ -2179,12 +2179,12 @@ void LIRGenerator::do_UnsafePutRaw(UnsafePutRaw* x) {
LIR_Opr index_op = idx.result();
#ifndef _LP64
- if (x->base()->type()->tag() == longTag) {
+ if (base_op->type() == T_LONG) {
base_op = new_register(T_INT);
__ convert(Bytecodes::_l2i, base.result(), base_op);
}
if (x->has_index()) {
- if (x->index()->type()->tag() == longTag) {
+ if (index_op->type() == T_LONG) {
index_op = new_register(T_INT);
__ convert(Bytecodes::_l2i, idx.result(), index_op);
}
@@ -2194,7 +2194,7 @@ void LIRGenerator::do_UnsafePutRaw(UnsafePutRaw* x) {
assert(!x->has_index() || (index_op->type() == T_INT && !index_op->is_constant()), "index should be an non-constant int");
#else
if (x->has_index()) {
- if (x->index()->type()->tag() == intTag) {
+ if (index_op->type() == T_INT) {
index_op = new_register(T_LONG);
__ convert(Bytecodes::_i2l, idx.result(), index_op);
}
From db57351f4352dda9fbfd8c59d1943e760c84b83b Mon Sep 17 00:00:00 2001
From: Chris Plummer
Date: Fri, 3 Oct 2014 13:56:18 -0700
Subject: [PATCH 11/82] 8046607: Code cleanup:
PerfMemory::backing_store_filename() should be removed
Removed PerfMemory::backing_store_filename() API since it is not used anywhere.
Reviewed-by: sla, hseigel
---
hotspot/src/os/aix/vm/perfMemory_aix.cpp | 4 ----
hotspot/src/os/bsd/vm/perfMemory_bsd.cpp | 4 ----
hotspot/src/os/linux/vm/perfMemory_linux.cpp | 4 ----
hotspot/src/os/solaris/vm/perfMemory_solaris.cpp | 4 ----
hotspot/src/os/windows/vm/perfMemory_windows.cpp | 4 ----
hotspot/src/share/vm/runtime/perfMemory.hpp | 3 ---
6 files changed, 23 deletions(-)
diff --git a/hotspot/src/os/aix/vm/perfMemory_aix.cpp b/hotspot/src/os/aix/vm/perfMemory_aix.cpp
index a30919c70df..36644f0f679 100644
--- a/hotspot/src/os/aix/vm/perfMemory_aix.cpp
+++ b/hotspot/src/os/aix/vm/perfMemory_aix.cpp
@@ -1020,7 +1020,3 @@ void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
unmap_shared(addr, bytes);
}
-
-char* PerfMemory::backing_store_filename() {
- return backing_store_file_name;
-}
diff --git a/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp b/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp
index 2737fe38ce1..631366e2944 100644
--- a/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp
+++ b/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp
@@ -1043,7 +1043,3 @@ void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
unmap_shared(addr, bytes);
}
-
-char* PerfMemory::backing_store_filename() {
- return backing_store_file_name;
-}
diff --git a/hotspot/src/os/linux/vm/perfMemory_linux.cpp b/hotspot/src/os/linux/vm/perfMemory_linux.cpp
index 2eef5da69f9..6d92575563e 100644
--- a/hotspot/src/os/linux/vm/perfMemory_linux.cpp
+++ b/hotspot/src/os/linux/vm/perfMemory_linux.cpp
@@ -1049,7 +1049,3 @@ void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
unmap_shared(addr, bytes);
}
-
-char* PerfMemory::backing_store_filename() {
- return backing_store_file_name;
-}
diff --git a/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp b/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp
index 2d279af0c2b..7f956338e6b 100644
--- a/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp
+++ b/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp
@@ -1068,7 +1068,3 @@ void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
unmap_shared(addr, bytes);
}
-
-char* PerfMemory::backing_store_filename() {
- return backing_store_file_name;
-}
diff --git a/hotspot/src/os/windows/vm/perfMemory_windows.cpp b/hotspot/src/os/windows/vm/perfMemory_windows.cpp
index e1b59253e82..edbd0bf622d 100644
--- a/hotspot/src/os/windows/vm/perfMemory_windows.cpp
+++ b/hotspot/src/os/windows/vm/perfMemory_windows.cpp
@@ -1846,7 +1846,3 @@ void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
remove_file_mapping(addr);
}
}
-
-char* PerfMemory::backing_store_filename() {
- return sharedmem_fileName;
-}
diff --git a/hotspot/src/share/vm/runtime/perfMemory.hpp b/hotspot/src/share/vm/runtime/perfMemory.hpp
index 18a2efd2f55..07e119ef8f8 100644
--- a/hotspot/src/share/vm/runtime/perfMemory.hpp
+++ b/hotspot/src/share/vm/runtime/perfMemory.hpp
@@ -155,9 +155,6 @@ class PerfMemory : AllStatic {
}
}
- // filename of backing store or NULL if none.
- static char* backing_store_filename();
-
// returns the complete file path of hsperfdata.
// the caller is expected to free the allocated memory.
static char* get_perfdata_file_path();
From 4c1c76ae4f3e4ee82c59ed53ee9c5639ed63f2e3 Mon Sep 17 00:00:00 2001
From: Tobias Hartmann
Date: Mon, 6 Oct 2014 07:58:50 +0200
Subject: [PATCH 12/82] 8059559: SIGSEGV at CodeHeap::allocate(unsigned int,
bool)
Create the non-profiled code heap if TieredStopAtLevel=0 is set because we compile method handle intrinsics.
Reviewed-by: kvn
---
hotspot/src/share/vm/code/codeCache.cpp | 3 +--
.../codecache/CheckSegmentedCodeCache.java | 21 +++++++++++++------
2 files changed, 16 insertions(+), 8 deletions(-)
diff --git a/hotspot/src/share/vm/code/codeCache.cpp b/hotspot/src/share/vm/code/codeCache.cpp
index a2653d10b43..b21604f8549 100644
--- a/hotspot/src/share/vm/code/codeCache.cpp
+++ b/hotspot/src/share/vm/code/codeCache.cpp
@@ -254,8 +254,7 @@ bool CodeCache::heap_available(int code_blob_type) {
if (!SegmentedCodeCache) {
// No segmentation: use a single code heap
return (code_blob_type == CodeBlobType::All);
- } else if ((Arguments::mode() == Arguments::_int) ||
- (TieredStopAtLevel == CompLevel_none)) {
+ } else if (Arguments::mode() == Arguments::_int) {
// Interpreter only: we don't need any method code heaps
return (code_blob_type == CodeBlobType::NonNMethod);
} else if (TieredCompilation && (TieredStopAtLevel > CompLevel_simple)) {
diff --git a/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java b/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java
index 5ed11c21233..06330d840b6 100644
--- a/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java
+++ b/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java
@@ -38,22 +38,26 @@ public class CheckSegmentedCodeCache {
private static void verifySegmentedCodeCache(ProcessBuilder pb, boolean enabled) throws Exception {
OutputAnalyzer out = new OutputAnalyzer(pb.start());
+ out.shouldHaveExitValue(0);
if (enabled) {
try {
// Non-nmethod code heap should be always available with the segmented code cache
out.shouldContain(NON_METHOD);
} catch (RuntimeException e) {
- // TieredCompilation is disabled in a client VM
- out.shouldContain("TieredCompilation is disabled in this release.");
+ // Check if TieredCompilation is disabled (in a client VM)
+ if(!out.getOutput().contains("TieredCompilation is disabled in this release.")) {
+ // Code cache is not segmented
+ throw new RuntimeException("No code cache segmentation.");
+ }
}
} else {
out.shouldNotContain(NON_METHOD);
}
- out.shouldHaveExitValue(0);
}
private static void verifyCodeHeapNotExists(ProcessBuilder pb, String... heapNames) throws Exception {
OutputAnalyzer out = new OutputAnalyzer(pb.start());
+ out.shouldHaveExitValue(0);
for (String name : heapNames) {
out.shouldNotContain(name);
}
@@ -86,6 +90,10 @@ public class CheckSegmentedCodeCache {
"-XX:ReservedCodeCacheSize=240m",
"-XX:+PrintCodeCache", "-version");
verifySegmentedCodeCache(pb, true);
+ pb = ProcessTools.createJavaProcessBuilder("-XX:+TieredCompilation",
+ "-XX:ReservedCodeCacheSize=400m",
+ "-XX:+PrintCodeCache", "-version");
+ verifySegmentedCodeCache(pb, true);
// Always enabled if SegmentedCodeCache is set
pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
@@ -100,12 +108,13 @@ public class CheckSegmentedCodeCache {
"-Xint",
"-XX:+PrintCodeCache", "-version");
verifyCodeHeapNotExists(pb, PROFILED, NON_PROFILED);
+
+ // If we stop compilation at CompLevel_none or CompLevel_simple we
+ // don't need a profiled code heap.
pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
"-XX:TieredStopAtLevel=0",
"-XX:+PrintCodeCache", "-version");
- verifyCodeHeapNotExists(pb, PROFILED, NON_PROFILED);
-
- // If we stop compilation at CompLevel_simple
+ verifyCodeHeapNotExists(pb, PROFILED);
pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
"-XX:TieredStopAtLevel=1",
"-XX:+PrintCodeCache", "-version");
From 18eb46eb952e27dc60e74d01f4eb0db6005986ad Mon Sep 17 00:00:00 2001
From: Stefan Johansson
Date: Mon, 6 Oct 2014 10:11:13 +0200
Subject: [PATCH 13/82] 8059466: Force young GC to initiate marking cycle when
stat update is requested
Enable yc to be forced for stat update.
Reviewed-by: mgerdin, jcoomes
---
.../src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp | 1 +
.../src/share/vm/gc_implementation/g1/vm_operations_g1.cpp | 5 +++--
hotspot/src/share/vm/gc_interface/gcCause.cpp | 3 ++-
hotspot/src/share/vm/gc_interface/gcCause.hpp | 3 ++-
4 files changed, 8 insertions(+), 4 deletions(-)
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
index f6aad1c81c6..133e2094f63 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
@@ -2343,6 +2343,7 @@ bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
case GCCause::_gc_locker: return GCLockerInvokesConcurrent;
case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;
case GCCause::_g1_humongous_allocation: return true;
+ case GCCause::_update_allocation_context_stats_inc: return true;
default: return false;
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp
index c3847e0da4e..9b50ae6af53 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp
@@ -95,8 +95,9 @@ void VM_G1IncCollectionPause::doit() {
assert(!_should_initiate_conc_mark ||
((_gc_cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
(_gc_cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent) ||
- _gc_cause == GCCause::_g1_humongous_allocation),
- "only a GC locker, a System.gc() or a hum allocation induced GC should start a cycle");
+ _gc_cause == GCCause::_g1_humongous_allocation ||
+ _gc_cause == GCCause::_update_allocation_context_stats_inc),
+ "only a GC locker, a System.gc(), stats update or a hum allocation induced GC should start a cycle");
if (_word_size > 0) {
// An allocation has been requested. So, try to do that first.
diff --git a/hotspot/src/share/vm/gc_interface/gcCause.cpp b/hotspot/src/share/vm/gc_interface/gcCause.cpp
index ff9402507c5..4778d8aa45a 100644
--- a/hotspot/src/share/vm/gc_interface/gcCause.cpp
+++ b/hotspot/src/share/vm/gc_interface/gcCause.cpp
@@ -54,7 +54,8 @@ const char* GCCause::to_string(GCCause::Cause cause) {
case _wb_young_gc:
return "WhiteBox Initiated Young GC";
- case _update_allocation_context_stats:
+ case _update_allocation_context_stats_inc:
+ case _update_allocation_context_stats_full:
return "Update Allocation Context Stats";
case _no_gc:
diff --git a/hotspot/src/share/vm/gc_interface/gcCause.hpp b/hotspot/src/share/vm/gc_interface/gcCause.hpp
index 25b55d2f6c5..4af99f1cf7e 100644
--- a/hotspot/src/share/vm/gc_interface/gcCause.hpp
+++ b/hotspot/src/share/vm/gc_interface/gcCause.hpp
@@ -47,7 +47,8 @@ class GCCause : public AllStatic {
_heap_inspection,
_heap_dump,
_wb_young_gc,
- _update_allocation_context_stats,
+ _update_allocation_context_stats_inc,
+ _update_allocation_context_stats_full,
/* implementation independent, but reserved for GC use */
_no_gc,
From 82171aa7abc81058ba571a4ed424d6a99c1aab05 Mon Sep 17 00:00:00 2001
From: Albert Noll
Date: Mon, 6 Oct 2014 06:51:37 -0700
Subject: [PATCH 14/82] 8059331: Print additional information for the assert in
Compile::start()
Add additional output that shows the failure reason
Reviewed-by: kvn
---
hotspot/src/share/vm/opto/compile.cpp | 10 ++++++++--
hotspot/src/share/vm/opto/compile.hpp | 15 +++++++++------
2 files changed, 17 insertions(+), 8 deletions(-)
diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp
index 1e3a6fc7b73..0163dce638c 100644
--- a/hotspot/src/share/vm/opto/compile.cpp
+++ b/hotspot/src/share/vm/opto/compile.cpp
@@ -1153,12 +1153,18 @@ void Compile::init_start(StartNode* s) {
assert(s == start(), "");
}
+/**
+ * Return the 'StartNode'. We must not have a pending failure, since the ideal graph
+ * can be in an inconsistent state, i.e., we can get segmentation faults when traversing
+ * the ideal graph.
+ */
StartNode* Compile::start() const {
- assert(!failing(), "");
+ assert (!failing(), err_msg_res("Must not have pending failure. Reason is: %s", failure_reason()));
for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
Node* start = root()->fast_out(i);
- if( start->is_Start() )
+ if (start->is_Start()) {
return start->as_Start();
+ }
}
fatal("Did not find Start node!");
return NULL;
diff --git a/hotspot/src/share/vm/opto/compile.hpp b/hotspot/src/share/vm/opto/compile.hpp
index 3dfda2b285f..2ac023235a9 100644
--- a/hotspot/src/share/vm/opto/compile.hpp
+++ b/hotspot/src/share/vm/opto/compile.hpp
@@ -707,12 +707,15 @@ class Compile : public Phase {
void sort_expensive_nodes();
// Compilation environment.
- Arena* comp_arena() { return &_comp_arena; }
- ciEnv* env() const { return _env; }
- CompileLog* log() const { return _log; }
- bool failing() const { return _env->failing() || _failure_reason != NULL; }
- const char* failure_reason() { return _failure_reason; }
- bool failure_reason_is(const char* r) { return (r==_failure_reason) || (r!=NULL && _failure_reason!=NULL && strcmp(r, _failure_reason)==0); }
+ Arena* comp_arena() { return &_comp_arena; }
+ ciEnv* env() const { return _env; }
+ CompileLog* log() const { return _log; }
+ bool failing() const { return _env->failing() || _failure_reason != NULL; }
+ const char* failure_reason() const { return (_env->failing()) ? _env->failure_reason() : _failure_reason; }
+
+ bool failure_reason_is(const char* r) const {
+ return (r == _failure_reason) || (r != NULL && _failure_reason != NULL && strcmp(r, _failure_reason) == 0);
+ }
void record_failure(const char* reason);
void record_method_not_compilable(const char* reason, bool all_tiers = false) {
From 6d1c35615acfef2824aa38e8afcfb9c7baa46c26 Mon Sep 17 00:00:00 2001
From: Marcus Larsson
Date: Tue, 7 Oct 2014 14:54:53 +0200
Subject: [PATCH 15/82] 8058298: Separate heap region iterator claim values
from the data structures iterated over
Reviewed-by: tschatzl, brutisso
---
.../gc_implementation/g1/concurrentMark.cpp | 102 +++-------
.../gc_implementation/g1/g1CollectedHeap.cpp | 186 +++---------------
.../gc_implementation/g1/g1CollectedHeap.hpp | 42 +---
.../g1/g1CollectorPolicy.cpp | 22 +--
.../vm/gc_implementation/g1/g1EvacFailure.hpp | 19 +-
.../vm/gc_implementation/g1/g1RemSet.cpp | 8 +-
.../vm/gc_implementation/g1/g1RemSet.hpp | 6 +-
.../vm/gc_implementation/g1/heapRegion.cpp | 14 +-
.../vm/gc_implementation/g1/heapRegion.hpp | 22 ---
.../g1/heapRegionManager.cpp | 55 ++++--
.../g1/heapRegionManager.hpp | 35 +++-
11 files changed, 157 insertions(+), 354 deletions(-)
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
index 8666c7a1583..755525123df 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
@@ -1683,6 +1683,8 @@ protected:
int _failures;
bool _verbose;
+ HeapRegionClaimer _hrclaimer;
+
public:
G1ParVerifyFinalCountTask(G1CollectedHeap* g1h,
BitMap* region_bm, BitMap* card_bm,
@@ -1692,19 +1694,8 @@ public:
_actual_region_bm(region_bm), _actual_card_bm(card_bm),
_expected_region_bm(expected_region_bm), _expected_card_bm(expected_card_bm),
_failures(0), _verbose(false),
- _n_workers(0) {
+ _n_workers(_g1h->workers()->active_workers()), _hrclaimer(_n_workers) {
assert(VerifyDuringGC, "don't call this otherwise");
-
- // Use the value already set as the number of active threads
- // in the call to run_task().
- if (G1CollectedHeap::use_parallel_gc_threads()) {
- assert( _g1h->workers()->active_workers() > 0,
- "Should have been previously set");
- _n_workers = _g1h->workers()->active_workers();
- } else {
- _n_workers = 1;
- }
-
assert(_expected_card_bm->size() == _actual_card_bm->size(), "sanity");
assert(_expected_region_bm->size() == _actual_region_bm->size(), "sanity");
@@ -1721,10 +1712,7 @@ public:
_verbose);
if (G1CollectedHeap::use_parallel_gc_threads()) {
- _g1h->heap_region_par_iterate_chunked(&verify_cl,
- worker_id,
- _n_workers,
- HeapRegion::VerifyCountClaimValue);
+ _g1h->heap_region_par_iterate(&verify_cl, worker_id, &_hrclaimer);
} else {
_g1h->heap_region_iterate(&verify_cl);
}
@@ -1813,22 +1801,14 @@ protected:
BitMap* _actual_card_bm;
uint _n_workers;
+ HeapRegionClaimer _hrclaimer;
public:
G1ParFinalCountTask(G1CollectedHeap* g1h, BitMap* region_bm, BitMap* card_bm)
: AbstractGangTask("G1 final counting"),
_g1h(g1h), _cm(_g1h->concurrent_mark()),
_actual_region_bm(region_bm), _actual_card_bm(card_bm),
- _n_workers(0) {
- // Use the value already set as the number of active threads
- // in the call to run_task().
- if (G1CollectedHeap::use_parallel_gc_threads()) {
- assert( _g1h->workers()->active_workers() > 0,
- "Should have been previously set");
- _n_workers = _g1h->workers()->active_workers();
- } else {
- _n_workers = 1;
- }
+ _n_workers(_g1h->workers()->active_workers()), _hrclaimer(_n_workers) {
}
void work(uint worker_id) {
@@ -1839,10 +1819,7 @@ public:
_actual_card_bm);
if (G1CollectedHeap::use_parallel_gc_threads()) {
- _g1h->heap_region_par_iterate_chunked(&final_update_cl,
- worker_id,
- _n_workers,
- HeapRegion::FinalCountClaimValue);
+ _g1h->heap_region_par_iterate(&final_update_cl, worker_id, &_hrclaimer);
} else {
_g1h->heap_region_iterate(&final_update_cl);
}
@@ -1929,12 +1906,12 @@ protected:
size_t _max_live_bytes;
size_t _freed_bytes;
FreeRegionList* _cleanup_list;
+ HeapRegionClaimer _hrclaimer;
public:
- G1ParNoteEndTask(G1CollectedHeap* g1h,
- FreeRegionList* cleanup_list) :
- AbstractGangTask("G1 note end"), _g1h(g1h),
- _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list) { }
+ G1ParNoteEndTask(G1CollectedHeap* g1h, FreeRegionList* cleanup_list, uint n_workers) :
+ AbstractGangTask("G1 note end"), _g1h(g1h), _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list), _hrclaimer(n_workers) {
+ }
void work(uint worker_id) {
double start = os::elapsedTime();
@@ -1943,9 +1920,7 @@ public:
G1NoteEndOfConcMarkClosure g1_note_end(_g1h, &local_cleanup_list,
&hrrs_cleanup_task);
if (G1CollectedHeap::use_parallel_gc_threads()) {
- _g1h->heap_region_par_iterate_chunked(&g1_note_end, worker_id,
- _g1h->workers()->active_workers(),
- HeapRegion::NoteEndClaimValue);
+ _g1h->heap_region_par_iterate(&g1_note_end, worker_id, &_hrclaimer);
} else {
_g1h->heap_region_iterate(&g1_note_end);
}
@@ -1991,16 +1966,16 @@ protected:
G1RemSet* _g1rs;
BitMap* _region_bm;
BitMap* _card_bm;
+ HeapRegionClaimer _hrclaimer;
+
public:
- G1ParScrubRemSetTask(G1CollectedHeap* g1h,
- BitMap* region_bm, BitMap* card_bm) :
- AbstractGangTask("G1 ScrubRS"), _g1rs(g1h->g1_rem_set()),
- _region_bm(region_bm), _card_bm(card_bm) { }
+ G1ParScrubRemSetTask(G1CollectedHeap* g1h, BitMap* region_bm, BitMap* card_bm, uint n_workers) :
+ AbstractGangTask("G1 ScrubRS"), _g1rs(g1h->g1_rem_set()), _region_bm(region_bm), _card_bm(card_bm), _hrclaimer(n_workers) {
+ }
void work(uint worker_id) {
if (G1CollectedHeap::use_parallel_gc_threads()) {
- _g1rs->scrub_par(_region_bm, _card_bm, worker_id,
- HeapRegion::ScrubRemSetClaimValue);
+ _g1rs->scrub_par(_region_bm, _card_bm, worker_id, &_hrclaimer);
} else {
_g1rs->scrub(_region_bm, _card_bm);
}
@@ -2043,9 +2018,6 @@ void ConcurrentMark::cleanup() {
G1ParFinalCountTask g1_par_count_task(g1h, &_region_bm, &_card_bm);
if (G1CollectedHeap::use_parallel_gc_threads()) {
- assert(g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
- "sanity check");
-
g1h->set_par_threads();
n_workers = g1h->n_par_threads();
assert(g1h->n_par_threads() == n_workers,
@@ -2053,9 +2025,6 @@ void ConcurrentMark::cleanup() {
g1h->workers()->run_task(&g1_par_count_task);
// Done with the parallel phase so reset to 0.
g1h->set_par_threads(0);
-
- assert(g1h->check_heap_region_claim_values(HeapRegion::FinalCountClaimValue),
- "sanity check");
} else {
n_workers = 1;
g1_par_count_task.work(0);
@@ -2080,9 +2049,6 @@ void ConcurrentMark::cleanup() {
g1h->workers()->run_task(&g1_par_verify_task);
// Done with the parallel phase so reset to 0.
g1h->set_par_threads(0);
-
- assert(g1h->check_heap_region_claim_values(HeapRegion::VerifyCountClaimValue),
- "sanity check");
} else {
g1_par_verify_task.work(0);
}
@@ -2108,14 +2074,11 @@ void ConcurrentMark::cleanup() {
g1h->reset_gc_time_stamp();
// Note end of marking in all heap regions.
- G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list);
+ G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list, n_workers);
if (G1CollectedHeap::use_parallel_gc_threads()) {
g1h->set_par_threads((int)n_workers);
g1h->workers()->run_task(&g1_par_note_end_task);
g1h->set_par_threads(0);
-
- assert(g1h->check_heap_region_claim_values(HeapRegion::NoteEndClaimValue),
- "sanity check");
} else {
g1_par_note_end_task.work(0);
}
@@ -2132,15 +2095,11 @@ void ConcurrentMark::cleanup() {
// regions.
if (G1ScrubRemSets) {
double rs_scrub_start = os::elapsedTime();
- G1ParScrubRemSetTask g1_par_scrub_rs_task(g1h, &_region_bm, &_card_bm);
+ G1ParScrubRemSetTask g1_par_scrub_rs_task(g1h, &_region_bm, &_card_bm, n_workers);
if (G1CollectedHeap::use_parallel_gc_threads()) {
g1h->set_par_threads((int)n_workers);
g1h->workers()->run_task(&g1_par_scrub_rs_task);
g1h->set_par_threads(0);
-
- assert(g1h->check_heap_region_claim_values(
- HeapRegion::ScrubRemSetClaimValue),
- "sanity check");
} else {
g1_par_scrub_rs_task.work(0);
}
@@ -3288,6 +3247,7 @@ protected:
BitMap* _cm_card_bm;
uint _max_worker_id;
int _active_workers;
+ HeapRegionClaimer _hrclaimer;
public:
G1AggregateCountDataTask(G1CollectedHeap* g1h,
@@ -3295,18 +3255,18 @@ public:
BitMap* cm_card_bm,
uint max_worker_id,
int n_workers) :
- AbstractGangTask("Count Aggregation"),
- _g1h(g1h), _cm(cm), _cm_card_bm(cm_card_bm),
- _max_worker_id(max_worker_id),
- _active_workers(n_workers) { }
+ AbstractGangTask("Count Aggregation"),
+ _g1h(g1h), _cm(cm), _cm_card_bm(cm_card_bm),
+ _max_worker_id(max_worker_id),
+ _active_workers(n_workers),
+ _hrclaimer(_active_workers) {
+ }
void work(uint worker_id) {
AggregateCountDataHRClosure cl(_g1h, _cm_card_bm, _max_worker_id);
if (G1CollectedHeap::use_parallel_gc_threads()) {
- _g1h->heap_region_par_iterate_chunked(&cl, worker_id,
- _active_workers,
- HeapRegion::AggregateCountClaimValue);
+ _g1h->heap_region_par_iterate(&cl, worker_id, &_hrclaimer);
} else {
_g1h->heap_region_iterate(&cl);
}
@@ -3323,15 +3283,9 @@ void ConcurrentMark::aggregate_count_data() {
_max_worker_id, n_workers);
if (G1CollectedHeap::use_parallel_gc_threads()) {
- assert(_g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
- "sanity check");
_g1h->set_par_threads(n_workers);
_g1h->workers()->run_task(&g1_par_agg_task);
_g1h->set_par_threads(0);
-
- assert(_g1h->check_heap_region_claim_values(HeapRegion::AggregateCountClaimValue),
- "sanity check");
- _g1h->reset_heap_region_claim_values();
} else {
g1_par_agg_task.work(0);
}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
index 133e2094f63..bec4fd63b83 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
@@ -90,8 +90,8 @@ size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
// Notes on implementation of parallelism in different tasks.
//
-// G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
-// The number of GC workers is passed to heap_region_par_iterate_chunked().
+// G1ParVerifyTask uses heap_region_par_iterate() for parallelism.
+// The number of GC workers is passed to heap_region_par_iterate().
// It does use run_task() which sets _n_workers in the task.
// G1ParTask executes g1_process_roots() ->
// SharedHeap::process_roots() which calls eventually to
@@ -1215,17 +1215,15 @@ public:
class ParRebuildRSTask: public AbstractGangTask {
G1CollectedHeap* _g1;
+ HeapRegionClaimer _hrclaimer;
+
public:
- ParRebuildRSTask(G1CollectedHeap* g1)
- : AbstractGangTask("ParRebuildRSTask"),
- _g1(g1)
- { }
+ ParRebuildRSTask(G1CollectedHeap* g1) :
+ AbstractGangTask("ParRebuildRSTask"), _g1(g1), _hrclaimer(g1->workers()->active_workers()) {}
void work(uint worker_id) {
RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
- _g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,
- _g1->workers()->active_workers(),
- HeapRegion::RebuildRSClaimValue);
+ _g1->heap_region_par_iterate(&rebuild_rs, worker_id, &_hrclaimer);
}
};
@@ -1455,8 +1453,6 @@ bool G1CollectedHeap::do_collection(bool explicit_gc,
set_par_threads(n_workers);
ParRebuildRSTask rebuild_rs_task(this);
- assert(check_heap_region_claim_values(
- HeapRegion::InitialClaimValue), "sanity check");
assert(UseDynamicNumberOfGCThreads ||
workers()->active_workers() == workers()->total_workers(),
"Unless dynamic should use total workers");
@@ -1466,9 +1462,6 @@ bool G1CollectedHeap::do_collection(bool explicit_gc,
set_par_threads(workers()->active_workers());
workers()->run_task(&rebuild_rs_task);
set_par_threads(0);
- assert(check_heap_region_claim_values(
- HeapRegion::RebuildRSClaimValue), "sanity check");
- reset_heap_region_claim_values();
} else {
RebuildRSOutOfRegionClosure rebuild_rs(this);
heap_region_iterate(&rebuild_rs);
@@ -2634,111 +2627,12 @@ void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
}
void
-G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
- uint worker_id,
- uint num_workers,
- jint claim_value) const {
- _hrm.par_iterate(cl, worker_id, num_workers, claim_value);
+G1CollectedHeap::heap_region_par_iterate(HeapRegionClosure* cl,
+ uint worker_id,
+ HeapRegionClaimer *hrclaimer) const {
+ _hrm.par_iterate(cl, worker_id, hrclaimer);
}
-class ResetClaimValuesClosure: public HeapRegionClosure {
-public:
- bool doHeapRegion(HeapRegion* r) {
- r->set_claim_value(HeapRegion::InitialClaimValue);
- return false;
- }
-};
-
-void G1CollectedHeap::reset_heap_region_claim_values() {
- ResetClaimValuesClosure blk;
- heap_region_iterate(&blk);
-}
-
-void G1CollectedHeap::reset_cset_heap_region_claim_values() {
- ResetClaimValuesClosure blk;
- collection_set_iterate(&blk);
-}
-
-#ifdef ASSERT
-// This checks whether all regions in the heap have the correct claim
-// value. I also piggy-backed on this a check to ensure that the
-// humongous_start_region() information on "continues humongous"
-// regions is correct.
-
-class CheckClaimValuesClosure : public HeapRegionClosure {
-private:
- jint _claim_value;
- uint _failures;
- HeapRegion* _sh_region;
-
-public:
- CheckClaimValuesClosure(jint claim_value) :
- _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
- bool doHeapRegion(HeapRegion* r) {
- if (r->claim_value() != _claim_value) {
- gclog_or_tty->print_cr("Region " HR_FORMAT ", "
- "claim value = %d, should be %d",
- HR_FORMAT_PARAMS(r),
- r->claim_value(), _claim_value);
- ++_failures;
- }
- if (!r->is_humongous()) {
- _sh_region = NULL;
- } else if (r->is_starts_humongous()) {
- _sh_region = r;
- } else if (r->is_continues_humongous()) {
- if (r->humongous_start_region() != _sh_region) {
- gclog_or_tty->print_cr("Region " HR_FORMAT ", "
- "HS = "PTR_FORMAT", should be "PTR_FORMAT,
- HR_FORMAT_PARAMS(r),
- r->humongous_start_region(),
- _sh_region);
- ++_failures;
- }
- }
- return false;
- }
- uint failures() { return _failures; }
-};
-
-bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
- CheckClaimValuesClosure cl(claim_value);
- heap_region_iterate(&cl);
- return cl.failures() == 0;
-}
-
-class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
-private:
- jint _claim_value;
- uint _failures;
-
-public:
- CheckClaimValuesInCSetHRClosure(jint claim_value) :
- _claim_value(claim_value), _failures(0) { }
-
- uint failures() { return _failures; }
-
- bool doHeapRegion(HeapRegion* hr) {
- assert(hr->in_collection_set(), "how?");
- assert(!hr->is_humongous(), "H-region in CSet");
- if (hr->claim_value() != _claim_value) {
- gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
- "claim value = %d, should be %d",
- HR_FORMAT_PARAMS(hr),
- hr->claim_value(), _claim_value);
- _failures += 1;
- }
- return false;
- }
-};
-
-bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
- CheckClaimValuesInCSetHRClosure cl(claim_value);
- collection_set_iterate(&cl);
- return cl.failures() == 0;
-}
-#endif // ASSERT
-
// Clear the cached CSet starting regions and (more importantly)
// the time stamps. Called when we reset the GC time stamp.
void G1CollectedHeap::clear_cset_start_regions() {
@@ -3252,19 +3146,21 @@ public:
class G1ParVerifyTask: public AbstractGangTask {
private:
- G1CollectedHeap* _g1h;
- VerifyOption _vo;
- bool _failures;
+ G1CollectedHeap* _g1h;
+ VerifyOption _vo;
+ bool _failures;
+ HeapRegionClaimer _hrclaimer;
public:
// _vo == UsePrevMarking -> use "prev" marking information,
// _vo == UseNextMarking -> use "next" marking information,
// _vo == UseMarkWord -> use mark word from object header.
G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
- AbstractGangTask("Parallel verify task"),
- _g1h(g1h),
- _vo(vo),
- _failures(false) { }
+ AbstractGangTask("Parallel verify task"),
+ _g1h(g1h),
+ _vo(vo),
+ _failures(false),
+ _hrclaimer(g1h->workers()->active_workers()) {}
bool failures() {
return _failures;
@@ -3273,9 +3169,7 @@ public:
void work(uint worker_id) {
HandleMark hm;
VerifyRegionClosure blk(true, _vo);
- _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
- _g1h->workers()->active_workers(),
- HeapRegion::ParVerifyClaimValue);
+ _g1h->heap_region_par_iterate(&blk, worker_id, &_hrclaimer);
if (blk.failures()) {
_failures = true;
}
@@ -3317,8 +3211,6 @@ void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
if (!silent) { gclog_or_tty->print("HeapRegions "); }
if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
- assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
- "sanity check");
G1ParVerifyTask task(this, vo);
assert(UseDynamicNumberOfGCThreads ||
@@ -3332,15 +3224,6 @@ void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
failures = true;
}
- // Checks that the expected amount of parallel work was done.
- // The implication is that n_workers is > 0.
- assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
- "sanity check");
-
- reset_heap_region_claim_values();
-
- assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
- "sanity check");
} else {
VerifyRegionClosure blk(false, vo);
heap_region_iterate(&blk);
@@ -3927,8 +3810,6 @@ G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
}
assert(check_young_list_well_formed(), "young list should be well formed");
- assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
- "sanity check");
// Don't dynamically change the number of GC threads this early. A value of
// 0 is used to indicate serial work. When parallel work is done,
@@ -4289,26 +4170,12 @@ void G1CollectedHeap::finalize_for_evac_failure() {
}
void G1CollectedHeap::remove_self_forwarding_pointers() {
- assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
-
double remove_self_forwards_start = os::elapsedTime();
+ set_par_threads();
G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
-
- if (G1CollectedHeap::use_parallel_gc_threads()) {
- set_par_threads();
- workers()->run_task(&rsfp_task);
- set_par_threads(0);
- } else {
- rsfp_task.work(0);
- }
-
- assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
-
- // Reset the claim values in the regions in the collection set.
- reset_cset_heap_region_claim_values();
-
- assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
+ workers()->run_task(&rsfp_task);
+ set_par_threads(0);
// Now restore saved marks, if any.
assert(_objs_with_preserved_marks.size() ==
@@ -5949,11 +5816,6 @@ void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
purge_code_root_memory();
- if (g1_policy()->during_initial_mark_pause()) {
- // Reset the claim values set during marking the strong code roots
- reset_heap_region_claim_values();
- }
-
finalize_for_evac_failure();
if (evacuation_failed()) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp
index bcc0419bf76..4f6d064fe9a 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp
@@ -211,6 +211,7 @@ class G1CollectedHeap : public SharedHeap {
friend class G1FreeHumongousRegionClosure;
// Other related classes.
friend class G1MarkSweep;
+ friend class HeapRegionClaimer;
private:
// The one and only G1CollectedHeap, so static functions can find it.
@@ -1377,38 +1378,15 @@ public:
inline HeapWord* bottom_addr_for_region(uint index) const;
- // Divide the heap region sequence into "chunks" of some size (the number
- // of regions divided by the number of parallel threads times some
- // overpartition factor, currently 4). Assumes that this will be called
- // in parallel by ParallelGCThreads worker threads with distinct worker
- // ids in the range [0..max(ParallelGCThreads-1, 1)], that all parallel
- // calls will use the same "claim_value", and that that claim value is
- // different from the claim_value of any heap region before the start of
- // the iteration. Applies "blk->doHeapRegion" to each of the regions, by
- // attempting to claim the first region in each chunk, and, if
- // successful, applying the closure to each region in the chunk (and
- // setting the claim value of the second and subsequent regions of the
- // chunk.) For now requires that "doHeapRegion" always returns "false",
- // i.e., that a closure never attempt to abort a traversal.
- void heap_region_par_iterate_chunked(HeapRegionClosure* cl,
- uint worker_id,
- uint num_workers,
- jint claim_value) const;
-
- // It resets all the region claim values to the default.
- void reset_heap_region_claim_values();
-
- // Resets the claim values of regions in the current
- // collection set to the default.
- void reset_cset_heap_region_claim_values();
-
-#ifdef ASSERT
- bool check_heap_region_claim_values(jint claim_value);
-
- // Same as the routine above but only checks regions in the
- // current collection set.
- bool check_cset_heap_region_claim_values(jint claim_value);
-#endif // ASSERT
+ // Iterate over the heap regions in parallel. Assumes that this will be called
+ // in parallel by ParallelGCThreads worker threads with distinct worker ids
+ // in the range [0..max(ParallelGCThreads-1, 1)]. Applies "blk->doHeapRegion"
+ // to each of the regions, by attempting to claim the region using the
+ // HeapRegionClaimer and, if successful, applying the closure to the claimed
+ // region.
+ void heap_region_par_iterate(HeapRegionClosure* cl,
+ uint worker_id,
+ HeapRegionClaimer* hrclaimer) const;
// Clear the cached cset start regions and (more importantly)
// the time stamps. Called when we reset the GC time stamp.
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
index a2f33d12c38..1cf1b178afe 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
@@ -1598,19 +1598,17 @@ class ParKnownGarbageTask: public AbstractGangTask {
CollectionSetChooser* _hrSorted;
uint _chunk_size;
G1CollectedHeap* _g1;
+ HeapRegionClaimer _hrclaimer;
+
public:
- ParKnownGarbageTask(CollectionSetChooser* hrSorted, uint chunk_size) :
- AbstractGangTask("ParKnownGarbageTask"),
- _hrSorted(hrSorted), _chunk_size(chunk_size),
- _g1(G1CollectedHeap::heap()) { }
+ ParKnownGarbageTask(CollectionSetChooser* hrSorted, uint chunk_size, uint n_workers) :
+ AbstractGangTask("ParKnownGarbageTask"),
+ _hrSorted(hrSorted), _chunk_size(chunk_size),
+ _g1(G1CollectedHeap::heap()), _hrclaimer(n_workers) {}
void work(uint worker_id) {
ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size);
-
- // Back to zero for the claim value.
- _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, worker_id,
- _g1->workers()->active_workers(),
- HeapRegion::InitialClaimValue);
+ _g1->heap_region_par_iterate(&parKnownGarbageCl, worker_id, &_hrclaimer);
}
};
@@ -1641,12 +1639,8 @@ G1CollectorPolicy::record_concurrent_mark_cleanup_end(int no_of_gc_threads) {
}
_collectionSetChooser->prepare_for_par_region_addition(_g1->num_regions(),
WorkUnit);
- ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
- (int) WorkUnit);
+ ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser, WorkUnit, (uint) no_of_gc_threads);
_g1->workers()->run_task(&parKnownGarbageTask);
-
- assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
- "sanity check");
} else {
KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
_g1->heap_region_iterate(&knownGarbagecl);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp
index 28c57b4fcd4..96c675f42ec 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp
@@ -177,16 +177,18 @@ class RemoveSelfForwardPtrHRClosure: public HeapRegionClosure {
G1CollectedHeap* _g1h;
ConcurrentMark* _cm;
uint _worker_id;
+ HeapRegionClaimer* _hrclaimer;
DirtyCardQueue _dcq;
UpdateRSetDeferred _update_rset_cl;
public:
RemoveSelfForwardPtrHRClosure(G1CollectedHeap* g1h,
- uint worker_id) :
- _g1h(g1h), _dcq(&g1h->dirty_card_queue_set()), _update_rset_cl(g1h, &_dcq),
- _worker_id(worker_id), _cm(_g1h->concurrent_mark()) {
- }
+ uint worker_id,
+ HeapRegionClaimer* hrclaimer) :
+ _g1h(g1h), _dcq(&g1h->dirty_card_queue_set()), _update_rset_cl(g1h, &_dcq),
+ _worker_id(worker_id), _cm(_g1h->concurrent_mark()), _hrclaimer(hrclaimer) {
+ }
bool doHeapRegion(HeapRegion *hr) {
bool during_initial_mark = _g1h->g1_policy()->during_initial_mark_pause();
@@ -195,7 +197,7 @@ public:
assert(!hr->is_humongous(), "sanity");
assert(hr->in_collection_set(), "bad CS");
- if (hr->claimHeapRegion(HeapRegion::ParEvacFailureClaimValue)) {
+ if (_hrclaimer->claim_region(hr->hrm_index())) {
if (hr->evacuation_failed()) {
RemoveSelfForwardPtrObjClosure rspc(_g1h, _cm, hr, &_update_rset_cl,
during_initial_mark,
@@ -233,14 +235,15 @@ public:
class G1ParRemoveSelfForwardPtrsTask: public AbstractGangTask {
protected:
G1CollectedHeap* _g1h;
+ HeapRegionClaimer _hrclaimer;
public:
G1ParRemoveSelfForwardPtrsTask(G1CollectedHeap* g1h) :
- AbstractGangTask("G1 Remove Self-forwarding Pointers"),
- _g1h(g1h) { }
+ AbstractGangTask("G1 Remove Self-forwarding Pointers"), _g1h(g1h),
+ _hrclaimer(g1h->workers()->active_workers()) {}
void work(uint worker_id) {
- RemoveSelfForwardPtrHRClosure rsfp_cl(_g1h, worker_id);
+ RemoveSelfForwardPtrHRClosure rsfp_cl(_g1h, worker_id, &_hrclaimer);
HeapRegion* hr = _g1h->start_cset_region_for_worker(worker_id);
_g1h->collection_set_iterate_from(hr, &rsfp_cl);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp
index 02433dbc550..a24b5a8069e 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp
@@ -425,13 +425,9 @@ void G1RemSet::scrub(BitMap* region_bm, BitMap* card_bm) {
_g1->heap_region_iterate(&scrub_cl);
}
-void G1RemSet::scrub_par(BitMap* region_bm, BitMap* card_bm,
- uint worker_num, int claim_val) {
+void G1RemSet::scrub_par(BitMap* region_bm, BitMap* card_bm, uint worker_num, HeapRegionClaimer *hrclaimer) {
ScrubRSClosure scrub_cl(region_bm, card_bm);
- _g1->heap_region_par_iterate_chunked(&scrub_cl,
- worker_num,
- n_workers(),
- claim_val);
+ _g1->heap_region_par_iterate(&scrub_cl, worker_num, hrclaimer);
}
G1TriggerClosure::G1TriggerClosure() :
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp
index a6823dfdc14..73c79172361 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp
@@ -128,10 +128,10 @@ public:
void scrub(BitMap* region_bm, BitMap* card_bm);
// Like the above, but assumes is called in parallel: "worker_num" is the
- // parallel thread id of the current thread, and "claim_val" is the
- // value that should be used to claim heap regions.
+ // parallel thread id of the current thread, and "hrclaimer" is the shared
+ // HeapRegionClaimer that should be used to claim heap regions.
void scrub_par(BitMap* region_bm, BitMap* card_bm,
- uint worker_num, int claim_val);
+ uint worker_num, HeapRegionClaimer* hrclaimer);
// Refine the card corresponding to "card_ptr".
// If check_for_refs_into_cset is true, a true result is returned
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp
index bb549aa5625..55e74c6669c 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp
@@ -217,7 +217,6 @@ void HeapRegion::hr_clear(bool par, bool clear_space, bool locked) {
} else {
hrrs->clear();
}
- _claimed = InitialClaimValue;
}
zero_marked_bytes();
@@ -294,17 +293,6 @@ void HeapRegion::clear_humongous() {
_humongous_start_region = NULL;
}
-bool HeapRegion::claimHeapRegion(jint claimValue) {
- jint current = _claimed;
- if (current != claimValue) {
- jint res = Atomic::cmpxchg(claimValue, &_claimed, current);
- if (res == current) {
- return true;
- }
- }
- return false;
-}
-
HeapRegion::HeapRegion(uint hrm_index,
G1BlockOffsetSharedArray* sharedOffsetArray,
MemRegion mr) :
@@ -314,7 +302,7 @@ HeapRegion::HeapRegion(uint hrm_index,
_humongous_start_region(NULL),
_in_collection_set(false),
_next_in_special_set(NULL),
- _claimed(InitialClaimValue), _evacuation_failed(false),
+ _evacuation_failed(false),
_prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
_next_young_region(NULL),
_next_dirty_cards_region(NULL), _next(NULL), _prev(NULL),
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp
index 74f32bcee4e..916726e48a0 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp
@@ -254,9 +254,6 @@ class HeapRegion: public G1OffsetTableContigSpace {
HeapRegionSetBase* _containing_set;
#endif // ASSERT
- // For parallel heapRegion traversal.
- jint _claimed;
-
// We use concurrent marking to determine the amount of live data
// in each heap region.
size_t _prev_marked_bytes; // Bytes known to be live via last completed marking.
@@ -336,19 +333,6 @@ class HeapRegion: public G1OffsetTableContigSpace {
// up once during initialization time.
static void setup_heap_region_size(size_t initial_heap_size, size_t max_heap_size);
- enum ClaimValues {
- InitialClaimValue = 0,
- FinalCountClaimValue = 1,
- NoteEndClaimValue = 2,
- ScrubRemSetClaimValue = 3,
- ParVerifyClaimValue = 4,
- RebuildRSClaimValue = 5,
- ParEvacFailureClaimValue = 6,
- AggregateCountClaimValue = 7,
- VerifyCountClaimValue = 8,
- ParMarkRootClaimValue = 9
- };
-
// All allocated blocks are occupied by objects in a HeapRegion
bool block_is_obj(const HeapWord* p) const;
@@ -691,12 +675,6 @@ class HeapRegion: public G1OffsetTableContigSpace {
return (HeapWord *) obj >= next_top_at_mark_start();
}
- // For parallel heapRegion traversal.
- bool claimHeapRegion(int claimValue);
- jint claim_value() { return _claimed; }
- // Use this carefully: only when you're sure no one is claiming...
- void set_claim_value(int claimValue) { _claimed = claimValue; }
-
// Returns the "evacuation_failed" property of the region.
bool evacuation_failed() { return _evacuation_failed; }
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.cpp
index a88c4b355cf..5de9dbcce98 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.cpp
@@ -260,20 +260,17 @@ uint HeapRegionManager::find_unavailable_from_idx(uint start_idx, uint* res_idx)
return num_regions;
}
-uint HeapRegionManager::start_region_for_worker(uint worker_i, uint num_workers, uint num_regions) const {
- return num_regions * worker_i / num_workers;
-}
-
-void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, uint num_workers, jint claim_value) const {
- const uint start_index = start_region_for_worker(worker_id, num_workers, _allocated_heapregions_length);
+void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, HeapRegionClaimer* hrclaimer) const {
+ const uint start_index = hrclaimer->start_region_for_worker(worker_id);
// Every worker will actually look at all regions, skipping over regions that
// are currently not committed.
// This also (potentially) iterates over regions newly allocated during GC. This
// is no problem except for some extra work.
- for (uint count = 0; count < _allocated_heapregions_length; count++) {
- const uint index = (start_index + count) % _allocated_heapregions_length;
- assert(0 <= index && index < _allocated_heapregions_length, "sanity");
+ const uint n_regions = hrclaimer->n_regions();
+ for (uint count = 0; count < n_regions; count++) {
+ const uint index = (start_index + count) % n_regions;
+ assert(0 <= index && index < n_regions, "sanity");
// Skip over unavailable regions
if (!is_available(index)) {
continue;
@@ -282,11 +279,11 @@ void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, uint
// We'll ignore "continues humongous" regions (we'll process them
// when we come across their corresponding "start humongous"
// region) and regions already claimed.
- if (r->claim_value() == claim_value || r->is_continues_humongous()) {
+ if (hrclaimer->is_region_claimed(index) || r->is_continues_humongous()) {
continue;
}
// OK, try to claim it
- if (!r->claimHeapRegion(claim_value)) {
+ if (!hrclaimer->claim_region(index)) {
continue;
}
// Success!
@@ -306,13 +303,11 @@ void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, uint
assert(chr->humongous_start_region() == r,
err_msg("Must work on humongous continuation of the original start region "
PTR_FORMAT ", but is " PTR_FORMAT, p2i(r), p2i(chr)));
- assert(chr->claim_value() != claim_value,
+ assert(!hrclaimer->is_region_claimed(ch_index),
"Must not have been claimed yet because claiming of humongous continuation first claims the start region");
- bool claim_result = chr->claimHeapRegion(claim_value);
- // We should always be able to claim it; no one else should
- // be trying to claim this region.
- guarantee(claim_result, "We should always be able to claim the is_continues_humongous part of the humongous object");
+ // There's no need to actually claim the continues humongous region, but we can do it in an assert as an extra precaution.
+ assert(hrclaimer->claim_region(ch_index), "We should always be able to claim the continuesHumongous part of the humongous object");
bool res2 = blk->doHeapRegion(chr);
if (res2) {
@@ -445,3 +440,31 @@ void HeapRegionManager::verify_optional() {
}
#endif // PRODUCT
+HeapRegionClaimer::HeapRegionClaimer(uint n_workers) :
+ _n_workers(n_workers), _n_regions(G1CollectedHeap::heap()->_hrm._allocated_heapregions_length), _claims(NULL) {
+ assert(n_workers > 0, "Need at least one worker.");
+ _claims = NEW_C_HEAP_ARRAY(uint, _n_regions, mtGC);
+ memset(_claims, Unclaimed, sizeof(*_claims) * _n_regions);
+}
+
+HeapRegionClaimer::~HeapRegionClaimer() {
+ if (_claims != NULL) {
+ FREE_C_HEAP_ARRAY(uint, _claims, mtGC);
+ }
+}
+
+uint HeapRegionClaimer::start_region_for_worker(uint worker_id) const {
+ assert(worker_id < _n_workers, "Invalid worker_id.");
+ return _n_regions * worker_id / _n_workers;
+}
+
+bool HeapRegionClaimer::is_region_claimed(uint region_index) const {
+ assert(region_index < _n_regions, "Invalid index.");
+ return _claims[region_index] == Claimed;
+}
+
+bool HeapRegionClaimer::claim_region(uint region_index) {
+ assert(region_index < _n_regions, "Invalid index.");
+ uint old_val = Atomic::cmpxchg(Claimed, &_claims[region_index], Unclaimed);
+ return old_val == Unclaimed;
+}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.hpp
index 7f96df4b2b2..f94d20a5cf4 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.hpp
@@ -31,6 +31,7 @@
class HeapRegion;
class HeapRegionClosure;
+class HeapRegionClaimer;
class FreeRegionList;
class G1HeapRegionTable : public G1BiasedMappedArray {
@@ -66,6 +67,7 @@ class G1HeapRegionTable : public G1BiasedMappedArray {
class HeapRegionManager: public CHeapObj {
friend class VMStructs;
+ friend class HeapRegionClaimer;
G1HeapRegionTable _regions;
@@ -99,9 +101,6 @@ class HeapRegionManager: public CHeapObj {
// Notify other data structures about change in the heap layout.
void update_committed_space(HeapWord* old_end, HeapWord* new_end);
- // Calculate the starting region for each worker during parallel iteration so
- // that they do not all start from the same region.
- uint start_region_for_worker(uint worker_i, uint num_workers, uint num_regions) const;
// Find a contiguous set of empty or uncommitted regions of length num and return
// the index of the first region or G1_NO_HRM_INDEX if the search was unsuccessful.
@@ -223,7 +222,7 @@ public:
// terminating the iteration early if doHeapRegion() returns true.
void iterate(HeapRegionClosure* blk) const;
- void par_iterate(HeapRegionClosure* blk, uint worker_id, uint no_of_par_workers, jint claim_value) const;
+ void par_iterate(HeapRegionClosure* blk, uint worker_id, HeapRegionClaimer* hrclaimer) const;
// Uncommit up to num_regions_to_remove regions that are completely free.
// Return the actual number of uncommitted regions.
@@ -235,5 +234,33 @@ public:
void verify_optional() PRODUCT_RETURN;
};
+// The HeapRegionClaimer is used during parallel iteration over heap regions,
+// allowing workers to claim heap regions, gaining exclusive rights to these regions.
+class HeapRegionClaimer : public StackObj {
+ uint _n_workers;
+ uint _n_regions;
+ uint* _claims;
+
+ static const uint Unclaimed = 0;
+ static const uint Claimed = 1;
+
+ public:
+ HeapRegionClaimer(uint n_workers);
+ ~HeapRegionClaimer();
+
+ inline uint n_regions() const {
+ return _n_regions;
+ }
+
+ // Calculate the starting region for given worker so
+ // that they do not all start from the same region.
+ uint start_region_for_worker(uint worker_id) const;
+
+ // Check if region has been claimed with this HRClaimer.
+ bool is_region_claimed(uint region_index) const;
+
+ // Claim the given region, returns true if successfully claimed.
+ bool claim_region(uint region_index);
+};
#endif // SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGIONMANAGER_HPP
From 3ed02be10e68612ebdb5e8058a6259af314e9435 Mon Sep 17 00:00:00 2001
From: Tobias Hartmann
Date: Wed, 8 Oct 2014 09:23:18 +0200
Subject: [PATCH 16/82] 8059735: make_not_entrant_or_zombie sees zombies
Make sure nmethod is not set to zombie state twice by sweeper and safepoint code.
Reviewed-by: kvn, anoll, mgerdin
---
hotspot/src/share/vm/runtime/sweeper.cpp | 26 ++++++++++++++++--------
1 file changed, 17 insertions(+), 9 deletions(-)
diff --git a/hotspot/src/share/vm/runtime/sweeper.cpp b/hotspot/src/share/vm/runtime/sweeper.cpp
index ab1c113138e..cecb8ff08a1 100644
--- a/hotspot/src/share/vm/runtime/sweeper.cpp
+++ b/hotspot/src/share/vm/runtime/sweeper.cpp
@@ -540,17 +540,25 @@ int NMethodSweeper::process_nmethod(nmethod *nm) {
// If there are no current activations of this method on the
// stack we can safely convert it to a zombie method
if (nm->can_not_entrant_be_converted()) {
- if (PrintMethodFlushing && Verbose) {
- tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
- }
// Clear ICStubs to prevent back patching stubs of zombie or unloaded
// nmethods during the next safepoint (see ICStub::finalize).
- MutexLocker cl(CompiledIC_lock);
- nm->clear_ic_stubs();
- // Code cache state change is tracked in make_zombie()
- nm->make_zombie();
- _zombified_count++;
- SWEEP(nm);
+ {
+ MutexLocker cl(CompiledIC_lock);
+ nm->clear_ic_stubs();
+ }
+ // Acquiring the CompiledIC_lock may block for a safepoint and set the
+ // nmethod to zombie (see 'CodeCache::make_marked_nmethods_zombies').
+ // Check if nmethod is still non-entrant at this point.
+ if (nm->is_not_entrant()) {
+ if (PrintMethodFlushing && Verbose) {
+ tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
+ }
+ // Code cache state change is tracked in make_zombie()
+ nm->make_zombie();
+ _zombified_count++;
+ SWEEP(nm);
+ }
+ assert(nm->is_zombie(), "nmethod must be zombie");
} else {
// Still alive, clean up its inline caches
MutexLocker cl(CompiledIC_lock);
From edc10143cb71052df6b6dc2ff8dd23f0a12a976f Mon Sep 17 00:00:00 2001
From: Lois Foltan
Date: Wed, 7 May 2014 19:38:22 +0400
Subject: [PATCH 17/82] 8036805: Correct linker method lookup
Correct handling of array of primitive type qualifiers during field and method resolution.
Reviewed-by: acorn, hseigel, ahgross
---
.../src/share/vm/interpreter/linkResolver.cpp | 52 ++++++++++++-------
hotspot/src/share/vm/oops/arrayKlass.cpp | 7 +++
hotspot/src/share/vm/oops/arrayKlass.hpp | 4 ++
hotspot/src/share/vm/oops/klass.cpp | 9 ++++
hotspot/src/share/vm/oops/klass.hpp | 2 +
5 files changed, 54 insertions(+), 20 deletions(-)
diff --git a/hotspot/src/share/vm/interpreter/linkResolver.cpp b/hotspot/src/share/vm/interpreter/linkResolver.cpp
index 6fbb3bfa6f1..5bf368a1765 100644
--- a/hotspot/src/share/vm/interpreter/linkResolver.cpp
+++ b/hotspot/src/share/vm/interpreter/linkResolver.cpp
@@ -246,6 +246,12 @@ void LinkResolver::lookup_method_in_klasses(methodHandle& result, KlassHandle kl
// Ignore overpasses so statics can be found during resolution
Method* result_oop = klass->uncached_lookup_method(name, signature, Klass::skip_overpass);
+ if (klass->oop_is_array()) {
+ // Only consider klass and super klass for arrays
+ result = methodHandle(THREAD, result_oop);
+ return;
+ }
+
// JDK 8, JVMS 5.4.3.4: Interface method resolution should
// ignore static and non-public methods of java.lang.Object,
// like clone, finalize, registerNatives.
@@ -290,6 +296,11 @@ void LinkResolver::lookup_instance_method_in_klasses(methodHandle& result, Klass
result = methodHandle(THREAD, super_klass->uncached_lookup_method(name, signature, Klass::normal));
}
+ if (klass->oop_is_array()) {
+ // Only consider klass and super klass for arrays
+ return;
+ }
+
if (result.is_null()) {
Array* default_methods = InstanceKlass::cast(klass())->default_methods();
if (default_methods != NULL) {
@@ -545,7 +556,7 @@ void LinkResolver::resolve_method(methodHandle& resolved_method, KlassHandle res
// 2. lookup method in resolved klass and its super klasses
lookup_method_in_klasses(resolved_method, resolved_klass, method_name, method_signature, true, false, CHECK);
- if (resolved_method.is_null()) { // not found in the class hierarchy
+ if (resolved_method.is_null() && !resolved_klass->oop_is_array()) { // not found in the class hierarchy
// 3. lookup method in all the interfaces implemented by the resolved klass
lookup_method_in_interfaces(resolved_method, resolved_klass, method_name, method_signature, CHECK);
@@ -558,16 +569,16 @@ void LinkResolver::resolve_method(methodHandle& resolved_method, KlassHandle res
CLEAR_PENDING_EXCEPTION;
}
}
+ }
- if (resolved_method.is_null()) {
- // 4. method lookup failed
- ResourceMark rm(THREAD);
- THROW_MSG_CAUSE(vmSymbols::java_lang_NoSuchMethodError(),
- Method::name_and_sig_as_C_string(resolved_klass(),
- method_name,
- method_signature),
- nested_exception);
- }
+ if (resolved_method.is_null()) {
+ // 4. method lookup failed
+ ResourceMark rm(THREAD);
+ THROW_MSG_CAUSE(vmSymbols::java_lang_NoSuchMethodError(),
+ Method::name_and_sig_as_C_string(resolved_klass(),
+ method_name,
+ method_signature),
+ nested_exception);
}
// 5. access checks, access checking may be turned off when calling from within the VM.
@@ -633,17 +644,18 @@ void LinkResolver::resolve_interface_method(methodHandle& resolved_method,
// JDK8: also look for static methods
lookup_method_in_klasses(resolved_method, resolved_klass, method_name, method_signature, false, true, CHECK);
- if (resolved_method.is_null()) {
+ if (resolved_method.is_null() && !resolved_klass->oop_is_array()) {
// lookup method in all the super-interfaces
lookup_method_in_interfaces(resolved_method, resolved_klass, method_name, method_signature, CHECK);
- if (resolved_method.is_null()) {
- // no method found
- ResourceMark rm(THREAD);
- THROW_MSG(vmSymbols::java_lang_NoSuchMethodError(),
- Method::name_and_sig_as_C_string(resolved_klass(),
- method_name,
- method_signature));
- }
+ }
+
+ if (resolved_method.is_null()) {
+ // no method found
+ ResourceMark rm(THREAD);
+ THROW_MSG(vmSymbols::java_lang_NoSuchMethodError(),
+ Method::name_and_sig_as_C_string(resolved_klass(),
+ method_name,
+ method_signature));
}
if (check_access) {
@@ -775,7 +787,7 @@ void LinkResolver::resolve_field(fieldDescriptor& fd, KlassHandle resolved_klass
}
// Resolve instance field
- KlassHandle sel_klass(THREAD, InstanceKlass::cast(resolved_klass())->find_field(field, sig, &fd));
+ KlassHandle sel_klass(THREAD, resolved_klass->find_field(field, sig, &fd));
// check if field exists; i.e., if a klass containing the field def has been selected
if (sel_klass.is_null()) {
ResourceMark rm(THREAD);
diff --git a/hotspot/src/share/vm/oops/arrayKlass.cpp b/hotspot/src/share/vm/oops/arrayKlass.cpp
index 21de8cb42cf..740ae166adf 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.cpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.cpp
@@ -64,6 +64,13 @@ oop ArrayKlass::multi_allocate(int rank, jint* sizes, TRAPS) {
return NULL;
}
+// find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
+Klass* ArrayKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
+ // There are no fields in an array klass but look to the super class (Object)
+ assert(super(), "super klass must be present");
+ return super()->find_field(name, sig, fd);
+}
+
Method* ArrayKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
// There are no methods in an array klass but the super class (Object) has some
assert(super(), "super klass must be present");
diff --git a/hotspot/src/share/vm/oops/arrayKlass.hpp b/hotspot/src/share/vm/oops/arrayKlass.hpp
index 39ae5768aaf..248fde0373a 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.hpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.hpp
@@ -28,6 +28,7 @@
#include "memory/universe.hpp"
#include "oops/klass.hpp"
+class fieldDescriptor;
class klassVtable;
// ArrayKlass is the abstract baseclass for all array classes
@@ -77,6 +78,9 @@ class ArrayKlass: public Klass {
virtual oop multi_allocate(int rank, jint* sizes, TRAPS);
objArrayOop allocate_arrayArray(int n, int length, TRAPS);
+ // find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
+ Klass* find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
+
// Lookup operations
Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp
index 810c8d729cd..bdd4839be46 100644
--- a/hotspot/src/share/vm/oops/klass.cpp
+++ b/hotspot/src/share/vm/oops/klass.cpp
@@ -130,6 +130,15 @@ bool Klass::compute_is_subtype_of(Klass* k) {
return is_subclass_of(k);
}
+Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
+#ifdef ASSERT
+ tty->print_cr("Error: find_field called on a klass oop."
+ " Likely error: reflection method does not correctly"
+ " wrap return value in a mirror object.");
+#endif
+ ShouldNotReachHere();
+ return NULL;
+}
Method* Klass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
#ifdef ASSERT
diff --git a/hotspot/src/share/vm/oops/klass.hpp b/hotspot/src/share/vm/oops/klass.hpp
index 5af2104e594..fd7691462f3 100644
--- a/hotspot/src/share/vm/oops/klass.hpp
+++ b/hotspot/src/share/vm/oops/klass.hpp
@@ -62,6 +62,7 @@ class ClassLoaderData;
class klassVtable;
class ParCompactionManager;
class KlassSizeStats;
+class fieldDescriptor;
class Klass : public Metadata {
friend class VMStructs;
@@ -411,6 +412,7 @@ protected:
virtual void initialize(TRAPS);
// lookup operation for MethodLookupCache
friend class MethodLookupCache;
+ virtual Klass* find_field(Symbol* name, Symbol* signature, fieldDescriptor* fd) const;
virtual Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
public:
Method* lookup_method(Symbol* name, Symbol* signature) const {
From 6037f786bb1c4e4101a3a54bca0a7581591b2fe0 Mon Sep 17 00:00:00 2001
From: Alexander Zuev
Date: Thu, 8 May 2014 21:09:57 +0400
Subject: [PATCH 18/82] 8041529: Better parameterization of parameter lists
Reviewed-by: twisti, ahgross
---
.../java.base/share/classes/java/lang/invoke/MethodType.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java
index 3eab50e26ea..00e0a046efe 100644
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java
@@ -727,7 +727,7 @@ class MethodType implements java.io.Serializable {
* @return the parameter types (as an immutable list)
*/
public List> parameterList() {
- return Collections.unmodifiableList(Arrays.asList(ptypes));
+ return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
}
/*non-public*/ Class> lastParameterType() {
From 23a1b5481b2c14158082d79b446fc0f4f7c68e16 Mon Sep 17 00:00:00 2001
From: Joe Wang
Date: Mon, 13 Oct 2014 14:09:03 -0700
Subject: [PATCH 19/82] 8036951: Xerces Update: XMLSchemaValidator.java and
XMLSchemaLoader.java
Reviewed-by: lancea
---
.../internal/dom/DOMConfigurationImpl.java | 73 +--
.../xerces/internal/dom/PSVIAttrNSImpl.java | 100 +--
.../internal/dom/PSVIElementNSImpl.java | 106 +--
.../xerces/internal/impl/Constants.java | 9 +-
.../internal/impl/XMLEntityManager.java | 23 +-
.../internal/impl/XMLErrorReporter.java | 64 +-
.../internal/impl/dtd/XMLDTDValidator.java | 28 +-
.../internal/impl/dtd/models/CMNode.java | 91 +--
.../internal/impl/dv/ValidatedInfo.java | 93 ++-
.../internal/impl/dv/util/ByteListImpl.java | 18 +-
.../internal/impl/dv/xs/XSSimpleTypeDecl.java | 228 +++++--
.../impl/dv/xs/XSSimpleTypeDelegate.java | 5 +
.../impl/msg/XMLSchemaMessages.properties | 18 +-
.../ConfigurableValidationState.java | 27 +-
.../impl/validation/ValidationState.java | 37 +-
.../internal/impl/xs/AttributePSVImpl.java | 136 ++--
.../internal/impl/xs/ElementPSVImpl.java | 143 +++--
.../internal/impl/xs/PSVIErrorList.java | 92 +++
.../internal/impl/xs/SchemaGrammar.java | 111 ++--
.../impl/xs/SubstitutionGroupHandler.java | 48 +-
.../internal/impl/xs/XMLSchemaLoader.java | 239 ++++---
.../internal/impl/xs/XMLSchemaValidator.java | 604 ++++++++++++------
.../internal/impl/xs/XSAttributeDecl.java | 16 +-
.../internal/impl/xs/XSAttributeUseImpl.java | 16 +-
.../internal/impl/xs/XSComplexTypeDecl.java | 37 +-
.../internal/impl/xs/XSConstraints.java | 13 +-
.../internal/impl/xs/XSElementDecl.java | 16 +-
.../internal/impl/xs/XSElementDeclHelper.java | 34 +
.../xerces/internal/impl/xs/XSModelImpl.java | 67 +-
.../internal/impl/xs/identity/Field.java | 116 +++-
.../impl/xs/identity/FieldActivator.java | 31 +-
.../internal/impl/xs/identity/ValueStore.java | 16 +-
.../internal/impl/xs/models/CMBuilder.java | 52 +-
.../impl/xs/models/CMNodeFactory.java | 17 +-
.../internal/impl/xs/models/XSAllCM.java | 38 +-
.../impl/xs/models/XSCMValidator.java | 60 +-
.../internal/impl/xs/models/XSDFACM.java | 55 +-
.../internal/impl/xs/models/XSEmptyCM.java | 34 +-
.../xs/traversers/XSDSimpleTypeTraverser.java | 13 +-
.../internal/impl/xs/util/XS10TypeHelper.java | 65 ++
.../XMLSchemaValidatorComponentManager.java | 4 +
.../internal/parsers/DOMParserImpl.java | 51 +-
.../parsers/StandardParserConfiguration.java | 8 +
.../internal/parsers/XML11Configuration.java | 8 +
.../internal/util/XMLAttributesImpl.java | 93 +--
.../apache/xerces/internal/xs/ItemPSVI.java | 69 +-
.../internal/xs/XSAttributeDeclaration.java | 24 +-
.../xerces/internal/xs/XSAttributeUse.java | 29 +-
.../internal/xs/XSElementDeclaration.java | 27 +-
.../apache/xerces/internal/xs/XSFacet.java | 29 +-
.../apache/xerces/internal/xs/XSModel.java | 30 +-
.../xerces/internal/xs/XSMultiValueFacet.java | 18 +-
.../xerces/internal/xs/XSNamespaceItem.java | 23 +-
.../internal/xs/XSSimpleTypeDefinition.java | 16 +-
.../apache/xerces/internal/xs/XSValue.java | 108 ++++
.../internal/xs/datatypes/ByteList.java | 16 +-
56 files changed, 2384 insertions(+), 1158 deletions(-)
create mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/PSVIErrorList.java
create mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDeclHelper.java
create mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/util/XS10TypeHelper.java
create mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSValue.java
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java
index 189abdff259..c6c689a359e 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -51,8 +51,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
-import java.util.Vector;
-import javax.xml.XMLConstants;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMErrorHandler;
import org.w3c.dom.DOMException;
@@ -976,41 +974,40 @@ public class DOMConfigurationImpl extends ParserConfigurationSettings
*/
public DOMStringList getParameterNames() {
if (fRecognizedParameters == null){
- Vector parameters = new Vector();
+ ArrayList parameters = new ArrayList();
- //Add DOM recognized parameters
- //REVISIT: Would have been nice to have a list of
- //recognized paramters.
- parameters.add(Constants.DOM_COMMENTS);
- parameters.add(Constants.DOM_DATATYPE_NORMALIZATION);
- parameters.add(Constants.DOM_CDATA_SECTIONS);
- parameters.add(Constants.DOM_ENTITIES);
- parameters.add(Constants.DOM_SPLIT_CDATA);
- parameters.add(Constants.DOM_NAMESPACES);
- parameters.add(Constants.DOM_VALIDATE);
+ //Add DOM recognized parameters
+ //REVISIT: Would have been nice to have a list of
+ //recognized paramters.
+ parameters.add(Constants.DOM_COMMENTS);
+ parameters.add(Constants.DOM_DATATYPE_NORMALIZATION);
+ parameters.add(Constants.DOM_CDATA_SECTIONS);
+ parameters.add(Constants.DOM_ENTITIES);
+ parameters.add(Constants.DOM_SPLIT_CDATA);
+ parameters.add(Constants.DOM_NAMESPACES);
+ parameters.add(Constants.DOM_VALIDATE);
- parameters.add(Constants.DOM_INFOSET);
- parameters.add(Constants.DOM_NORMALIZE_CHARACTERS);
- parameters.add(Constants.DOM_CANONICAL_FORM);
- parameters.add(Constants.DOM_VALIDATE_IF_SCHEMA);
- parameters.add(Constants.DOM_CHECK_CHAR_NORMALIZATION);
- parameters.add(Constants.DOM_WELLFORMED);
+ parameters.add(Constants.DOM_INFOSET);
+ parameters.add(Constants.DOM_NORMALIZE_CHARACTERS);
+ parameters.add(Constants.DOM_CANONICAL_FORM);
+ parameters.add(Constants.DOM_VALIDATE_IF_SCHEMA);
+ parameters.add(Constants.DOM_CHECK_CHAR_NORMALIZATION);
+ parameters.add(Constants.DOM_WELLFORMED);
- parameters.add(Constants.DOM_NAMESPACE_DECLARATIONS);
- parameters.add(Constants.DOM_ELEMENT_CONTENT_WHITESPACE);
+ parameters.add(Constants.DOM_NAMESPACE_DECLARATIONS);
+ parameters.add(Constants.DOM_ELEMENT_CONTENT_WHITESPACE);
- parameters.add(Constants.DOM_ERROR_HANDLER);
- parameters.add(Constants.DOM_SCHEMA_TYPE);
- parameters.add(Constants.DOM_SCHEMA_LOCATION);
- parameters.add(Constants.DOM_RESOURCE_RESOLVER);
+ parameters.add(Constants.DOM_ERROR_HANDLER);
+ parameters.add(Constants.DOM_SCHEMA_TYPE);
+ parameters.add(Constants.DOM_SCHEMA_LOCATION);
+ parameters.add(Constants.DOM_RESOURCE_RESOLVER);
- //Add recognized xerces features and properties
- parameters.add(GRAMMAR_POOL);
- parameters.add(SYMBOL_TABLE);
- parameters.add(SEND_PSVI);
-
- fRecognizedParameters = new DOMStringListImpl(parameters);
+ //Add recognized xerces features and properties
+ parameters.add(GRAMMAR_POOL);
+ parameters.add(SYMBOL_TABLE);
+ parameters.add(SEND_PSVI);
+ fRecognizedParameters = new DOMStringListImpl(parameters);
}
return fRecognizedParameters;
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIAttrNSImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIAttrNSImpl.java
index cefe92dcca0..593959ac287 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIAttrNSImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIAttrNSImpl.java
@@ -1,13 +1,10 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright 2002-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,14 +17,16 @@
package com.sun.org.apache.xerces.internal.dom;
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.AttributePSVImpl;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.*;
+import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
-import com.sun.org.apache.xerces.internal.xs.*;
-
/**
* Attribute namespace implementation; stores PSVI attribute items.
*
@@ -67,20 +66,8 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
* value in the original document, this is true; otherwise, it is false */
protected boolean fSpecified = true;
- /** schema normalized value property */
- protected String fNormalizedValue = null;
-
- /** schema actual value */
- protected Object fActualValue = null;
-
- /** schema actual value type */
- protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
- /** actual value types if the value is a list */
- protected ShortList fItemValueTypes = null;
-
- /** member type definition against which attribute was validated */
- protected XSSimpleTypeDefinition fMemberType = null;
+ /** Schema value */
+ protected ValidatedInfo fValue = new ValidatedInfo();
/** validation attempted: none, partial, full */
protected short fValidationAttempted = AttributePSVI.VALIDATION_NONE;
@@ -91,6 +78,9 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
/** error codes */
protected StringList fErrorCodes = null;
+ /** error messages */
+ protected StringList fErrorMessages = null;
+
/** validation context: could be QName or XPath expression*/
protected String fValidationContext = null;
@@ -98,6 +88,20 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
// AttributePSVI methods
//
+ /* (non-Javadoc)
+ * @see org.apache.xerces.xs.ItemPSVI#constant()
+ */
+ public ItemPSVI constant() {
+ return new AttributePSVImpl(true, this);
+ }
+
+ /* (non-Javadoc)
+ * @see org.apache.xerces.xs.ItemPSVI#isConstant()
+ */
+ public boolean isConstant() {
+ return false;
+ }
+
/**
* [schema default]
*
@@ -116,7 +120,7 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
* @return the normalized value of this item after validation
*/
public String getSchemaNormalizedValue() {
- return fNormalizedValue;
+ return fValue.getNormalizedValue();
}
/**
@@ -157,7 +161,23 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
* @return list of error codes
*/
public StringList getErrorCodes() {
- return fErrorCodes;
+ if (fErrorCodes != null) {
+ return fErrorCodes;
+ }
+ return StringListImpl.EMPTY_LIST;
+ }
+
+ /**
+ * A list of error messages generated from the validation attempt or
+ * an empty StringList if no errors occurred during the
+ * validation attempt. The indices of error messages in this list are
+ * aligned with those in the [schema error code] list.
+ */
+ public StringList getErrorMessages() {
+ if (fErrorMessages != null) {
+ return fErrorMessages;
+ }
+ return StringListImpl.EMPTY_LIST;
}
// This is the only information we can provide in a pipeline.
@@ -177,14 +197,14 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
/**
* If and only if that type definition is a simple type definition
* with {variety} union, or a complex type definition whose {content type}
- * is a simple thype definition with {variety} union, then an item isomorphic
+ * is a simple type definition with {variety} union, then an item isomorphic
* to that member of the union's {member type definitions} which actually
* validated the element item's normalized value.
*
* @return a simple type declaration
*/
public XSSimpleTypeDefinition getMemberTypeDefinition() {
- return fMemberType;
+ return fValue.getMemberTypeDefinition();
}
/**
@@ -208,12 +228,9 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
this.fValidity = attr.getValidity();
this.fValidationAttempted = attr.getValidationAttempted();
this.fErrorCodes = attr.getErrorCodes();
- this.fNormalizedValue = attr.getSchemaNormalizedValue();
- this.fActualValue = attr.getActualNormalizedValue();
- this.fActualValueType = attr.getActualNormalizedValueType();
- this.fItemValueTypes = attr.getItemValueTypes();
+ this.fErrorMessages = attr.getErrorMessages();
+ this.fValue.copyFrom(attr.getSchemaValue());
this.fTypeDecl = attr.getTypeDefinition();
- this.fMemberType = attr.getMemberTypeDefinition();
this.fSpecified = attr.getIsSchemaSpecified();
}
@@ -221,21 +238,28 @@ public class PSVIAttrNSImpl extends AttrNSImpl implements AttributePSVI {
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
*/
public Object getActualNormalizedValue() {
- return this.fActualValue;
+ return fValue.getActualValue();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
*/
public short getActualNormalizedValueType() {
- return this.fActualValueType;
+ return fValue.getActualValueType();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
*/
public ShortList getItemValueTypes() {
- return this.fItemValueTypes;
+ return fValue.getListValueTypes();
+ }
+
+ /* (non-Javadoc)
+ * @see org.apache.xerces.xs.ItemPSVI#getSchemaValue()
+ */
+ public XSValue getSchemaValue() {
+ return fValue;
}
// REVISIT: Forbid serialization of PSVI DOM until
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIElementNSImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIElementNSImpl.java
index 272a7c93a18..e1fa27a5c7c 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIElementNSImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIElementNSImpl.java
@@ -1,13 +1,10 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright 2002-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,14 +17,16 @@
package com.sun.org.apache.xerces.internal.dom;
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.ElementPSVImpl;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.*;
+import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
-import com.sun.org.apache.xerces.internal.xs.*;
-
/**
* Element namespace implementation; stores PSVI element items.
*
@@ -72,24 +71,12 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
*/
protected boolean fSpecified = true;
- /** schema normalized value property */
- protected String fNormalizedValue = null;
-
- /** schema actual value */
- protected Object fActualValue = null;
-
- /** schema actual value type */
- protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
- /** actual value types if the value is a list */
- protected ShortList fItemValueTypes = null;
+ /** Schema value */
+ protected ValidatedInfo fValue = new ValidatedInfo();
/** http://www.w3.org/TR/xmlschema-1/#e-notation*/
protected XSNotationDeclaration fNotation = null;
- /** member type definition against which element was validated */
- protected XSSimpleTypeDefinition fMemberType = null;
-
/** validation attempted: none, partial, full */
protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE;
@@ -99,6 +86,9 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
/** error codes */
protected StringList fErrorCodes = null;
+ /** error messages */
+ protected StringList fErrorMessages = null;
+
/** validation context: could be QName or XPath expression*/
protected String fValidationContext = null;
@@ -109,6 +99,20 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
// ElementPSVI methods
//
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#constant()
+ */
+ public ItemPSVI constant() {
+ return new ElementPSVImpl(true, this);
+ }
+
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#isConstant()
+ */
+ public boolean isConstant() {
+ return false;
+ }
+
/**
* [schema default]
*
@@ -127,7 +131,7 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
* @return the normalized value of this item after validation
*/
public String getSchemaNormalizedValue() {
- return fNormalizedValue;
+ return fValue.getNormalizedValue();
}
/**
@@ -167,9 +171,24 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
* @return Array of error codes
*/
public StringList getErrorCodes() {
- return fErrorCodes;
+ if (fErrorCodes != null) {
+ return fErrorCodes;
+ }
+ return StringListImpl.EMPTY_LIST;
}
+ /**
+ * A list of error messages generated from the validation attempt or
+ * an empty StringList if no errors occurred during the
+ * validation attempt. The indices of error messages in this list are
+ * aligned with those in the [schema error code] list.
+ */
+ public StringList getErrorMessages() {
+ if (fErrorMessages != null) {
+ return fErrorMessages;
+ }
+ return StringListImpl.EMPTY_LIST;
+ }
// This is the only information we can provide in a pipeline.
public String getValidationContext() {
@@ -213,7 +232,7 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
* @return a simple type declaration
*/
public XSSimpleTypeDefinition getMemberTypeDefinition() {
- return fMemberType;
+ return fValue.getMemberTypeDefinition();
}
/**
@@ -239,7 +258,7 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
/**
* Copy PSVI properties from another psvi item.
*
- * @param attr the source of attribute PSVI items
+ * @param elem the source of element PSVI items
*/
public void setPSVI(ElementPSVI elem) {
this.fDeclaration = elem.getElementDeclaration();
@@ -250,11 +269,15 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
this.fValidity = elem.getValidity();
this.fValidationAttempted = elem.getValidationAttempted();
this.fErrorCodes = elem.getErrorCodes();
- this.fNormalizedValue = elem.getSchemaNormalizedValue();
- this.fActualValue = elem.getActualNormalizedValue();
- this.fActualValueType = elem.getActualNormalizedValueType();
- this.fItemValueTypes = elem.getItemValueTypes();
- this.fMemberType = elem.getMemberTypeDefinition();
+ this.fErrorMessages = elem.getErrorMessages();
+ if (fTypeDecl instanceof XSSimpleTypeDefinition ||
+ fTypeDecl instanceof XSComplexTypeDefinition &&
+ ((XSComplexTypeDefinition)fTypeDecl).getContentType() == XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) {
+ this.fValue.copyFrom(elem.getSchemaValue());
+ }
+ else {
+ this.fValue.reset();
+ }
this.fSpecified = elem.getIsSchemaSpecified();
this.fNil = elem.getNil();
}
@@ -263,21 +286,28 @@ public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
*/
public Object getActualNormalizedValue() {
- return this.fActualValue;
+ return fValue.getActualValue();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
*/
public short getActualNormalizedValueType() {
- return this.fActualValueType;
+ return fValue.getActualValueType();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
*/
public ShortList getItemValueTypes() {
- return this.fItemValueTypes;
+ return fValue.getListValueTypes();
+ }
+
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getSchemaValue()
+ */
+ public XSValue getSchemaValue() {
+ return fValue;
}
// REVISIT: Forbid serialization of PSVI DOM until
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/Constants.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/Constants.java
index 3a84797138b..2176c984eca 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/Constants.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/Constants.java
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -632,9 +635,12 @@ public final class Constants {
/** Validation manager property ("internal/validation-manager"). */
public static final String VALIDATION_MANAGER_PROPERTY = "internal/validation-manager";
- /** Schema type of the root element in a document ("validation/schema/root-type-definition"). */
+ /** Schema type for the root element in a document ("validation/schema/root-type-definition"). */
public static final String ROOT_TYPE_DEFINITION_PROPERTY = "validation/schema/root-type-definition";
+ /** Schema element declaration for the root element in a document ("validation/schema/root-element-declaration"). */
+ public static final String ROOT_ELEMENT_DECLARATION_PROPERTY = "validation/schema/root-element-declaration";
+
/** XPointer Schema property ("xpointer-schema"). */
public static final String XPOINTER_SCHEMA_PROPERTY = "xpointer-schema";
@@ -803,6 +809,7 @@ public final class Constants {
BUFFER_SIZE_PROPERTY,
SECURITY_MANAGER_PROPERTY,
ROOT_TYPE_DEFINITION_PROPERTY,
+ ROOT_ELEMENT_DECLARATION_PROPERTY,
LOCALE_PROPERTY,
SCHEMA_DV_FACTORY_PROPERTY,
};
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
index 7a70b3abece..96774da47be 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
@@ -1,6 +1,5 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -22,11 +21,11 @@
package com.sun.org.apache.xerces.internal.impl ;
import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
import com.sun.org.apache.xerces.internal.impl.io.ASCIIReader;
import com.sun.org.apache.xerces.internal.impl.io.UCSReader;
import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;
import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
-import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
import com.sun.org.apache.xerces.internal.util.*;
import com.sun.org.apache.xerces.internal.util.URI;
@@ -54,6 +53,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
+import javax.xml.stream.XMLInputFactory;
/**
@@ -305,6 +305,11 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
/** Property Manager. This is used from Stax */
protected PropertyManager fPropertyManager ;
+ /** StAX properties */
+ boolean fSupportDTD = true;
+ boolean fReplaceEntityReferences = true;
+ boolean fSupportExternalEntities = true;
+
/** used to restrict external access */
protected String fAccessExternalDTD = EXTERNAL_ACCESS_DEFAULT;
@@ -1136,7 +1141,8 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
boolean parameter = entityName.startsWith("%");
boolean general = !parameter;
if (unparsed || (general && !fExternalGeneralEntities) ||
- (parameter && !fExternalParameterEntities)) {
+ (parameter && !fExternalParameterEntities) ||
+ !fSupportDTD || !fSupportExternalEntities) {
if (fEntityHandler != null) {
fResourceIdentifier.clear();
@@ -1431,6 +1437,10 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
fStaxEntityResolver = null;
}
+ fSupportDTD = ((Boolean)propertyManager.getProperty(XMLInputFactory.SUPPORT_DTD)).booleanValue();
+ fReplaceEntityReferences = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)).booleanValue();
+ fSupportExternalEntities = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)).booleanValue();
+
// Zephyr feature ignore-external-dtd is the opposite of Xerces' load-external-dtd
fLoadExternalDTD = !((Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.IGNORE_EXTERNAL_DTD)).booleanValue();
@@ -1501,7 +1511,10 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER, null);
fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER, null);
entityExpansionIndex = fSecurityManager.getIndex(Constants.JDK_ENTITY_EXPANSION_LIMIT);
-
+ //StAX Property
+ fSupportDTD = true;
+ fReplaceEntityReferences = true;
+ fSupportExternalEntities = true;
// JAXP 1.5 feature
XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER, null);
if (spm == null) {
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLErrorReporter.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLErrorReporter.java
index e6ce89d3816..1c74f385773 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLErrorReporter.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLErrorReporter.java
@@ -3,60 +3,20 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * The Apache Software License, Version 1.1
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Copyright (c) 1999-2004 The Apache Software Foundation.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- * if any, must include the following acknowledgment:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgment may appear in the software itself,
- * if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Xerces" and "Apache Software Foundation" must
- * not be used to endorse or promote products derived from this
- * software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- * nor may "Apache" appear in their name, without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation and was
- * originally based on software copyright (c) 1999, International
- * Business Machines, Inc., http://www.apache.org. For more
- * information on the Apache Software Foundation, please see
- * .
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package com.sun.org.apache.xerces.internal.impl;
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/XMLDTDValidator.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/XMLDTDValidator.java
index 01c8c54f7a7..62d50dc7dc7 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/XMLDTDValidator.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/XMLDTDValidator.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -51,6 +52,7 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentFilter;
import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentSource;
+import java.util.Iterator;
/**
* The DTD validator. The validator implements a document
@@ -334,7 +336,7 @@ public class XMLDTDValidator
// temporary variables
/** Temporary element declaration. */
- private XMLElementDecl fTempElementDecl = new XMLElementDecl();
+ private final XMLElementDecl fTempElementDecl = new XMLElementDecl();
/** Temporary atribute declaration. */
private final XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl();
@@ -2020,12 +2022,14 @@ public class XMLDTDValidator
// IDREF and IDREFS attr (V_IDREF0)
//
if (fPerformValidation) {
- String value = fValidationState.checkIDRefID();
- if (value != null) {
- fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN,
- "MSG_ELEMENT_WITH_ID_REQUIRED",
- new Object[]{value},
- XMLErrorReporter.SEVERITY_ERROR );
+ Iterator invIdRefs = fValidationState.checkIDRefID();
+ if (invIdRefs != null) {
+ while (invIdRefs.hasNext()) {
+ fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN,
+ "MSG_ELEMENT_WITH_ID_REQUIRED",
+ new Object[]{invIdRefs.next()},
+ XMLErrorReporter.SEVERITY_ERROR );
+ }
}
}
return;
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/models/CMNode.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/models/CMNode.java
index 29bfc43e09d..b394f93bdc9 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/models/CMNode.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/models/CMNode.java
@@ -1,62 +1,21 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * The Apache Software License, Version 1.1
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Copyright (c) 1999-2002 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- * if any, must include the following acknowledgment:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgment may appear in the software itself,
- * if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Xerces" and "Apache Software Foundation" must
- * not be used to endorse or promote products derived from this
- * software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- * nor may "Apache" appear in their name, without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation and was
- * originally based on software copyright (c) 1999, International
- * Business Machines, Inc., http://www.apache.org. For more
- * information on the Apache Software Foundation, please see
- * .
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package com.sun.org.apache.xerces.internal.impl.dtd.models;
@@ -125,6 +84,14 @@ public abstract class CMNode
fMaxStates = maxStates;
}
+ public boolean isCompactedForUPA() {
+ return fCompactedForUPA;
+ }
+
+ public void setIsCompactUPAModel(boolean value) {
+ fCompactedForUPA = value;
+ }
+
/**
* Allows the user to set arbitrary data on this content model
* node. This is used by the a{n,m} optimization that runs
@@ -181,10 +148,16 @@ public abstract class CMNode
// init to to -1 so it will cause an error if its used without
// being initialized.
// -------------------------------------------------------------------
- private int fType;
- private CMStateSet fFirstPos = null;
- private CMStateSet fFollowPos = null;
- private CMStateSet fLastPos = null;
- private int fMaxStates = -1;
+ private final int fType;
+ private CMStateSet fFirstPos = null;
+ private CMStateSet fFollowPos = null;
+ private CMStateSet fLastPos = null;
+ private int fMaxStates = -1;
private Object fUserData = null;
+ /*
+ * This boolean is true if the model represented by the CMNode does not represent
+ * the true model from the schema, but has had its min/maxOccurs modified for a
+ * more compact representation (for purposes of UPA).
+ */
+ private boolean fCompactedForUPA = false;
};
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java
index cc84353bd64..318147ddf56 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java
@@ -1,3 +1,7 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -17,8 +21,13 @@
package com.sun.org.apache.xerces.internal.impl.dv;
+import com.sun.org.apache.xerces.internal.impl.xs.util.ShortListImpl;
+import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.xs.ShortList;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
+import com.sun.org.apache.xerces.internal.xs.XSObjectList;
+import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
/**
* Class to get the information back after content is validated. This info
@@ -29,7 +38,7 @@ import com.sun.org.apache.xerces.internal.xs.XSConstants;
* @author Neeraj Bajaj, Sun Microsystems, inc.
*
*/
-public class ValidatedInfo {
+public class ValidatedInfo implements XSValue {
/**
* The normalized value of a string value
@@ -50,6 +59,11 @@ public class ValidatedInfo {
*/
public short actualValueType;
+ /**
+ * The declared type of the value.
+ */
+ public XSSimpleType actualType;
+
/**
* If the type is a union type, then the member type which
* actually validated the string value.
@@ -79,8 +93,11 @@ public class ValidatedInfo {
public void reset() {
this.normalizedValue = null;
this.actualValue = null;
+ this.actualValueType = XSConstants.UNAVAILABLE_DT;
+ this.actualType = null;
this.memberType = null;
this.memberTypes = null;
+ this.itemValueTypes = null;
}
/**
@@ -88,10 +105,12 @@ public class ValidatedInfo {
* value, use toString; otherwise, use the normalized value.
*/
public String stringValue() {
- if (actualValue == null)
+ if (actualValue == null) {
return normalizedValue;
- else
+ }
+ else {
return actualValue.toString();
+ }
}
/**
@@ -149,4 +168,72 @@ public class ValidatedInfo {
/** Other types. */
return valueType;
}
+
+ // XSValue methods
+
+ public Object getActualValue() {
+ return actualValue;
+ }
+
+ public short getActualValueType() {
+ return actualValueType;
+ }
+
+ public ShortList getListValueTypes() {
+ return itemValueTypes == null ? ShortListImpl.EMPTY_LIST : itemValueTypes;
+ }
+
+ public XSObjectList getMemberTypeDefinitions() {
+ if (memberTypes == null) {
+ return XSObjectListImpl.EMPTY_LIST;
+ }
+ return new XSObjectListImpl(memberTypes, memberTypes.length);
+ }
+
+ public String getNormalizedValue() {
+ return normalizedValue;
+ }
+
+ public XSSimpleTypeDefinition getTypeDefinition() {
+ return actualType;
+ }
+
+ public XSSimpleTypeDefinition getMemberTypeDefinition() {
+ return memberType;
+ }
+
+ public void copyFrom(XSValue o) {
+ if (o == null) {
+ reset();
+ }
+ else if (o instanceof ValidatedInfo) {
+ ValidatedInfo other = (ValidatedInfo)o;
+ normalizedValue = other.normalizedValue;
+ actualValue = other.actualValue;
+ actualValueType = other.actualValueType;
+ actualType = other.actualType;
+ memberType = other.memberType;
+ memberTypes = other.memberTypes;
+ itemValueTypes = other.itemValueTypes;
+ }
+ else {
+ normalizedValue = o.getNormalizedValue();
+ actualValue = o.getActualValue();
+ actualValueType = o.getActualValueType();
+ actualType = (XSSimpleType)o.getTypeDefinition();
+ memberType = (XSSimpleType)o.getMemberTypeDefinition();
+ XSSimpleType realType = memberType == null ? actualType : memberType;
+ if (realType != null && realType.getBuiltInKind() == XSConstants.LISTOFUNION_DT) {
+ XSObjectList members = o.getMemberTypeDefinitions();
+ memberTypes = new XSSimpleType[members.getLength()];
+ for (int i = 0; i < members.getLength(); i++) {
+ memberTypes[i] = (XSSimpleType)members.get(i);
+ }
+ }
+ else {
+ memberTypes = null;
+ }
+ itemValueTypes = o.getListValueTypes();
+ }
+ }
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/util/ByteListImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/util/ByteListImpl.java
index 3357593489d..c725743ffa8 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/util/ByteListImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/util/ByteListImpl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,6 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.impl.dv.util;
import java.util.AbstractList;
@@ -102,4 +104,10 @@ public class ByteListImpl extends AbstractList implements ByteList {
public int size() {
return getLength();
}
+
+ public byte[] toByteArray() {
+ byte[] ret = new byte[data.length];
+ System.arraycopy(data, 0, ret, 0, data.length);
+ return ret;
+ }
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDecl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDecl.java
index fa4a495a571..133161d1a69 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDecl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDecl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,11 +21,6 @@
package com.sun.org.apache.xerces.internal.impl.dv.xs;
-import java.util.AbstractList;
-import java.util.Locale;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.DatatypeException;
import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeFacetException;
@@ -33,9 +29,10 @@ import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.ValidationContext;
import com.sun.org.apache.xerces.internal.impl.dv.XSFacets;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
-import com.sun.org.apache.xerces.internal.impl.xpath.regex.RegularExpression;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
+import com.sun.org.apache.xerces.internal.impl.xpath.regex.RegularExpression;
import com.sun.org.apache.xerces.internal.impl.xs.SchemaSymbols;
+import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.ShortListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
@@ -48,10 +45,16 @@ import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSFacet;
import com.sun.org.apache.xerces.internal.xs.XSMultiValueFacet;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
+import com.sun.org.apache.xerces.internal.xs.XSObject;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
+import java.math.BigInteger;
+import java.util.AbstractList;
+import java.util.Locale;
+import java.util.StringTokenizer;
+import java.util.Vector;
import org.w3c.dom.TypeInfo;
/**
@@ -267,9 +270,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
private int fFractionDigits = -1;
private Vector fPattern;
private Vector fPatternStr;
- private Vector fEnumeration;
- private short[] fEnumerationType;
- private ShortList[] fEnumerationItemType; // used in case fenumerationType value is LIST or LISTOFUNION
+ private ValidatedInfo[] fEnumeration;
+ private int fEnumerationSize;
private ShortList fEnumerationTypeList;
private ObjectList fEnumerationItemTypeList;
private StringList fLexicalPattern;
@@ -387,8 +389,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
fPattern = fBase.fPattern;
fPatternStr = fBase.fPatternStr;
fEnumeration = fBase.fEnumeration;
- fEnumerationType = fBase.fEnumerationType;
- fEnumerationItemType = fBase.fEnumerationItemType;
+ fEnumerationSize = fBase.fEnumerationSize;
fWhiteSpace = fBase.fWhiteSpace;
fMaxExclusive = fBase.fMaxExclusive;
fMaxInclusive = fBase.fMaxInclusive;
@@ -508,8 +509,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
fPattern = fBase.fPattern;
fPatternStr = fBase.fPatternStr;
fEnumeration = fBase.fEnumeration;
- fEnumerationType = fBase.fEnumerationType;
- fEnumerationItemType = fBase.fEnumerationItemType;
+ fEnumerationSize = fBase.fEnumerationSize;
fWhiteSpace = fBase.fWhiteSpace;
fMaxExclusive = fBase.fMaxExclusive;
fMaxInclusive = fBase.fMaxInclusive;
@@ -873,22 +873,20 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
if ((allowedFacet & FACET_ENUMERATION) == 0) {
reportError("cos-applicable-facets", new Object[]{"enumeration", fTypeName});
} else {
- fEnumeration = new Vector();
Vector enumVals = facets.enumeration;
- fEnumerationType = new short[enumVals.size()];
- fEnumerationItemType = new ShortList[enumVals.size()];
+ int size = enumVals.size();
+ fEnumeration = new ValidatedInfo[size];
Vector enumNSDecls = facets.enumNSDecls;
ValidationContextImpl ctx = new ValidationContextImpl(context);
enumerationAnnotations = facets.enumAnnotations;
- for (int i = 0; i < enumVals.size(); i++) {
+ fEnumerationSize = 0;
+ for (int i = 0; i < size; i++) {
if (enumNSDecls != null)
ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i));
try {
- ValidatedInfo info = getActualEnumValue((String)enumVals.elementAt(i), ctx, tempInfo);
+ ValidatedInfo info = getActualEnumValue((String)enumVals.elementAt(i), ctx, null);
// check 4.3.5.c0 must: enumeration values from the value space of base
- fEnumeration.addElement(info.actualValue);
- fEnumerationType[i] = info.actualValueType;
- fEnumerationItemType[i] = info.itemValueTypes;
+ fEnumeration[fEnumerationSize++] = info;
} catch (InvalidDatatypeValueException ide) {
reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i), this.getBaseType().getName()});
}
@@ -1478,6 +1476,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) {
fFacetsDefined |= FACET_ENUMERATION;
fEnumeration = fBase.fEnumeration;
+ fEnumerationSize = fBase.fEnumerationSize;
enumerationAnnotations = fBase.enumerationAnnotations;
}
// inherit maxExclusive
@@ -1673,16 +1672,16 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
//enumeration
if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) {
boolean present = false;
- final int enumSize = fEnumeration.size();
+ final int enumSize = fEnumerationSize;
final short primitiveType1 = convertToPrimitiveKind(type);
for (int i = 0; i < enumSize; i++) {
- final short primitiveType2 = convertToPrimitiveKind(fEnumerationType[i]);
+ final short primitiveType2 = convertToPrimitiveKind(fEnumeration[i].actualValueType);
if ((primitiveType1 == primitiveType2 ||
primitiveType1 == XSConstants.ANYSIMPLETYPE_DT && primitiveType2 == XSConstants.STRING_DT ||
primitiveType1 == XSConstants.STRING_DT && primitiveType2 == XSConstants.ANYSIMPLETYPE_DT)
- && fEnumeration.elementAt(i).equals(ob)) {
+ && fEnumeration[i].actualValue.equals(ob)) {
if (primitiveType1 == XSConstants.LIST_DT || primitiveType1 == XSConstants.LISTOFUNION_DT) {
- ShortList enumItemType = fEnumerationItemType[i];
+ ShortList enumItemType = fEnumeration[i].itemValueTypes;
final int typeList1Length = itemType != null ? itemType.getLength() : 0;
final int typeList2Length = enumItemType != null ? enumItemType.getLength() : 0;
if (typeList1Length == typeList2Length) {
@@ -1711,8 +1710,10 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
}
}
if(!present){
+ StringBuffer sb = new StringBuffer();
+ appendEnumString(sb);
throw new InvalidDatatypeValueException("cvc-enumeration-valid",
- new Object [] {content, fEnumeration.toString()});
+ new Object [] {content, sb.toString()});
}
}
@@ -1827,12 +1828,6 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
nvalue = content.toString();
}
if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) {
- if (fPattern.size()==0 && nvalue.length()>0) {
- throw new InvalidDatatypeValueException("cvc-pattern-valid",
- new Object[]{content,
- "(empty string)",
- fTypeName});
- }
RegularExpression regex;
for (int idx = fPattern.size()-1; idx >= 0; idx--) {
regex = (RegularExpression)fPattern.elementAt(idx);
@@ -1840,6 +1835,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
throw new InvalidDatatypeValueException("cvc-pattern-valid",
new Object[]{content,
fPatternStr.elementAt(idx),
+
fTypeName});
}
}
@@ -1873,6 +1869,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context);
validatedInfo.actualValue = avalue;
validatedInfo.actualValueType = fBuiltInKind;
+ validatedInfo.actualType = this;
return avalue;
@@ -1910,6 +1907,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
validatedInfo.memberTypes = memberTypes;
validatedInfo.itemValueTypes = new ShortListImpl(itemTypes, itemTypes.length);
validatedInfo.normalizedValue = nvalue;
+ // Need to set it here or it will become the item type
+ validatedInfo.actualType = this;
return v;
@@ -1929,6 +1928,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
fMemberTypes[i].checkFacets(validatedInfo);
}
validatedInfo.memberType = fMemberTypes[i];
+ // Need to set it here or it will become the member type
+ validatedInfo.actualType = this;
return aValue;
} catch(InvalidDatatypeValueException invalidValue) {
}
@@ -1946,14 +1947,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
}
typesBuffer.append(decl.fTypeName);
if(decl.fEnumeration != null) {
- Vector v = decl.fEnumeration;
- typesBuffer.append(" : [");
- for(int j = 0;j < v.size(); j++) {
- if(j != 0)
- typesBuffer.append(',');
- typesBuffer.append(v.elementAt(j));
- }
- typesBuffer.append(']');
+ typesBuffer.append(" : ");
+ decl.appendEnumString(typesBuffer);
}
}
throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.3",
@@ -2245,10 +2240,10 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
if (fLexicalEnumeration == null){
if (fEnumeration == null)
return StringListImpl.EMPTY_LIST;
- int size = fEnumeration.size();
+ int size = fEnumerationSize;
String[] strs = new String[size];
for (int i = 0; i < size; i++)
- strs[i] = fEnumeration.elementAt(i).toString();
+ strs[i] = fEnumeration[i].normalizedValue;
fLexicalEnumeration = new StringListImpl(strs, size);
}
return fLexicalEnumeration;
@@ -2262,16 +2257,24 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
if (fActualEnumeration == null) {
fActualEnumeration = new AbstractObjectList() {
public int getLength() {
- return (fEnumeration != null) ? fEnumeration.size() : 0;
+ return (fEnumeration != null) ? fEnumerationSize : 0;
}
public boolean contains(Object item) {
- return (fEnumeration != null && fEnumeration.contains(item));
+ if (fEnumeration == null) {
+ return false;
+ }
+ for (int i = 0; i < fEnumerationSize; i++) {
+ if (fEnumeration[i].getActualValue().equals(item)) {
+ return true;
+ }
+ }
+ return false;
}
public Object item(int index) {
if (index < 0 || index >= getLength()) {
return null;
}
- return fEnumeration.elementAt(index);
+ return fEnumeration[index].getActualValue();
}
};
}
@@ -2284,17 +2287,18 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
*/
public ObjectList getEnumerationItemTypeList() {
if (fEnumerationItemTypeList == null) {
- if(fEnumerationItemType == null)
+ if (fEnumeration == null) {
return null;
+ }
fEnumerationItemTypeList = new AbstractObjectList() {
public int getLength() {
- return (fEnumerationItemType != null) ? fEnumerationItemType.length : 0;
+ return (fEnumeration != null) ? fEnumerationSize : 0;
}
public boolean contains(Object item) {
- if(fEnumerationItemType == null || !(item instanceof ShortList))
+ if (fEnumeration == null || !(item instanceof ShortList))
return false;
- for(int i = 0;i < fEnumerationItemType.length; i++)
- if(fEnumerationItemType[i] == item)
+ for (int i = 0;i < fEnumerationSize; i++)
+ if (fEnumeration[i].itemValueTypes == item)
return true;
return false;
}
@@ -2302,7 +2306,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
if (index < 0 || index >= getLength()) {
return null;
}
- return fEnumerationItemType[index];
+ return fEnumeration[index].itemValueTypes;
}
};
}
@@ -2311,10 +2315,14 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
public ShortList getEnumerationTypeList() {
if (fEnumerationTypeList == null) {
- if (fEnumerationType == null) {
+ if (fEnumeration == null) {
return ShortListImpl.EMPTY_LIST;
}
- fEnumerationTypeList = new ShortListImpl (fEnumerationType, fEnumerationType.length);
+ short[] list = new short[fEnumerationSize];
+ for (int i = 0; i < fEnumerationSize; i++) {
+ list[i] = fEnumeration[i].actualValueType;
+ }
+ fEnumerationTypeList = new ShortListImpl(list, fEnumerationSize);
}
return fEnumerationTypeList;
}
@@ -2978,10 +2986,11 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
fPattern = null;
fPatternStr = null;
fEnumeration = null;
- fEnumerationType = null;
- fEnumerationItemType = null;
fLexicalPattern = null;
fLexicalEnumeration = null;
+ fActualEnumeration = null;
+ fEnumerationTypeList = null;
+ fEnumerationItemTypeList = null;
fMaxInclusive = null;
fMaxExclusive = null;
fMinExclusive = null;
@@ -3043,6 +3052,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_WHITESPACE,
WS_FACET_STRING[fWhiteSpace],
+ 0,
+ null,
(fFixedFacet & FACET_WHITESPACE) != 0,
whiteSpaceAnnotation);
count++;
@@ -3052,6 +3063,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_LENGTH,
Integer.toString(fLength),
+ fLength,
+ null,
(fFixedFacet & FACET_LENGTH) != 0,
lengthAnnotation);
count++;
@@ -3061,6 +3074,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_MINLENGTH,
Integer.toString(fMinLength),
+ fMinLength,
+ null,
(fFixedFacet & FACET_MINLENGTH) != 0,
minLengthAnnotation);
count++;
@@ -3070,6 +3085,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_MAXLENGTH,
Integer.toString(fMaxLength),
+ fMaxLength,
+ null,
(fFixedFacet & FACET_MAXLENGTH) != 0,
maxLengthAnnotation);
count++;
@@ -3079,6 +3096,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_TOTALDIGITS,
Integer.toString(fTotalDigits),
+ fTotalDigits,
+ null,
(fFixedFacet & FACET_TOTALDIGITS) != 0,
totalDigitsAnnotation);
count++;
@@ -3088,6 +3107,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_FRACTIONDIGITS,
"0",
+ 0,
+ null,
true,
fractionDigitsAnnotation);
count++;
@@ -3097,6 +3118,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_FRACTIONDIGITS,
Integer.toString(fFractionDigits),
+ fFractionDigits,
+ null,
(fFixedFacet & FACET_FRACTIONDIGITS) != 0,
fractionDigitsAnnotation);
count++;
@@ -3106,6 +3129,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_MAXINCLUSIVE,
fMaxInclusive.toString(),
+ 0,
+ fMaxInclusive,
(fFixedFacet & FACET_MAXINCLUSIVE) != 0,
maxInclusiveAnnotation);
count++;
@@ -3115,6 +3140,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_MAXEXCLUSIVE,
fMaxExclusive.toString(),
+ 0,
+ fMaxExclusive,
(fFixedFacet & FACET_MAXEXCLUSIVE) != 0,
maxExclusiveAnnotation);
count++;
@@ -3124,6 +3151,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_MINEXCLUSIVE,
fMinExclusive.toString(),
+ 0,
+ fMinExclusive,
(fFixedFacet & FACET_MINEXCLUSIVE) != 0,
minExclusiveAnnotation);
count++;
@@ -3133,6 +3162,8 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSFacetImpl(
FACET_MININCLUSIVE,
fMinInclusive.toString(),
+ 0,
+ fMinInclusive,
(fFixedFacet & FACET_MININCLUSIVE) != 0,
minInclusiveAnnotation);
count++;
@@ -3142,6 +3173,28 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
return (fFacets != null) ? fFacets : XSObjectListImpl.EMPTY_LIST;
}
+ public XSObject getFacet(int facetType) {
+ if (facetType == FACET_ENUMERATION || facetType == FACET_PATTERN) {
+ XSObjectList list = getMultiValueFacets();
+ for (int i = 0; i < list.getLength(); i++) {
+ XSMultiValueFacet f = (XSMultiValueFacet)list.item(i);
+ if (f.getFacetKind() == facetType) {
+ return f;
+ }
+ }
+ }
+ else {
+ XSObjectList list = getFacets();
+ for (int i = 0; i < list.getLength(); i++) {
+ XSFacet f = (XSFacet)list.item(i);
+ if (f.getFacetKind() == facetType) {
+ return f;
+ }
+ }
+ }
+ return null;
+ }
+
/**
* A list of enumeration and pattern constraining facets if it exists,
* otherwise an empty XSObjectList.
@@ -3162,6 +3215,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSMVFacetImpl(
FACET_PATTERN,
this.getLexicalPattern(),
+ null,
patternAnnotations);
count++;
}
@@ -3170,6 +3224,7 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
new XSMVFacetImpl(
FACET_ENUMERATION,
this.getLexicalEnumeration(),
+ new ObjectListImpl(fEnumeration, fEnumerationSize),
enumerationAnnotations);
count++;
}
@@ -3201,13 +3256,17 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
private static final class XSFacetImpl implements XSFacet {
final short kind;
- final String value;
+ final String svalue;
+ final int ivalue;
+ Object avalue;
final boolean fixed;
final XSObjectList annotations;
- public XSFacetImpl(short kind, String value, boolean fixed, XSAnnotation annotation) {
+ public XSFacetImpl(short kind, String svalue, int ivalue, Object avalue, boolean fixed, XSAnnotation annotation) {
this.kind = kind;
- this.value = value;
+ this.svalue = svalue;
+ this.ivalue = ivalue;
+ this.avalue = avalue;
this.fixed = fixed;
if (annotation != null) {
@@ -3254,7 +3313,24 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
* @see com.sun.org.apache.xerces.internal.xs.XSFacet#getLexicalFacetValue()
*/
public String getLexicalFacetValue() {
- return value;
+ return svalue;
+ }
+
+ public Object getActualFacetValue() {
+ if (avalue == null) {
+ if (kind == FACET_WHITESPACE) {
+ avalue = svalue;
+ }
+ else {
+ // Must a facet with an integer value. Use BigInteger.
+ avalue = BigInteger.valueOf(ivalue);
+ }
+ }
+ return avalue;
+ }
+
+ public int getIntFacetValue() {
+ return ivalue;
}
/* (non-Javadoc)
@@ -3298,11 +3374,13 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
private static final class XSMVFacetImpl implements XSMultiValueFacet {
final short kind;
final XSObjectList annotations;
- final StringList values;
+ final StringList svalues;
+ final ObjectList avalues;
- public XSMVFacetImpl(short kind, StringList values, XSObjectList annotations) {
+ public XSMVFacetImpl(short kind, StringList svalues, ObjectList avalues, XSObjectList annotations) {
this.kind = kind;
- this.values = values;
+ this.svalues = svalues;
+ this.avalues = avalues;
this.annotations = (annotations != null) ? annotations : XSObjectListImpl.EMPTY_LIST;
}
@@ -3324,7 +3402,11 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
* @see com.sun.org.apache.xerces.internal.xs.XSMultiValueFacet#getLexicalFacetValues()
*/
public StringList getLexicalFacetValues() {
- return values;
+ return svalues;
+ }
+
+ public ObjectList getEnumerationValues() {
+ return avalues;
}
/* (non-Javadoc)
@@ -3394,4 +3476,14 @@ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
return valueType;
}
+ private void appendEnumString(StringBuffer sb) {
+ sb.append('[');
+ for (int i = 0; i < fEnumerationSize; i++) {
+ if (i != 0) {
+ sb.append(", ");
+ }
+ sb.append(fEnumeration[i].actualValue);
+ }
+ sb.append(']');
+ }
} // class XSSimpleTypeDecl
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDelegate.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDelegate.java
index 318bc69299e..b5db8703c11 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDelegate.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDelegate.java
@@ -30,6 +30,7 @@ import com.sun.org.apache.xerces.internal.impl.dv.XSFacets;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
+import com.sun.org.apache.xerces.internal.xs.XSObject;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
@@ -76,6 +77,10 @@ public class XSSimpleTypeDelegate
return type.getFacets();
}
+ public XSObject getFacet(int facetType) {
+ return type.getFacet(facetType);
+ }
+
public boolean getFinite() {
return type.getFinite();
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties
index 5b73376eb50..89b1713a8a1 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties
@@ -41,7 +41,13 @@
cvc-complex-type.2.4.b = cvc-complex-type.2.4.b: The content of element ''{0}'' is not complete. One of ''{1}'' is expected.
cvc-complex-type.2.4.c = cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ''{0}''.
cvc-complex-type.2.4.d = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element is expected at this point.
- cvc-complex-type.2.4.e = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element ''{1}'' is expected at this point.
+ cvc-complex-type.2.4.d.1 = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element ''{1}'' is expected at this point.
+ cvc-complex-type.2.4.e = cvc-complex-type.2.4.e: ''{0}'' can occur a maximum of ''{2}'' times in the current sequence. This limit was exceeded. At this point one of ''{1}'' is expected.
+ cvc-complex-type.2.4.f = cvc-complex-type.2.4.f: ''{0}'' can occur a maximum of ''{1}'' times in the current sequence. This limit was exceeded. No child element is expected at this point.
+ cvc-complex-type.2.4.g = cvc-complex-type.2.4.g: Invalid content was found starting with element ''{0}''. ''{1}'' is expected to occur a minimum of ''{2}'' times in the current sequence. One more instance is required to satisfy this constraint.
+ cvc-complex-type.2.4.h = cvc-complex-type.2.4.h: Invalid content was found starting with element ''{0}''. ''{1}'' is expected to occur a minimum of ''{2}'' times in the current sequence. ''{3}'' more instances are required to satisfy this constraint.
+ cvc-complex-type.2.4.i = cvc-complex-type.2.4.i: The content of element ''{0}'' is not complete. ''{1}'' is expected to occur a minimum of ''{2}'' times. One more instance is required to satisfy this constraint.
+ cvc-complex-type.2.4.j = cvc-complex-type.2.4.j: The content of element ''{0}'' is not complete. ''{1}'' is expected to occur a minimum of ''{2}'' times. ''{3}'' more instances are required to satisfy this constraint.
cvc-complex-type.3.1 = cvc-complex-type.3.1: Value ''{2}'' of attribute ''{1}'' of element ''{0}'' is not valid with respect to the corresponding attribute use. Attribute ''{1}'' has a fixed value of ''{3}''.
cvc-complex-type.3.2.1 = cvc-complex-type.3.2.1: Element ''{0}'' does not have an attribute wildcard for attribute ''{1}''.
cvc-complex-type.3.2.2 = cvc-complex-type.3.2.2: Attribute ''{1}'' is not allowed to appear in element ''{0}''.
@@ -51,7 +57,8 @@
cvc-datatype-valid.1.2.1 = cvc-datatype-valid.1.2.1: ''{0}'' is not a valid value for ''{1}''.
cvc-datatype-valid.1.2.2 = cvc-datatype-valid.1.2.2: ''{0}'' is not a valid value of list type ''{1}''.
cvc-datatype-valid.1.2.3 = cvc-datatype-valid.1.2.3: ''{0}'' is not a valid value of union type ''{1}''.
- cvc-elt.1 = cvc-elt.1: Cannot find the declaration of element ''{0}''.
+ cvc-elt.1.a = cvc-elt.1.a: Cannot find the declaration of element ''{0}''.
+ cvc-elt.1.b = cvc-elt.1.b: The name of the element does not match the name of the element declaration. Saw ''{0}''. Expected ''{1}''.
cvc-elt.2 = cvc-elt.2: The value of '{'abstract'}' in the element declaration for ''{0}'' must be false.
cvc-elt.3.1 = cvc-elt.3.1: Attribute ''{1}'' must not appear on element ''{0}'', because the '{'nillable'}' property of ''{0}'' is false.
cvc-elt.3.2.1 = cvc-elt.3.2.1: Element ''{0}'' cannot have character or element information [children], because ''{1}'' is specified.
@@ -289,3 +296,10 @@
TargetNamespace.2 = TargetNamespace.2: Expecting no namespace, but the schema document has a target namespace of ''{1}''.
UndeclaredEntity = UndeclaredEntity: Entity ''{0}'' is not declared.
UndeclaredPrefix = UndeclaredPrefix: Cannot resolve ''{0}'' as a QName: the prefix ''{1}'' is not declared.
+
+
+# JAXP 1.2 schema source property errors
+
+ jaxp12-schema-source-type.1 = The ''http://java.sun.com/xml/jaxp/properties/schemaSource'' property cannot have a value of type ''{0}''. Possible types of the value supported are String, File, InputStream, InputSource or an array of these types.
+ jaxp12-schema-source-type.2 = The ''http://java.sun.com/xml/jaxp/properties/schemaSource'' property cannot have an array value of type ''{0}''. Possible types of the array supported are Object, String, File, InputStream and InputSource.
+ jaxp12-schema-source-ns = When using an array of Objects as the value of the 'http://java.sun.com/xml/jaxp/properties/schemaSource' property, it is illegal to have two schemas that share the same target namespace.
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ConfigurableValidationState.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ConfigurableValidationState.java
index ac8406dd325..00a93fda389 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ConfigurableValidationState.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ConfigurableValidationState.java
@@ -1,9 +1,14 @@
/*
- * Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -16,6 +21,8 @@
package com.sun.org.apache.xerces.internal.impl.validation;
+import java.util.Iterator;
+
/**
*
An extension of ValidationState which can be configured to turn
* off checking for ID/IDREF errors and unparsed entity errors.
@@ -49,7 +56,7 @@ public final class ConfigurableValidationState extends ValidationState {
/**
* Turns checking for ID/IDREF errors on and off.
- * @param setting: true to turn on error checking
+ * @param setting true to turn on error checking,
* false to turn off error checking
*/
public void setIdIdrefChecking(boolean setting) {
@@ -58,7 +65,7 @@ public final class ConfigurableValidationState extends ValidationState {
/**
* Turns checking for unparsed entity errors on and off.
- * @param setting: true to turn on error checking
+ * @param setting true to turn on error checking,
* false to turn off error checking
*/
public void setUnparsedEntityChecking(boolean setting) {
@@ -70,7 +77,7 @@ public final class ConfigurableValidationState extends ValidationState {
* @return null, if ID/IDREF checking is turned off
* otherwise, returns the value of the super implementation
*/
- public String checkIDRefID() {
+ public Iterator checkIDRefID() {
return (fIdIdrefChecking) ? super.checkIDRefID() : null;
}
@@ -103,7 +110,7 @@ public final class ConfigurableValidationState extends ValidationState {
/**
* Adds the ID, if ID/IDREF checking is enabled.
- * @param the ID to add
+ * @param name the ID to add
*/
public void addId(String name) {
if (fIdIdrefChecking) {
@@ -113,7 +120,7 @@ public final class ConfigurableValidationState extends ValidationState {
/**
* Adds the IDREF, if ID/IDREF checking is enabled.
- * @param the IDREF to add
+ * @param name the IDREF to add
*/
public void addIdRef(String name) {
if (fIdIdrefChecking) {
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ValidationState.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ValidationState.java
index 686e2b1c916..c3a94519458 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ValidationState.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ValidationState.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001, 2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,11 +21,12 @@
package com.sun.org.apache.xerces.internal.impl.validation;
-import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.impl.dv.ValidationContext;
-
+import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
import java.util.Locale;
/**
@@ -86,25 +88,24 @@ public class ValidationState implements ValidationContext {
/**
* return null if all IDREF values have a corresponding ID value;
- * otherwise return the first IDREF value without a matching ID value.
+ * otherwise return an iterator for all the IDREF values without
+ * a matching ID value.
*/
- public String checkIDRefID () {
- if (fIdList == null) {
- if (fIdRefList != null) {
- return fIdRefList.get(0);
- }
- }
-
+ public Iterator checkIDRefID () {
+ HashSet missingIDs = null;
if (fIdRefList != null) {
String key;
for (int i = 0; i < fIdRefList.size(); i++) {
key = fIdRefList.get(i);
- if (!fIdList.contains(key)) {
- return key;
+ if (fIdList == null || !fIdList.contains(key)) {
+ if (missingIDs == null) {
+ missingIDs = new HashSet();
+ }
+ missingIDs.add(key);
}
}
}
- return null;
+ return (missingIDs != null) ? missingIDs.iterator() : null;
}
public void reset () {
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/AttributePSVImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/AttributePSVImpl.java
index 14fb075b24b..fdbf305c47a 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/AttributePSVImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/AttributePSVImpl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2000-2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,14 +21,17 @@
package com.sun.org.apache.xerces.internal.impl.xs;
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
+import com.sun.org.apache.xerces.internal.xs.ItemPSVI;
import com.sun.org.apache.xerces.internal.xs.ShortList;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
+import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
-import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
-import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
-import com.sun.org.apache.xerces.internal.xs.XSConstants;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
/**
* Attribute PSV infoset augmentations implementation.
@@ -49,20 +53,8 @@ public class AttributePSVImpl implements AttributePSVI {
* value in the original document, this is false; otherwise, it is true */
protected boolean fSpecified = false;
- /** schema normalized value property */
- protected String fNormalizedValue = null;
-
- /** schema actual value */
- protected Object fActualValue = null;
-
- /** schema actual value type */
- protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
- /** actual value types if the value is a list */
- protected ShortList fItemValueTypes = null;
-
- /** member type definition against which attribute was validated */
- protected XSSimpleTypeDefinition fMemberType = null;
+ /** Schema value */
+ protected ValidatedInfo fValue = new ValidatedInfo();
/** validation attempted: none, partial, full */
protected short fValidationAttempted = AttributePSVI.VALIDATION_NONE;
@@ -70,16 +62,67 @@ public class AttributePSVImpl implements AttributePSVI {
/** validity: valid, invalid, unknown */
protected short fValidity = AttributePSVI.VALIDITY_NOTKNOWN;
- /** error codes */
- protected String[] fErrorCodes = null;
+ /** error codes and error messages */
+ protected String[] fErrors = null;
/** validation context: could be QName or XPath expression*/
protected String fValidationContext = null;
+ /** true if this object is immutable **/
+ protected boolean fIsConstant;
+
+ public AttributePSVImpl() {}
+
+ public AttributePSVImpl(boolean isConstant, AttributePSVI attrPSVI) {
+ fDeclaration = attrPSVI.getAttributeDeclaration();
+ fTypeDecl = attrPSVI.getTypeDefinition();
+ fSpecified = attrPSVI.getIsSchemaSpecified();
+ fValue.copyFrom(attrPSVI.getSchemaValue());
+ fValidationAttempted = attrPSVI.getValidationAttempted();
+ fValidity = attrPSVI.getValidity();
+ if (attrPSVI instanceof AttributePSVImpl) {
+ final AttributePSVImpl attrPSVIImpl = (AttributePSVImpl) attrPSVI;
+ fErrors = (attrPSVIImpl.fErrors != null) ?
+ (String[]) attrPSVIImpl.fErrors.clone() : null;
+ }
+ else {
+ final StringList errorCodes = attrPSVI.getErrorCodes();
+ final int length = errorCodes.getLength();
+ if (length > 0) {
+ final StringList errorMessages = attrPSVI.getErrorMessages();
+ final String[] errors = new String[length << 1];
+ for (int i = 0, j = 0; i < length; ++i) {
+ errors[j++] = errorCodes.item(i);
+ errors[j++] = errorMessages.item(i);
+ }
+ fErrors = errors;
+ }
+ }
+ fValidationContext = attrPSVI.getValidationContext();
+ fIsConstant = isConstant;
+ }
+
//
// AttributePSVI methods
//
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#constant()
+ */
+ public ItemPSVI constant() {
+ if (isConstant()) {
+ return this;
+ }
+ return new AttributePSVImpl(true, this);
+ }
+
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#isConstant()
+ */
+ public boolean isConstant() {
+ return fIsConstant;
+ }
+
/**
* [schema default]
*
@@ -98,7 +141,7 @@ public class AttributePSVImpl implements AttributePSVI {
* @return the normalized value of this item after validation
*/
public String getSchemaNormalizedValue() {
- return fNormalizedValue;
+ return fValue.getNormalizedValue();
}
/**
@@ -139,9 +182,23 @@ public class AttributePSVImpl implements AttributePSVI {
* @return list of error codes
*/
public StringList getErrorCodes() {
- if (fErrorCodes == null)
- return null;
- return new StringListImpl(fErrorCodes, fErrorCodes.length);
+ if (fErrors == null || fErrors.length == 0) {
+ return StringListImpl.EMPTY_LIST;
+ }
+ return new PSVIErrorList(fErrors, true);
+ }
+
+ /**
+ * A list of error messages generated from the validation attempt or
+ * an empty StringList if no errors occurred during the
+ * validation attempt. The indices of error messages in this list are
+ * aligned with those in the [schema error code] list.
+ */
+ public StringList getErrorMessages() {
+ if (fErrors == null || fErrors.length == 0) {
+ return StringListImpl.EMPTY_LIST;
+ }
+ return new PSVIErrorList(fErrors, false);
}
// This is the only information we can provide in a pipeline.
@@ -168,7 +225,7 @@ public class AttributePSVImpl implements AttributePSVI {
* @return a simple type declaration
*/
public XSSimpleTypeDefinition getMemberTypeDefinition() {
- return fMemberType;
+ return fValue.getMemberTypeDefinition();
}
/**
@@ -185,38 +242,41 @@ public class AttributePSVImpl implements AttributePSVI {
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
*/
public Object getActualNormalizedValue() {
- return this.fActualValue;
+ return fValue.getActualValue();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
*/
public short getActualNormalizedValueType() {
- return this.fActualValueType;
+ return fValue.getActualValueType();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
*/
public ShortList getItemValueTypes() {
- return this.fItemValueTypes;
+ return fValue.getListValueTypes();
+ }
+
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getSchemaValue()
+ */
+ public XSValue getSchemaValue() {
+ return fValue;
}
/**
* Reset()
*/
public void reset() {
- fNormalizedValue = null;
- fActualValue = null;
- fActualValueType = XSConstants.UNAVAILABLE_DT;
- fItemValueTypes = null;
+ fValue.reset();
fDeclaration = null;
fTypeDecl = null;
fSpecified = false;
- fMemberType = null;
fValidationAttempted = AttributePSVI.VALIDATION_NONE;
fValidity = AttributePSVI.VALIDITY_NOTKNOWN;
- fErrorCodes = null;
+ fErrors = null;
fValidationContext = null;
}
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/ElementPSVImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/ElementPSVImpl.java
index b5a77064f9d..0c4d9a3957e 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/ElementPSVImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/ElementPSVImpl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2000-2002,2004,2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,16 +21,19 @@
package com.sun.org.apache.xerces.internal.impl.xs;
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
+import com.sun.org.apache.xerces.internal.xs.ItemPSVI;
import com.sun.org.apache.xerces.internal.xs.ShortList;
import com.sun.org.apache.xerces.internal.xs.StringList;
+import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
-import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
-import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
-import com.sun.org.apache.xerces.internal.xs.XSConstants;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
/**
* Element PSV infoset augmentations implementation.
@@ -61,32 +65,20 @@ public class ElementPSVImpl implements ElementPSVI {
*/
protected boolean fSpecified = false;
- /** schema normalized value property */
- protected String fNormalizedValue = null;
-
- /** schema actual value */
- protected Object fActualValue = null;
-
- /** schema actual value type */
- protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
- /** actual value types if the value is a list */
- protected ShortList fItemValueTypes = null;
+ /** Schema value */
+ protected ValidatedInfo fValue = new ValidatedInfo();
/** http://www.w3.org/TR/xmlschema-1/#e-notation*/
protected XSNotationDeclaration fNotation = null;
- /** member type definition against which element was validated */
- protected XSSimpleTypeDefinition fMemberType = null;
-
/** validation attempted: none, partial, full */
protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE;
/** validity: valid, invalid, unknown */
protected short fValidity = ElementPSVI.VALIDITY_NOTKNOWN;
- /** error codes */
- protected String[] fErrorCodes = null;
+ /** error codes and error messages */
+ protected String[] fErrors = null;
/** validation context: could be QName or XPath expression*/
protected String fValidationContext = null;
@@ -97,10 +89,65 @@ public class ElementPSVImpl implements ElementPSVI {
/** the schema information property */
protected XSModel fSchemaInformation = null;
+ /** true if this object is immutable **/
+ protected boolean fIsConstant;
+
+ public ElementPSVImpl() {}
+
+ public ElementPSVImpl(boolean isConstant, ElementPSVI elementPSVI) {
+ fDeclaration = elementPSVI.getElementDeclaration();
+ fTypeDecl = elementPSVI.getTypeDefinition();
+ fNil = elementPSVI.getNil();
+ fSpecified = elementPSVI.getIsSchemaSpecified();
+ fValue.copyFrom(elementPSVI.getSchemaValue());
+ fNotation = elementPSVI.getNotation();
+ fValidationAttempted = elementPSVI.getValidationAttempted();
+ fValidity = elementPSVI.getValidity();
+ fValidationContext = elementPSVI.getValidationContext();
+ if (elementPSVI instanceof ElementPSVImpl) {
+ final ElementPSVImpl elementPSVIImpl = (ElementPSVImpl) elementPSVI;
+ fErrors = (elementPSVIImpl.fErrors != null) ?
+ (String[]) elementPSVIImpl.fErrors.clone() : null;
+ elementPSVIImpl.copySchemaInformationTo(this);
+ }
+ else {
+ final StringList errorCodes = elementPSVI.getErrorCodes();
+ final int length = errorCodes.getLength();
+ if (length > 0) {
+ final StringList errorMessages = elementPSVI.getErrorMessages();
+ final String[] errors = new String[length << 1];
+ for (int i = 0, j = 0; i < length; ++i) {
+ errors[j++] = errorCodes.item(i);
+ errors[j++] = errorMessages.item(i);
+ }
+ fErrors = errors;
+ }
+ fSchemaInformation = elementPSVI.getSchemaInformation();
+ }
+ fIsConstant = isConstant;
+ }
+
//
// ElementPSVI methods
//
+ /* (non-Javadoc)
+ * @see org.apache.xerces.xs.ItemPSVI#constant()
+ */
+ public ItemPSVI constant() {
+ if (isConstant()) {
+ return this;
+ }
+ return new ElementPSVImpl(true, this);
+ }
+
+ /* (non-Javadoc)
+ * @see org.apache.xerces.xs.ItemPSVI#isConstant()
+ */
+ public boolean isConstant() {
+ return fIsConstant;
+ }
+
/**
* [schema default]
*
@@ -119,7 +166,7 @@ public class ElementPSVImpl implements ElementPSVI {
* @return the normalized value of this item after validation
*/
public String getSchemaNormalizedValue() {
- return fNormalizedValue;
+ return fValue.getNormalizedValue();
}
/**
@@ -159,11 +206,24 @@ public class ElementPSVImpl implements ElementPSVI {
* @return Array of error codes
*/
public StringList getErrorCodes() {
- if (fErrorCodes == null)
- return null;
- return new StringListImpl(fErrorCodes, fErrorCodes.length);
+ if (fErrors == null || fErrors.length == 0) {
+ return StringListImpl.EMPTY_LIST;
+ }
+ return new PSVIErrorList(fErrors, true);
}
+ /**
+ * A list of error messages generated from the validation attempt or
+ * an empty StringList if no errors occurred during the
+ * validation attempt. The indices of error messages in this list are
+ * aligned with those in the [schema error code] list.
+ */
+ public StringList getErrorMessages() {
+ if (fErrors == null || fErrors.length == 0) {
+ return StringListImpl.EMPTY_LIST;
+ }
+ return new PSVIErrorList(fErrors, false);
+ }
// This is the only information we can provide in a pipeline.
public String getValidationContext() {
@@ -207,7 +267,7 @@ public class ElementPSVImpl implements ElementPSVI {
* @return a simple type declaration
*/
public XSSimpleTypeDefinition getMemberTypeDefinition() {
- return fMemberType;
+ return fValue.getMemberTypeDefinition();
}
/**
@@ -237,21 +297,28 @@ public class ElementPSVImpl implements ElementPSVI {
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
*/
public Object getActualNormalizedValue() {
- return this.fActualValue;
+ return fValue.getActualValue();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
*/
public short getActualNormalizedValueType() {
- return this.fActualValueType;
+ return fValue.getActualValueType();
}
/* (non-Javadoc)
* @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
*/
public ShortList getItemValueTypes() {
- return this.fItemValueTypes;
+ return fValue.getListValueTypes();
+ }
+
+ /* (non-Javadoc)
+ * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getSchemaValue()
+ */
+ public XSValue getSchemaValue() {
+ return fValue;
}
/**
@@ -263,15 +330,15 @@ public class ElementPSVImpl implements ElementPSVI {
fNil = false;
fSpecified = false;
fNotation = null;
- fMemberType = null;
fValidationAttempted = ElementPSVI.VALIDATION_NONE;
fValidity = ElementPSVI.VALIDITY_NOTKNOWN;
- fErrorCodes = null;
+ fErrors = null;
fValidationContext = null;
- fNormalizedValue = null;
- fActualValue = null;
- fActualValueType = XSConstants.UNAVAILABLE_DT;
- fItemValueTypes = null;
+ fValue.reset();
}
+ public void copySchemaInformationTo(ElementPSVImpl target) {
+ target.fGrammars = fGrammars;
+ target.fSchemaInformation = fSchemaInformation;
+ }
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/PSVIErrorList.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/PSVIErrorList.java
new file mode 100644
index 00000000000..ee78210bdba
--- /dev/null
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/PSVIErrorList.java
@@ -0,0 +1,92 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sun.org.apache.xerces.internal.impl.xs;
+
+import java.util.AbstractList;
+
+import com.sun.org.apache.xerces.internal.xs.StringList;
+
+/**
+ * StringList implementation for schema error codes and error messages.
+ *
+ * @xerces.internal
+ *
+ * @author Michael Glavassevich, IBM
+ *
+ */
+final class PSVIErrorList extends AbstractList implements StringList {
+
+ private final String[] fArray;
+ private final int fLength;
+ private final int fOffset;
+
+ public PSVIErrorList(String[] array, boolean even) {
+ fArray = array;
+ fLength = (fArray.length >> 1);
+ fOffset = even ? 0 : 1;
+ }
+
+ public boolean contains(String item) {
+ if (item == null) {
+ for (int i = 0; i < fLength; ++i) {
+ if (fArray[(i << 1) + fOffset] == null) {
+ return true;
+ }
+ }
+ }
+ else {
+ for (int i = 0; i < fLength; ++i) {
+ if (item.equals(fArray[(i << 1) + fOffset])) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public int getLength() {
+ return fLength;
+ }
+
+ public String item(int index) {
+ if (index < 0 || index >= fLength) {
+ return null;
+ }
+ return fArray[(index << 1) + fOffset];
+ }
+
+ /*
+ * List methods
+ */
+
+ public Object get(int index) {
+ if (index >= 0 && index < fLength) {
+ return fArray[(index << 1) + fOffset];
+ }
+ throw new IndexOutOfBoundsException("Index: " + index);
+ }
+
+ public int size() {
+ return getLength();
+ }
+
+} // class PSVIErrorList
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SchemaGrammar.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SchemaGrammar.java
index 06ec54dd9d2..1219ee7eb3b 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SchemaGrammar.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SchemaGrammar.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,9 +21,6 @@
package com.sun.org.apache.xerces.internal.impl.xs;
-import java.lang.ref.SoftReference;
-import java.util.Vector;
-
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
@@ -49,6 +47,7 @@ import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
+import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
@@ -59,6 +58,8 @@ import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
+import java.lang.ref.SoftReference;
+import java.util.Vector;
import org.xml.sax.SAXException;
/**
@@ -135,7 +136,7 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
* Default constructor.
*
* @param targetNamespace
- * @param grammarDesc the XMLGrammarDescription corresponding to this objec
+ * @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
@@ -145,35 +146,39 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
- // REVISIT: do we know the numbers of the following global decls
- // when creating this grammar? If so, we can pass the numbers in,
- // and use that number to initialize the following hashtables.
- fGlobalAttrDecls = new SymbolHash();
- fGlobalAttrGrpDecls = new SymbolHash();
- fGlobalElemDecls = new SymbolHash();
- fGlobalGroupDecls = new SymbolHash();
- fGlobalNotationDecls = new SymbolHash();
- fGlobalIDConstraintDecls = new SymbolHash();
+ // REVISIT: the initial sizes being chosen for each SymbolHash
+ // may not be ideal and could still be tuned. They were chosen
+ // somewhat arbitrarily to reduce the initial footprint of
+ // SymbolHash buckets from 1,515 to 177 (about 12% of the
+ // default size).
+ fGlobalAttrDecls = new SymbolHash(12);
+ fGlobalAttrGrpDecls = new SymbolHash(5);
+ fGlobalElemDecls = new SymbolHash(25);
+ fGlobalGroupDecls = new SymbolHash(5);
+ fGlobalNotationDecls = new SymbolHash(1);
+ fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
- fGlobalAttrDeclsExt = new SymbolHash();
- fGlobalAttrGrpDeclsExt = new SymbolHash();
- fGlobalElemDeclsExt = new SymbolHash();
- fGlobalGroupDeclsExt = new SymbolHash();
- fGlobalNotationDeclsExt = new SymbolHash();
- fGlobalIDConstraintDeclsExt = new SymbolHash();
- fGlobalTypeDeclsExt = new SymbolHash();
+ fGlobalAttrDeclsExt = new SymbolHash(12);
+ fGlobalAttrGrpDeclsExt = new SymbolHash(5);
+ fGlobalElemDeclsExt = new SymbolHash(25);
+ fGlobalGroupDeclsExt = new SymbolHash(5);
+ fGlobalNotationDeclsExt = new SymbolHash(1);
+ fGlobalIDConstraintDeclsExt = new SymbolHash(3);
+ fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
- fAllGlobalElemDecls = new SymbolHash();
+ fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
- if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA)
+ if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
- else
- fGlobalTypeDecls = new SymbolHash();
+ }
+ else {
+ fGlobalTypeDecls = new SymbolHash(25);
+ }
} // (String, XSDDescription)
// Clone an existing schema grammar
@@ -232,7 +237,7 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
- System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount);
+ System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
@@ -626,19 +631,19 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
- XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, new XSObjectListImpl(null, 0));
+ XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
- XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0));
+ XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
- XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0));
+ XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
@@ -1178,8 +1183,8 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
- fParticle = null;
- fAttrGrp = null;
+ fParticle = createParticle();
+ fAttrGrp = createAttrGrp();
}
// overridden methods
@@ -1211,11 +1216,15 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// null implementation
}
- public XSObjectList getAttributeUses() {
+ public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
- public XSAttributeGroupDecl getAttrGrp() {
+ public XSNamespaceItem getNamespaceItem() {
+ return SG_SchemaNS;
+ }
+
+ private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
@@ -1223,13 +1232,7 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
return attrGrp;
}
- public XSWildcard getAttributeWildcard() {
- XSWildcardDecl wildcard = new XSWildcardDecl();
- wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
- return wildcard;
- }
-
- public XSParticle getParticle() {
+ private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
@@ -1253,14 +1256,6 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
return particleG;
}
-
- public XSObjectList getAnnotations() {
- return XSObjectListImpl.EMPTY_LIST;
- }
-
- public XSNamespaceItem getNamespaceItem() {
- return SG_SchemaNS;
- }
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
@@ -1347,7 +1342,7 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
false, // model group
false, // particle
false, // wildcard
- false, // idc
+ true, // idc
true, // notation
false, // annotation
false, // facet
@@ -1484,6 +1479,9 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
+ case XSConstants.IDENTITY_CONSTRAINT:
+ table = this.fGlobalIDConstraintDecls;
+ break;
}
// for complex/simple types, create a special implementation,
@@ -1533,6 +1531,9 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
+ case XSConstants.IDENTITY_CONSTRAINT:
+ table = this.fGlobalIDConstraintDeclsExt;
+ break;
}
Object[] entries = table.getEntries();
@@ -1610,6 +1611,10 @@ public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
return getGlobalNotationDecl(name);
}
+ public XSIDCDefinition getIDCDefinition(String name) {
+ return getIDConstraintDecl(name);
+ }
+
/**
* [document location]
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SubstitutionGroupHandler.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SubstitutionGroupHandler.java
index f2d4e745af4..0bb9a180446 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SubstitutionGroupHandler.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SubstitutionGroupHandler.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -40,14 +41,14 @@ public class SubstitutionGroupHandler {
private static final XSElementDecl[] EMPTY_GROUP = new XSElementDecl[0];
- // grammar resolver
- XSGrammarBucket fGrammarBucket;
+ // global element declaration resolver
+ private final XSElementDeclHelper fXSElementDeclHelper;
/**
* Default constructor
*/
- public SubstitutionGroupHandler(XSGrammarBucket grammarBucket) {
- fGrammarBucket = grammarBucket;
+ public SubstitutionGroupHandler(XSElementDeclHelper elementDeclHelper) {
+ fXSElementDeclHelper = elementDeclHelper;
}
// 3.9.4 Element Sequence Locally Valid (Particle) 2.3.3
@@ -60,26 +61,25 @@ public class SubstitutionGroupHandler {
// if the exemplar is not a global element decl, then it's not possible
// to be substituted by another element.
- if (exemplar.fScope != XSConstants.SCOPE_GLOBAL)
+ if (exemplar.fScope != XSConstants.SCOPE_GLOBAL) {
return null;
+ }
// if the decl blocks substitution, return false
- if ((exemplar.fBlock & XSConstants.DERIVATION_SUBSTITUTION) != 0)
- return null;
-
- // get grammar of the element
- SchemaGrammar sGrammar = fGrammarBucket.getGrammar(element.uri);
- if (sGrammar == null)
+ if ((exemplar.fBlock & XSConstants.DERIVATION_SUBSTITUTION) != 0) {
return null;
+ }
// get the decl for the element
- XSElementDecl eDecl = sGrammar.getGlobalElementDecl(element.localpart);
- if (eDecl == null)
+ XSElementDecl eDecl = fXSElementDeclHelper.getGlobalElementDecl(element);
+ if (eDecl == null) {
return null;
+ }
// and check by using substitutionGroup information
- if (substitutionGroupOK(eDecl, exemplar, exemplar.fBlock))
+ if (substitutionGroupOK(eDecl, exemplar, exemplar.fBlock)) {
return eDecl;
+ }
return null;
}
@@ -89,13 +89,15 @@ public class SubstitutionGroupHandler {
protected boolean substitutionGroupOK(XSElementDecl element, XSElementDecl exemplar, short blockingConstraint) {
// For an element declaration (call it D) to be validly substitutable for another element declaration (call it C) subject to a blocking constraint (a subset of {substitution, extension, restriction}, the value of a {disallowed substitutions}) one of the following must be true:
// 1. D and C are the same element declaration.
- if (element == exemplar)
+ if (element == exemplar) {
return true;
+ }
// 2 All of the following must be true:
// 2.1 The blocking constraint does not contain substitution.
- if ((blockingConstraint & XSConstants.DERIVATION_SUBSTITUTION) != 0)
+ if ((blockingConstraint & XSConstants.DERIVATION_SUBSTITUTION) != 0) {
return false;
+ }
// 2.2 There is a chain of {substitution group affiliation}s from D to C, that is, either D's {substitution group affiliation} is C, or D's {substitution group affiliation}'s {substitution group affiliation} is C, or . . .
XSElementDecl subGroup = element.fSubGroup;
@@ -103,14 +105,16 @@ public class SubstitutionGroupHandler {
subGroup = subGroup.fSubGroup;
}
- if (subGroup == null)
+ if (subGroup == null) {
return false;
+ }
// 2.3 The set of all {derivation method}s involved in the derivation of D's {type definition} from C's {type definition} does not intersect with the union of the blocking constraint, C's {prohibited substitutions} (if C is complex, otherwise the empty set) and the {prohibited substitutions} (respectively the empty set) of any intermediate {type definition}s in the derivation of D's {type definition} from C's {type definition}.
// prepare the combination of {derivation method} and
// {disallowed substitution}
return typeDerivationOK(element.fType, exemplar.fType, blockingConstraint);
}
+
private boolean typeDerivationOK(XSTypeDefinition derived, XSTypeDefinition base, short blockingConstraint) {
short devMethod = 0, blockConstraint = blockingConstraint;
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java
index 23289a7b55f..3a656e777d2 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 2000-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,26 +20,12 @@
package com.sun.org.apache.xerces.internal.impl.xs;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.Hashtable;
-import java.util.Locale;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
import com.sun.org.apache.xerces.internal.dom.DOMMessageFormatter;
import com.sun.org.apache.xerces.internal.dom.DOMStringListImpl;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.XMLEntityManager;
import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
-import com.sun.org.apache.xerces.internal.impl.dv.DVFactoryException;
import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeValueException;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.xs.SchemaDVFactoryImpl;
@@ -49,13 +35,16 @@ import com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler;
import com.sun.org.apache.xerces.internal.util.DOMEntityResolverWrapper;
import com.sun.org.apache.xerces.internal.util.DOMErrorHandlerWrapper;
import com.sun.org.apache.xerces.internal.util.DefaultErrorHandler;
+import com.sun.org.apache.xerces.internal.util.MessageFormatter;
import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
import com.sun.org.apache.xerces.internal.util.Status;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException;
import com.sun.org.apache.xerces.internal.util.XMLSymbols;
import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
+import com.sun.org.apache.xerces.internal.xni.QName;
import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.grammars.Grammar;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
@@ -72,14 +61,26 @@ import com.sun.org.apache.xerces.internal.xs.LSInputList;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSLoader;
import com.sun.org.apache.xerces.internal.xs.XSModel;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.WeakHashMap;
import javax.xml.XMLConstants;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMError;
import org.w3c.dom.DOMErrorHandler;
-import org.w3c.dom.DOMStringList;
import org.w3c.dom.DOMException;
+import org.w3c.dom.DOMStringList;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
@@ -101,7 +102,7 @@ import org.xml.sax.InputSource;
* @author Neil Graham, IBM
*/
-public class XMLSchemaLoader implements XMLGrammarLoader, XMLComponent,
+public class XMLSchemaLoader implements XMLGrammarLoader, XMLComponent, XSElementDeclHelper,
// XML Component API
XSLoader, DOMConfiguration {
@@ -249,8 +250,7 @@ XSLoader, DOMConfiguration {
// Data
// features and properties
- private ParserConfigurationSettings fLoaderConfig = new ParserConfigurationSettings();
- private SymbolTable fSymbolTable = null;
+ private final ParserConfigurationSettings fLoaderConfig = new ParserConfigurationSettings();
private XMLErrorReporter fErrorReporter = new XMLErrorReporter ();
private XMLEntityManager fEntityManager = null;
private XMLEntityResolver fUserEntityResolver = null;
@@ -276,7 +276,7 @@ XSLoader, DOMConfiguration {
private XSDDescription fXSDDescription = new XSDDescription();
private String faccessExternalSchema = Constants.EXTERNAL_ACCESS_DEFAULT;
- private Map fJAXPCache;
+ private WeakHashMap fJAXPCache;
private Locale fLocale = Locale.getDefault();
// XSLoader attributes
@@ -350,8 +350,8 @@ XSLoader, DOMConfiguration {
grammarBucket = new XSGrammarBucket();
}
fGrammarBucket = grammarBucket;
- if(sHandler == null) {
- sHandler = new SubstitutionGroupHandler(fGrammarBucket);
+ if (sHandler == null) {
+ sHandler = new SubstitutionGroupHandler(this);
}
fSubGroupHandler = sHandler;
@@ -360,10 +360,7 @@ XSLoader, DOMConfiguration {
}
fCMBuilder = builder;
fSchemaHandler = new XSDHandler(fGrammarBucket);
- if (fDeclPool != null) {
- fDeclPool.reset();
- }
- fJAXPCache = new HashMap();
+ fJAXPCache = new WeakHashMap();
fSettingsChanged = true;
}
@@ -527,8 +524,8 @@ XSLoader, DOMConfiguration {
* Returns a Grammar object by parsing the contents of the
* entities pointed to by sources.
*
- * @param source[] the locations of the entity which forms
- * the staring point of the grammars to be constructed
+ * @param source the locations of the entity which forms
+ * the staring point of the grammars to be constructed
* @throws IOException when a problem is encounted reading the entity
* @throws XNIException when a condition arises (such as a FatalError) that requires parsing
* of the entity be terminated
@@ -618,7 +615,8 @@ XSLoader, DOMConfiguration {
return grammar;
} // loadSchema(XSDDescription, XMLInputSource): SchemaGrammar
- /** This method tries to resolve location of the given schema.
+ /**
+ * This method tries to resolve location of the given schema.
* The loader stores the namespace/location pairs in a hashtable (use "" as the
* namespace of absent namespace). When resolving an entity, loader first tries
* to find in the hashtable whether there is a value for that namespace,
@@ -627,7 +625,7 @@ XSLoader, DOMConfiguration {
* @param desc
* @param locationPairs
* @param entityResolver
- * @return
+ * @return the XMLInputSource
* @throws IOException
*/
public static XMLInputSource resolveDocument(XSDDescription desc, Map locationPairs,
@@ -671,7 +669,7 @@ XSLoader, DOMConfiguration {
XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);
// validation the string value to get the list of URI's
attrDecl.fType.validate(sl, null, null);
- if (!tokenizeSchemaLocationStr(sl, locations)) {
+ if (!tokenizeSchemaLocationStr(sl, locations, null)) {
// report warning (odd number of items)
er.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"SchemaLocation",
@@ -714,7 +712,7 @@ XSLoader, DOMConfiguration {
// @param schemaStr The schemaLocation string to tokenize
// @param locations HashMap mapping namespaces to LocationArray objects holding lists of locaitons
// @return true if no problems; false if string could not be tokenized
- public static boolean tokenizeSchemaLocationStr(String schemaStr, Map locations) {
+ public static boolean tokenizeSchemaLocationStr(String schemaStr, Map locations, String base) {
if (schemaStr!= null) {
StringTokenizer t = new StringTokenizer(schemaStr, " \n\t\r");
String namespace, location;
@@ -729,6 +727,12 @@ XSLoader, DOMConfiguration {
la = new LocationArray();
locations.put(namespace, la);
}
+ if (base != null) {
+ try {
+ location = XMLEntityManager.expandSystemId(location, base, false);
+ } catch (MalformedURIException e) {
+ }
+ }
la.addLocation(location);
}
}
@@ -756,10 +760,10 @@ XSLoader, DOMConfiguration {
String sid = null;
if (componentType == null) {
// Not an array
- if(fJAXPSource instanceof InputStream ||
+ if (fJAXPSource instanceof InputStream ||
fJAXPSource instanceof InputSource) {
SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource);
- if(g != null) {
+ if (g != null) {
fGrammarBucket.putGrammar(g);
return;
}
@@ -776,38 +780,40 @@ XSLoader, DOMConfiguration {
}
SchemaGrammar g = loadSchema(fXSDDescription, xis, locationPairs);
// it is possible that we won't be able to resolve JAXP schema-source location
- if (g != null){
- if(fJAXPSource instanceof InputStream ||
+ if (g != null) {
+ if (fJAXPSource instanceof InputStream ||
fJAXPSource instanceof InputSource) {
fJAXPCache.put(fJAXPSource, g);
- if(fIsCheckedFully) {
+ if (fIsCheckedFully) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter);
}
}
fGrammarBucket.putGrammar(g);
}
- return ;
- } else if ( (componentType != Object.class) &&
+ return;
+ }
+ else if ( (componentType != Object.class) &&
(componentType != String.class) &&
- (componentType != File.class) &&
- (componentType != InputStream.class) &&
- (componentType != InputSource.class)
+ !File.class.isAssignableFrom(componentType) &&
+ !InputStream.class.isAssignableFrom(componentType) &&
+ !InputSource.class.isAssignableFrom(componentType) &&
+ !componentType.isInterface()
) {
// Not an Object[], String[], File[], InputStream[], InputSource[]
+ MessageFormatter mf = fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN);
throw new XMLConfigurationException(
- Status.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+
- "\" property cannot have an array of type {"+componentType.getName()+
- "}. Possible types of the array supported are Object, String, File, "+
- "InputStream, InputSource.");
+ Status.NOT_SUPPORTED,
+ mf.formatMessage(fErrorReporter.getLocale(), "jaxp12-schema-source-type.2",
+ new Object [] {componentType.getName()}));
}
// JAXP spec. allow []s of type String, File, InputStream,
// InputSource also, apart from [] of type Object.
Object[] objArr = (Object[]) fJAXPSource;
- //make local vector for storing targetn namespaces of schemasources specified in object arrays.
- Vector jaxpSchemaSourceNamespaces = new Vector() ;
+ // make local array for storing target namespaces of schemasources specified in object arrays.
+ ArrayList jaxpSchemaSourceNamespaces = new ArrayList();
for (int i = 0; i < objArr.length; i++) {
- if(objArr[i] instanceof InputStream ||
+ if (objArr[i] instanceof InputStream ||
objArr[i] instanceof InputSource) {
SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]);
if (g != null) {
@@ -829,18 +835,18 @@ XSLoader, DOMConfiguration {
// load schema
SchemaGrammar grammar = fSchemaHandler.parseSchema(xis,fXSDDescription, locationPairs);
- if(fIsCheckedFully) {
+ if (fIsCheckedFully) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter);
}
- if(grammar != null){
- targetNamespace = grammar.getTargetNamespace() ;
- if(jaxpSchemaSourceNamespaces.contains(targetNamespace)){
- //when an array of objects is passed it is illegal to have two schemas that share same namespace.
- throw new java.lang.IllegalArgumentException(
- " When using array of Objects as the value of SCHEMA_SOURCE property , " +
- "no two Schemas should share the same targetNamespace. " );
+ if (grammar != null) {
+ targetNamespace = grammar.getTargetNamespace();
+ if (jaxpSchemaSourceNamespaces.contains(targetNamespace)) {
+ // when an array of objects is passed it is illegal to have two schemas that share same namespace.
+ MessageFormatter mf = fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN);
+ throw new java.lang.IllegalArgumentException(mf.formatMessage(fErrorReporter.getLocale(),
+ "jaxp12-schema-source-ns", null));
}
- else{
+ else {
jaxpSchemaSourceNamespaces.add(targetNamespace) ;
}
if(objArr[i] instanceof InputStream ||
@@ -849,15 +855,13 @@ XSLoader, DOMConfiguration {
}
fGrammarBucket.putGrammar(grammar);
}
- else{
+ else {
//REVISIT: What should be the acutal behavior if grammar can't be loaded as specified in schema source?
}
}
}//processJAXPSchemaSource
- private XMLInputSource xsdToXMLInputSource(
- Object val)
- {
+ private XMLInputSource xsdToXMLInputSource(Object val) {
if (val instanceof String) {
// String value is treated as a URI that is passed through the
// EntityResolver
@@ -867,7 +871,8 @@ XSLoader, DOMConfiguration {
XMLInputSource xis = null;
try {
xis = fEntityManager.resolveEntity(fXSDDescription);
- } catch (IOException ex) {
+ }
+ catch (IOException ex) {
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"schema_reference.4",
new Object[] { loc }, XMLErrorReporter.SEVERITY_ERROR);
@@ -878,12 +883,15 @@ XSLoader, DOMConfiguration {
return new XMLInputSource(null, loc, null);
}
return xis;
- } else if (val instanceof InputSource) {
+ }
+ else if (val instanceof InputSource) {
return saxToXMLInputSource((InputSource) val);
- } else if (val instanceof InputStream) {
+ }
+ else if (val instanceof InputStream) {
return new XMLInputSource(null, null, null,
(InputStream) val, null);
- } else if (val instanceof File) {
+ }
+ else if (val instanceof File) {
File file = (File) val;
InputStream is = null;
try {
@@ -893,13 +901,13 @@ XSLoader, DOMConfiguration {
"schema_reference.4", new Object[] { file.toString() },
XMLErrorReporter.SEVERITY_ERROR);
}
- return new XMLInputSource(null, null, null, is, null);
+ return new XMLInputSource(null, file.toURI().toString(), null, is, null);
}
+ MessageFormatter mf = fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN);
throw new XMLConfigurationException(
- Status.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+
- "\" property cannot have a value of type {"+val.getClass().getName()+
- "}. Possible types of the value supported are String, File, InputStream, "+
- "InputSource OR an array of these types.");
+ Status.NOT_SUPPORTED,
+ mf.formatMessage(fErrorReporter.getLocale(), "jaxp12-schema-source-type.1",
+ new Object [] {val != null ? val.getClass().getName() : "null"}));
}
@@ -999,13 +1007,22 @@ XSLoader, DOMConfiguration {
fSubGroupHandler.reset();
- boolean parser_settings = componentManager.getFeature(PARSER_SETTINGS, true);
+ boolean parser_settings = true;
+ // If the component manager is the loader config don't bother querying it since it doesn't
+ // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being
+ // thrown.
+ if (componentManager != fLoaderConfig) {
+ parser_settings = componentManager.getFeature(PARSER_SETTINGS, true);
+ }
if (!parser_settings || !fSettingsChanged){
// need to reprocess JAXP schema sources
fJAXPProcessed = false;
// reinitialize grammar bucket
initGrammarBucket();
+ if (fDeclPool != null) {
+ fDeclPool.reset();
+ }
return;
}
@@ -1028,26 +1045,6 @@ XSLoader, DOMConfiguration {
fSchemaHandler.setDVFactory(dvFactory);
}
- boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false);
-
- if (!psvi) {
- if (fDeclPool != null) {
- fDeclPool.reset();
- }
- else {
- fDeclPool = new XSDeclarationPool();
- }
- fCMBuilder.setDeclPool(fDeclPool);
- fSchemaHandler.setDeclPool(fDeclPool);
- if (dvFactory instanceof SchemaDVFactoryImpl) {
- fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory);
- ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool);
- }
- } else {
- fCMBuilder.setDeclPool(null);
- fSchemaHandler.setDeclPool(null);
- }
-
// get schema location properties
try {
fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION);
@@ -1064,6 +1061,36 @@ XSLoader, DOMConfiguration {
// clear grammars, and put the one for schema namespace there
fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null);
initGrammarBucket();
+
+ boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false);
+
+ // Only use the decl pool when there is no chance that the schema
+ // components will be exposed or cached.
+ // TODO: when someone calls loadGrammar(XMLInputSource), the schema is
+ // always exposed even without the use of a grammar pool.
+ // Disabling the "decl pool" feature for now until we understand when
+ // it can be safely used.
+ if (!psvi && fGrammarPool == null && false) {
+ if (fDeclPool != null) {
+ fDeclPool.reset();
+ }
+ else {
+ fDeclPool = new XSDeclarationPool();
+ }
+ fCMBuilder.setDeclPool(fDeclPool);
+ fSchemaHandler.setDeclPool(fDeclPool);
+ if (dvFactory instanceof SchemaDVFactoryImpl) {
+ fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory);
+ ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool);
+ }
+ } else {
+ fCMBuilder.setDeclPool(null);
+ fSchemaHandler.setDeclPool(null);
+ if (dvFactory instanceof SchemaDVFactoryImpl) {
+ ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null);
+ }
+ }
+
// get continue-after-fatal-error feature
try {
boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false);
@@ -1083,7 +1110,8 @@ XSLoader, DOMConfiguration {
private void initGrammarBucket(){
if(fGrammarPool != null) {
Grammar [] initialGrammars = fGrammarPool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
- for (int i = 0; i < initialGrammars.length; i++) {
+ final int length = (initialGrammars != null) ? initialGrammars.length : 0;
+ for (int i = 0; i < length; ++i) {
// put this grammar into the bucket, along with grammars
// imported by it (directly or indirectly)
if (!fGrammarBucket.putGrammar((SchemaGrammar)(initialGrammars[i]), true)) {
@@ -1119,7 +1147,7 @@ XSLoader, DOMConfiguration {
}
/* (non-Javadoc)
- * @see com.sun.org.apache.xerces.internal.xs.XSLoader#loadInputList(com.sun.org.apache.xerces.internal.xs.DOMInputList)
+ * @see com.sun.org.apache.xerces.internal.xs.XSLoader#loadInputList(com.sun.org.apache.xerces.internal.xs.LSInputList)
*/
public XSModel loadInputList(LSInputList is) {
int length = is.getLength();
@@ -1250,7 +1278,7 @@ XSLoader, DOMConfiguration {
*/
public DOMStringList getParameterNames() {
if (fRecognizedParameters == null){
- Vector v = new Vector();
+ ArrayList v = new ArrayList();
v.add(Constants.DOM_VALIDATE);
v.add(Constants.DOM_ERROR_HANDLER);
v.add(Constants.DOM_RESOURCE_RESOLVER);
@@ -1391,4 +1419,13 @@ XSLoader, DOMConfiguration {
return xis;
}
+ // Implements XSElementDeclHelper interface
+ public XSElementDecl getGlobalElementDecl(QName element) {
+ SchemaGrammar sGrammar = fGrammarBucket.getGrammar(element.uri);
+ if (sGrammar != null) {
+ return sGrammar.getGlobalElementDecl(element.localpart);
+ }
+ return null;
+ }
+
} // XMLGrammarLoader
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java
index dbe788ac599..cc07cf26e29 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
+ */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -25,7 +28,6 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
-import java.util.ArrayList;
import javax.xml.XMLConstants;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.RevalidationHandler;
@@ -35,6 +37,7 @@ import com.sun.org.apache.xerces.internal.impl.dv.DatatypeException;
import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeValueException;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
+import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.validation.ConfigurableValidationState;
import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
import com.sun.org.apache.xerces.internal.impl.validation.ValidationState;
@@ -49,6 +52,7 @@ import com.sun.org.apache.xerces.internal.impl.xs.identity.XPathMatcher;
import com.sun.org.apache.xerces.internal.impl.xs.models.CMBuilder;
import com.sun.org.apache.xerces.internal.impl.xs.models.CMNodeFactory;
import com.sun.org.apache.xerces.internal.impl.xs.models.XSCMValidator;
+import com.sun.org.apache.xerces.internal.impl.xs.util.XS10TypeHelper;
import com.sun.org.apache.xerces.internal.util.AugmentationsImpl;
import com.sun.org.apache.xerces.internal.util.IntStack;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
@@ -107,7 +111,7 @@ import com.sun.org.apache.xerces.internal.parsers.XMLParser;
* @author Neeraj Bajaj, Sun Microsystems, inc.
*/
public class XMLSchemaValidator
- implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler {
+ implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler, XSElementDeclHelper {
//
// Constants
@@ -246,6 +250,10 @@ public class XMLSchemaValidator
protected static final String ROOT_TYPE_DEF =
Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY;
+ /** Property identifier: root element declaration. */
+ protected static final String ROOT_ELEMENT_DECL =
+ Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY;
+
/** Property identifier: Schema DV Factory */
protected static final String SCHEMA_DV_FACTORY =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY;
@@ -279,7 +287,7 @@ public class XMLSchemaValidator
NAMESPACE_GROWTH,
TOLERATE_DUPLICATES,
USE_SERVICE_MECHANISM
- };
+ };
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = { null,
@@ -324,19 +332,26 @@ public class XMLSchemaValidator
JAXP_SCHEMA_SOURCE,
JAXP_SCHEMA_LANGUAGE,
ROOT_TYPE_DEF,
+ ROOT_ELEMENT_DECL,
SCHEMA_DV_FACTORY,
XML_SECURITY_PROPERTY_MANAGER
- };
+ };
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS =
- { null, null, null, null, null, null, null, null, null, null, null};
+ { null, null, null, null, null, null, null, null, null, null, null, null};
// this is the number of valuestores of each kind
// we expect an element to have. It's almost
// never > 1; so leave it at that.
protected static final int ID_CONSTRAINT_NUM = 1;
+ // xsi:* attribute declarations
+ static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE);
+ static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL);
+ static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);
+ static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
+
//
private static final Hashtable EMPTY_TABLE = new Hashtable();
@@ -354,12 +369,6 @@ public class XMLSchemaValidator
// clear this before we introduce it into the pipeline.
protected final AugmentationsImpl fAugmentations = new AugmentationsImpl();
- /**
- * Map which is used to catch instance documents that try
- * and match a field several times in the same scope.
- */
- protected final HashMap fMayMatchFieldMap = new HashMap();
-
// this is included for the convenience of handleEndElement
protected XMLString fDefaultValue;
@@ -485,9 +494,10 @@ public class XMLSchemaValidator
public void reportError(String domain, String key, Object[] arguments, short severity)
throws XNIException {
- fErrorReporter.reportError(domain, key, arguments, severity);
+ String message = fErrorReporter.reportError(domain, key, arguments, severity);
if (fAugPSVI) {
fErrors.addElement(key);
+ fErrors.addElement(message);
}
} // reportError(String,String,Object[],short)
@@ -498,9 +508,10 @@ public class XMLSchemaValidator
Object[] arguments,
short severity)
throws XNIException {
- fErrorReporter.reportError(location, domain, key, arguments, severity);
+ String message = fErrorReporter.reportError(location, domain, key, arguments, severity);
if (fAugPSVI) {
fErrors.addElement(key);
+ fErrors.addElement(message);
}
} // reportError(XMLLocator,String,String,Object[],short)
}
@@ -594,7 +605,32 @@ public class XMLSchemaValidator
*/
public void setProperty(String propertyId, Object value) throws XMLConfigurationException {
if (propertyId.equals(ROOT_TYPE_DEF)) {
- fRootTypeQName = (javax.xml.namespace.QName)value;
+ if (value == null) {
+ fRootTypeQName = null;
+ fRootTypeDefinition = null;
+ }
+ else if (value instanceof javax.xml.namespace.QName) {
+ fRootTypeQName = (javax.xml.namespace.QName) value;
+ fRootTypeDefinition = null;
+ }
+ else {
+ fRootTypeDefinition = (XSTypeDefinition) value;
+ fRootTypeQName = null;
+ }
+ }
+ else if (propertyId.equals(ROOT_ELEMENT_DECL)) {
+ if (value == null) {
+ fRootElementDeclQName = null;
+ fRootElementDeclaration = null;
+ }
+ else if (value instanceof javax.xml.namespace.QName) {
+ fRootElementDeclQName = (javax.xml.namespace.QName) value;
+ fRootElementDeclaration = null;
+ }
+ else {
+ fRootElementDeclaration = (XSElementDecl) value;
+ fRootElementDeclQName = null;
+ }
}
} // setProperty(String,Object)
@@ -868,6 +904,7 @@ public class XMLSchemaValidator
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
+
handleIgnorableWhitespace(text);
// call handlers
if (fDocumentHandler != null) {
@@ -1160,7 +1197,7 @@ public class XMLSchemaValidator
/** Schema grammar resolver. */
private final XSGrammarBucket fGrammarBucket = new XSGrammarBucket();
- private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(fGrammarBucket);
+ private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(this);
/** the DV usd to convert xsi:type to a QName */
// REVISIT: in new simple type design, make things in DVs static,
@@ -1248,7 +1285,7 @@ public class XMLSchemaValidator
private boolean[] fStrictAssessStack = new boolean[INITIAL_STACK_SIZE];
/** Temporary string buffers. */
- private final StringBuffer fBuffer = new StringBuffer();
+ private final StringBuilder fBuffer = new StringBuilder();
/** Whether need to append characters to fBuffer */
private boolean fAppendBuffer = true;
@@ -1268,7 +1305,13 @@ public class XMLSchemaValidator
/** temporary qname */
private final QName fTempQName = new QName();
+ /** value of the "root-type-definition" property. */
private javax.xml.namespace.QName fRootTypeQName = null;
+ private XSTypeDefinition fRootTypeDefinition = null;
+
+ /** value of the "root-element-declaration" property. */
+ private javax.xml.namespace.QName fRootElementDeclQName = null;
+ private XSElementDecl fRootElementDeclaration = null;
private int fIgnoreXSITypeDepth;
@@ -1341,9 +1384,6 @@ public class XMLSchemaValidator
// cleanup id table
fValidationState.resetIDTables();
- //pass the component manager to the factory..
- nodeFactory.reset(componentManager);
-
// reset schema loader
fSchemaLoader.reset(componentManager);
@@ -1364,19 +1404,16 @@ public class XMLSchemaValidator
fMatcherStack.clear();
- if (!fMayMatchFieldMap.isEmpty()) {
- // should only clear this if the last schema had identity constraints.
- fMayMatchFieldMap.clear();
- }
-
// get error reporter
fXSIErrorReporter.reset((XMLErrorReporter) componentManager.getProperty(ERROR_REPORTER));
boolean parser_settings = componentManager.getFeature(PARSER_SETTINGS, true);
- if (!parser_settings){
+ if (!parser_settings) {
// parser settings have not been changed
fValidationManager.addValidationState(fValidationState);
+ // the node limit on the SecurityManager may have changed so need to refresh.
+ nodeFactory.reset();
// Re-parse external schema location properties.
XMLSchemaLoader.processExternalHints(
fExternalSchemas,
@@ -1386,6 +1423,8 @@ public class XMLSchemaValidator
return;
}
+ // pass the component manager to the factory..
+ nodeFactory.reset(componentManager);
// get symbol table. if it's a new one, add symbols to it.
SymbolTable symbolTable = (SymbolTable) componentManager.getProperty(SYMBOL_TABLE);
@@ -1413,8 +1452,8 @@ public class XMLSchemaValidator
fAugPSVI = componentManager.getFeature(SCHEMA_AUGMENT_PSVI, true);
fSchemaType =
- (String) componentManager.getProperty(
- Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, null);
+ (String) componentManager.getProperty(
+ Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, null);
fUseGrammarPoolOnly = componentManager.getFeature(USE_GRAMMAR_POOL_ONLY, false);
@@ -1424,13 +1463,48 @@ public class XMLSchemaValidator
fValidationManager.addValidationState(fValidationState);
fValidationState.setSymbolTable(fSymbolTable);
- boolean ignoreXSIType;
try {
- ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE);
+ final Object rootType = componentManager.getProperty(ROOT_TYPE_DEF);
+ if (rootType == null) {
+ fRootTypeQName = null;
+ fRootTypeDefinition = null;
+ }
+ else if (rootType instanceof javax.xml.namespace.QName) {
+ fRootTypeQName = (javax.xml.namespace.QName) rootType;
+ fRootTypeDefinition = null;
+ }
+ else {
+ fRootTypeDefinition = (XSTypeDefinition) rootType;
+ fRootTypeQName = null;
+ }
}
catch (XMLConfigurationException e) {
- ignoreXSIType = false;
+ fRootTypeQName = null;
+ fRootTypeDefinition = null;
}
+
+ try {
+ final Object rootDecl = componentManager.getProperty(ROOT_ELEMENT_DECL);
+ if (rootDecl == null) {
+ fRootElementDeclQName = null;
+ fRootElementDeclaration = null;
+ }
+ else if (rootDecl instanceof javax.xml.namespace.QName) {
+ fRootElementDeclQName = (javax.xml.namespace.QName) rootDecl;
+ fRootElementDeclaration = null;
+ }
+ else {
+ fRootElementDeclaration = (XSElementDecl) rootDecl;
+ fRootElementDeclQName = null;
+ }
+ }
+ catch (XMLConfigurationException e) {
+ fRootElementDeclQName = null;
+ fRootElementDeclaration = null;
+ }
+
+ boolean ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE, false);
+
// An initial value of -1 means that the root element considers itself
// below the depth where xsi:type stopped being ignored (which means that
// xsi:type attributes will not be ignored for the entire document)
@@ -1515,8 +1589,7 @@ public class XMLSchemaValidator
public XPathMatcher activateField(Field field, int initialDepth) {
ValueStore valueStore =
fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth);
- setMayMatch(field, Boolean.TRUE);
- XPathMatcher matcher = field.createMatcher(this, valueStore);
+ XPathMatcher matcher = field.createMatcher(valueStore);
fMatcherStack.addMatcher(matcher);
matcher.startDocumentFragment();
return matcher;
@@ -1535,28 +1608,6 @@ public class XMLSchemaValidator
} // endValueScopeFor(IdentityConstraint)
- /**
- * Sets whether the given field is permitted to match a value.
- * This should be used to catch instance documents that try
- * and match a field several times in the same scope.
- *
- * @param field The field that may be permitted to be matched.
- * @param state Boolean indiciating whether the field may be matched.
- */
- public void setMayMatch(Field field, Boolean state) {
- fMayMatchFieldMap.put(field, state);
- } // setMayMatch(Field, Boolean)
-
- /**
- * Returns whether the given field is permitted to match a value.
- *
- * @param field The field that may be permitted to be matched.
- * @return Boolean indicating whether the field may be matched.
- */
- public Boolean mayMatch(Field field) {
- return (Boolean) fMayMatchFieldMap.get(field);
- } // mayMatch(Field):Boolean
-
// a utility method for Identity constraints
private void activateSelectorFor(IdentityConstraint ic) {
Selector selector = ic.getSelector();
@@ -1568,6 +1619,21 @@ public class XMLSchemaValidator
matcher.startDocumentFragment();
}
+ // Implements XSElementDeclHelper interface
+ public XSElementDecl getGlobalElementDecl(QName element) {
+ final SchemaGrammar sGrammar =
+ findSchemaGrammar(
+ XSDDescription.CONTEXT_ELEMENT,
+ element.uri,
+ null,
+ element,
+ null);
+ if (sGrammar != null) {
+ return sGrammar.getGlobalElementDecl(element.localpart);
+ }
+ return null;
+ }
+
//
// Protected methods
//
@@ -1823,16 +1889,17 @@ public class XMLSchemaValidator
}
// get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes,
- // parse them to get the grammars
-
- String sLocation =
- attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION);
- String nsLocation =
- attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
- //store the location hints.. we need to do it so that we can defer the loading of grammar until
- //there is a reference to a component from that namespace. To provide location hints to the
- //application for a namespace
- storeLocations(sLocation, nsLocation);
+ // parse them to get the grammars. But only do this if the grammar can grow.
+ if (!fUseGrammarPoolOnly) {
+ String sLocation =
+ attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION);
+ String nsLocation =
+ attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
+ //store the location hints.. we need to do it so that we can defer the loading of grammar until
+ //there is a reference to a component from that namespace. To provide location hints to the
+ //application for a namespace
+ storeLocations(sLocation, nsLocation);
+ }
// if we are in the content of "skip", then just skip this element
// REVISIT: is this the correct behaviour for ID constraints? -NG
@@ -1843,15 +1910,6 @@ public class XMLSchemaValidator
return augs;
}
- //try to find schema grammar by different means..
- SchemaGrammar sGrammar =
- findSchemaGrammar(
- XSDDescription.CONTEXT_ELEMENT,
- element.uri,
- null,
- element,
- attributes);
-
// if we are not skipping this element, and there is a content model,
// we try to find the corresponding decl object for this element.
// the reason we move this part of code here is to make sure the
@@ -1864,15 +1922,57 @@ public class XMLSchemaValidator
if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType;
//REVISIT: is it the only case we will have particle = null?
- Vector next;
+ ArrayList next;
if (ctype.fParticle != null
&& (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) {
String expected = expectedStr(next);
- reportSchemaError(
- "cvc-complex-type.2.4.a",
- new Object[] { element.rawname, expected });
- } else {
- reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname });
+ final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState);
+ String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart;
+ if (occurenceInfo != null) {
+ final int minOccurs = occurenceInfo[0];
+ final int maxOccurs = occurenceInfo[1];
+ final int count = occurenceInfo[2];
+ // Check if this is a violation of minOccurs
+ if (count < minOccurs) {
+ final int required = minOccurs - count;
+ if (required > 1) {
+ reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname,
+ fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) });
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname,
+ fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) });
+ }
+ }
+ // Check if this is a violation of maxOccurs
+ else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) {
+ reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname,
+ expected, Integer.toString(maxOccurs) });
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected });
+ }
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected });
+ }
+ }
+ else {
+ final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState);
+ if (occurenceInfo != null) {
+ final int maxOccurs = occurenceInfo[1];
+ final int count = occurenceInfo[2];
+ // Check if this is a violation of maxOccurs
+ if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) {
+ reportSchemaError("cvc-complex-type.2.4.f", new Object[] { fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(maxOccurs) });
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname });
+ }
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname });
+ }
}
}
}
@@ -1926,23 +2026,21 @@ public class XMLSchemaValidator
return augs;
}
- // 1.2.1.1 A type definition was stipulated by the processor
- if (fElementDepth == 0 && fRootTypeQName != null) {
- String rootTypeNamespace = fRootTypeQName.getNamespaceURI();
- if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) {
- rootTypeNamespace = null;
+ if (fElementDepth == 0) {
+ // 1.1.1.1 An element declaration was stipulated by the processor
+ if (fRootElementDeclaration != null) {
+ fCurrentElemDecl = fRootElementDeclaration;
+ checkElementMatchesRootElementDecl(fCurrentElemDecl, element);
}
- SchemaGrammar grammarForRootType =
- findSchemaGrammar(
- XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null);
- if (grammarForRootType != null) {
- fCurrentType = grammarForRootType.getGlobalTypeDecl(fRootTypeQName.getLocalPart());
+ else if (fRootElementDeclQName != null) {
+ processRootElementDeclQName(fRootElementDeclQName, element);
}
- if (fCurrentType == null) {
- String typeName = (fRootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ?
- fRootTypeQName.getLocalPart() :
- fRootTypeQName.getPrefix()+":"+fRootTypeQName.getLocalPart();
- reportSchemaError("cvc-type.1", new Object[] {typeName});
+ // 1.2.1.1 A type definition was stipulated by the processor
+ else if (fRootTypeDefinition != null) {
+ fCurrentType = fRootTypeDefinition;
+ }
+ else if (fRootTypeQName != null) {
+ processRootTypeQName(fRootTypeQName);
}
}
@@ -1952,6 +2050,14 @@ public class XMLSchemaValidator
// case 1: find declaration for root element
// case 2: find declaration for element from another namespace
if (fCurrentElemDecl == null) {
+ // try to find schema grammar by different means..
+ SchemaGrammar sGrammar =
+ findSchemaGrammar(
+ XSDDescription.CONTEXT_ELEMENT,
+ element.uri,
+ null,
+ element,
+ attributes);
if (sGrammar != null) {
fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart);
}
@@ -1963,7 +2069,6 @@ public class XMLSchemaValidator
}
}
-
// check if we should be ignoring xsi:type on this element
if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) {
fIgnoreXSITypeDepth++;
@@ -2012,7 +2117,7 @@ public class XMLSchemaValidator
// of this. - SG
fXSIErrorReporter.fErrorReporter.reportError(
XSMessageFormatter.SCHEMA_DOMAIN,
- "cvc-elt.1",
+ "cvc-elt.1.a",
new Object[] { element.rawname },
XMLErrorReporter.SEVERITY_ERROR);
}
@@ -2189,6 +2294,8 @@ public class XMLSchemaValidator
fCurrentPSVI.fTypeDecl = fCurrentType;
// PSVI: add notation attribute
fCurrentPSVI.fNotation = fNotation;
+ // PSVI: add nil
+ fCurrentPSVI.fNil = fNil;
}
return augs;
@@ -2234,7 +2341,7 @@ public class XMLSchemaValidator
// validation attempted, validity, and error codes
// check extra schema constraints on root element
- if (fElementDepth == -1 && fFullChecking) {
+ if (fElementDepth == -1 && fFullChecking && !fUseGrammarPoolOnly) {
XSConstraints.fullSchemaChecking(
fGrammarBucket,
fSubGroupHandler,
@@ -2258,10 +2365,10 @@ public class XMLSchemaValidator
int oldCount = fMatcherStack.getMatcherCount();
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
- if (fCurrentElemDecl == null)
- matcher.endElement(element, null, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes);
-
- else
+ if (fCurrentElemDecl == null) {
+ matcher.endElement(element, fCurrentType, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes);
+ }
+ else {
matcher.endElement(
element,
fCurrentType,
@@ -2275,6 +2382,7 @@ public class XMLSchemaValidator
fDefaultValue == null
? fValidatedInfo.itemValueTypes
: fCurrentElemDecl.fDefault.itemValueTypes);
+ }
}
if (fMatcherStack.size() > 0) {
@@ -2305,7 +2413,9 @@ public class XMLSchemaValidator
&& id.getCategory() == IdentityConstraint.IC_KEYREF) {
ValueStoreBase values =
fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth());
- if (values != null) // nothing to do if nothing matched!
+ // nothing to do if nothing matched, or if not all
+ // fields are present.
+ if (values != null && values.fValuesCount == values.fFieldCount)
values.endDocumentFragment();
}
}
@@ -2324,13 +2434,15 @@ public class XMLSchemaValidator
// have we reached the end tag of the validation root?
if (fElementDepth == 0) {
// 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4).
- String invIdRef = fValidationState.checkIDRefID();
+ Iterator invIdRefs = fValidationState.checkIDRefID();
fValidationState.resetIDTables();
- if (invIdRef != null) {
- reportSchemaError("cvc-id.1", new Object[] { invIdRef });
+ if (invIdRefs != null) {
+ while (invIdRefs.hasNext()) {
+ reportSchemaError("cvc-id.1", new Object[] { invIdRefs.next() });
+ }
}
// check extra schema constraints
- if (fFullChecking) {
+ if (fFullChecking && !fUseGrammarPoolOnly) {
XSConstraints.fullSchemaChecking(
fGrammarBucket,
fSubGroupHandler,
@@ -2390,11 +2502,12 @@ public class XMLSchemaValidator
if (fAugPSVI) {
augs = getEmptyAugs(augs);
- // the 4 properties sent on startElement calls
+ // the 5 properties sent on startElement calls
fCurrentPSVI.fDeclaration = this.fCurrentElemDecl;
fCurrentPSVI.fTypeDecl = this.fCurrentType;
fCurrentPSVI.fNotation = this.fNotation;
fCurrentPSVI.fValidationContext = this.fValidationRoot;
+ fCurrentPSVI.fNil = this.fNil;
// PSVI: validation attempted
// nothing below or at the same level has none or partial
// (which means this level is strictly assessed, and all chidren
@@ -2423,12 +2536,7 @@ public class XMLSchemaValidator
if (fDefaultValue != null)
fCurrentPSVI.fSpecified = true;
- fCurrentPSVI.fNil = fNil;
- fCurrentPSVI.fMemberType = fValidatedInfo.memberType;
- fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue;
- fCurrentPSVI.fActualValue = fValidatedInfo.actualValue;
- fCurrentPSVI.fActualValueType = fValidatedInfo.actualValueType;
- fCurrentPSVI.fItemValueTypes = fValidatedInfo.itemValueTypes;
+ fCurrentPSVI.fValue.copyFrom(fValidatedInfo);
if (fStrictAssess) {
// get all errors for the current element, its attribute,
@@ -2438,7 +2546,7 @@ public class XMLSchemaValidator
String[] errors = fXSIErrorReporter.mergeContext();
// PSVI: error codes
- fCurrentPSVI.fErrorCodes = errors;
+ fCurrentPSVI.fErrors = errors;
// PSVI: validity
fCurrentPSVI.fValidity =
(errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID;
@@ -2475,7 +2583,7 @@ public class XMLSchemaValidator
void storeLocations(String sLocation, String nsLocation) {
if (sLocation != null) {
- if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs)) {
+ if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs, fLocator == null ? null : fLocator.getExpandedSystemId())) {
// error!
fXSIErrorReporter.reportError(
XSMessageFormatter.SCHEMA_DOMAIN,
@@ -2491,6 +2599,12 @@ public class XMLSchemaValidator
la = new XMLSchemaLoader.LocationArray();
fLocationPairs.put(XMLSymbols.EMPTY_STRING, la);
}
+ if (fLocator != null) {
+ try {
+ nsLocation = XMLEntityManager.expandSystemId(nsLocation, fLocator.getExpandedSystemId(), false);
+ } catch (MalformedURIException e) {
+ }
+ }
la.addLocation(nsLocation);
}
@@ -2503,7 +2617,7 @@ public class XMLSchemaValidator
short contextType,
String namespace,
QName enclosingElement,
- QName triggeringComponet,
+ QName triggeringComponent,
XMLAttributes attributes) {
SchemaGrammar grammar = null;
//get the grammar from local pool...
@@ -2530,12 +2644,14 @@ public class XMLSchemaValidator
}
}
}
- if ((grammar == null && !fUseGrammarPoolOnly) || fNamespaceGrowth) {
+
+ if (!fUseGrammarPoolOnly && (grammar == null ||
+ (fNamespaceGrowth && !hasSchemaComponent(grammar, contextType, triggeringComponent)))) {
fXSDDescription.reset();
fXSDDescription.fContextType = contextType;
fXSDDescription.setNamespace(namespace);
fXSDDescription.fEnclosedElementName = enclosingElement;
- fXSDDescription.fTriggeringComponent = triggeringComponet;
+ fXSDDescription.fTriggeringComponent = triggeringComponent;
fXSDDescription.fAttributes = attributes;
if (fLocator != null) {
fXSDDescription.setBaseSystemId(fLocator.getExpandedSystemId());
@@ -2579,13 +2695,14 @@ public class XMLSchemaValidator
if (toParseSchema) {
grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs);
}
- } catch (IOException ex) {
+ }
+ catch (IOException ex) {
final String [] locationHints = fXSDDescription.getLocationHints();
fXSIErrorReporter.fErrorReporter.reportError(
XSMessageFormatter.SCHEMA_DOMAIN,
"schema_reference.4",
new Object[] { locationHints != null ? locationHints[0] : XMLSymbols.EMPTY_STRING },
- XMLErrorReporter.SEVERITY_WARNING);
+ XMLErrorReporter.SEVERITY_WARNING, ex);
}
}
}
@@ -2593,6 +2710,24 @@ public class XMLSchemaValidator
return grammar;
} //findSchemaGrammar
+
+ private boolean hasSchemaComponent(SchemaGrammar grammar, short contextType, QName triggeringComponent) {
+ if (grammar != null && triggeringComponent != null) {
+ String localName = triggeringComponent.localpart;
+ if (localName != null && localName.length() > 0) {
+ switch (contextType) {
+ case XSDDescription.CONTEXT_ELEMENT:
+ return grammar.getElementDeclaration(localName) != null;
+ case XSDDescription.CONTEXT_ATTRIBUTE:
+ return grammar.getAttributeDeclaration(localName) != null;
+ case XSDDescription.CONTEXT_XSITYPE:
+ return grammar.getTypeDefinition(localName) != null;
+ }
+ }
+ }
+ return false;
+ }
+
private void setLocationHints(XSDDescription desc, String[] locations, SchemaGrammar grammar) {
int length = locations.length;
if (grammar == null) {
@@ -2610,13 +2745,8 @@ public class XMLSchemaValidator
int counter = 0;
for (int i=0; i= 0 && !fCurrentCM.endContentModel(fCurrCMState)) {
String expected = expectedStr(fCurrentCM.whatCanGoHere(fCurrCMState));
- reportSchemaError(
- "cvc-complex-type.2.4.b",
- new Object[] { element.rawname, expected });
+ final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState);
+ if (occurenceInfo != null) {
+ final int minOccurs = occurenceInfo[0];
+ final int count = occurenceInfo[2];
+ // Check if this is a violation of minOccurs
+ if (count < minOccurs) {
+ final int required = minOccurs - count;
+ if (required > 1) {
+ reportSchemaError("cvc-complex-type.2.4.j", new Object[] { element.rawname,
+ fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) });
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.i", new Object[] { element.rawname,
+ fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) });
+ }
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected });
+ }
+ }
+ else {
+ reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected });
+ }
} else {
// Constant space algorithm for a{n,m} for n > 1 and m <= unbounded
// After the DFA has completed, check minOccurs and maxOccurs
@@ -3363,11 +3505,70 @@ public class XMLSchemaValidator
}
}
}
- }
+ }
}
return actualValue;
} // elementLocallyValidComplexType
+ void processRootTypeQName(final javax.xml.namespace.QName rootTypeQName) {
+ String rootTypeNamespace = rootTypeQName.getNamespaceURI();
+ // Add namespace to symbol table, to make sure it's interned.
+ // This namespace may be later compared with other values using ==.
+ rootTypeNamespace = fSymbolTable.addSymbol(rootTypeNamespace);
+ if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) {
+ rootTypeNamespace = null;
+ }
+ if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(rootTypeNamespace)) {
+ fCurrentType = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(rootTypeQName.getLocalPart());
+ }
+ else {
+ final SchemaGrammar grammarForRootType = findSchemaGrammar(
+ XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null);
+ if (grammarForRootType != null) {
+ fCurrentType = grammarForRootType.getGlobalTypeDecl(rootTypeQName.getLocalPart());
+ }
+ }
+ if (fCurrentType == null) {
+ String typeName = (rootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ?
+ rootTypeQName.getLocalPart() :
+ rootTypeQName.getPrefix()+":"+rootTypeQName.getLocalPart();
+ reportSchemaError("cvc-type.1", new Object[] {typeName});
+ }
+ } // processRootTypeQName
+
+ void processRootElementDeclQName(final javax.xml.namespace.QName rootElementDeclQName, final QName element) {
+ String rootElementDeclNamespace = rootElementDeclQName.getNamespaceURI();
+ // Add namespace to symbol table, to make sure it's interned.
+ // This namespace may be later compared with other values using ==.
+ rootElementDeclNamespace = fSymbolTable.addSymbol(rootElementDeclNamespace);
+ if (rootElementDeclNamespace != null && rootElementDeclNamespace.equals(XMLConstants.NULL_NS_URI)) {
+ rootElementDeclNamespace = null;
+ }
+ final SchemaGrammar grammarForRootElement = findSchemaGrammar(
+ XSDDescription.CONTEXT_ELEMENT, rootElementDeclNamespace, null, null, null);
+ if (grammarForRootElement != null) {
+ fCurrentElemDecl = grammarForRootElement.getGlobalElementDecl(rootElementDeclQName.getLocalPart());
+ }
+ if (fCurrentElemDecl == null) {
+ String declName = (rootElementDeclQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ?
+ rootElementDeclQName.getLocalPart() :
+ rootElementDeclQName.getPrefix()+":"+rootElementDeclQName.getLocalPart();
+ reportSchemaError("cvc-elt.1.a", new Object[] {declName});
+ }
+ else {
+ checkElementMatchesRootElementDecl(fCurrentElemDecl, element);
+ }
+ } // processRootElementDeclQName
+
+ void checkElementMatchesRootElementDecl(final XSElementDecl rootElementDecl, final QName element) {
+ // Report an error if the name of the element does
+ // not match the name of the specified element declaration.
+ if (element.localpart != rootElementDecl.fName ||
+ element.uri != rootElementDecl.fTargetNamespace) {
+ reportSchemaError("cvc-elt.1.b", new Object[] {element.rawname, rootElementDecl.fName});
+ }
+ } // checkElementMatchesRootElementDecl
+
void reportSchemaError(String key, Object[] arguments) {
if (fDoValidation)
fXSIErrorReporter.reportError(
@@ -3377,14 +3578,13 @@ public class XMLSchemaValidator
XMLErrorReporter.SEVERITY_ERROR);
}
-
- private String expectedStr(Vector expected) {
- StringBuffer ret = new StringBuffer("{");
+ private String expectedStr(ArrayList expected) {
+ StringBuilder ret = new StringBuilder("{");
int size = expected.size();
for (int i = 0; i < size; i++) {
if (i > 0)
ret.append(", ");
- ret.append(expected.elementAt(i).toString());
+ ret.append(expected.get(i).toString());
}
ret.append('}');
return ret.toString();
@@ -3520,7 +3720,7 @@ public class XMLSchemaValidator
private ShortList fItemValueType = null;
/** buffer for error messages */
- final StringBuffer fTempBuffer = new StringBuffer();
+ final StringBuilder fTempBuffer = new StringBuilder();
//
// Constructors
@@ -3645,9 +3845,12 @@ public class XMLSchemaValidator
* @param field The field associated to the value. This reference
* is used to ensure that each field only adds a value
* once within a selection scope.
+ * @param mayMatch a flag indiciating whether the field may be matched.
* @param actualValue The value to add.
+ * @param valueType Type of the value to add.
+ * @param itemValueType If the value is a list, a list of types for each of the values in the list.
*/
- public void addValue(Field field, Object actualValue, short valueType, ShortList itemValueType) {
+ public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType) {
int i;
for (i = fFieldCount - 1; i > -1; i--) {
if (fFields[i] == field) {
@@ -3662,11 +3865,12 @@ public class XMLSchemaValidator
reportSchemaError(code, new Object[] { field.toString(), eName, cName });
return;
}
- if (Boolean.TRUE != mayMatch(field)) {
+ if (!mayMatch) {
String code = "FieldMultipleMatch";
String cName = fIdentityConstraint.getIdentityConstraintName();
reportSchemaError(code, new Object[] { field.toString(), cName });
- } else {
+ }
+ else {
fValuesCount++;
}
fLocalValues[i] = actualValue;
@@ -3815,7 +4019,7 @@ public class XMLSchemaValidator
}
// construct value string
- StringBuffer str = new StringBuffer();
+ StringBuilder str = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i > 0) {
str.append(',');
@@ -4075,7 +4279,7 @@ public class XMLSchemaValidator
// values stores
/** stores all global Values stores. */
- protected final Vector fValueStores = new Vector();
+ protected final ArrayList fValueStores = new ArrayList();
/**
* Values stores associated to specific identity constraints.
@@ -4086,7 +4290,7 @@ public class XMLSchemaValidator
* descendant-or-self axes occur on recursively-defined
* elements.
*/
- protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable();
+ protected final HashMap fIdentityConstraint2ValueStoreMap = new HashMap();
// sketch of algorithm:
// - when a constraint is first encountered, its
@@ -4108,7 +4312,7 @@ public class XMLSchemaValidator
// the fGlobalIDConstraintMap contains descendants+self.
// keyrefs can only match descendants+self.
protected final Stack fGlobalMapStack = new Stack();
- protected final Hashtable fGlobalIDConstraintMap = new Hashtable();
+ protected final HashMap fGlobalIDConstraintMap = new HashMap();
//
// Constructors
@@ -4124,7 +4328,7 @@ public class XMLSchemaValidator
/** Resets the identity constraint cache. */
public void startDocument() {
- fValueStores.removeAllElements();
+ fValueStores.clear();
fIdentityConstraint2ValueStoreMap.clear();
fGlobalIDConstraintMap.clear();
fGlobalMapStack.removeAllElements();
@@ -4133,7 +4337,7 @@ public class XMLSchemaValidator
// startElement: pushes the current fGlobalIDConstraintMap
// onto fGlobalMapStack and clears fGlobalIDConstraint map.
public void startElement() {
- // only clone the hashtable when there are elements
+ // only clone the map when there are elements
if (fGlobalIDConstraintMap.size() > 0)
fGlobalMapStack.push(fGlobalIDConstraintMap.clone());
else
@@ -4148,7 +4352,7 @@ public class XMLSchemaValidator
if (fGlobalMapStack.isEmpty()) {
return; // must be an invalid doc!
}
- Hashtable oldMap = (Hashtable) fGlobalMapStack.pop();
+ HashMap oldMap = (HashMap) fGlobalMapStack.pop();
// return if there is no element
if (oldMap == null) {
return;
@@ -4193,7 +4397,7 @@ public class XMLSchemaValidator
} else {
uniqueValueStore.clear();
}
- fValueStores.addElement(uniqueValueStore);
+ fValueStores.add(uniqueValueStore);
activateSelectorFor(icArray[i]);
break;
case (IdentityConstraint.IC_KEY) :
@@ -4208,7 +4412,7 @@ public class XMLSchemaValidator
} else {
keyValueStore.clear();
}
- fValueStores.addElement(keyValueStore);
+ fValueStores.add(keyValueStore);
activateSelectorFor(icArray[i]);
break;
case (IdentityConstraint.IC_KEYREF) :
@@ -4223,7 +4427,7 @@ public class XMLSchemaValidator
} else {
keyRefValueStore.clear();
}
- fValueStores.addElement(keyRefValueStore);
+ fValueStores.add(keyRefValueStore);
activateSelectorFor(icArray[i]);
break;
}
@@ -4267,7 +4471,7 @@ public class XMLSchemaValidator
int count = fValueStores.size();
for (int i = 0; i < count; i++) {
- ValueStoreBase valueStore = (ValueStoreBase) fValueStores.elementAt(i);
+ ValueStoreBase valueStore = (ValueStoreBase) fValueStores.get(i);
valueStore.endDocument();
}
@@ -4295,7 +4499,7 @@ public class XMLSchemaValidator
// the purpose of this class is to enable IdentityConstraint,int
// pairs to be used easily as keys in Hashtables.
- protected class LocalIDKey {
+ protected static final class LocalIDKey {
public IdentityConstraint fId;
public int fDepth;
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeDecl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeDecl.java
index 7542c684f69..553481192f7 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeDecl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeDecl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -32,6 +33,7 @@ import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
/**
* The XML representation for an attribute declaration
@@ -211,4 +213,8 @@ public class XSAttributeDecl implements XSAttributeDeclaration {
fDefault.itemValueTypes;
}
+ public XSValue getValueConstraintValue() {
+ return fDefault;
+ }
+
} // class XSAttributeDecl
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeUseImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeUseImpl.java
index 42e64e3c87a..578e2ff2ba7 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeUseImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeUseImpl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 1999-2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -28,6 +29,7 @@ import com.sun.org.apache.xerces.internal.xs.XSAttributeUse;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
/**
* The XML representation for an attribute use
@@ -142,6 +144,10 @@ public class XSAttributeUseImpl implements XSAttributeUse {
fDefault.itemValueTypes;
}
+ public XSValue getValueConstraintValue() {
+ return fDefault;
+ }
+
/**
* Optional. Annotations.
*/
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSComplexTypeDecl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSComplexTypeDecl.java
index 3096988cb2e..0ac46fef187 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSComplexTypeDecl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSComplexTypeDecl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -77,7 +78,7 @@ public class XSComplexTypeDecl implements XSComplexTypeDefinition, TypeInfo {
volatile XSCMValidator fCMValidator = null;
// the content model that's sufficient for computing UPA
- XSCMValidator fUPACMValidator = null;
+ volatile XSCMValidator fUPACMValidator = null;
// list of annotations affiliated with this type
XSObjectListImpl fAnnotations = null;
@@ -165,12 +166,28 @@ public class XSComplexTypeDecl implements XSComplexTypeDefinition, TypeInfo {
fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY) {
return null;
}
- if (fCMValidator == null)
- synchronized (this) {
- if (fCMValidator == null) {
- fCMValidator = cmBuilder.getContentModel(this);
+ if (fCMValidator == null) {
+ fCMValidator = getContentModel(cmBuilder, false);
+ }
+ return fCMValidator;
+ }
+
+ public synchronized XSCMValidator getContentModel(CMBuilder cmBuilder, boolean forUPA) {
+ if (fCMValidator == null) {
+ if (forUPA) {
+ if (fUPACMValidator == null) {
+ fUPACMValidator = cmBuilder.getContentModel(this, true);
+
+ if (fUPACMValidator != null && !fUPACMValidator.isCompactedForUPA()) {
+ fCMValidator = fUPACMValidator;
+ }
}
+ return fUPACMValidator;
}
+ else {
+ fCMValidator = cmBuilder.getContentModel(this, false);
+ }
+ }
return fCMValidator;
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSConstraints.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSConstraints.java
index 3b5e28c2d77..9f8422379a8 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSConstraints.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSConstraints.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -488,7 +489,7 @@ public class XSConstraints {
}
// 3. UPA
// get the content model and check UPA
- XSCMValidator cm = types[j].getContentModel(cmBuilder);
+ XSCMValidator cm = types[j].getContentModel(cmBuilder, true);
further = false;
if (cm != null) {
try {
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDecl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDecl.java
index 70d5347e5c2..76009036b38 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDecl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDecl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -34,6 +35,7 @@ import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
/**
* The XML representation for an element declaration
@@ -384,4 +386,8 @@ public class XSElementDecl implements XSElementDeclaration {
fDefault.itemValueTypes;
}
+ public XSValue getValueConstraintValue() {
+ return fDefault;
+ }
+
} // class XSElementDecl
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDeclHelper.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDeclHelper.java
new file mode 100644
index 00000000000..78b568fda0a
--- /dev/null
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDeclHelper.java
@@ -0,0 +1,34 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sun.org.apache.xerces.internal.impl.xs;
+
+import com.sun.org.apache.xerces.internal.xni.QName;
+
+/**
+ * @xerces.internal
+ *
+ * @version $Id$
+ */
+public interface XSElementDeclHelper {
+
+ public XSElementDecl getGlobalElementDecl(QName element);
+}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSModelImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSModelImpl.java
index 01201a766ea..596b46ed8c2 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSModelImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSModelImpl.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2002-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,13 +21,6 @@
package com.sun.org.apache.xerces.internal.impl.xs;
-import java.lang.reflect.Array;
-import java.util.AbstractList;
-import java.util.Iterator;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
@@ -39,6 +33,7 @@ import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
+import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
@@ -48,6 +43,12 @@ import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObject;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
+import java.lang.reflect.Array;
+import java.util.AbstractList;
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+import java.util.Vector;
/**
* Implements XSModel: a read-only interface that represents an XML Schema,
@@ -72,7 +73,7 @@ public final class XSModelImpl extends AbstractList implements XSModel, XSNamesp
false, // model group
false, // particle
false, // wildcard
- false, // idc
+ true, // idc
true, // notation
false, // annotation
false, // facet
@@ -326,6 +327,9 @@ public final class XSModelImpl extends AbstractList implements XSModel, XSNamesp
case XSConstants.NOTATION_DECLARATION:
tables[i] = fGrammarList[i].fGlobalNotationDecls;
break;
+ case XSConstants.IDENTITY_CONSTRAINT:
+ tables[i] = fGrammarList[i].fGlobalIDConstraintDecls;
+ break;
}
}
// for complex/simple types, create a special implementation,
@@ -405,6 +409,9 @@ public final class XSModelImpl extends AbstractList implements XSModel, XSNamesp
case XSConstants.NOTATION_DECLARATION:
table = fGrammarList[i].fGlobalNotationDecls;
break;
+ case XSConstants.IDENTITY_CONSTRAINT:
+ table = fGrammarList[i].fGlobalIDConstraintDecls;
+ break;
}
// for complex/simple types, create a special implementation,
@@ -595,6 +602,40 @@ public final class XSModelImpl extends AbstractList implements XSModel, XSNamesp
return sg.getGlobalGroupDecl(name, loc);
}
+ /**
+ * Convenience method. Returns a top-level model group definition.
+ *
+ * @param name The name of the definition.
+ * @param namespace The namespace of the definition, otherwise null.
+ * @return A top-level model group definition definition or null if such
+ * definition does not exist.
+ */
+ public XSIDCDefinition getIDCDefinition(String name, String namespace) {
+ SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace));
+ if (sg == null) {
+ return null;
+ }
+ return (XSIDCDefinition)sg.fGlobalIDConstraintDecls.get(name);
+ }
+
+ /**
+ * Convenience method. Returns a top-level model group definition.
+ *
+ * @param name The name of the definition.
+ * @param namespace The namespace of the definition, otherwise null.
+ * @param loc The schema location where the component was defined
+ * @return A top-level model group definition definition or null if such
+ * definition does not exist.
+ */
+ public XSIDCDefinition getIDCDefinition(String name, String namespace,
+ String loc) {
+ SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace));
+ if (sg == null) {
+ return null;
+ }
+ return sg.getIDConstraintDecl(name, loc);
+ }
+
/**
* @see org.apache.xerces.xs.XSModel#getNotationDeclaration(String, String)
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/Field.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/Field.java
index c00e802e6d4..abee52b02c7 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/Field.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/Field.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -23,6 +24,7 @@ package com.sun.org.apache.xerces.internal.impl.xs.identity;
import com.sun.org.apache.xerces.internal.impl.xpath.XPathException;
import com.sun.org.apache.xerces.internal.impl.xs.util.ShortListImpl;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.util.XMLChar;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xs.ShortList;
import com.sun.org.apache.xerces.internal.xs.XSComplexTypeDefinition;
@@ -43,11 +45,11 @@ public class Field {
//
/** Field XPath. */
- protected Field.XPath fXPath;
+ protected final Field.XPath fXPath;
/** Identity constraint. */
- protected IdentityConstraint fIdentityConstraint;
+ protected final IdentityConstraint fIdentityConstraint;
//
// Constructors
@@ -67,7 +69,7 @@ public class Field {
/** Returns the field XPath. */
public com.sun.org.apache.xerces.internal.impl.xpath.XPath getXPath() {
return fXPath;
- } // getXPath():com.sun.org.apache.xerces.internal.impl.v1.schema.identity.XPath
+ } // getXPath():org.apache.xerces.impl.v1.schema.identity.XPath
/** Returns the identity constraint. */
public IdentityConstraint getIdentityConstraint() {
@@ -77,8 +79,8 @@ public class Field {
// factory method
/** Creates a field matcher. */
- public XPathMatcher createMatcher(FieldActivator activator, ValueStore store) {
- return new Field.Matcher(fXPath, activator, store);
+ public XPathMatcher createMatcher(ValueStore store) {
+ return new Field.Matcher(fXPath, store);
} // createMatcher(ValueStore):XPathMatcher
//
@@ -110,15 +112,7 @@ public class Field {
public XPath(String xpath,
SymbolTable symbolTable,
NamespaceContext context) throws XPathException {
- // NOTE: We have to prefix the field XPath with "./" in
- // order to handle selectors such as "@attr" that
- // select the attribute because the fields could be
- // relative to the selector element. -Ac
- // Unless xpath starts with a descendant node -Achille Fokoue
- // ... or a / or a . - NG
- super(((xpath.trim().startsWith("/") ||xpath.trim().startsWith("."))?
- xpath:"./"+xpath),
- symbolTable, context);
+ super(fixupXPath(xpath), symbolTable, context);
// verify that only one attribute is selected per branch
for (int i=0;i(String,SymbolTable,NamespacesContext)
+ /** Fixup XPath expression. Avoid creating a new String if possible. */
+ private static String fixupXPath(String xpath) {
+
+ final int end = xpath.length();
+ int offset = 0;
+ boolean whitespace = true;
+ char c;
+
+ // NOTE: We have to prefix the field XPath with "./" in
+ // order to handle selectors such as "@attr" that
+ // select the attribute because the fields could be
+ // relative to the selector element. -Ac
+ // Unless xpath starts with a descendant node -Achille Fokoue
+ // ... or a / or a . - NG
+ for (; offset < end; ++offset) {
+ c = xpath.charAt(offset);
+ if (whitespace) {
+ if (!XMLChar.isSpace(c)) {
+ if (c == '.' || c == '/') {
+ whitespace = false;
+ }
+ else if (c != '|') {
+ return fixupXPath2(xpath, offset, end);
+ }
+ }
+ }
+ else if (c == '|') {
+ whitespace = true;
+ }
+ }
+ return xpath;
+
+ } // fixupXPath(String):String
+
+ private static String fixupXPath2(String xpath, int offset, final int end) {
+
+ StringBuffer buffer = new StringBuffer(end + 2);
+ for (int i = 0; i < offset; ++i) {
+ buffer.append(xpath.charAt(i));
+ }
+ buffer.append("./");
+
+ boolean whitespace = false;
+ char c;
+
+ for (; offset < end; ++offset) {
+ c = xpath.charAt(offset);
+ if (whitespace) {
+ if (!XMLChar.isSpace(c)) {
+ if (c == '.' || c == '/') {
+ whitespace = false;
+ }
+ else if (c != '|') {
+ buffer.append("./");
+ whitespace = false;
+ }
+ }
+ }
+ else if (c == '|') {
+ whitespace = true;
+ }
+ buffer.append(c);
+ }
+ return buffer.toString();
+
+ } // fixupXPath2(String, int, int):String
+
} // class XPath
/**
@@ -147,20 +208,19 @@ public class Field {
// Data
//
- /** Field activator. */
- protected FieldActivator fFieldActivator;
-
/** Value store for data values. */
- protected ValueStore fStore;
+ protected final ValueStore fStore;
+
+ /** A flag indicating whether the field is allowed to match a value. */
+ protected boolean fMayMatch = true;
//
// Constructors
//
/** Constructs a field matcher. */
- public Matcher(Field.XPath xpath, FieldActivator activator, ValueStore store) {
+ public Matcher(Field.XPath xpath, ValueStore store) {
super(xpath);
- fFieldActivator = activator;
fStore = store;
} // (Field.XPath,ValueStore)
@@ -179,11 +239,11 @@ public class Field {
fStore.reportError(code,
new Object[]{fIdentityConstraint.getElementName(), fIdentityConstraint.getIdentityConstraintName()});
}
- fStore.addValue(Field.this, actualValue, convertToPrimitiveKind(valueType), convertToPrimitiveKind(itemValueType));
+ fStore.addValue(Field.this, fMayMatch, actualValue, convertToPrimitiveKind(valueType), convertToPrimitiveKind(itemValueType));
// once we've stored the value for this field, we set the mayMatch
- // member to false so that, in the same scope, we don't match any more
+ // member to false so that in the same scope, we don't match any more
// values (and throw an error instead).
- fFieldActivator.setMayMatch(Field.this, Boolean.FALSE);
+ fMayMatch = false;
} // matched(String)
private short convertToPrimitiveKind(short valueType) {
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/FieldActivator.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/FieldActivator.java
index fa5bd050a45..1fd1a567063 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/FieldActivator.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/FieldActivator.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001,2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -51,32 +52,12 @@ public interface FieldActivator {
/**
* Request to activate the specified field. This method returns the
* matcher for the field.
- * It's also important for the implementor to ensure that it marks whether a Field
- * is permitted to match a value--that is, to call the setMayMatch(Field, Boolean) method.
*
* @param field The field to activate.
* @param initialDepth the 0-indexed depth in the instance document at which the Selector began to match.
*/
public XPathMatcher activateField(Field field, int initialDepth);
- /**
- * Sets whether the given field is permitted to match a value.
- * This should be used to catch instance documents that try
- * and match a field several times in the same scope.
- *
- * @param field The field that may be permitted to be matched.
- * @param state Boolean indiciating whether the field may be matched.
- */
- public void setMayMatch(Field field, Boolean state);
-
- /**
- * Returns whether the given field is permitted to match a value.
- *
- * @param field The field that may be permitted to be matched.
- * @return Boolean indicating whether the field may be matched.
- */
- public Boolean mayMatch(Field field);
-
/**
* Ends the value scope for the specified identity constraint.
*
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/ValueStore.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/ValueStore.java
index 434771994b7..070d86ba3cf 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/ValueStore.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/ValueStore.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001, 2002,2004,2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -54,9 +55,12 @@ public interface ValueStore {
* @param field The field associated to the value. This reference
* is used to ensure that each field only adds a value
* once within a selection scope.
+ * @param mayMatch a flag indiciating whether the field may be matched.
* @param actualValue The value to add.
+ * @param valueType Type of the value to add.
+ * @param itemValueType If the value is a list, a list of types for each of the values in the list.
*/
- public void addValue(Field field, Object actualValue, short valueType, ShortList itemValueType);
+ public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType);
/**
* Since the valueStore will have access to an error reporter, this
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMBuilder.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMBuilder.java
index e03ca553540..f1ae5867752 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMBuilder.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMBuilder.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -65,9 +65,10 @@ public class CMBuilder {
* Get content model for the a given type
*
* @param typeDecl get content model for which complex type
+ * @param forUPA a flag indicating whether it is for UPA
* @return a content model validator
*/
- public XSCMValidator getContentModel(XSComplexTypeDecl typeDecl) {
+ public XSCMValidator getContentModel(XSComplexTypeDecl typeDecl, boolean forUPA) {
// for complex type with empty or simple content,
// there is no content model validator
@@ -92,7 +93,7 @@ public class CMBuilder {
cmValidator = createAllCM(particle);
}
else {
- cmValidator = createDFACM(particle);
+ cmValidator = createDFACM(particle, forUPA);
}
//now we are throught building content model and have passed sucessfully of the nodecount check
@@ -124,11 +125,11 @@ public class CMBuilder {
return allContent;
}
- XSCMValidator createDFACM(XSParticleDecl particle) {
+ XSCMValidator createDFACM(XSParticleDecl particle, boolean forUPA) {
fLeafCount = 0;
fParticleCount = 0;
// convert particle tree to CM tree
- CMNode node = useRepeatingLeafNodes(particle) ? buildCompactSyntaxTree(particle) : buildSyntaxTree(particle, true);
+ CMNode node = useRepeatingLeafNodes(particle) ? buildCompactSyntaxTree(particle) : buildSyntaxTree(particle, forUPA, true);
if (node == null)
return null;
// build DFA content model from the CM tree
@@ -141,10 +142,31 @@ public class CMBuilder {
// 3. convert model groups (a, b, c, ...) or (a | b | c | ...) to
// binary tree: (((a,b),c),...) or (((a|b)|c)|...)
// 4. make sure each leaf node (XSCMLeaf) has a distinct position
- private CMNode buildSyntaxTree(XSParticleDecl particle, boolean optimize) {
+ private CMNode buildSyntaxTree(XSParticleDecl particle, boolean forUPA, boolean optimize) {
int maxOccurs = particle.fMaxOccurs;
int minOccurs = particle.fMinOccurs;
+
+ boolean compactedForUPA = false;
+ if (forUPA) {
+ // When doing UPA, we reduce the size of the minOccurs/maxOccurs values to make
+ // processing the DFA faster. For UPA the exact values don't matter.
+ if (minOccurs > 1) {
+ if (maxOccurs > minOccurs || particle.getMaxOccursUnbounded()) {
+ minOccurs = 1;
+ compactedForUPA = true;
+ }
+ else { // maxOccurs == minOccurs
+ minOccurs = 2;
+ compactedForUPA = true;
+ }
+ }
+ if (maxOccurs > 1) {
+ maxOccurs = 2;
+ compactedForUPA = true;
+ }
+ }
+
short type = particle.fType;
CMNode nodeRet = null;
@@ -159,6 +181,9 @@ public class CMBuilder {
nodeRet = fNodeFactory.getCMLeafNode(particle.fType, particle.fValue, fParticleCount++, fLeafCount++);
// (task 2) expand occurrence values
nodeRet = expandContentModel(nodeRet, minOccurs, maxOccurs, optimize);
+ if (nodeRet != null) {
+ nodeRet.setIsCompactUPAModel(compactedForUPA);
+ }
}
else if (type == XSParticleDecl.PARTICLE_MODELGROUP) {
// (task 1,3) convert model groups to binary trees
@@ -178,12 +203,14 @@ public class CMBuilder {
for (int i = 0; i < group.fParticleCount; i++) {
// first convert each child to a CM tree
temp = buildSyntaxTree(group.fParticles[i],
+ forUPA,
optimize &&
minOccurs == 1 && maxOccurs == 1 &&
(group.fCompositor == XSModelGroupImpl.MODELGROUP_SEQUENCE ||
group.fParticleCount == 1));
// then combine them using binary operation
if (temp != null) {
+ compactedForUPA |= temp.isCompactedForUPA();
if (nodeRet == null) {
nodeRet = temp;
}
@@ -205,6 +232,7 @@ public class CMBuilder {
nodeRet = fNodeFactory.getCMUniOpNode(XSParticleDecl.PARTICLE_ZERO_OR_ONE, nodeRet);
}
nodeRet = expandContentModel(nodeRet, minOccurs, maxOccurs, false);
+ nodeRet.setIsCompactUPAModel(compactedForUPA);
}
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java
index 8962280abbb..9a6adcd6caf 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java
@@ -1,6 +1,5 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Copyright 2003-2004 The Apache Software Foundation.
@@ -73,14 +72,11 @@ public class CMNodeFactory {
public CMNodeFactory() {
}
- public void reset(XMLComponentManager componentManager){
+ public void reset(XMLComponentManager componentManager) {
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
try {
fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER);
- //we are setting the limit of number of nodes to 3times the maxOccur value..
- if(fSecurityManager != null){
- maxNodeLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT) * MULTIPLICITY ;
- }
+ reset();
}
catch (XMLConfigurationException e) {
fSecurityManager = null;
@@ -88,6 +84,13 @@ public class CMNodeFactory {
}//reset()
+ public void reset() {
+ // we are setting the limit of number of nodes to 3 times the maxOccurs value.
+ if (fSecurityManager != null) {
+ maxNodeLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT) * MULTIPLICITY ;
+ }
+ }
+
public CMNode getCMLeafNode(int type, Object leaf, int id, int position) {
return new XSCMLeaf(type, leaf, id, position) ;
}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSAllCM.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSAllCM.java
index d3060915341..57b4d1596f5 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSAllCM.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSAllCM.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -25,8 +25,6 @@ import com.sun.org.apache.xerces.internal.impl.xs.XSElementDecl;
import com.sun.org.apache.xerces.internal.impl.xs.SubstitutionGroupHandler;
import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
import com.sun.org.apache.xerces.internal.impl.xs.XSConstraints;
-
-import java.util.Vector;
import java.util.ArrayList;
/**
@@ -202,16 +200,17 @@ public class XSAllCM implements XSCMValidator {
* have been seen.
*
* @param state the current state
- * @return a Vector whose entries are instances of
+ * @return a list whose entries are instances of
* either XSWildcardDecl or XSElementDecl.
*/
- public Vector whatCanGoHere(int[] state) {
- Vector ret = new Vector();
+ public ArrayList whatCanGoHere(int[] state) {
+ ArrayList ret = new ArrayList();
for (int i = 0; i < fNumElements; i++) {
// we only try to look for a matching decl if we have not seen
// this element yet.
- if (state[i+1] == STATE_START)
- ret.addElement(fAllElements[i]);
+ if (state[i+1] == STATE_START) {
+ ret.add(fAllElements[i]);
+ }
}
return ret;
}
@@ -220,4 +219,15 @@ public class XSAllCM implements XSCMValidator {
return null;
}
+ public int [] occurenceInfo(int[] state) {
+ return null;
+ }
+
+ public String getTermName(int termId) {
+ return null;
+ }
+
+ public boolean isCompactedForUPA() {
+ return false;
+ }
} // class XSAllCM
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSCMValidator.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSCMValidator.java
index d387ac52261..6d0cd91f7b2 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSCMValidator.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSCMValidator.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -23,8 +23,6 @@ package com.sun.org.apache.xerces.internal.impl.xs.models;
import com.sun.org.apache.xerces.internal.xni.QName;
import com.sun.org.apache.xerces.internal.impl.xs.SubstitutionGroupHandler;
import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
-
-import java.util.Vector;
import java.util.ArrayList;
/**
@@ -87,24 +85,60 @@ public interface XSCMValidator {
* have been seen.
*
* @param state the current state
- * @return a Vector whose entries are instances of
+ * @return a list whose entries are instances of
* either XSWildcardDecl or XSElementDecl.
*/
- public Vector whatCanGoHere(int[] state);
+ public ArrayList whatCanGoHere(int[] state);
/**
* Used by constant space algorithm for a{n,m} for n > 1 and
* m <= unbounded. Called by a validator if validation of
* countent model succeeds after subsuming a{n,m} to a*
* (or a+) to check the n and m bounds.
- * Returns null if validation of bounds is
+ *
+ * @return null if validation of bounds is
* successful. Returns a list of strings with error info
* if not. Even entries in list returned are error codes
* (used to look up properties) and odd entries are parameters
* to be passed when formatting error message. Each parameter
- * is associated with the error code that preceeds it in
+ * is associated with the error code that proceeds it in
* the list.
*/
public ArrayList checkMinMaxBounds();
+ /**
+ *
Returns an array containing information about the current repeating term
+ * or null if no occurrence counting was being performed at the
+ * current state.
+ *
+ *
If an array is returned it will have a length == 4 and will contain:
+ *
+ *
a[0] :: min occurs
+ *
a[1] :: max occurs
+ *
a[2] :: current value of the counter
+ *
a[3] :: identifier for the repeating term
+ *
+ *
+ *
+ * @param state the current state
+ * @return an array containing information about the current repeating term
+ */
+ public int [] occurenceInfo(int[] state);
+
+ /**
+ * Returns the name of the term (element or wildcard) for the given identifier.
+ *
+ * @param termId identifier for the element declaration or wildcard
+ * @return the name of the element declaration or wildcard
+ */
+ public String getTermName(int termId);
+
+ /**
+ * Checks if this content model has had its min/maxOccurs values reduced for
+ * purposes of speeding up UPA. If so, this content model should not be used
+ * for any purpose other than checking unique particle attribution
+ *
+ * @return a boolean that says whether this content has been compacted for UPA
+ */
+ public boolean isCompactedForUPA();
} // XSCMValidator
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSDFACM.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSDFACM.java
index 997ca17cb95..abb0d7a6bfb 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSDFACM.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSDFACM.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -31,8 +31,6 @@ import com.sun.org.apache.xerces.internal.impl.xs.XSModelGroupImpl;
import com.sun.org.apache.xerces.internal.impl.xs.XSWildcardDecl;
import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
import com.sun.org.apache.xerces.internal.impl.xs.XSConstraints;
-
-import java.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
@@ -166,6 +164,8 @@ public class XSDFACM
*/
private int fTransTableSize = 0;
+ private boolean fIsCompactedForUPA;
+
/**
* Array of counters for all the for elements (or wildcards)
* of the form a{n,m} where n > 1 and m <= unbounded. Used
@@ -1165,10 +1165,10 @@ public class XSDFACM
* have been seen.
*
* @param state the current state
- * @return a Vector whose entries are instances of
+ * @return a list whose entries are instances of
* either XSWildcardDecl or XSElementDecl.
*/
- public Vector whatCanGoHere(int[] state) {
+ public ArrayList whatCanGoHere(int[] state) {
int curState = state[0];
if (curState < 0)
curState = state[1];
@@ -1176,7 +1176,7 @@ public class XSDFACM
fCountingStates[curState] : null;
int count = state[2];
- Vector ret = new Vector();
+ ArrayList ret = new ArrayList();
for (int elemIndex = 0; elemIndex < fElemMapSize; elemIndex++) {
int nextState = fTransTable[curState][elemIndex];
if (nextState != -1) {
@@ -1196,7 +1196,7 @@ public class XSDFACM
continue;
}
}
- ret.addElement(fElemMap[elemIndex]);
+ ret.add(fElemMap[elemIndex]);
}
}
return ret;
@@ -1231,11 +1231,38 @@ public class XSDFACM
}
if (maxOccurs != -1 && count > maxOccurs) {
if (result == null) result = new ArrayList();
- result.add("cvc-complex-type.2.4.e");
+ result.add("cvc-complex-type.2.4.d.1");
result.add("{" + fElemMap[elemIndex] + "}");
}
}
return result;
}
+ public int [] occurenceInfo(int[] state) {
+ if (fCountingStates != null) {
+ int curState = state[0];
+ if (curState < 0) {
+ curState = state[1];
+ }
+ Occurence o = fCountingStates[curState];
+ if (o != null) {
+ int [] occurenceInfo = new int[4];
+ occurenceInfo[0] = o.minOccurs;
+ occurenceInfo[1] = o.maxOccurs;
+ occurenceInfo[2] = state[2];
+ occurenceInfo[3] = o.elemIndex;
+ return occurenceInfo;
+ }
+ }
+ return null;
+ }
+
+ public String getTermName(int termId) {
+ Object term = fElemMap[termId];
+ return (term != null) ? term.toString() : null;
+ }
+
+ public boolean isCompactedForUPA() {
+ return fIsCompactedForUPA;
+ }
} // class DFAContentModel
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSEmptyCM.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSEmptyCM.java
index bf730d692c9..4c39b4adca6 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSEmptyCM.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSEmptyCM.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -18,13 +18,12 @@
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.impl.xs.models;
import com.sun.org.apache.xerces.internal.xni.QName;
import com.sun.org.apache.xerces.internal.impl.xs.SubstitutionGroupHandler;
import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
-
-import java.util.Vector;
import java.util.ArrayList;
/**
@@ -47,7 +46,7 @@ public class XSEmptyCM implements XSCMValidator {
// start the content model: did not see any children
private static final short STATE_START = 0;
- private static final Vector EMPTY = new Vector(0);
+ private static final ArrayList EMPTY = new ArrayList(0);
//
// Data
@@ -126,10 +125,10 @@ public class XSEmptyCM implements XSCMValidator {
* have been seen.
*
* @param state the current state
- * @return a Vector whose entries are instances of
+ * @return a list whose entries are instances of
* either XSWildcardDecl or XSElementDecl.
*/
- public Vector whatCanGoHere(int[] state) {
+ public ArrayList whatCanGoHere(int[] state) {
return EMPTY;
}
@@ -137,4 +136,15 @@ public class XSEmptyCM implements XSCMValidator {
return null;
}
+ public int [] occurenceInfo(int[] state) {
+ return null;
+ }
+
+ public String getTermName(int termId) {
+ return null;
+ }
+
+ public boolean isCompactedForUPA() {
+ return false;
+ }
} // class XSEmptyCM
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDSimpleTypeTraverser.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDSimpleTypeTraverser.java
index 1564227b1f5..3c247a5a104 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDSimpleTypeTraverser.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDSimpleTypeTraverser.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -24,9 +25,7 @@ import java.util.ArrayList;
import java.util.Vector;
import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeFacetException;
-import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
-import com.sun.org.apache.xerces.internal.impl.dv.xs.SchemaDVFactoryImpl;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.SchemaGrammar;
import com.sun.org.apache.xerces.internal.impl.xs.SchemaSymbols;
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/util/XS10TypeHelper.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/util/XS10TypeHelper.java
new file mode 100644
index 00000000000..afe5161795e
--- /dev/null
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/util/XS10TypeHelper.java
@@ -0,0 +1,65 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sun.org.apache.xerces.internal.impl.xs.util;
+
+import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
+import com.sun.org.apache.xerces.internal.impl.xs.XSComplexTypeDecl;
+import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
+
+/**
+ * Class defining utility/helper methods to support XML Schema 1.0 implementation.
+ *
+ * @xerces.internal
+ *
+ * @author Mukul Gandhi, IBM
+ */
+public class XS10TypeHelper {
+
+ /*
+ * Class constructor.
+ */
+ private XS10TypeHelper() {
+ // a private constructor, to prohibit instantiating this class from an outside class/application.
+ // this is a good practice, since all methods of this class are "static".
+ }
+
+ /*
+ * Get name of an XSD type definition as a string value (which will typically be the value of "name" attribute of a
+ * type definition, or an internal name determined by the validator for anonymous types).
+ */
+ public static String getSchemaTypeName(XSTypeDefinition typeDefn) {
+
+ String typeNameStr;
+ if (typeDefn instanceof XSSimpleTypeDefinition) {
+ typeNameStr = ((XSSimpleTypeDecl) typeDefn).getTypeName();
+ }
+ else {
+ typeNameStr = ((XSComplexTypeDecl) typeDefn).getTypeName();
+ }
+
+ return typeNameStr;
+
+ } // getSchemaTypeName
+
+
+} // class XS10TypeHelper
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java
index 807dc917908..e8bd3e446df 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
+ */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -529,6 +532,7 @@ final class XMLSchemaValidatorComponentManager extends ParserConfigurationSettin
fComponents.put(LOCALE, null);
// Restore initial security manager
+ fInitSecurityManager.setSecureProcessing(true);
fComponents.put(SECURITY_MANAGER, fInitSecurityManager);
// Set the Locale back to null.
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DOMParserImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DOMParserImpl.java
index 0053d984291..84ffa4f0445 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DOMParserImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DOMParserImpl.java
@@ -1,13 +1,13 @@
/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * Copyright 2000-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,12 +20,6 @@
package com.sun.org.apache.xerces.internal.parsers;
-import java.io.StringReader;
-import java.util.Locale;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
import com.sun.org.apache.xerces.internal.dom.DOMMessageFormatter;
import com.sun.org.apache.xerces.internal.dom.DOMStringListImpl;
@@ -55,7 +49,11 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLEntityResolver;
import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
import com.sun.org.apache.xerces.internal.xni.parser.XMLParseException;
import com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration;
-import com.sun.org.apache.xerces.internal.parsers.XIncludeAwareParserConfiguration;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Locale;
+import java.util.Stack;
+import java.util.StringTokenizer;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMError;
import org.w3c.dom.DOMErrorHandler;
@@ -152,7 +150,6 @@ extends AbstractDOMParser implements LSParser, DOMConfiguration {
protected final static boolean DEBUG = false;
- private Vector fSchemaLocations = new Vector ();
private String fSchemaLocation = null;
private DOMStringList fRecognizedParameters;
@@ -286,17 +283,17 @@ extends AbstractDOMParser implements LSParser, DOMConfiguration {
* @throws SAXException Thrown on initialization error.
*/
public void reset () {
- super.reset ();
+ super.reset();
// get state of namespace-declarations parameter.
fNamespaceDeclarations =
fConfiguration.getFeature(Constants.DOM_NAMESPACE_DECLARATIONS);
// DOM Filter
- if (fSkippedElemStack!=null) {
- fSkippedElemStack.removeAllElements ();
+ if (fSkippedElemStack != null) {
+ fSkippedElemStack.removeAllElements();
}
- fSchemaLocations.clear ();
+
fRejectedElementDepth = 0;
fFilterReject = false;
fSchemaType = null;
@@ -521,15 +518,15 @@ extends AbstractDOMParser implements LSParser, DOMConfiguration {
// map DOM schema-location to JAXP schemaSource property
// tokenize location string
StringTokenizer t = new StringTokenizer (fSchemaLocation, " \n\t\r");
- if (t.hasMoreTokens ()){
- fSchemaLocations.clear ();
- fSchemaLocations.add (t.nextToken ());
- while (t.hasMoreTokens ()) {
- fSchemaLocations.add (t.nextToken ());
+ if (t.hasMoreTokens()) {
+ ArrayList locations = new ArrayList();
+ locations.add (t.nextToken());
+ while (t.hasMoreTokens()) {
+ locations.add (t.nextToken());
}
fConfiguration.setProperty (
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE,
- fSchemaLocations.toArray ());
+ locations.toArray());
}
else {
fConfiguration.setProperty (
@@ -865,7 +862,7 @@ extends AbstractDOMParser implements LSParser, DOMConfiguration {
*/
public DOMStringList getParameterNames () {
if (fRecognizedParameters == null){
- Vector parameters = new Vector();
+ ArrayList parameters = new ArrayList();
// REVISIT: add Xerces recognized properties/features
parameters.add(Constants.DOM_NAMESPACES);
@@ -1116,7 +1113,7 @@ extends AbstractDOMParser implements LSParser, DOMConfiguration {
}
/**
- * @see org.w3c.dom.ls.DOMParser#abort()
+ * @see org.w3c.dom.ls.LSParser#abort()
*/
public void abort () {
// If parse operation is in progress then reset it
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/StandardParserConfiguration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/StandardParserConfiguration.java
index 464f93e8c92..9ec3731a9ae 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/StandardParserConfiguration.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/StandardParserConfiguration.java
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -152,6 +155,10 @@ public class StandardParserConfiguration
protected static final String ROOT_TYPE_DEF =
Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY;
+ /** Property identifier: root element declaration. */
+ protected static final String ROOT_ELEMENT_DECL =
+ Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY;
+
//
// Data
//
@@ -259,6 +266,7 @@ public class StandardParserConfiguration
SCHEMA_LOCATION,
SCHEMA_NONS_LOCATION,
ROOT_TYPE_DEF,
+ ROOT_ELEMENT_DECL,
SCHEMA_DV_FACTORY,
};
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java
index 975367eb2be..459067067a1 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
+ */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -282,6 +285,10 @@ public class XML11Configuration extends ParserConfigurationSettings
protected static final String ROOT_TYPE_DEF =
Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY;
+ /** Property identifier: root element declaration. */
+ protected static final String ROOT_ELEMENT_DECL =
+ Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY;
+
/** Property identifier: locale. */
protected static final String LOCALE =
Constants.XERCES_PROPERTY_PREFIX + Constants.LOCALE_PROPERTY;
@@ -553,6 +560,7 @@ public class XML11Configuration extends ParserConfigurationSettings
SCHEMA_LOCATION,
SCHEMA_NONS_LOCATION,
ROOT_TYPE_DEF,
+ ROOT_ELEMENT_DECL,
LOCALE,
SCHEMA_DV_FACTORY,
SECURITY_MANAGER,
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLAttributesImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLAttributesImpl.java
index 55717373866..96b0e418a79 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLAttributesImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLAttributesImpl.java
@@ -3,60 +3,20 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * The Apache Software License, Version 1.1
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- * if any, must include the following acknowledgment:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgment may appear in the software itself,
- * if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Xerces" and "Apache Software Foundation" must
- * not be used to endorse or promote products derived from this
- * software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- * nor may "Apache" appear in their name, without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation and was
- * originally based on software copyright (c) 1999, International
- * Business Machines, Inc., http://www.apache.org. For more
- * information on the Apache Software Foundation, please see
- * .
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
package com.sun.org.apache.xerces.internal.util;
@@ -222,7 +182,7 @@ implements XMLAttributes, XMLBufferListener {
int index;
if (fLength < SIZE_LIMIT) {
- index = name.uri != null && !name.uri.equals("")
+ index = name.uri != null && name.uri.length() != 0
? getIndexFast(name.uri, name.localpart)
: getIndexFast(name.rawname);
@@ -1097,29 +1057,6 @@ implements XMLAttributes, XMLBufferListener {
} // getURI(int,QName)
// Implementation methods
- public void setSchemaId(int attrIndex, boolean schemaId) {
- fAttributes[attrIndex].schemaId = schemaId;
- }
-
- public boolean getSchemaId(int index) {
- if (index < 0 || index >= fLength) {
- return false;
- }
- return fAttributes[index].schemaId;
- }
-
- public boolean getSchemaId(String qname) {
- int index = getIndex(qname);
- return index != -1 ? fAttributes[index].schemaId : false;
- } // getType(String):String
-
- public boolean getSchemaId(String uri, String localName) {
- if (!fNamespaces) {
- return false;
- }
- int index = getIndex(uri, localName);
- return index != -1 ? fAttributes[index].schemaId : false;
- } // getType(String,String):String
//XMLBufferListener methods
/**
@@ -1154,7 +1091,7 @@ implements XMLAttributes, XMLBufferListener {
// basic info
/** Name. */
- public QName name = new QName();
+ public final QName name = new QName();
/** Type. */
public String type;
@@ -1171,8 +1108,6 @@ implements XMLAttributes, XMLBufferListener {
/** Specified. */
public boolean specified;
- /** Schema ID type. */
- public boolean schemaId;
/**
* Augmentations information for this attribute.
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/ItemPSVI.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/ItemPSVI.java
index 48d863e8868..8230abff87e 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/ItemPSVI.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/ItemPSVI.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -31,19 +32,19 @@ public interface ItemPSVI {
*/
public static final short VALIDITY_NOTKNOWN = 0;
/**
- * Validity value indicating that validation has been strictly assessed
+ * Validity value indicating that validation has been strictly assessed
* and the item in question is invalid according to the rules of schema
* validation.
*/
public static final short VALIDITY_INVALID = 1;
/**
- * Validation status indicating that schema validation has been performed
+ * Validation status indicating that schema validation has been performed
* and the item in question is valid according to the rules of schema
* validation.
*/
public static final short VALIDITY_VALID = 2;
/**
- * Validation status indicating that schema validation has been performed
+ * Validation status indicating that schema validation has been performed
* and the item in question has specifically been skipped.
*/
public static final short VALIDATION_NONE = 0;
@@ -53,12 +54,25 @@ public interface ItemPSVI {
*/
public static final short VALIDATION_PARTIAL = 1;
/**
- * Validation status indicating that full schema validation has been
+ * Validation status indicating that full schema validation has been
* performed on the item.
*/
public static final short VALIDATION_FULL = 2;
+
/**
- * The nearest ancestor element information item with a
+ * Returns a reference to an immutable instance with the same data
+ * that this instance of ItemPSVI currently has.
+ */
+ public ItemPSVI constant();
+
+ /**
+ * Returns true if this specific instance of
+ * ItemPSVI is immutable, otherwise false.
+ */
+ public boolean isConstant();
+
+ /**
+ * The nearest ancestor element information item with a
* [schema information] property (or this element item
* itself if it has such a property). For more information refer to
* element validation context and attribute validation context .
@@ -66,7 +80,7 @@ public interface ItemPSVI {
public String getValidationContext();
/**
- * [validity]: determines the validity of the schema item
+ * [validity]: determines the validity of the schema item
* with respect to the validation being attempted. The value will be one
* of the constants: VALIDITY_NOTKNOWN,
* VALIDITY_INVALID or VALIDITY_VALID.
@@ -74,7 +88,7 @@ public interface ItemPSVI {
public short getValidity();
/**
- * [validation attempted]: determines the extent to which
+ * [validation attempted]: determines the extent to which
* the schema item has been validated. The value will be one of the
* constants: VALIDATION_NONE,
* VALIDATION_PARTIAL or VALIDATION_FULL.
@@ -82,15 +96,25 @@ public interface ItemPSVI {
public short getValidationAttempted();
/**
- * [schema error code]: a list of error codes generated from
+ * [schema error code]: a list of error codes generated from
* the validation attempt or an empty StringList if no
* errors occurred during the validation attempt.
*/
public StringList getErrorCodes();
+ /**
+ * A list of error messages generated from the validation attempt or
+ * an empty StringList if no errors occurred during the
+ * validation attempt. The indices of error messages in this list are
+ * aligned with those in the [schema error code] list.
+ */
+ public StringList getErrorMessages();
+
/**
* [schema normalized value]: the normalized value of this
* item after validation.
+ *
+ * @deprecated Use getSchemaValue().getNormalizedValue() instead
*/
public String getSchemaNormalizedValue();
@@ -100,6 +124,8 @@ public interface ItemPSVI {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getSchemaValue().getActualValue() instead
*/
public Object getActualNormalizedValue()
throws XSException;
@@ -113,11 +139,12 @@ public interface ItemPSVI {
* method returns LISTOFUNION_DT. To query the actual value
* of the list or list of union type definitions use
* itemValueTypes. If the actualNormalizedValue
- * is null, this method returns UNAVAILABLE_DT
- * .
+ * is null, this method returns UNAVAILABLE_DT.
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getSchemaValue().getActualValueType() instead
*/
public short getActualNormalizedValueType()
throws XSException;
@@ -152,12 +179,22 @@ public interface ItemPSVI {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getSchemaValue().getListValueTypes() instead
*/
public ShortList getItemValueTypes()
throws XSException;
/**
- * [type definition]: an item isomorphic to the type
+ * If this item has a simple type definition or a complex type with simple
+ * content, then return the value with respect to the simple type. If
+ * this item doesn't have a simple-typed value, the behavior of this method
+ * is not specified.
+ */
+ public XSValue getSchemaValue();
+
+ /**
+ * [type definition]: an item isomorphic to the type
* definition used to validate the schema item.
*/
public XSTypeDefinition getTypeDefinition();
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeDeclaration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeDeclaration.java
index 350a148e006..7fa9563b8a2 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeDeclaration.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeDeclaration.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -51,6 +52,8 @@ public interface XSAttributeDeclaration extends XSObject {
/**
* Value constraint: The constraint value with respect to the [type
* definition], otherwise null.
+ *
+ * @deprecated Use getValueConstraintValue().getNormalizedValue() instead
*/
public String getConstraintValue();
@@ -61,6 +64,8 @@ public interface XSAttributeDeclaration extends XSObject {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getActualValue() instead
*/
public Object getActualVC()
throws XSException;
@@ -78,6 +83,8 @@ public interface XSAttributeDeclaration extends XSObject {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getActualValueType() instead
*/
public short getActualVCType()
throws XSException;
@@ -94,10 +101,17 @@ public interface XSAttributeDeclaration extends XSObject {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getListValueTypes() instead
*/
public ShortList getItemValueTypes()
throws XSException;
+ /**
+ * The actual value of the default or fixed value constraint.
+ */
+ public XSValue getValueConstraintValue();
+
/**
* An annotation if it exists, otherwise null.
* If not null then the first [annotation] from the sequence of annotations.
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeUse.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeUse.java
index b55e530899f..5545b028b64 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeUse.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSAttributeUse.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -38,12 +39,14 @@ public interface XSAttributeUse extends XSObject {
public XSAttributeDeclaration getAttrDeclaration();
/**
- * Value Constraint: one of default, fixed.
+ * Value Constraint: one of default, fixed, or none.
*/
public short getConstraintType();
/**
* Value Constraint: The constraint value, otherwise null.
+ *
+ * @deprecated Use getValueConstraintValue().getNormalizedValue() instead
*/
public String getConstraintValue();
@@ -54,6 +57,8 @@ public interface XSAttributeUse extends XSObject {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getActualValue() instead
*/
public Object getActualVC()
throws XSException;
@@ -67,11 +72,12 @@ public interface XSAttributeUse extends XSObject {
* method returns LISTOFUNION_DT. To query the actual
* constraint value of the list or list of union type definitions use
* itemValueTypes. If the actualNormalizedValue
- * is null, this method returns UNAVAILABLE_DT
- * .
+ * is null, this method returns UNAVAILABLE_DT.
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getActualValueType() instead
*/
public short getActualVCType()
throws XSException;
@@ -88,10 +94,17 @@ public interface XSAttributeUse extends XSObject {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getListValueTypes() instead
*/
public ShortList getItemValueTypes()
throws XSException;
+ /**
+ * The actual value of the default or fixed value constraint.
+ */
+ public XSValue getValueConstraintValue();
+
/**
* A sequence of [annotations] or an empty XSObjectList.
*/
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSElementDeclaration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSElementDeclaration.java
index 48ae9dd9de6..cf2fea85b27 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSElementDeclaration.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSElementDeclaration.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -52,6 +53,8 @@ public interface XSElementDeclaration extends XSTerm {
/**
* [Value constraint]: the constraint value with respect to the [type
* definition], otherwise null.
+ *
+ * @deprecated Use getValueConstraintValue().getNormalizedValue() instead
*/
public String getConstraintValue();
@@ -62,6 +65,8 @@ public interface XSElementDeclaration extends XSTerm {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getActualValue() instead
*/
public Object getActualVC()
throws XSException;
@@ -75,11 +80,12 @@ public interface XSElementDeclaration extends XSTerm {
* method returns LISTOFUNION_DT. To query the actual
* constraint value of the list or list of union type definitions use
* itemValueTypes. If the actualNormalizedValue
- * is null, this method returns UNAVAILABLE_DT
- * .
+ * is null, this method returns UNAVAILABLE_DT.
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getActualValueType() instead
*/
public short getActualVCType()
throws XSException;
@@ -96,10 +102,17 @@ public interface XSElementDeclaration extends XSTerm {
* @exception XSException
* NOT_SUPPORTED_ERR: Raised if the implementation does not support this
* method.
+ *
+ * @deprecated Use getValueConstraintValue().getListValueTypes() instead
*/
public ShortList getItemValueTypes()
throws XSException;
+ /**
+ * The actual value of the default or fixed value constraint.
+ */
+ public XSValue getValueConstraintValue();
+
/**
* If nillable is true, then an element may also be valid if it carries
* the namespace qualified attribute with local name nil
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSFacet.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSFacet.java
index 2bef026f7ca..28db7f0c8ba 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSFacet.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSFacet.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -36,6 +37,24 @@ public interface XSFacet extends XSObject {
*/
public String getLexicalFacetValue();
+ /**
+ * If this facet is length, minLength, maxLength, totalDigits, or
+ * fractionDigits, and if the value can fit in "int", then return the value
+ * of the facet as an int. If the value can't fit, return -1. Use
+ * getActualFacetValue() to get the BigInteger representation. For all other
+ * facets, return 0.
+ */
+ public int getIntFacetValue();
+
+ /**
+ * If this facet is minInclusive, maxInclusive, minExclusive, or
+ * maxExclusive, then return the actual value of the facet. If this facet
+ * is length, minLength, maxLength, totalDigits, or fractionDigits, then
+ * return a BigInteger representation of the value. If this facet is
+ * whiteSpace, then return the String representation of the facet.
+ */
+ public Object getActualFacetValue();
+
/**
* [Facets]: check whether a facet is fixed.
*/
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSModel.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSModel.java
index 96a70aea7d6..d882b96f9a7 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSModel.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSModel.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -44,7 +45,9 @@ public interface XSModel {
/**
* Returns a list of top-level components, i.e. element declarations,
- * attribute declarations, etc.
+ * attribute declarations, etc. Identity-constraint definitions are also
+ * considered top-level.
+ *
* @param objectType The type of the declaration, i.e.
* ELEMENT_DECLARATION. Note that
* XSTypeDefinition.SIMPLE_TYPE and
@@ -60,7 +63,9 @@ public interface XSModel {
/**
* Convenience method. Returns a list of top-level component declarations
* that are defined within the specified namespace, i.e. element
- * declarations, attribute declarations, etc.
+ * declarations, attribute declarations, etc. Identity-constraint
+ * definitions are also considered top-level.
+ *
* @param objectType The type of the declaration, i.e.
* ELEMENT_DECLARATION.
* @param namespace The namespace to which the declaration belongs or
@@ -145,6 +150,17 @@ public interface XSModel {
public XSNotationDeclaration getNotationDeclaration(String name,
String namespace);
+ /**
+ * Convenience method. Returns an identity-constraint definition.
+ * @param name The name of the definition.
+ * @param namespace The namespace of the definition, otherwise
+ * null.
+ * @return An identity-constraint definition or null if such
+ * a declaration does not exist.
+ */
+ public XSIDCDefinition getIDCDefinition(String name,
+ String namespace);
+
/**
* Convenience method. Returns a list containing the members of the
* substitution group for the given XSElementDeclaration
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSMultiValueFacet.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSMultiValueFacet.java
index 960d79869aa..e0193466e72 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSMultiValueFacet.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSMultiValueFacet.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -20,6 +21,8 @@
package com.sun.org.apache.xerces.internal.xs;
+import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
+
/**
* Describes a multi-value constraining facets: pattern and enumeration.
*/
@@ -35,6 +38,11 @@ public interface XSMultiValueFacet extends XSObject {
*/
public StringList getLexicalFacetValues();
+ /**
+ * A list of XSValue objects. The actual enumeration values.
+ */
+ public ObjectList getEnumerationValues();
+
/**
* A sequence of [annotations] or an empty XSObjectList.
*/
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSNamespaceItem.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSNamespaceItem.java
index a83d1e030a1..51c952c879f 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSNamespaceItem.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSNamespaceItem.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -33,7 +34,9 @@ public interface XSNamespaceItem {
/**
* [schema components]: a list of top-level components, i.e. element
- * declarations, attribute declarations, etc.
+ * declarations, attribute declarations, etc. Identity-constraint
+ * definitions are also considered top-level.
+ *
* @param objectType The type of the declaration, i.e.
* ELEMENT_DECLARATION. Note that
* XSTypeDefinition.SIMPLE_TYPE and
@@ -101,6 +104,14 @@ public interface XSNamespaceItem {
*/
public XSNotationDeclaration getNotationDeclaration(String name);
+ /**
+ * Convenience method. Returns an identity-constraint definition.
+ * @param name The name of the definition.
+ * @return An identity-constraint definition or null if such
+ * a declaration does not exist.
+ */
+ public XSIDCDefinition getIDCDefinition(String name);
+
/**
* [document location] - a list of location URIs for the documents that
* contributed to the XSModel.
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSSimpleTypeDefinition.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSSimpleTypeDefinition.java
index 84427804b54..88da4d319b0 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSSimpleTypeDefinition.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSSimpleTypeDefinition.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2003,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -234,6 +235,11 @@ public interface XSSimpleTypeDefinition extends XSTypeDefinition {
*/
public XSObjectList getMultiValueFacets();
+ /**
+ * A constraining facet object. An instance of XSFacet or XSMultiValueFacet.
+ */
+ public XSObject getFacet(int facetType);
+
/**
* A sequence of [annotations] or an empty XSObjectList.
*/
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSValue.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSValue.java
new file mode 100644
index 00000000000..56ea59db4e2
--- /dev/null
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/XSValue.java
@@ -0,0 +1,108 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sun.org.apache.xerces.internal.xs;
+
+/**
+ * Represents an actual value of a simple type.
+ */
+public interface XSValue {
+
+ /**
+ * The schema normalized value.
+ * @return The normalized value.
+ */
+ public String getNormalizedValue();
+
+ /**
+ * The actual value. null if the value is in error.
+ * @return The actual value.
+ */
+ public Object getActualValue();
+
+ /**
+ * The declared simple type definition used to validate this value.
+ * It can be a union type.
+ * @return The declared simple type definition
+ */
+ public XSSimpleTypeDefinition getTypeDefinition();
+
+ /**
+ * If the declared simple type definition is a union, return the member
+ * type actually used to validate the value. Otherwise null.
+ * @return The member type
+ */
+ public XSSimpleTypeDefinition getMemberTypeDefinition();
+
+ /**
+ * If getTypeDefinition() returns a list type whose item type
+ * is a union type, then this method returns a list with the same length
+ * as the value list, for simple types that actually validated
+ * the corresponding item in the value.
+ * @return A list of type definitions
+ */
+ public XSObjectList getMemberTypeDefinitions();
+
+ /**
+ * The actual value built-in datatype, e.g.
+ * STRING_DT, SHORT_DT. If the type definition of this
+ * value is a list type definition, this method returns
+ * LIST_DT. If the type definition of this value is a list
+ * type definition whose item type is a union type definition, this
+ * method returns LISTOFUNION_DT. To query the actual value
+ * of the list or list of union type definitions use
+ * itemValueTypes().
+ * @return The actual value type
+ */
+ public short getActualValueType();
+
+ /**
+ * In the case the actual value represents a list, i.e. the
+ * actualNormalizedValueType is LIST_DT, the
+ * returned array consists of one type kind which represents the itemType
+ * . For example:
+ *
+ *
+ * The schemaNormalizedValue value is "1 2 3", the
+ * actualNormalizedValueType value is LIST_DT,
+ * and the itemValueTypes is an array of size 1 with the
+ * value POSITIVEINTEGER_DT.
+ * If the actual value represents a list type definition whose item
+ * type is a union type definition, i.e. LISTOFUNION_DT,
+ * for each actual value in the list the array contains the
+ * corresponding memberType kind. For example:
+ *
+ * The
+ * schemaNormalizedValue value is "1 2 foo", the
+ * actualNormalizedValueType is LISTOFUNION_DT
+ * , and the itemValueTypes is an array of size 3 with the
+ * following values: INTEGER_DT, INTEGER_DT, STRING_DT.
+ * @return The list value types
+ */
+ public ShortList getListValueTypes();
+
+}
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/datatypes/ByteList.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/datatypes/ByteList.java
index c1d1edefd03..84b878830e0 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/datatypes/ByteList.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xs/datatypes/ByteList.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2004,2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,6 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.xs.datatypes;
import java.util.List;
@@ -60,4 +62,8 @@ public interface ByteList extends List {
*/
public byte item(int index) throws XSException;
+ /**
+ * Construct and return a byte array for bytes contained in this list.
+ */
+ public byte[] toByteArray();
}
From dbbe5b9419f20c39fa1ba59225fb4839d6be2fd0 Mon Sep 17 00:00:00 2001
From: Joe Wang
Date: Fri, 9 May 2014 11:35:21 -0700
Subject: [PATCH 20/82] 8039533: Higher resolution resolvers
Reviewed-by: lancea, dfuchs, skoivu
---
.../impl/XMLDocumentFragmentScannerImpl.java | 4 ++--
.../internal/impl/XMLEntityManager.java | 20 ++++++++++---------
2 files changed, 13 insertions(+), 11 deletions(-)
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
index 1f0a5b8db0d..c1c6406bcf4 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
@@ -611,9 +611,9 @@ public class XMLDocumentFragmentScannerImpl
//fElementStack2.clear();
//fReplaceEntityReferences = true;
//fSupportExternalEntities = true;
- Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_REPLACING_ENTITY_REFERENCES);
+ Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES);
fReplaceEntityReferences = bo.booleanValue();
- bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_SUPPORTING_EXTERNAL_ENTITIES);
+ bo = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES);
fSupportExternalEntities = bo.booleanValue();
Boolean cdata = (Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.STAX_REPORT_CDATA_EVENT) ;
if(cdata != null)
diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
index 96774da47be..7d2e50580ba 100644
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
@@ -305,10 +305,10 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
/** Property Manager. This is used from Stax */
protected PropertyManager fPropertyManager ;
- /** StAX properties */
- boolean fSupportDTD = true;
- boolean fReplaceEntityReferences = true;
- boolean fSupportExternalEntities = true;
+ /** StAX properties */
+ boolean fSupportDTD = true;
+ boolean fReplaceEntityReferences = true;
+ boolean fSupportExternalEntities = true;
/** used to restrict external access */
protected String fAccessExternalDTD = EXTERNAL_ACCESS_DEFAULT;
@@ -1438,8 +1438,8 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
}
fSupportDTD = ((Boolean)propertyManager.getProperty(XMLInputFactory.SUPPORT_DTD)).booleanValue();
- fReplaceEntityReferences = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)).booleanValue();
- fSupportExternalEntities = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)).booleanValue();
+ fReplaceEntityReferences = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)).booleanValue();
+ fSupportExternalEntities = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)).booleanValue();
// Zephyr feature ignore-external-dtd is the opposite of Xerces' load-external-dtd
fLoadExternalDTD = !((Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.IGNORE_EXTERNAL_DTD)).booleanValue();
@@ -1511,10 +1511,12 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER, null);
fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER, null);
entityExpansionIndex = fSecurityManager.getIndex(Constants.JDK_ENTITY_EXPANSION_LIMIT);
+
//StAX Property
- fSupportDTD = true;
- fReplaceEntityReferences = true;
- fSupportExternalEntities = true;
+ fSupportDTD = true;
+ fReplaceEntityReferences = true;
+ fSupportExternalEntities = true;
+
// JAXP 1.5 feature
XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER, null);
if (spm == null) {
From 3e5a530aff8642d44ef252eb804e080843588ad3 Mon Sep 17 00:00:00 2001
From: Coleen Phillimore
Date: Tue, 22 Jul 2014 16:24:48 +0400
Subject: [PATCH 21/82] 8015256: Better class accessibility
Improve protection domain check in forName()
Reviewed-by: mchung, acorn, jdn
---
.../share/classes/java/lang/Class.java | 23 +++++++++++--------
jdk/src/java.base/share/native/include/jvm.h | 13 +++++++++++
.../java.base/share/native/libjava/Class.c | 5 ++--
3 files changed, 29 insertions(+), 12 deletions(-)
diff --git a/jdk/src/java.base/share/classes/java/lang/Class.java b/jdk/src/java.base/share/classes/java/lang/Class.java
index 2179ee809f5..5c03b975326 100644
--- a/jdk/src/java.base/share/classes/java/lang/Class.java
+++ b/jdk/src/java.base/share/classes/java/lang/Class.java
@@ -262,8 +262,8 @@ public final class Class implements java.io.Serializable,
@CallerSensitive
public static Class> forName(String className)
throws ClassNotFoundException {
- return forName0(className, true,
- ClassLoader.getClassLoader(Reflection.getCallerClass()));
+ Class> caller = Reflection.getCallerClass();
+ return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
@@ -333,22 +333,27 @@ public final class Class implements java.io.Serializable,
ClassLoader loader)
throws ClassNotFoundException
{
- if (sun.misc.VM.isSystemDomainLoader(loader)) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
+ Class> caller = null;
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ // Reflective call to get caller class is only needed if a security manager
+ // is present. Avoid the overhead of making this call otherwise.
+ caller = Reflection.getCallerClass();
+ if (sun.misc.VM.isSystemDomainLoader(loader)) {
+ ClassLoader ccl = ClassLoader.getClassLoader(caller);
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
sm.checkPermission(
SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
- return forName0(name, initialize, loader);
+ return forName0(name, initialize, loader, caller);
}
- /** Called after security checks have been made. */
+ /** Called after security check for system loader access checks have been made. */
private static native Class> forName0(String name, boolean initialize,
- ClassLoader loader)
+ ClassLoader loader,
+ Class> caller)
throws ClassNotFoundException;
/**
diff --git a/jdk/src/java.base/share/native/include/jvm.h b/jdk/src/java.base/share/native/include/jvm.h
index f3ac9286cdc..26f988a2b58 100644
--- a/jdk/src/java.base/share/native/include/jvm.h
+++ b/jdk/src/java.base/share/native/include/jvm.h
@@ -385,6 +385,19 @@ JVM_ResolveClass(JNIEnv *env, jclass cls);
JNIEXPORT jclass JNICALL
JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
+/*
+ * Find a class from a given class loader. Throws ClassNotFoundException.
+ * name: name of class
+ * init: whether initialization is done
+ * loader: class loader to look up the class. This may not be the same as the caller's
+ * class loader.
+ * caller: initiating class. The initiating class may be null when a security
+ * manager is not installed.
+ */
+JNIEXPORT jclass JNICALL
+JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
+ jobject loader, jclass caller);
+
/*
* Find a class from a given class loader. Throw ClassNotFoundException
* or NoClassDefFoundError depending on the value of the last
diff --git a/jdk/src/java.base/share/native/libjava/Class.c b/jdk/src/java.base/share/native/libjava/Class.c
index 98726d38ebd..ae759514a79 100644
--- a/jdk/src/java.base/share/native/libjava/Class.c
+++ b/jdk/src/java.base/share/native/libjava/Class.c
@@ -93,7 +93,7 @@ Java_java_lang_Class_registerNatives(JNIEnv *env, jclass cls)
JNIEXPORT jclass JNICALL
Java_java_lang_Class_forName0(JNIEnv *env, jclass this, jstring classname,
- jboolean initialize, jobject loader)
+ jboolean initialize, jobject loader, jclass caller)
{
char *clname;
jclass cls = 0;
@@ -131,8 +131,7 @@ Java_java_lang_Class_forName0(JNIEnv *env, jclass this, jstring classname,
goto done;
}
- cls = JVM_FindClassFromClassLoader(env, clname, initialize,
- loader, JNI_FALSE);
+ cls = JVM_FindClassFromCaller(env, clname, initialize, loader, caller);
done:
if (clname != buf) {
From 70ef26d4d0fefcd5cd1aee8f63043753b2c4a97b Mon Sep 17 00:00:00 2001
From: Sean Mullan
Date: Mon, 12 May 2014 10:18:51 -0400
Subject: [PATCH 22/82] 8038364: Use certificate exceptions correctly
Reviewed-by: vinnie, skoivu
---
.../security/cert/CertificateRevokedException.java | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java b/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java
index a545627061a..8c1f0664023 100644
--- a/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java
+++ b/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -84,6 +84,8 @@ public class CertificateRevokedException extends CertificateException {
* @throws NullPointerException if {@code revocationDate},
* {@code reason}, {@code authority}, or
* {@code extensions} is {@code null}
+ * @throws ClassCastException if {@code extensions} contains an incorrectly
+ * typed key or value
*/
public CertificateRevokedException(Date revocationDate, CRLReason reason,
X500Principal authority, Map extensions) {
@@ -94,7 +96,10 @@ public class CertificateRevokedException extends CertificateException {
this.revocationDate = new Date(revocationDate.getTime());
this.reason = reason;
this.authority = authority;
- this.extensions = new HashMap(extensions);
+ // make sure Map only contains correct types
+ this.extensions = Collections.checkedMap(new HashMap<>(),
+ String.class, Extension.class);
+ this.extensions.putAll(extensions);
}
/**
@@ -172,7 +177,8 @@ public class CertificateRevokedException extends CertificateException {
public String getMessage() {
return "Certificate has been revoked, reason: "
+ reason + ", revocation date: " + revocationDate
- + ", authority: " + authority + ", extensions: " + extensions;
+ + ", authority: " + authority + ", extension OIDs: "
+ + extensions.keySet();
}
/**
From 14363dbaab1b4365367e96c7ce1ff125fc25ce1e Mon Sep 17 00:00:00 2001
From: Daniel Fuchs
Date: Wed, 14 May 2014 15:40:39 +0200
Subject: [PATCH 23/82] 8041564: Improved management of logger resources
Reviewed-by: skoivu, mchung, igerasim
---
.../share/classes/java/util/logging/Logger.java | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
diff --git a/jdk/src/java.logging/share/classes/java/util/logging/Logger.java b/jdk/src/java.logging/share/classes/java/util/logging/Logger.java
index ae4c1e46baf..fc4101f20f4 100644
--- a/jdk/src/java.logging/share/classes/java/util/logging/Logger.java
+++ b/jdk/src/java.logging/share/classes/java/util/logging/Logger.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -1937,6 +1937,9 @@ public class Logger {
}
setCallersClassLoaderRef(callersClass);
+ if (isSystemLogger && getCallersClassLoader() != null) {
+ checkPermission();
+ }
if (findResourceBundle(name, true) == null) {
// We've failed to find an expected ResourceBundle.
// unset the caller's ClassLoader since we were unable to find the
@@ -2170,11 +2173,13 @@ public class Logger {
return trb;
}
final String rbName = isSystemLogger
- ? trb.resourceBundleName
+ // ancestor of a system logger is expected to be a system logger.
+ // ignore resource bundle name if it's not.
+ ? (target.isSystemLogger ? trb.resourceBundleName : null)
: target.getResourceBundleName();
if (rbName != null) {
return LoggerBundle.get(rbName,
- findResourceBundle(rbName, true));
+ findResourceBundle(rbName, true));
}
target = isSystemLogger ? target.parent : target.getParent();
}
From 91823dc0c8428ec5edd9628314b2e9913891e7d9 Mon Sep 17 00:00:00 2001
From: Phil Race
Date: Thu, 22 May 2014 12:28:27 -0700
Subject: [PATCH 24/82] 8041540: Better use of pages in font processing
Reviewed-by: srl, bae, mschoene
---
.../layout/ContextualSubstSubtables.cpp | 98 +++++++++++++------
1 file changed, 69 insertions(+), 29 deletions(-)
diff --git a/jdk/src/java.desktop/share/native/libfontmanager/layout/ContextualSubstSubtables.cpp b/jdk/src/java.desktop/share/native/libfontmanager/layout/ContextualSubstSubtables.cpp
index 3707efdfb4f..14906145e54 100644
--- a/jdk/src/java.desktop/share/native/libfontmanager/layout/ContextualSubstSubtables.cpp
+++ b/jdk/src/java.desktop/share/native/libfontmanager/layout/ContextualSubstSubtables.cpp
@@ -243,12 +243,22 @@ le_uint32 ContextualSubstitutionFormat1Subtable::process(const LETableReference
le_uint16 srSetCount = SWAPW(subRuleSetCount);
if (coverageIndex < srSetCount) {
+ LEReferenceToArrayOf subRuleSetTableOffsetArrayRef(base, success,
+ &subRuleSetTableOffsetArray[coverageIndex], 1);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
Offset subRuleSetTableOffset = SWAPW(subRuleSetTableOffsetArray[coverageIndex]);
LEReferenceTo
subRuleSetTable(base, success, (const SubRuleSetTable *) ((char *) this + subRuleSetTableOffset));
le_uint16 subRuleCount = SWAPW(subRuleSetTable->subRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
+ LEReferenceToArrayOf subRuleTableOffsetArrayRef(base, success,
+ subRuleSetTable->subRuleTableOffsetArray, subRuleCount);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
for (le_uint16 subRule = 0; subRule < subRuleCount; subRule += 1) {
Offset subRuleTableOffset =
SWAPW(subRuleSetTable->subRuleTableOffsetArray[subRule]);
@@ -301,34 +311,44 @@ le_uint32 ContextualSubstitutionFormat2Subtable::process(const LETableReference
glyphIterator->getCurrGlyphID(),
success);
- if (setClass < scSetCount && subClassSetTableOffsetArray[setClass] != 0) {
- Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
- LEReferenceTo
- subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
- le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
- le_int32 position = glyphIterator->getCurrStreamPosition();
+ if (setClass < scSetCount) {
+ LEReferenceToArrayOf
+ subClassSetTableOffsetArrayRef(base, success, subClassSetTableOffsetArray, setClass);
+ if (LE_FAILURE(success)) { return 0; }
+ if (subClassSetTableOffsetArray[setClass] != 0) {
- for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
- Offset subClassRuleTableOffset =
- SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
- LEReferenceTo
- subClassRuleTable(subClassSetTable, success, subClassRuleTableOffset);
- le_uint16 matchCount = SWAPW(subClassRuleTable->glyphCount) - 1;
- le_uint16 substCount = SWAPW(subClassRuleTable->substCount);
-
- LEReferenceToArrayOf classArray(base, success, subClassRuleTable->classArray, matchCount+1);
-
- if (LE_FAILURE(success)) { return 0; }
- if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
- LEReferenceToArrayOf
- substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
-
- applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
-
- return matchCount + 1;
+ Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
+ LEReferenceTo
+ subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
+ le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
+ le_int32 position = glyphIterator->getCurrStreamPosition();
+ LEReferenceToArrayOf
+ subClassRuleTableOffsetArrayRef(base, success, subClassSetTable->subClassRuleTableOffsetArray, subClassRuleCount);
+ if (LE_FAILURE(success)) {
+ return 0;
}
+ for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
+ Offset subClassRuleTableOffset =
+ SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
+ LEReferenceTo
+ subClassRuleTable(subClassSetTable, success, subClassRuleTableOffset);
+ le_uint16 matchCount = SWAPW(subClassRuleTable->glyphCount) - 1;
+ le_uint16 substCount = SWAPW(subClassRuleTable->substCount);
- glyphIterator->setCurrStreamPosition(position);
+ LEReferenceToArrayOf classArray(base, success, subClassRuleTable->classArray, matchCount+1);
+
+ if (LE_FAILURE(success)) { return 0; }
+ if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
+ LEReferenceToArrayOf
+ substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
+
+ applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
+
+ return matchCount + 1;
+ }
+
+ glyphIterator->setCurrStreamPosition(position);
+ }
}
}
@@ -442,13 +462,22 @@ le_uint32 ChainingContextualSubstitutionFormat1Subtable::process(const LETableRe
le_uint16 srSetCount = SWAPW(chainSubRuleSetCount);
if (coverageIndex < srSetCount) {
+ LEReferenceToArrayOf
+ chainSubRuleSetTableOffsetArrayRef(base, success, chainSubRuleSetTableOffsetArray, coverageIndex);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
Offset chainSubRuleSetTableOffset = SWAPW(chainSubRuleSetTableOffsetArray[coverageIndex]);
LEReferenceTo
chainSubRuleSetTable(base, success, (const ChainSubRuleSetTable *) ((char *) this + chainSubRuleSetTableOffset));
le_uint16 chainSubRuleCount = SWAPW(chainSubRuleSetTable->chainSubRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
-
+ LEReferenceToArrayOf
+ chainSubRuleTableOffsetArrayRef(base, success, chainSubRuleSetTable->chainSubRuleTableOffsetArray, chainSubRuleCount);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
for (le_uint16 subRule = 0; subRule < chainSubRuleCount; subRule += 1) {
Offset chainSubRuleTableOffset =
SWAPW(chainSubRuleSetTable->chainSubRuleTableOffsetArray[subRule]);
@@ -530,6 +559,11 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
le_int32 setClass = inputClassDefinitionTable->getGlyphClass(inputClassDefinitionTable,
glyphIterator->getCurrGlyphID(),
success);
+ LEReferenceToArrayOf
+ chainSubClassSetTableOffsetArrayRef(base, success, chainSubClassSetTableOffsetArray, setClass);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
if (setClass < scSetCount && chainSubClassSetTableOffsetArray[setClass] != 0) {
Offset chainSubClassSetTableOffset = SWAPW(chainSubClassSetTableOffsetArray[setClass]);
@@ -538,7 +572,11 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
le_uint16 chainSubClassRuleCount = SWAPW(chainSubClassSetTable->chainSubClassRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
-
+ LEReferenceToArrayOf
+ chainSubClassRuleTableOffsetArrayRef(base, success, chainSubClassSetTable->chainSubClassRuleTableOffsetArray, chainSubClassRuleCount);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
for (le_uint16 scRule = 0; scRule < chainSubClassRuleCount; scRule += 1) {
Offset chainSubClassRuleTableOffset =
SWAPW(chainSubClassSetTable->chainSubClassRuleTableOffsetArray[scRule]);
@@ -603,12 +641,14 @@ le_uint32 ChainingContextualSubstitutionFormat3Subtable::process(const LETableRe
}
le_uint16 backtrkGlyphCount = SWAPW(backtrackGlyphCount);
+ LEReferenceToArrayOf backtrackGlyphArrayRef(base, success, backtrackCoverageTableOffsetArray, backtrkGlyphCount);
+ if (LE_FAILURE(success)) {
+ return 0;
+ }
le_uint16 inputGlyphCount = (le_uint16) SWAPW(backtrackCoverageTableOffsetArray[backtrkGlyphCount]);
LEReferenceToArrayOf inputCoverageTableOffsetArray(base, success, &backtrackCoverageTableOffsetArray[backtrkGlyphCount + 1], inputGlyphCount+2); // offset
if (LE_FAILURE(success)) { return 0; }
const le_uint16 lookaheadGlyphCount = (le_uint16) SWAPW(inputCoverageTableOffsetArray[inputGlyphCount]);
-
- if( LE_FAILURE(success)) { return 0; }
LEReferenceToArrayOf lookaheadCoverageTableOffsetArray(base, success, inputCoverageTableOffsetArray.getAlias(inputGlyphCount + 1, success), lookaheadGlyphCount+2);
if( LE_FAILURE(success) ) { return 0; }
From f97c6a8a967258a654d0bcab6287b58865a11dac Mon Sep 17 00:00:00 2001
From: Petr Pchelko
Date: Fri, 23 May 2014 10:56:42 +0400
Subject: [PATCH 25/82] 8041545: Better validation of generated rasters
Reviewed-by: prr, serb, bae, skoivu
---
.../share/classes/sun/awt/image/BytePackedRaster.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/jdk/src/java.desktop/share/classes/sun/awt/image/BytePackedRaster.java b/jdk/src/java.desktop/share/classes/sun/awt/image/BytePackedRaster.java
index bd3835d5184..3e60f193ac2 100644
--- a/jdk/src/java.desktop/share/classes/sun/awt/image/BytePackedRaster.java
+++ b/jdk/src/java.desktop/share/classes/sun/awt/image/BytePackedRaster.java
@@ -1408,10 +1408,10 @@ public class BytePackedRaster extends SunWritableRaster {
}
}
- int lastbit = (dataBitOffset
- + (height-1) * scanlineStride * 8
- + (width-1) * pixelBitStride
- + pixelBitStride - 1);
+ long lastbit = (long) dataBitOffset
+ + (long) (height - 1) * (long) scanlineStride * 8
+ + (long) (width - 1) * (long) pixelBitStride
+ + (long) pixelBitStride - 1;
if (lastbit < 0 || lastbit / 8 >= data.length) {
throw new RasterFormatException("raster dimensions overflow " +
"array bounds");
From 91bc3af39256625034b4ff73cac6c08c5f00e406 Mon Sep 17 00:00:00 2001
From: Sean Mullan
Date: Tue, 27 May 2014 08:56:59 -0400
Subject: [PATCH 26/82] 8038908: Make Signature more robust
Reviewed-by: valeriep, skoivu, asmotrak
---
.../classes/java/security/Signature.java | 42 +++++++++++++++----
1 file changed, 35 insertions(+), 7 deletions(-)
diff --git a/jdk/src/java.base/share/classes/java/security/Signature.java b/jdk/src/java.base/share/classes/java/security/Signature.java
index 60a7e01b6c9..738cf84ef5e 100644
--- a/jdk/src/java.base/share/classes/java/security/Signature.java
+++ b/jdk/src/java.base/share/classes/java/security/Signature.java
@@ -604,9 +604,13 @@ public abstract class Signature extends SignatureSpi {
* @return the number of bytes placed into {@code outbuf}.
*
* @exception SignatureException if this signature object is not
- * initialized properly, if this signature algorithm is unable to
- * process the input data provided, or if {@code len} is less
- * than the actual signature length.
+ * initialized properly, if this signature algorithm is unable to
+ * process the input data provided, or if {@code len} is less
+ * than the actual signature length.
+ * @exception IllegalArgumentException if {@code outbuf} is {@code null},
+ * or {@code offset} or {@code len} is less than 0, or the sum of
+ * {@code offset} and {@code len} is greater than the length of
+ * {@code outbuf}.
*
* @since 1.2
*/
@@ -615,6 +619,9 @@ public abstract class Signature extends SignatureSpi {
if (outbuf == null) {
throw new IllegalArgumentException("No output buffer given");
}
+ if (offset < 0 || len < 0) {
+ throw new IllegalArgumentException("offset or len is less than 0");
+ }
if (outbuf.length - offset < len) {
throw new IllegalArgumentException
("Output buffer too small for specified offset and length");
@@ -683,9 +690,16 @@ public abstract class Signature extends SignatureSpi {
public final boolean verify(byte[] signature, int offset, int length)
throws SignatureException {
if (state == VERIFY) {
- if ((signature == null) || (offset < 0) || (length < 0) ||
- (length > signature.length - offset)) {
- throw new IllegalArgumentException("Bad arguments");
+ if (signature == null) {
+ throw new IllegalArgumentException("signature is null");
+ }
+ if (offset < 0 || length < 0) {
+ throw new IllegalArgumentException
+ ("offset or length is less than 0");
+ }
+ if (signature.length - offset < length) {
+ throw new IllegalArgumentException
+ ("signature too small for specified offset and length");
}
return engineVerify(signature, offset, length);
@@ -733,11 +747,25 @@ public abstract class Signature extends SignatureSpi {
* @param len the number of bytes to use, starting at offset.
*
* @exception SignatureException if this signature object is not
- * initialized properly.
+ * initialized properly.
+ * @exception IllegalArgumentException if {@code data} is {@code null},
+ * or {@code off} or {@code len} is less than 0, or the sum of
+ * {@code off} and {@code len} is greater than the length of
+ * {@code data}.
*/
public final void update(byte[] data, int off, int len)
throws SignatureException {
if (state == SIGN || state == VERIFY) {
+ if (data == null) {
+ throw new IllegalArgumentException("data is null");
+ }
+ if (off < 0 || len < 0) {
+ throw new IllegalArgumentException("off or len is less than 0");
+ }
+ if (data.length - off < len) {
+ throw new IllegalArgumentException
+ ("data too small for specified offset and length");
+ }
engineUpdate(data, off, len);
} else {
throw new SignatureException("object not initialized for "
From be3dc19daeacc4e5fac376c6bceaba47df00de92 Mon Sep 17 00:00:00 2001
From: Michael McMahon
Date: Wed, 28 May 2014 14:51:24 +0100
Subject: [PATCH 27/82] 8039509: Wrap sockets more thoroughly
Reviewed-by: chegar, alanb
---
jdk/make/mapfiles/libnet/mapfile-vers | 2 +
.../net/AbstractPlainDatagramSocketImpl.java | 4 +
.../classes/java/net/DatagramSocket.java | 42 ++++++++-
.../classes/java/net/DatagramSocketImpl.java | 6 ++
.../sun/nio/ch/DatagramChannelImpl.java | 19 ++++
.../libnet/AbstractPlainDatagramSocketImpl.c | 89 +++++++++++++++++++
.../libnet/AbstractPlainDatagramSocketImpl.c | 82 +++++++++++++++++
7 files changed, 241 insertions(+), 3 deletions(-)
create mode 100644 jdk/src/java.base/unix/native/libnet/AbstractPlainDatagramSocketImpl.c
create mode 100644 jdk/src/java.base/windows/native/libnet/AbstractPlainDatagramSocketImpl.c
diff --git a/jdk/make/mapfiles/libnet/mapfile-vers b/jdk/make/mapfiles/libnet/mapfile-vers
index ab621a923a8..168d38d8ee3 100644
--- a/jdk/make/mapfiles/libnet/mapfile-vers
+++ b/jdk/make/mapfiles/libnet/mapfile-vers
@@ -28,6 +28,8 @@
SUNWprivate_1.1 {
global:
JNI_OnLoad;
+ Java_java_net_AbstractPlainDatagramSocketImpl_init;
+ Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable;
Java_java_net_PlainSocketImpl_socketListen;
Java_java_net_PlainDatagramSocketImpl_getTTL;
Java_java_net_PlainDatagramSocketImpl_init;
diff --git a/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java b/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java
index a557299798b..0ffe37f8d9f 100644
--- a/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java
+++ b/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java
@@ -68,6 +68,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
return null;
}
});
+ init();
}
/**
@@ -362,4 +363,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
protected boolean nativeConnectDisabled() {
return connectDisabled;
}
+
+ native int dataAvailable();
+ private static native void init();
}
diff --git a/jdk/src/java.base/share/classes/java/net/DatagramSocket.java b/jdk/src/java.base/share/classes/java/net/DatagramSocket.java
index c9cf26f0b1f..c047b3cf6a4 100644
--- a/jdk/src/java.base/share/classes/java/net/DatagramSocket.java
+++ b/jdk/src/java.base/share/classes/java/net/DatagramSocket.java
@@ -85,6 +85,17 @@ class DatagramSocket implements java.io.Closeable {
*/
boolean oldImpl = false;
+ /**
+ * Set when a socket is ST_CONNECTED until we are certain
+ * that any packets which might have been received prior
+ * to calling connect() but not read by the application
+ * have been read. During this time we check the source
+ * address of all packets received to be sure they are from
+ * the connected destination. Other packets are read but
+ * silently dropped.
+ */
+ private boolean explicitFilter = false;
+ private int bytesLeftToFilter;
/*
* Connection state:
* ST_NOT_CONNECTED = socket not connected
@@ -144,6 +155,15 @@ class DatagramSocket implements java.io.Closeable {
// socket is now connected by the impl
connectState = ST_CONNECTED;
+ // Do we need to filter some packets?
+ int avail = getImpl().dataAvailable();
+ if (avail == -1) {
+ throw new SocketException();
+ }
+ explicitFilter = avail > 0;
+ if (explicitFilter) {
+ bytesLeftToFilter = getReceiveBufferSize();
+ }
} catch (SocketException se) {
// connection will be emulated by DatagramSocket
@@ -492,6 +512,7 @@ class DatagramSocket implements java.io.Closeable {
connectedAddress = null;
connectedPort = -1;
connectState = ST_NOT_CONNECTED;
+ explicitFilter = false;
}
}
@@ -750,10 +771,12 @@ class DatagramSocket implements java.io.Closeable {
} // end of while
}
}
- if (connectState == ST_CONNECTED_NO_IMPL) {
+ if ((connectState == ST_CONNECTED_NO_IMPL) || explicitFilter) {
// We have to do the filtering the old fashioned way since
// the native impl doesn't support connect or the connect
- // via the impl failed.
+ // via the impl failed, or .. "explicitFilter" may be set when
+ // a socket is connected via the impl, for a period of time
+ // when packets from other sources might be queued on socket.
boolean stop = false;
while (!stop) {
InetAddress peekAddress = null;
@@ -772,8 +795,12 @@ class DatagramSocket implements java.io.Closeable {
if ((!connectedAddress.equals(peekAddress)) ||
(connectedPort != peekPort)) {
// throw the packet away and silently continue
- DatagramPacket tmp = new DatagramPacket(new byte[1], 1);
+ DatagramPacket tmp = new DatagramPacket(
+ new byte[1024], 1024);
getImpl().receive(tmp);
+ if (explicitFilter) {
+ bytesLeftToFilter -= tmp.getLength();
+ }
} else {
stop = true;
}
@@ -782,6 +809,15 @@ class DatagramSocket implements java.io.Closeable {
// If the security check succeeds, or the datagram is
// connected then receive the packet
getImpl().receive(p);
+ if (explicitFilter) {
+ bytesLeftToFilter -= p.getLength();
+ if (bytesLeftToFilter <= 0) {
+ explicitFilter = false;
+ } else {
+ // break out of filter, if there is no more data queued
+ explicitFilter = getImpl().dataAvailable() > 0;
+ }
+ }
}
}
diff --git a/jdk/src/java.base/share/classes/java/net/DatagramSocketImpl.java b/jdk/src/java.base/share/classes/java/net/DatagramSocketImpl.java
index 50d5369f66d..2abaaf9a237 100644
--- a/jdk/src/java.base/share/classes/java/net/DatagramSocketImpl.java
+++ b/jdk/src/java.base/share/classes/java/net/DatagramSocketImpl.java
@@ -63,6 +63,12 @@ public abstract class DatagramSocketImpl implements SocketOptions {
return socket;
}
+ int dataAvailable() {
+ // default impl returns zero, which disables the calling
+ // functionality
+ return 0;
+ }
+
/**
* Creates a datagram socket.
* @exception SocketException if there is an error in the
diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java
index a34286bddb4..b9fd16eae29 100644
--- a/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java
+++ b/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java
@@ -740,6 +740,25 @@ class DatagramChannelImpl
// set or refresh local address
localAddress = Net.localAddress(fd);
+
+ // flush any packets already received.
+ boolean blocking = false;
+ synchronized (blockingLock()) {
+ try {
+ blocking = isBlocking();
+ ByteBuffer tmpBuf = ByteBuffer.allocate(100);
+ if (blocking) {
+ configureBlocking(false);
+ }
+ do {
+ tmpBuf.clear();
+ } while (read(tmpBuf) > 0);
+ } finally {
+ if (blocking) {
+ configureBlocking(true);
+ }
+ }
+ }
}
}
}
diff --git a/jdk/src/java.base/unix/native/libnet/AbstractPlainDatagramSocketImpl.c b/jdk/src/java.base/unix/native/libnet/AbstractPlainDatagramSocketImpl.c
new file mode 100644
index 00000000000..075fffc5176
--- /dev/null
+++ b/jdk/src/java.base/unix/native/libnet/AbstractPlainDatagramSocketImpl.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+#include
+#include
+
+#ifdef __solaris__
+#include
+#include
+
+#ifndef BSD_COMP
+#define BSD_COMP
+#endif
+
+#endif
+
+#include
+
+#include "jvm.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#include "java_net_AbstractPlainDatagramSocketImpl.h"
+
+static jfieldID IO_fd_fdID;
+
+static jfieldID apdsi_fdID;
+
+
+/*
+ * Class: java_net_AbstractPlainDatagramSocketImpl
+ * Method: init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
+
+ apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
+ "Ljava/io/FileDescriptor;");
+ CHECK_NULL(apdsi_fdID);
+
+ IO_fd_fdID = NET_GetFileDescriptorID(env);
+}
+
+/*
+ * Class: java_net_AbstractPlainDatagramSocketImpl
+ * Method: dataAvailable
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
+(JNIEnv *env, jobject this) {
+ int fd, retval;
+
+ jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
+
+ if (IS_NULL(fdObj)) {
+ JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+ "Socket closed");
+ return -1;
+ }
+ fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
+
+ if (ioctl(fd, FIONREAD, &retval) < 0) {
+ return -1;
+ }
+ return retval;
+}
diff --git a/jdk/src/java.base/windows/native/libnet/AbstractPlainDatagramSocketImpl.c b/jdk/src/java.base/windows/native/libnet/AbstractPlainDatagramSocketImpl.c
new file mode 100644
index 00000000000..7244e664c9e
--- /dev/null
+++ b/jdk/src/java.base/windows/native/libnet/AbstractPlainDatagramSocketImpl.c
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+#include
+#include
+
+#include "jvm.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#include "java_net_AbstractPlainDatagramSocketImpl.h"
+
+static jfieldID IO_fd_fdID;
+
+static jfieldID apdsi_fdID;
+
+
+/*
+ * Class: java_net_AbstractPlainDatagramSocketImpl
+ * Method: init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
+
+ apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
+ "Ljava/io/FileDescriptor;");
+ CHECK_NULL(apdsi_fdID);
+
+ IO_fd_fdID = NET_GetFileDescriptorID(env);
+ CHECK_NULL(IO_fd_fdID);
+
+ JNU_CHECK_EXCEPTION(env);
+}
+
+/*
+ * Class: java_net_AbstractPlainDatagramSocketImpl
+ * Method: dataAvailable
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
+(JNIEnv *env, jobject this) {
+ SOCKET fd;
+ int retval;
+
+ jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
+
+ if (IS_NULL(fdObj)) {
+ JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+ "Socket closed");
+ return -1;
+ }
+ fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID);
+
+ if (ioctlsocket(fd, FIONREAD, &retval) < 0) {
+ return -1;
+ }
+ return retval;
+}
+
From 7d730f7819cf1a1472f1b85921ff88bc9f85495e Mon Sep 17 00:00:00 2001
From: Alexander Zvegintsev
Date: Fri, 30 May 2014 16:09:49 +0400
Subject: [PATCH 28/82] 8042609: Limit splashiness of splash images
Reviewed-by: mschoene, serb
---
.../native/libsplashscreen/splashscreen_sys.c | 13 +++++++++----
1 file changed, 9 insertions(+), 4 deletions(-)
diff --git a/jdk/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c b/jdk/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c
index 6bbfd517db8..3c1fe7f5091 100644
--- a/jdk/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c
+++ b/jdk/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -213,6 +213,14 @@ SplashPaint(Splash * splash, HDC hdc)
void
SplashRedrawWindow(Splash * splash)
{
+ if (!SplashIsStillLooping(splash)) {
+ KillTimer(splash->hWnd, 0);
+ }
+
+ if (splash->currentFrame < 0) {
+ return;
+ }
+
SplashUpdateScreenData(splash);
if (splash->isLayered) {
BLENDFUNCTION bf;
@@ -303,9 +311,6 @@ SplashRedrawWindow(Splash * splash)
time = 0;
SetTimer(splash->hWnd, 0, time, NULL);
}
- else {
- KillTimer(splash->hWnd, 0);
- }
}
void SplashReconfigureNow(Splash * splash) {
From 7bd17413f23754f03c5706ab0e261c4bd5e76764 Mon Sep 17 00:00:00 2001
From: Coleen Phillimore
Date: Tue, 14 Oct 2014 13:10:50 -0700
Subject: [PATCH 29/82] 8015256: Better class accessibility
Improve protection domain check in forName()
Reviewed-by: mchung, acorn, jdn
---
hotspot/make/aix/makefiles/mapfile-vers-debug | 1 +
.../make/aix/makefiles/mapfile-vers-product | 1 +
.../bsd/makefiles/mapfile-vers-darwin-debug | 1 +
.../bsd/makefiles/mapfile-vers-darwin-product | 1 +
hotspot/make/bsd/makefiles/mapfile-vers-debug | 1 +
.../make/bsd/makefiles/mapfile-vers-product | 1 +
.../make/linux/makefiles/mapfile-vers-debug | 1 +
.../make/linux/makefiles/mapfile-vers-product | 1 +
hotspot/make/solaris/makefiles/mapfile-vers | 1 +
hotspot/src/share/vm/prims/jvm.cpp | 46 ++++++++++++++++++-
hotspot/src/share/vm/prims/jvm.h | 13 ++++++
11 files changed, 66 insertions(+), 2 deletions(-)
diff --git a/hotspot/make/aix/makefiles/mapfile-vers-debug b/hotspot/make/aix/makefiles/mapfile-vers-debug
index 49beedda9ed..6557af2e313 100644
--- a/hotspot/make/aix/makefiles/mapfile-vers-debug
+++ b/hotspot/make/aix/makefiles/mapfile-vers-debug
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/aix/makefiles/mapfile-vers-product b/hotspot/make/aix/makefiles/mapfile-vers-product
index 8adbf613849..f1b93ad37b3 100644
--- a/hotspot/make/aix/makefiles/mapfile-vers-product
+++ b/hotspot/make/aix/makefiles/mapfile-vers-product
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug
index adf6616885a..60ec58b0229 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug
@@ -82,6 +82,7 @@
_JVM_EnableCompiler
_JVM_Exit
_JVM_FillInStackTrace
+ _JVM_FindClassFromCaller
_JVM_FindClassFromClass
_JVM_FindClassFromClassLoader
_JVM_FindClassFromBootLoader
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product
index adf6616885a..60ec58b0229 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product
@@ -82,6 +82,7 @@
_JVM_EnableCompiler
_JVM_Exit
_JVM_FillInStackTrace
+ _JVM_FindClassFromCaller
_JVM_FindClassFromClass
_JVM_FindClassFromClassLoader
_JVM_FindClassFromBootLoader
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-debug b/hotspot/make/bsd/makefiles/mapfile-vers-debug
index 6c79e8b9b75..e60cc7d6fcc 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-debug
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-product b/hotspot/make/bsd/makefiles/mapfile-vers-product
index 6c79e8b9b75..e60cc7d6fcc 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-product
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-product
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/linux/makefiles/mapfile-vers-debug b/hotspot/make/linux/makefiles/mapfile-vers-debug
index 6c79e8b9b75..e60cc7d6fcc 100644
--- a/hotspot/make/linux/makefiles/mapfile-vers-debug
+++ b/hotspot/make/linux/makefiles/mapfile-vers-debug
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/linux/makefiles/mapfile-vers-product b/hotspot/make/linux/makefiles/mapfile-vers-product
index 6c79e8b9b75..e60cc7d6fcc 100644
--- a/hotspot/make/linux/makefiles/mapfile-vers-product
+++ b/hotspot/make/linux/makefiles/mapfile-vers-product
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/solaris/makefiles/mapfile-vers b/hotspot/make/solaris/makefiles/mapfile-vers
index 51cb3f9657b..35078f1241a 100644
--- a/hotspot/make/solaris/makefiles/mapfile-vers
+++ b/hotspot/make/solaris/makefiles/mapfile-vers
@@ -84,6 +84,7 @@ SUNWprivate_1.1 {
JVM_EnableCompiler;
JVM_Exit;
JVM_FillInStackTrace;
+ JVM_FindClassFromCaller;
JVM_FindClassFromClass;
JVM_FindClassFromClassLoader;
JVM_FindClassFromBootLoader;
diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp
index fa02d67b4a7..0d6b682404e 100644
--- a/hotspot/src/share/vm/prims/jvm.cpp
+++ b/hotspot/src/share/vm/prims/jvm.cpp
@@ -805,6 +805,7 @@ JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
return (jclass) JNIHandles::make_local(env, k->java_mirror());
JVM_END
+// Not used; JVM_FindClassFromCaller replaces this.
JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
jboolean init, jobject loader,
jboolean throwError))
@@ -831,6 +832,42 @@ JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
return result;
JVM_END
+// Find a class with this name in this loader, using the caller's protection domain.
+JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
+ jboolean init, jobject loader,
+ jclass caller))
+ JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
+ // Java libraries should ensure that name is never null...
+ if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
+ // It's impossible to create this class; the name cannot fit
+ // into the constant pool.
+ THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
+ }
+
+ TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
+
+ oop loader_oop = JNIHandles::resolve(loader);
+ oop from_class = JNIHandles::resolve(caller);
+ oop protection_domain = NULL;
+ // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
+ // NPE. Put it in another way, the bootstrap class loader has all permission and
+ // thus no checkPackageAccess equivalence in the VM class loader.
+ // The caller is also passed as NULL by the java code if there is no security
+ // manager to avoid the performance cost of getting the calling class.
+ if (from_class != NULL && loader_oop != NULL) {
+ protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
+ }
+
+ Handle h_loader(THREAD, loader_oop);
+ Handle h_prot(THREAD, protection_domain);
+ jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
+ h_prot, false, THREAD);
+
+ if (TraceClassResolution && result != NULL) {
+ trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
+ }
+ return result;
+JVM_END
JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
jboolean init, jclass from))
@@ -3921,10 +3958,15 @@ JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
// Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
-jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) {
+jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
+ Handle loader, Handle protection_domain,
+ jboolean throwError, TRAPS) {
// Security Note:
// The Java level wrapper will perform the necessary security check allowing
- // us to pass the NULL as the initiating class loader.
+ // us to pass the NULL as the initiating class loader. The VM is responsible for
+ // the checkPackageAccess relative to the initiating class loader via the
+ // protection_domain. The protection_domain is passed as NULL by the java code
+ // if there is no security manager in 3-arg Class.forName().
Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
KlassHandle klass_handle(THREAD, klass);
diff --git a/hotspot/src/share/vm/prims/jvm.h b/hotspot/src/share/vm/prims/jvm.h
index c1aa8080cd3..52fd28fc4e1 100644
--- a/hotspot/src/share/vm/prims/jvm.h
+++ b/hotspot/src/share/vm/prims/jvm.h
@@ -419,6 +419,19 @@ JVM_FindClassFromClassLoader(JNIEnv *env, const char *name, jboolean init,
JNIEXPORT jclass JNICALL
JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
+/*
+ * Find a class from a given class loader. Throws ClassNotFoundException.
+ * name: name of class
+ * init: whether initialization is done
+ * loader: class loader to look up the class. This may not be the same as the caller's
+ * class loader.
+ * caller: initiating class. The initiating class may be null when a security
+ * manager is not installed.
+ */
+JNIEXPORT jclass JNICALL
+JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
+ jobject loader, jclass caller);
+
/*
* Find a class from a given class.
*/
From f203dcbfbf4153b12262b6834969a2ff516742cd Mon Sep 17 00:00:00 2001
From: Harold Seigel
Date: Tue, 22 Jul 2014 16:16:51 +0400
Subject: [PATCH 30/82] 8036533: Method for correct defaults 8036156: Limit
default method hierarchy
Fix protected access checks
Reviewed-by: coleenp, lfoltan, acorn, ahgross
---
.../src/share/vm/classfile/stackMapFrame.cpp | 10 +++++-----
.../src/share/vm/classfile/stackMapFrame.hpp | 6 +++---
.../share/vm/classfile/verificationType.cpp | 16 ++++++++++------
.../share/vm/classfile/verificationType.hpp | 10 +++++++---
hotspot/src/share/vm/classfile/verifier.cpp | 18 +++++++++---------
hotspot/src/share/vm/runtime/reflection.cpp | 3 ++-
6 files changed, 36 insertions(+), 27 deletions(-)
diff --git a/hotspot/src/share/vm/classfile/stackMapFrame.cpp b/hotspot/src/share/vm/classfile/stackMapFrame.cpp
index 9cb1d307a52..1332a081c76 100644
--- a/hotspot/src/share/vm/classfile/stackMapFrame.cpp
+++ b/hotspot/src/share/vm/classfile/stackMapFrame.cpp
@@ -148,7 +148,7 @@ int StackMapFrame::is_assignable_to(
VerificationType* from, VerificationType* to, int32_t len, TRAPS) const {
int32_t i = 0;
for (i = 0; i < len; i++) {
- if (!to[i].is_assignable_from(from[i], verifier(), THREAD)) {
+ if (!to[i].is_assignable_from(from[i], verifier(), false, THREAD)) {
break;
}
}
@@ -245,7 +245,7 @@ VerificationType StackMapFrame::pop_stack_ex(VerificationType type, TRAPS) {
}
VerificationType top = _stack[--_stack_size];
bool subtype = type.is_assignable_from(
- top, verifier(), CHECK_(VerificationType::bogus_type()));
+ top, verifier(), false, CHECK_(VerificationType::bogus_type()));
if (!subtype) {
verifier()->verify_error(
ErrorContext::bad_type(_offset, stack_top_ctx(),
@@ -265,7 +265,7 @@ VerificationType StackMapFrame::get_local(
return VerificationType::bogus_type();
}
bool subtype = type.is_assignable_from(_locals[index],
- verifier(), CHECK_(VerificationType::bogus_type()));
+ verifier(), false, CHECK_(VerificationType::bogus_type()));
if (!subtype) {
verifier()->verify_error(
ErrorContext::bad_type(_offset,
@@ -288,14 +288,14 @@ void StackMapFrame::get_local_2(
"get long/double overflows locals");
return;
}
- bool subtype = type1.is_assignable_from(_locals[index], verifier(), CHECK);
+ bool subtype = type1.is_assignable_from(_locals[index], verifier(), false, CHECK);
if (!subtype) {
verifier()->verify_error(
ErrorContext::bad_type(_offset,
TypeOrigin::local(index, this), TypeOrigin::implicit(type1)),
"Bad local variable type");
} else {
- subtype = type2.is_assignable_from(_locals[index + 1], verifier(), CHECK);
+ subtype = type2.is_assignable_from(_locals[index + 1], verifier(), false, CHECK);
if (!subtype) {
/* Unreachable? All local store routines convert a split long or double
* into a TOP during the store. So we should never end up seeing an
diff --git a/hotspot/src/share/vm/classfile/stackMapFrame.hpp b/hotspot/src/share/vm/classfile/stackMapFrame.hpp
index 53582c1673c..24cbae330bb 100644
--- a/hotspot/src/share/vm/classfile/stackMapFrame.hpp
+++ b/hotspot/src/share/vm/classfile/stackMapFrame.hpp
@@ -234,7 +234,7 @@ class StackMapFrame : public ResourceObj {
if (_stack_size != 0) {
VerificationType top = _stack[_stack_size - 1];
bool subtype = type.is_assignable_from(
- top, verifier(), CHECK_(VerificationType::bogus_type()));
+ top, verifier(), false, CHECK_(VerificationType::bogus_type()));
if (subtype) {
--_stack_size;
return top;
@@ -249,9 +249,9 @@ class StackMapFrame : public ResourceObj {
assert(type2.is_long() || type2.is_double(), "must be long/double_2");
if (_stack_size >= 2) {
VerificationType top1 = _stack[_stack_size - 1];
- bool subtype1 = type1.is_assignable_from(top1, verifier(), CHECK);
+ bool subtype1 = type1.is_assignable_from(top1, verifier(), false, CHECK);
VerificationType top2 = _stack[_stack_size - 2];
- bool subtype2 = type2.is_assignable_from(top2, verifier(), CHECK);
+ bool subtype2 = type2.is_assignable_from(top2, verifier(), false, CHECK);
if (subtype1 && subtype2) {
_stack_size -= 2;
return;
diff --git a/hotspot/src/share/vm/classfile/verificationType.cpp b/hotspot/src/share/vm/classfile/verificationType.cpp
index 561618bdebe..120d9a37d62 100644
--- a/hotspot/src/share/vm/classfile/verificationType.cpp
+++ b/hotspot/src/share/vm/classfile/verificationType.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,8 @@ VerificationType VerificationType::from_tag(u1 tag) {
}
bool VerificationType::is_reference_assignable_from(
- const VerificationType& from, ClassVerifier* context, TRAPS) const {
+ const VerificationType& from, ClassVerifier* context,
+ bool from_field_is_protected, TRAPS) const {
instanceKlassHandle klass = context->current_class();
if (from.is_null()) {
// null is assignable to any reference
@@ -62,9 +63,11 @@ bool VerificationType::is_reference_assignable_from(
Handle(THREAD, klass->protection_domain()), true, CHECK_false);
KlassHandle this_class(THREAD, obj);
- if (this_class->is_interface()) {
- // We treat interfaces as java.lang.Object, including
- // java.lang.Cloneable and java.io.Serializable
+ if (this_class->is_interface() && (!from_field_is_protected ||
+ from.name() != vmSymbols::java_lang_Object())) {
+ // If we are not trying to access a protected field or method in
+ // java.lang.Object then we treat interfaces as java.lang.Object,
+ // including java.lang.Cloneable and java.io.Serializable.
return true;
} else if (from.is_object()) {
Klass* from_class = SystemDictionary::resolve_or_fail(
@@ -76,7 +79,8 @@ bool VerificationType::is_reference_assignable_from(
VerificationType comp_this = get_component(context, CHECK_false);
VerificationType comp_from = from.get_component(context, CHECK_false);
if (!comp_this.is_bogus() && !comp_from.is_bogus()) {
- return comp_this.is_assignable_from(comp_from, context, CHECK_false);
+ return comp_this.is_assignable_from(comp_from, context,
+ from_field_is_protected, CHECK_false);
}
}
return false;
diff --git a/hotspot/src/share/vm/classfile/verificationType.hpp b/hotspot/src/share/vm/classfile/verificationType.hpp
index 16266477ec1..43bd79e21b1 100644
--- a/hotspot/src/share/vm/classfile/verificationType.hpp
+++ b/hotspot/src/share/vm/classfile/verificationType.hpp
@@ -265,7 +265,8 @@ class VerificationType VALUE_OBJ_CLASS_SPEC {
// is assignable to another. Returns true if one can assign 'from' to
// this.
bool is_assignable_from(
- const VerificationType& from, ClassVerifier* context, TRAPS) const {
+ const VerificationType& from, ClassVerifier* context,
+ bool from_field_is_protected, TRAPS) const {
if (equals(from) || is_bogus()) {
return true;
} else {
@@ -286,7 +287,9 @@ class VerificationType VALUE_OBJ_CLASS_SPEC {
return from.is_integer();
default:
if (is_reference() && from.is_reference()) {
- return is_reference_assignable_from(from, context, CHECK_false);
+ return is_reference_assignable_from(from, context,
+ from_field_is_protected,
+ CHECK_false);
} else {
return false;
}
@@ -308,7 +311,8 @@ class VerificationType VALUE_OBJ_CLASS_SPEC {
private:
bool is_reference_assignable_from(
- const VerificationType&, ClassVerifier*, TRAPS) const;
+ const VerificationType&, ClassVerifier*, bool from_field_is_protected,
+ TRAPS) const;
};
#endif // SHARE_VM_CLASSFILE_VERIFICATIONTYPE_HPP
diff --git a/hotspot/src/share/vm/classfile/verifier.cpp b/hotspot/src/share/vm/classfile/verifier.cpp
index 877eebd0e0b..92dfb14f9dc 100644
--- a/hotspot/src/share/vm/classfile/verifier.cpp
+++ b/hotspot/src/share/vm/classfile/verifier.cpp
@@ -1721,7 +1721,7 @@ void ClassVerifier::verify_exception_handler_table(u4 code_length, char* code_da
VerificationType throwable =
VerificationType::reference_type(vmSymbols::java_lang_Throwable());
bool is_subclass = throwable.is_assignable_from(
- catch_type, this, CHECK_VERIFY(this));
+ catch_type, this, false, CHECK_VERIFY(this));
if (!is_subclass) {
// 4286534: should throw VerifyError according to recent spec change
verify_error(ErrorContext::bad_type(handler_pc,
@@ -2174,7 +2174,7 @@ void ClassVerifier::verify_field_instructions(RawBytecodeStream* bcs,
stack_object_type = current_type();
}
is_assignable = target_class_type.is_assignable_from(
- stack_object_type, this, CHECK_VERIFY(this));
+ stack_object_type, this, false, CHECK_VERIFY(this));
if (!is_assignable) {
verify_error(ErrorContext::bad_type(bci,
current_frame->stack_top_ctx(),
@@ -2201,7 +2201,7 @@ void ClassVerifier::verify_field_instructions(RawBytecodeStream* bcs,
// It's protected access, check if stack object is assignable to
// current class.
is_assignable = current_type().is_assignable_from(
- stack_object_type, this, CHECK_VERIFY(this));
+ stack_object_type, this, true, CHECK_VERIFY(this));
if (!is_assignable) {
verify_error(ErrorContext::bad_type(bci,
current_frame->stack_top_ctx(),
@@ -2475,7 +2475,7 @@ void ClassVerifier::verify_invoke_init(
instanceKlassHandle mh(THREAD, m->method_holder());
if (m->is_protected() && !mh->is_same_class_package(_klass())) {
bool assignable = current_type().is_assignable_from(
- objectref_type, this, CHECK_VERIFY(this));
+ objectref_type, this, true, CHECK_VERIFY(this));
if (!assignable) {
verify_error(ErrorContext::bad_type(bci,
TypeOrigin::cp(new_class_index, objectref_type),
@@ -2646,11 +2646,11 @@ void ClassVerifier::verify_invoke_instructions(
bool have_imr_indirect = cp->tag_at(index).value() == JVM_CONSTANT_InterfaceMethodref;
if (!current_class()->is_anonymous()) {
subtype = ref_class_type.is_assignable_from(
- current_type(), this, CHECK_VERIFY(this));
+ current_type(), this, false, CHECK_VERIFY(this));
} else {
VerificationType host_klass_type =
VerificationType::reference_type(current_class()->host_klass()->name());
- subtype = ref_class_type.is_assignable_from(host_klass_type, this, CHECK_VERIFY(this));
+ subtype = ref_class_type.is_assignable_from(host_klass_type, this, false, CHECK_VERIFY(this));
// If invokespecial of IMR, need to recheck for same or
// direct interface relative to the host class
@@ -2694,7 +2694,7 @@ void ClassVerifier::verify_invoke_instructions(
VerificationType top = current_frame->pop_stack(CHECK_VERIFY(this));
VerificationType hosttype =
VerificationType::reference_type(current_class()->host_klass()->name());
- bool subtype = hosttype.is_assignable_from(top, this, CHECK_VERIFY(this));
+ bool subtype = hosttype.is_assignable_from(top, this, false, CHECK_VERIFY(this));
if (!subtype) {
verify_error( ErrorContext::bad_type(current_frame->offset(),
current_frame->stack_top_ctx(),
@@ -2719,7 +2719,7 @@ void ClassVerifier::verify_invoke_instructions(
// It's protected access, check if stack object is
// assignable to current class.
bool is_assignable = current_type().is_assignable_from(
- stack_object_type, this, CHECK_VERIFY(this));
+ stack_object_type, this, true, CHECK_VERIFY(this));
if (!is_assignable) {
if (ref_class_type.name() == vmSymbols::java_lang_Object()
&& stack_object_type.is_array()
@@ -2902,7 +2902,7 @@ void ClassVerifier::verify_return_value(
"Method expects a return value");
return;
}
- bool match = return_type.is_assignable_from(type, this, CHECK_VERIFY(this));
+ bool match = return_type.is_assignable_from(type, this, false, CHECK_VERIFY(this));
if (!match) {
verify_error(ErrorContext::bad_type(bci,
current_frame->stack_top_ctx(), TypeOrigin::signature(return_type)),
diff --git a/hotspot/src/share/vm/runtime/reflection.cpp b/hotspot/src/share/vm/runtime/reflection.cpp
index 42c9ed3e8ef..c6cb79ce7a4 100644
--- a/hotspot/src/share/vm/runtime/reflection.cpp
+++ b/hotspot/src/share/vm/runtime/reflection.cpp
@@ -507,7 +507,8 @@ bool Reflection::verify_field_access(Klass* current_class,
if (access.is_protected()) {
if (!protected_restriction) {
// See if current_class (or outermost host class) is a subclass of field_class
- if (host_class->is_subclass_of(field_class)) {
+ // An interface may not access protected members of j.l.Object
+ if (!host_class->is_interface() && host_class->is_subclass_of(field_class)) {
if (access.is_static() || // static fields are ok, see 6622385
current_class == resolved_class ||
field_class == resolved_class ||
From 9f06aa633c74aacdb826bea0b8f804c3cbae11e1 Mon Sep 17 00:00:00 2001
From: Harold Seigel
Date: Fri, 30 May 2014 13:23:27 -0400
Subject: [PATCH 31/82] 8041717: Issue with class file parser
Add better checking for bad values.
Reviewed-by: coleenp, lfoltan, mschoene
---
hotspot/src/share/vm/classfile/classFileParser.cpp | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp
index 8b3ef37d590..0f2f8d590c4 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp
@@ -2859,6 +2859,11 @@ void ClassFileParser::parse_classfile_bootstrap_methods_attribute(u4 attribute_b
"bootstrap_method_index %u has bad constant type in class file %s",
bootstrap_method_index,
CHECK);
+
+ guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
+ "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
+ CHECK);
+
operands->at_put(operand_fill_index++, bootstrap_method_index);
operands->at_put(operand_fill_index++, argument_count);
@@ -2875,8 +2880,6 @@ void ClassFileParser::parse_classfile_bootstrap_methods_attribute(u4 attribute_b
}
}
- assert(ConstantPool::operand_array_length(operands) == attribute_array_length, "correct decode");
-
u1* current_end = cfs->current();
guarantee_property(current_end == current_start + attribute_byte_length,
"Bad length on BootstrapMethods in class file %s",
From 52d7b541a6413c6c88b8b95461d974edd1f72d00 Mon Sep 17 00:00:00 2001
From: Daniel Fuchs
Date: Thu, 5 Jun 2014 18:46:37 +0200
Subject: [PATCH 32/82] 8042797: Avoid strawberries in LogRecord
Reviewed-by: mchung, skoivu, igerasim
---
.../share/classes/java/util/logging/LogRecord.java | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java b/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java
index bfc05201ebc..1ea4d72008d 100644
--- a/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java
+++ b/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java
@@ -509,7 +509,13 @@ public class LogRecord implements java.io.Serializable {
// If necessary, try to regenerate the resource bundle.
if (resourceBundleName != null) {
try {
- resourceBundle = ResourceBundle.getBundle(resourceBundleName);
+ // use system class loader to ensure the ResourceBundle
+ // instance is a different instance than null loader uses
+ final ResourceBundle bundle =
+ ResourceBundle.getBundle(resourceBundleName,
+ Locale.getDefault(),
+ ClassLoader.getSystemClassLoader());
+ resourceBundle = bundle;
} catch (MissingResourceException ex) {
// This is not a good place to throw an exception,
// so we simply leave the resourceBundle null.
From 38479150516d0f851b1f4a1bea410de11ca2614b Mon Sep 17 00:00:00 2001
From: Sean Mullan
Date: Wed, 11 Jun 2014 16:25:59 -0400
Subject: [PATCH 33/82] 8038913: Bolster XML support
Reviewed-by: xuelei, skoivu
---
.../apache/xml/internal/security/Init.java | 72 +++++++++++--------
.../security/algorithms/JCEMapper.java | 7 ++
.../algorithms/SignatureAlgorithm.java | 13 +++-
.../internal/security/c14n/Canonicalizer.java | 9 ++-
.../keys/keyresolver/KeyResolver.java | 13 ++++
.../security/transforms/Transform.java | 7 ++
.../internal/security/utils/ElementProxy.java | 3 +
.../internal/security/utils/JavaUtils.java | 22 ++++++
.../xml/internal/security/utils/XMLUtils.java | 12 ++++
.../utils/resolver/ResourceResolver.java | 13 ++++
10 files changed, 136 insertions(+), 35 deletions(-)
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java
index 6176370878a..5f3b9f53c8f 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java
@@ -25,6 +25,8 @@ package com.sun.org.apache.xml.internal.security;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
@@ -35,6 +37,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@@ -118,43 +121,50 @@ public class Init {
log.log(java.util.logging.Level.FINE, "Registering default algorithms");
}
try {
- //
- // Bind the default prefixes
- //
- ElementProxy.registerDefaultPrefixes();
+ AccessController.doPrivileged(new PrivilegedExceptionAction(){
+ @Override public Void run() throws XMLSecurityException {
+ //
+ // Bind the default prefixes
+ //
+ ElementProxy.registerDefaultPrefixes();
- //
- // Set the default Transforms
- //
- Transform.registerDefaultAlgorithms();
+ //
+ // Set the default Transforms
+ //
+ Transform.registerDefaultAlgorithms();
- //
- // Set the default signature algorithms
- //
- SignatureAlgorithm.registerDefaultAlgorithms();
+ //
+ // Set the default signature algorithms
+ //
+ SignatureAlgorithm.registerDefaultAlgorithms();
- //
- // Set the default JCE algorithms
- //
- JCEMapper.registerDefaultAlgorithms();
+ //
+ // Set the default JCE algorithms
+ //
+ JCEMapper.registerDefaultAlgorithms();
- //
- // Set the default c14n algorithms
- //
- Canonicalizer.registerDefaultAlgorithms();
+ //
+ // Set the default c14n algorithms
+ //
+ Canonicalizer.registerDefaultAlgorithms();
- //
- // Register the default resolvers
- //
- ResourceResolver.registerDefaultResolvers();
+ //
+ // Register the default resolvers
+ //
+ ResourceResolver.registerDefaultResolvers();
- //
- // Register the default key resolvers
- //
- KeyResolver.registerDefaultResolvers();
- } catch (Exception ex) {
- log.log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
- ex.printStackTrace();
+ //
+ // Register the default key resolvers
+ //
+ KeyResolver.registerDefaultResolvers();
+
+ return null;
+ }
+ });
+ } catch (PrivilegedActionException ex) {
+ XMLSecurityException xse = (XMLSecurityException)ex.getException();
+ log.log(java.util.logging.Level.SEVERE, xse.getMessage(), xse);
+ xse.printStackTrace();
}
}
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java
index 6001e510532..3656f248848 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java
@@ -27,6 +27,7 @@ import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Element;
@@ -49,8 +50,11 @@ public class JCEMapper {
*
* @param id
* @param algorithm
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the JCE algorithm
*/
public static void register(String id, Algorithm algorithm) {
+ JavaUtils.checkRegisterPermission();
algorithmsMap.put(id, algorithm);
}
@@ -296,8 +300,11 @@ public class JCEMapper {
/**
* Sets the default Provider for obtaining the security algorithms
* @param provider the default providerId.
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to set the JCE provider
*/
public static void setProviderId(String provider) {
+ JavaUtils.checkRegisterPermission();
providerName = provider;
}
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java
index 6e94f4b16d9..253e35ca864 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java
@@ -37,6 +37,7 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
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.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -314,18 +315,21 @@ public class SignatureAlgorithm extends Algorithm {
}
/**
- * Registers implementing class of the Transform algorithm with algorithmURI
+ * Registers implementing class of the SignatureAlgorithm with algorithmURI
*
- * @param algorithmURI algorithmURI URI representation of Transform algorithm.
+ * @param algorithmURI algorithmURI URI representation of SignatureAlgorithm.
* @param implementingClass implementingClass the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the signature algorithm
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
+ JavaUtils.checkRegisterPermission();
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
}
@@ -352,15 +356,18 @@ public class SignatureAlgorithm extends Algorithm {
/**
* Registers implementing class of the Transform algorithm with algorithmURI
*
- * @param algorithmURI algorithmURI URI representation of Transform algorithm.
+ * @param algorithmURI algorithmURI URI representation of SignatureAlgorithm.
* @param implementingClass implementingClass the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the signature algorithm
*/
public static void register(String algorithmURI, Class extends SignatureAlgorithmSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
+ JavaUtils.checkRegisterPermission();
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
}
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java
index 2f0b31f5ed4..ae33b72c91d 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java
@@ -41,6 +41,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicaliz
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -142,10 +143,13 @@ public class Canonicalizer {
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the canonicalizer
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
+ JavaUtils.checkRegisterPermission();
// check whether URI is already registered
Class extends CanonicalizerSpi> registeredClass =
canonicalizerHash.get(algorithmURI);
@@ -166,9 +170,12 @@ public class Canonicalizer {
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the canonicalizer
*/
- public static void register(String algorithmURI, Class implementingClass)
+ public static void register(String algorithmURI, Class extends CanonicalizerSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
+ JavaUtils.checkRegisterPermission();
// check whether URI is already registered
Class extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java
index fe541ff044f..e8622d938b6 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java
@@ -42,6 +42,7 @@ import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -175,9 +176,12 @@ public class KeyResolver {
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the key resolver
*/
public static void register(String className, boolean globalResolver)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+ JavaUtils.checkRegisterPermission();
KeyResolverSpi keyResolverSpi =
(KeyResolverSpi) Class.forName(className).newInstance();
keyResolverSpi.setGlobalResolver(globalResolver);
@@ -195,8 +199,11 @@ public class KeyResolver {
*
* @param className
* @param globalResolver Whether the KeyResolverSpi is a global resolver or not
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the key resolver
*/
public static void registerAtStart(String className, boolean globalResolver) {
+ JavaUtils.checkRegisterPermission();
KeyResolverSpi keyResolverSpi = null;
Exception ex = null;
try {
@@ -228,11 +235,14 @@ public class KeyResolver {
*
* @param keyResolverSpi a KeyResolverSpi instance to register
* @param start whether to register the KeyResolverSpi at the start of the list or not
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the key resolver
*/
public static void register(
KeyResolverSpi keyResolverSpi,
boolean start
) {
+ JavaUtils.checkRegisterPermission();
KeyResolver resolver = new KeyResolver(keyResolverSpi);
if (start) {
resolverVector.add(0, resolver);
@@ -254,9 +264,12 @@ public class KeyResolver {
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the key resolver
*/
public static void registerClassNames(List classNames)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+ JavaUtils.checkRegisterPermission();
List keyResolverList = new ArrayList(classNames.size());
for (String className : classNames) {
KeyResolverSpi keyResolverSpi =
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java
index 37d67ba9f24..3fc1d21bb9c 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java
@@ -46,6 +46,7 @@ import com.sun.org.apache.xml.internal.security.transforms.implementations.Trans
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
@@ -181,11 +182,14 @@ public final class Transform extends SignatureElementProxy {
* class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the transform
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
InvalidTransformException {
+ JavaUtils.checkRegisterPermission();
// are we already registered?
Class extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
if (transformSpi != null) {
@@ -206,9 +210,12 @@ public final class Transform extends SignatureElementProxy {
* class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register the transform
*/
public static void register(String algorithmURI, Class extends TransformSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException {
+ JavaUtils.checkRegisterPermission();
// are we already registered?
Class extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
if (transformSpi != null) {
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java
index ac7a53eba4f..fe8bdb1f1d6 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java
@@ -468,9 +468,12 @@ public abstract class ElementProxy {
* @param namespace
* @param prefix
* @throws XMLSecurityException
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to set the default prefix
*/
public static void setDefaultPrefix(String namespace, String prefix)
throws XMLSecurityException {
+ JavaUtils.checkRegisterPermission();
if (prefixMappings.containsValue(prefix)) {
String storedPrefix = prefixMappings.get(namespace);
if (!storedPrefix.equals(prefix)) {
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java
index 99b2d1f77e1..80c582fe8e2 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java
@@ -28,6 +28,7 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.security.SecurityPermission;
/**
* A collection of different, general-purpose methods for JAVA-specific things
@@ -39,6 +40,10 @@ public class JavaUtils {
private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(JavaUtils.class.getName());
+ private static final SecurityPermission REGISTER_PERMISSION =
+ new SecurityPermission(
+ "com.sun.org.apache.xml.internal.security.register");
+
private JavaUtils() {
// we don't allow instantiation
}
@@ -146,6 +151,23 @@ public class JavaUtils {
return retBytes;
}
+ /**
+ * Throws a {@code SecurityException} if a security manager is installed
+ * and the caller is not allowed to register an implementation of an
+ * algorithm, transform, or other security sensitive XML Signature function.
+ *
+ * @throws SecurityException if a security manager is installed and the
+ * caller has not been granted the
+ * {@literal "com.sun.org.apache.xml.internal.security.register"}
+ * {@code SecurityPermission}
+ */
+ public static void checkRegisterPermission() {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPermission(REGISTER_PERMISSION);
+ }
+ }
+
/**
* Converts an ASN.1 DSA value to a XML Signature DSA Value.
*
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java
index b73e5e8a5ec..3463dc75fec 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java
@@ -80,32 +80,44 @@ public class XMLUtils {
/**
* Set the prefix for the digital signature namespace
* @param prefix the new prefix for the digital signature namespace
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to set the prefix
*/
public static void setDsPrefix(String prefix) {
+ JavaUtils.checkRegisterPermission();
dsPrefix = prefix;
}
/**
* Set the prefix for the digital signature 1.1 namespace
* @param prefix the new prefix for the digital signature 1.1 namespace
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to set the prefix
*/
public static void setDs11Prefix(String prefix) {
+ JavaUtils.checkRegisterPermission();
ds11Prefix = prefix;
}
/**
* Set the prefix for the encryption namespace
* @param prefix the new prefix for the encryption namespace
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to set the prefix
*/
public static void setXencPrefix(String prefix) {
+ JavaUtils.checkRegisterPermission();
xencPrefix = prefix;
}
/**
* Set the prefix for the encryption namespace 1.1
* @param prefix the new prefix for the encryption namespace 1.1
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to set the prefix
*/
public static void setXenc11Prefix(String prefix) {
+ JavaUtils.checkRegisterPermission();
xenc11Prefix = prefix;
}
diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java
index 7570a019064..012d2fb8bc4 100644
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Map;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverLocalFilesystem;
@@ -199,9 +200,12 @@ public class ResourceResolver {
* the class cannot be registered.
*
* @param className the name of the ResourceResolverSpi class to be registered
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register a resource resolver
*/
@SuppressWarnings("unchecked")
public static void register(String className) {
+ JavaUtils.checkRegisterPermission();
try {
Class resourceResolverClass =
(Class) Class.forName(className);
@@ -216,9 +220,12 @@ public class ResourceResolver {
* list. This method logs a warning if the class cannot be registered.
*
* @param className the name of the ResourceResolverSpi class to be registered
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register a resource resolver
*/
@SuppressWarnings("unchecked")
public static void registerAtStart(String className) {
+ JavaUtils.checkRegisterPermission();
try {
Class resourceResolverClass =
(Class) Class.forName(className);
@@ -233,8 +240,11 @@ public class ResourceResolver {
* cannot be registered.
* @param className
* @param start
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register a resource resolver
*/
public static void register(Class extends ResourceResolverSpi> className, boolean start) {
+ JavaUtils.checkRegisterPermission();
try {
ResourceResolverSpi resourceResolverSpi = className.newInstance();
register(resourceResolverSpi, start);
@@ -250,8 +260,11 @@ public class ResourceResolver {
* cannot be registered.
* @param resourceResolverSpi
* @param start
+ * @throws SecurityException if a security manager is installed and the
+ * caller does not have permission to register a resource resolver
*/
public static void register(ResourceResolverSpi resourceResolverSpi, boolean start) {
+ JavaUtils.checkRegisterPermission();
synchronized(resolverList) {
if (start) {
resolverList.add(0, new ResourceResolver(resourceResolverSpi));
From a71432a188c552ce65507962abab8156ddbf724e Mon Sep 17 00:00:00 2001
From: Zhengyu Gu
Date: Mon, 16 Jun 2014 10:23:46 -0400
Subject: [PATCH 34/82] 8038903: More native monitor monitoring
Moved ntive monitor monitoring flags to experimental
Reviewed-by: acorn, hseigel, mschoene
---
hotspot/src/share/vm/runtime/globals.hpp | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp
index 7d5a99a20c4..d2952060e8d 100644
--- a/hotspot/src/share/vm/runtime/globals.hpp
+++ b/hotspot/src/share/vm/runtime/globals.hpp
@@ -1177,11 +1177,11 @@ class CommandLineFlags {
"When true prevents OS-level spurious, or premature, wakeups " \
"from Object.wait (Ignored for Windows)") \
\
- product(intx, NativeMonitorTimeout, -1, "(Unstable)") \
+ experimental(intx, NativeMonitorTimeout, -1, "(Unstable)") \
\
- product(intx, NativeMonitorFlags, 0, "(Unstable)") \
+ experimental(intx, NativeMonitorFlags, 0, "(Unstable)") \
\
- product(intx, NativeMonitorSpinLimit, 20, "(Unstable)") \
+ experimental(intx, NativeMonitorSpinLimit, 20, "(Unstable)") \
\
develop(bool, UsePthreads, false, \
"Use pthread-based instead of libthread-based synchronization " \
From cc10c541608b5f927e25f2367a69a3c87bad4e73 Mon Sep 17 00:00:00 2001
From: Phil Race
Date: Tue, 24 Jun 2014 10:03:46 -0700
Subject: [PATCH 35/82] 8035162: Service printing service
Reviewed-by: bae, jgodinez, mschoene
---
.../java.desktop/unix/classes/sun/print/CUPSPrinter.java | 8 ++++----
.../unix/classes/sun/print/IPPPrintService.java | 8 ++++++--
2 files changed, 10 insertions(+), 6 deletions(-)
diff --git a/jdk/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java b/jdk/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java
index 6d1b54e32f3..c1f0423b2b1 100644
--- a/jdk/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java
+++ b/jdk/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java
@@ -136,7 +136,7 @@ public class CUPSPrinter {
/**
* Returns array of MediaSizeNames derived from PPD.
*/
- public MediaSizeName[] getMediaSizeNames() {
+ MediaSizeName[] getMediaSizeNames() {
initMedia();
return cupsMediaSNames;
}
@@ -145,7 +145,7 @@ public class CUPSPrinter {
/**
* Returns array of Custom MediaSizeNames derived from PPD.
*/
- public CustomMediaSizeName[] getCustomMediaSizeNames() {
+ CustomMediaSizeName[] getCustomMediaSizeNames() {
initMedia();
return cupsCustomMediaSNames;
}
@@ -157,7 +157,7 @@ public class CUPSPrinter {
/**
* Returns array of MediaPrintableArea derived from PPD.
*/
- public MediaPrintableArea[] getMediaPrintableArea() {
+ MediaPrintableArea[] getMediaPrintableArea() {
initMedia();
return cupsMediaPrintables;
}
@@ -165,7 +165,7 @@ public class CUPSPrinter {
/**
* Returns array of MediaTrays derived from PPD.
*/
- public MediaTray[] getMediaTrays() {
+ MediaTray[] getMediaTrays() {
initMedia();
return cupsMediaTrays;
}
diff --git a/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java b/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java
index 22cc7bb48bf..698cd429bda 100644
--- a/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java
+++ b/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java
@@ -1002,7 +1002,9 @@ public class IPPPrintService implements PrintService, SunPrinterJobService {
public synchronized Class>[] getSupportedAttributeCategories() {
if (supportedCats != null) {
- return supportedCats;
+ Class> [] copyCats = new Class>[supportedCats.length];
+ System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
+ return copyCats;
}
initAttributes();
@@ -1065,7 +1067,9 @@ public class IPPPrintService implements PrintService, SunPrinterJobService {
supportedCats = new Class>[catList.size()];
catList.toArray(supportedCats);
- return supportedCats;
+ Class>[] copyCats = new Class>[supportedCats.length];
+ System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
+ return copyCats;
}
From 47d69e2546d005b5d170671e62a6553f389504ee Mon Sep 17 00:00:00 2001
From: Naoto Sato
Date: Tue, 24 Jun 2014 14:00:01 -0700
Subject: [PATCH 36/82] 8044274: Proper property processing
Reviewed-by: okutsu
---
.../classes/java/util/ResourceBundle.java | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/jdk/src/java.base/share/classes/java/util/ResourceBundle.java b/jdk/src/java.base/share/classes/java/util/ResourceBundle.java
index 151f1fd560a..3b8d06e01a7 100644
--- a/jdk/src/java.base/share/classes/java/util/ResourceBundle.java
+++ b/jdk/src/java.base/share/classes/java/util/ResourceBundle.java
@@ -2646,7 +2646,10 @@ public abstract class ResourceBundle {
} catch (ClassNotFoundException e) {
}
} else if (format.equals("java.properties")) {
- final String resourceName = toResourceName(bundleName, "properties");
+ final String resourceName = toResourceName0(bundleName, "properties");
+ if (resourceName == null) {
+ return bundle;
+ }
final ClassLoader classLoader = loader;
final boolean reloadFlag = reload;
InputStream stream = null;
@@ -2800,7 +2803,10 @@ public abstract class ResourceBundle {
}
boolean result = false;
try {
- String resourceName = toResourceName(toBundleName(baseName, locale), format);
+ String resourceName = toResourceName0(toBundleName(baseName, locale), format);
+ if (resourceName == null) {
+ return result;
+ }
URL url = loader.getResource(resourceName);
if (url != null) {
long lastModified = 0;
@@ -2934,6 +2940,15 @@ public abstract class ResourceBundle {
sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
return sb.toString();
}
+
+ private String toResourceName0(String bundleName, String suffix) {
+ // application protocol check
+ if (bundleName.contains("://")) {
+ return null;
+ } else {
+ return toResourceName(bundleName, suffix);
+ }
+ }
}
private static class SingleFormatControl extends Control {
From 5ef677511773ec611615b7de26ff4b3f68c8e848 Mon Sep 17 00:00:00 2001
From: Xueming Shen
Date: Thu, 7 Aug 2014 12:57:23 -0700
Subject: [PATCH 37/82] 8048025: Ensure cache consistency
To support zip entry with null character(s) embedded
Reviewed-by: alanb, weijun
---
.../java.base/share/native/libzip/ZipFile.c | 8 +---
.../java.base/share/native/libzip/zip_util.c | 44 +++++++++++++++----
.../java.base/share/native/libzip/zip_util.h | 4 +-
3 files changed, 41 insertions(+), 15 deletions(-)
diff --git a/jdk/src/java.base/share/native/libzip/ZipFile.c b/jdk/src/java.base/share/native/libzip/ZipFile.c
index 4604d8ff229..1649021c477 100644
--- a/jdk/src/java.base/share/native/libzip/ZipFile.c
+++ b/jdk/src/java.base/share/native/libzip/ZipFile.c
@@ -174,11 +174,7 @@ Java_java_util_zip_ZipFile_getEntry(JNIEnv *env, jclass cls, jlong zfile,
}
(*env)->GetByteArrayRegion(env, name, 0, ulen, (jbyte *)path);
path[ulen] = '\0';
- if (addSlash == JNI_FALSE) {
- ze = ZIP_GetEntry(zip, path, 0);
- } else {
- ze = ZIP_GetEntry(zip, path, (jint)ulen);
- }
+ ze = ZIP_GetEntry2(zip, path, (jint)ulen, addSlash);
if (path != buf) {
free(path);
}
@@ -271,7 +267,7 @@ Java_java_util_zip_ZipFile_getEntryBytes(JNIEnv *env,
switch (type) {
case java_util_zip_ZipFile_JZENTRY_NAME:
if (ze->name != 0) {
- len = (int)strlen(ze->name);
+ len = (int)ze->nlen;
// Unlike for extra and comment, we never return null for
// an (extremely rarely seen) empty name
if ((jba = (*env)->NewByteArray(env, len)) == NULL)
diff --git a/jdk/src/java.base/share/native/libzip/zip_util.c b/jdk/src/java.base/share/native/libzip/zip_util.c
index a072e6624c4..b172cde3172 100644
--- a/jdk/src/java.base/share/native/libzip/zip_util.c
+++ b/jdk/src/java.base/share/native/libzip/zip_util.c
@@ -1021,6 +1021,7 @@ newEntry(jzfile *zip, jzcell *zc, AccessHint accessHint)
if ((ze->name = malloc(nlen + 1)) == NULL) goto Catch;
memcpy(ze->name, cen + CENHDR, nlen);
ze->name[nlen] = '\0';
+ ze->nlen = nlen;
if (elen > 0) {
char *extra = cen + CENHDR + nlen;
@@ -1118,7 +1119,34 @@ ZIP_FreeEntry(jzfile *jz, jzentry *ze)
jzentry *
ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
{
- unsigned int hsh = hash(name);
+ if (ulen == 0) {
+ return ZIP_GetEntry2(zip, name, strlen(name), JNI_FALSE);
+ }
+ return ZIP_GetEntry2(zip, name, ulen, JNI_TRUE);
+}
+
+jboolean equals(char* name1, int len1, char* name2, int len2) {
+ if (len1 != len2) {
+ return JNI_FALSE;
+ }
+ while (len1-- > 0) {
+ if (*name1++ != *name2++) {
+ return JNI_FALSE;
+ }
+ }
+ return JNI_TRUE;
+}
+
+/*
+ * Returns the zip entry corresponding to the specified name, or
+ * NULL if not found.
+ * This method supports embedded null character in "name", use ulen
+ * for the length of "name".
+ */
+jzentry *
+ZIP_GetEntry2(jzfile *zip, char *name, jint ulen, jboolean addSlash)
+{
+ unsigned int hsh = hashN(name, ulen);
jint idx;
jzentry *ze = 0;
@@ -1139,7 +1167,7 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
/* Check the cached entry first */
ze = zip->cache;
- if (ze && strcmp(ze->name,name) == 0) {
+ if (ze && equals(ze->name, ze->nlen, name, ulen)) {
/* Cache hit! Remove and return the cached entry. */
zip->cache = 0;
ZIP_Unlock(zip);
@@ -1165,7 +1193,7 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
* we keep searching.
*/
ze = newEntry(zip, zc, ACCESS_RANDOM);
- if (ze && strcmp(ze->name, name)==0) {
+ if (ze && equals(ze->name, ze->nlen, name, ulen)) {
break;
}
if (ze != 0) {
@@ -1184,8 +1212,8 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
break;
}
- /* If no real length was passed in, we are done */
- if (ulen == 0) {
+ /* If no need to try appending slash, we are done */
+ if (!addSlash) {
break;
}
@@ -1195,11 +1223,11 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
}
/* Add slash and try once more */
- name[ulen] = '/';
- name[ulen+1] = '\0';
+ name[ulen++] = '/';
+ name[ulen] = '\0';
hsh = hash_append(hsh, '/');
idx = zip->table[hsh % zip->tablelen];
- ulen = 0;
+ addSlash = JNI_FALSE;
}
Finally:
diff --git a/jdk/src/java.base/share/native/libzip/zip_util.h b/jdk/src/java.base/share/native/libzip/zip_util.h
index a4aaf83823b..a64668cd6d9 100644
--- a/jdk/src/java.base/share/native/libzip/zip_util.h
+++ b/jdk/src/java.base/share/native/libzip/zip_util.h
@@ -154,6 +154,7 @@
* - If pos <= 0 then it is the position of entry LOC header.
* If pos > 0 then it is the position of entry data.
* pos should not be accessed directly, but only by ZIP_GetEntryDataOffset.
+ * - entry name may include embedded null character, use nlen for length
*/
typedef struct jzentry { /* Zip file entry */
@@ -166,6 +167,7 @@ typedef struct jzentry { /* Zip file entry */
jbyte *extra; /* optional extra data */
jlong pos; /* position of LOC header or entry data */
jint flag; /* general purpose flag */
+ jint nlen; /* length of the entry name */
} jzentry;
/*
@@ -269,5 +271,5 @@ void ZIP_Unlock(jzfile *zip);
jint ZIP_Read(jzfile *zip, jzentry *entry, jlong pos, void *buf, jint len);
void ZIP_FreeEntry(jzfile *zip, jzentry *ze);
jlong ZIP_GetEntryDataOffset(jzfile *zip, jzentry *entry);
-
+jzentry * ZIP_GetEntry2(jzfile *zip, char *name, jint ulen, jboolean addSlash);
#endif /* !_ZIP_H_ */
From 21f7f36b9e2375908c246c86268271bd2b067369 Mon Sep 17 00:00:00 2001
From: Jiangli Zhou
Date: Thu, 14 Aug 2014 21:46:27 -0400
Subject: [PATCH 38/82] 8044269: Analysis of archive files
Add checksum verification.
Reviewed-by: iklam, dholmes, mschoene
---
jdk/make/lib/CoreLibraries.gmk | 2 +-
jdk/src/java.base/share/native/libzip/CRC32.c | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/jdk/make/lib/CoreLibraries.gmk b/jdk/make/lib/CoreLibraries.gmk
index 852879f09ee..6e17ae0634a 100644
--- a/jdk/make/lib/CoreLibraries.gmk
+++ b/jdk/make/lib/CoreLibraries.gmk
@@ -224,7 +224,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBZIP, \
$(call SET_SHARED_LIBRARY_ORIGIN) \
$(EXPORT_ZIP_FUNCS), \
LDFLAGS_windows := -export:ZIP_Open -export:ZIP_Close -export:ZIP_FindEntry \
- -export:ZIP_ReadEntry -export:ZIP_GetNextEntry jvm.lib \
+ -export:ZIP_ReadEntry -export:ZIP_GetNextEntry -export:ZIP_CRC32 jvm.lib \
$(WIN_JAVA_LIB), \
LDFLAGS_SUFFIX_linux := -ljvm -ljava $(LIBZ), \
LDFLAGS_SUFFIX_solaris := -ljvm -ljava $(LIBZ) -lc, \
diff --git a/jdk/src/java.base/share/native/libzip/CRC32.c b/jdk/src/java.base/share/native/libzip/CRC32.c
index e9185b5fb1b..b03b2b9c53c 100644
--- a/jdk/src/java.base/share/native/libzip/CRC32.c
+++ b/jdk/src/java.base/share/native/libzip/CRC32.c
@@ -54,7 +54,8 @@ Java_java_util_zip_CRC32_updateBytes(JNIEnv *env, jclass cls, jint crc,
return crc;
}
-JNIEXPORT jint ZIP_CRC32(jint crc, const jbyte *buf, jint len)
+JNIEXPORT jint JNICALL
+ZIP_CRC32(jint crc, const jbyte *buf, jint len)
{
return crc32(crc, (Bytef*)buf, len);
}
From 4f08e490bb387fde5262e6e7da55222533eedeca Mon Sep 17 00:00:00 2001
From: Jonathan Gibbons
Date: Thu, 9 Oct 2014 19:14:30 -0700
Subject: [PATCH 39/82] 8060043: Rename Locations.Path to Locations.SearchPath
Reviewed-by: ksrini
---
.../com/sun/tools/javac/file/Locations.java | 38 +++++++++----------
1 file changed, 19 insertions(+), 19 deletions(-)
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java
index 41068493961..33cb4c8245e 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java
@@ -173,14 +173,14 @@ public class Locations {
* Utility class to help evaluate a path option. Duplicate entries are ignored, jar class paths
* can be expanded.
*/
- private class Path extends LinkedHashSet {
+ private class SearchPath extends LinkedHashSet {
private static final long serialVersionUID = 0;
private boolean expandJarClassPaths = false;
private final Set canonicalValues = new HashSet<>();
- public Path expandJarClassPaths(boolean x) {
+ public SearchPath expandJarClassPaths(boolean x) {
expandJarClassPaths = x;
return this;
}
@@ -190,12 +190,12 @@ public class Locations {
*/
private File emptyPathDefault = null;
- public Path emptyPathDefault(File x) {
+ public SearchPath emptyPathDefault(File x) {
emptyPathDefault = x;
return this;
}
- public Path addDirectories(String dirs, boolean warn) {
+ public SearchPath addDirectories(String dirs, boolean warn) {
boolean prev = expandJarClassPaths;
expandJarClassPaths = true;
try {
@@ -210,7 +210,7 @@ public class Locations {
}
}
- public Path addDirectories(String dirs) {
+ public SearchPath addDirectories(String dirs) {
return addDirectories(dirs, warn);
}
@@ -235,18 +235,18 @@ public class Locations {
}
}
- public Path addFiles(String files, boolean warn) {
+ public SearchPath addFiles(String files, boolean warn) {
if (files != null) {
addFiles(getPathEntries(files, emptyPathDefault), warn);
}
return this;
}
- public Path addFiles(String files) {
+ public SearchPath addFiles(String files) {
return addFiles(files, warn);
}
- public Path addFiles(Iterable extends File> files, boolean warn) {
+ public SearchPath addFiles(Iterable extends File> files, boolean warn) {
if (files != null) {
for (File file : files) {
addFile(file, warn);
@@ -255,7 +255,7 @@ public class Locations {
return this;
}
- public Path addFiles(Iterable extends File> files) {
+ public SearchPath addFiles(Iterable extends File> files) {
return addFiles(files, warn);
}
@@ -458,7 +458,7 @@ public class Locations {
@Override
void setLocation(Iterable extends File> files) {
- Path p;
+ SearchPath p;
if (files == null) {
p = computePath(null);
} else {
@@ -467,12 +467,12 @@ public class Locations {
searchPath = Collections.unmodifiableCollection(p);
}
- protected Path computePath(String value) {
+ protected SearchPath computePath(String value) {
return createPath().addFiles(value);
}
- protected Path createPath() {
- return new Path();
+ protected SearchPath createPath() {
+ return new SearchPath();
}
}
@@ -494,7 +494,7 @@ public class Locations {
}
@Override
- protected Path computePath(String value) {
+ protected SearchPath computePath(String value) {
String cp = value;
// CLASSPATH environment variable when run from `javac'.
@@ -517,8 +517,8 @@ public class Locations {
}
@Override
- protected Path createPath() {
- return new Path()
+ protected SearchPath createPath() {
+ return new SearchPath()
.expandJarClassPaths(true) // Only search user jars for Class-Paths
.emptyPathDefault(new File(".")); // Empty path elt ==> current directory
}
@@ -616,15 +616,15 @@ public class Locations {
} else {
defaultBootClassPathRtJar = null;
isDefaultBootClassPath = false;
- Path p = new Path().addFiles(files, false);
+ SearchPath p = new SearchPath().addFiles(files, false);
searchPath = Collections.unmodifiableCollection(p);
optionValues.clear();
}
}
- Path computePath() {
+ SearchPath computePath() {
defaultBootClassPathRtJar = null;
- Path path = new Path();
+ SearchPath path = new SearchPath();
String bootclasspathOpt = optionValues.get(BOOTCLASSPATH);
String endorseddirsOpt = optionValues.get(ENDORSEDDIRS);
From f2913f0270a10cb7b98ef2b78223281af6550e8c Mon Sep 17 00:00:00 2001
From: Athijegannathan Sundararajan
Date: Fri, 10 Oct 2014 17:59:22 +0530
Subject: [PATCH 40/82] 8060101: AssertionError: __noSuchProperty__ placeholder
called from NativeJavaImporter
Reviewed-by: attila, jlaskey
---
.../internal/objects/NativeJavaImporter.java | 24 ++++-----
.../nashorn/internal/runtime/WithObject.java | 13 +++++
.../runtime/resources/Messages.properties | 1 +
nashorn/test/script/basic/JDK-8060101.js | 54 +++++++++++++++++++
4 files changed, 80 insertions(+), 12 deletions(-)
create mode 100644 nashorn/test/script/basic/JDK-8060101.js
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJavaImporter.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJavaImporter.java
index d1aa8cb1653..498c263cba6 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJavaImporter.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJavaImporter.java
@@ -25,6 +25,7 @@
package jdk.nashorn.internal.objects;
+import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
import jdk.internal.dynalink.CallSiteDescriptor;
@@ -36,9 +37,11 @@ import jdk.nashorn.internal.objects.annotations.Constructor;
import jdk.nashorn.internal.objects.annotations.Function;
import jdk.nashorn.internal.objects.annotations.ScriptClass;
import jdk.nashorn.internal.runtime.Context;
+import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.NativeJavaPackage;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptObject;
+import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
/**
@@ -94,33 +97,30 @@ public final class NativeJavaImporter extends ScriptObject {
}
/**
- * "No such property" call placeholder.
- *
- * This can never be called as we override {@link ScriptObject#noSuchProperty}. We do declare it here as it's a signal
- * to {@link jdk.nashorn.internal.runtime.WithObject} that it's worth trying doing a {@code noSuchProperty} on this object.
+ * "No such property" handler.
*
* @param self self reference
* @param name property name
- * @return never returns
+ * @return value of the missing property
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object __noSuchProperty__(final Object self, final Object name) {
- throw new AssertionError("__noSuchProperty__ placeholder called");
+ if (! (self instanceof NativeJavaImporter)) {
+ throw typeError("not.a.java.importer", ScriptRuntime.safeToString(self));
+ }
+ return ((NativeJavaImporter)self).createProperty(JSType.toString(name));
}
/**
- * "No such method call" placeholder
- *
- * This can never be called as we override {@link ScriptObject#noSuchMethod}. We do declare it here as it's a signal
- * to {@link jdk.nashorn.internal.runtime.WithObject} that it's worth trying doing a noSuchProperty on this object.
+ * "No such method call" handler
*
* @param self self reference
* @param args arguments to method
- * @return never returns
+ * @return never returns always throw TypeError
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object __noSuchMethod__(final Object self, final Object... args) {
- throw new AssertionError("__noSuchMethod__ placeholder called");
+ throw typeError("not.a.function", ScriptRuntime.safeToString(args[0]));
}
@Override
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/WithObject.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/WithObject.java
index 54ec06f5319..20510dfd36b 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/WithObject.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/WithObject.java
@@ -209,6 +209,19 @@ public final class WithObject extends ScriptObject implements Scope {
return super.findProperty(key, deep, start);
}
+ @Override
+ protected Object invokeNoSuchProperty(final String name, final int programPoint) {
+ FindProperty find = expression.findProperty(NO_SUCH_PROPERTY_NAME, true);
+ if (find != null) {
+ final Object func = find.getObjectValue();
+ if (func instanceof ScriptFunction) {
+ return ScriptRuntime.apply((ScriptFunction)func, expression, name);
+ }
+ }
+
+ return getProto().invokeNoSuchProperty(name, programPoint);
+ }
+
@Override
public void setSplitState(final int state) {
getNonWithParent().setSplitState(state);
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties
index 056dc87deed..3a161c8d352 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties
@@ -73,6 +73,7 @@ type.error.strict.getter.setter.poison=In strict mode, "caller", "callee", and "
type.error.not.an.object={0} is not an Object
type.error.not.a.boolean={0} is not a Boolean
type.error.not.a.date={0} is not a Date
+type.error.not.a.java.importer={0} is not a JavaImporter object
type.error.not.a.number={0} is not a Number
type.error.not.a.regexp={0} is not a RegExp
type.error.not.a.string={0} is not a String
diff --git a/nashorn/test/script/basic/JDK-8060101.js b/nashorn/test/script/basic/JDK-8060101.js
new file mode 100644
index 00000000000..617bbccde72
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8060101.js
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+/**
+ * JDK-8060101: AssertionError: __noSuchProperty__ placeholder called from NativeJavaImporter
+ *
+ * @test
+ * @run
+ */
+
+var constant = 0.50;
+var ind = 0.0;
+
+// make sure callsites are exercised quite a few times
+// to induce megamorphic callsite for with/JavaImporter
+// combo - which triggered that AssertionError.
+for (var i = 0; i < 50; i++) {
+ var math = new JavaImporter(java.lang.StrictMath);
+ ind += 10.0;
+ with (math) {
+ StrictMath.exp(-constant*ind);
+ }
+}
+
+for (var i = 0; i < 50; i++) {
+ var math = new JavaImporter(java.lang.StrictMath);
+ try {
+ math.Foo();
+ } catch (e) {
+ if (! (e instanceof TypeError)) {
+ throw e;
+ }
+ }
+}
From a7b8ca6209719848f9fac5b25ff016951a9dafbb Mon Sep 17 00:00:00 2001
From: Sonali Goel
Date: Fri, 10 Oct 2014 14:41:50 -0700
Subject: [PATCH 41/82] 8058410: Group 10b: golden files for tests in
tools/javac dir
Reviewed-by: jjg
---
.../test/tools/javac/7129225/NegTest.out | 2 ++
.../test/tools/javac/7129225/NegTest.ref | 2 --
.../tools/javac/7129225/TestImportStar.java | 31 ++----------------
...{TestImportStar.ref => TestImportStar.out} | 4 +--
.../QualifiedAccess/QualifiedAccess_4.java | 31 ++----------------
.../QualifiedAccess/QualifiedAccess_4.out | 2 ++
.../test/tools/javac/T4848619/T4848619a.java | 27 ++--------------
.../test/tools/javac/T4848619/T4848619a.out | 2 ++
.../test/tools/javac/T4848619/T4848619b.java | 27 ++--------------
.../test/tools/javac/T4848619/T4848619b.out | 2 ++
.../tools/javac/scope/6225935/Estatico4.java | 29 ++---------------
.../tools/javac/scope/6225935/Estatico4.out | 2 ++
.../tools/javac/scope/6225935/T6214959.java | 29 ++---------------
.../tools/javac/scope/6225935/T6214959.out | 2 ++
.../test/tools/javac/warnings/DepAnn.java | 32 ++-----------------
.../test/tools/javac/warnings/DepAnn.out | 5 +++
.../test/tools/javac/warnings/Finally.java | 32 ++-----------------
.../test/tools/javac/warnings/Finally.out | 2 ++
.../test/tools/javac/warnings/Serial.java | 31 ++----------------
.../test/tools/javac/warnings/Serial.out | 5 +++
20 files changed, 47 insertions(+), 252 deletions(-)
create mode 100644 langtools/test/tools/javac/7129225/NegTest.out
delete mode 100644 langtools/test/tools/javac/7129225/NegTest.ref
rename langtools/test/tools/javac/7129225/{TestImportStar.ref => TestImportStar.out} (64%)
create mode 100644 langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.out
create mode 100644 langtools/test/tools/javac/T4848619/T4848619a.out
create mode 100644 langtools/test/tools/javac/T4848619/T4848619b.out
create mode 100644 langtools/test/tools/javac/scope/6225935/Estatico4.out
create mode 100644 langtools/test/tools/javac/scope/6225935/T6214959.out
create mode 100644 langtools/test/tools/javac/warnings/DepAnn.out
create mode 100644 langtools/test/tools/javac/warnings/Finally.out
create mode 100644 langtools/test/tools/javac/warnings/Serial.out
diff --git a/langtools/test/tools/javac/7129225/NegTest.out b/langtools/test/tools/javac/7129225/NegTest.out
new file mode 100644
index 00000000000..112000104ae
--- /dev/null
+++ b/langtools/test/tools/javac/7129225/NegTest.out
@@ -0,0 +1,2 @@
+TestImportStar.java:14:1: compiler.err.doesnt.exist: xxx
+1 error
diff --git a/langtools/test/tools/javac/7129225/NegTest.ref b/langtools/test/tools/javac/7129225/NegTest.ref
deleted file mode 100644
index 3895c11ba03..00000000000
--- a/langtools/test/tools/javac/7129225/NegTest.ref
+++ /dev/null
@@ -1,2 +0,0 @@
-TestImportStar.java:39:1: compiler.err.doesnt.exist: xxx
-1 error
diff --git a/langtools/test/tools/javac/7129225/TestImportStar.java b/langtools/test/tools/javac/7129225/TestImportStar.java
index eaca9ed23c3..37f93a93cf4 100644
--- a/langtools/test/tools/javac/7129225/TestImportStar.java
+++ b/langtools/test/tools/javac/7129225/TestImportStar.java
@@ -1,36 +1,11 @@
-/*
- * Copyright (c) 2012, 2013, 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.
- */
-
-/* @test
+/* @test /nodynamiccopyright/
* @bug 7129225
* @summary import xxx.* isn't handled correctly by annotation processing
* @library /tools/javac/lib
* @build JavacTestingAbstractProcessor
- * @compile/fail/ref=NegTest.ref -XDrawDiagnostics TestImportStar.java
+ * @compile/fail/ref=NegTest.out -XDrawDiagnostics TestImportStar.java
* @compile Anno.java AnnoProcessor.java
- * @compile/fail/ref=TestImportStar.ref -XDrawDiagnostics -processor AnnoProcessor -proc:only TestImportStar.java
+ * @compile/fail/ref=TestImportStar.out -XDrawDiagnostics -processor AnnoProcessor -proc:only TestImportStar.java
*/
//The @compile/fail... verifies that the fix doesn't break the normal compilation of import xxx.*
diff --git a/langtools/test/tools/javac/7129225/TestImportStar.ref b/langtools/test/tools/javac/7129225/TestImportStar.out
similarity index 64%
rename from langtools/test/tools/javac/7129225/TestImportStar.ref
rename to langtools/test/tools/javac/7129225/TestImportStar.out
index 5b3c75d7d89..8f7dfb0b5ad 100644
--- a/langtools/test/tools/javac/7129225/TestImportStar.ref
+++ b/langtools/test/tools/javac/7129225/TestImportStar.out
@@ -1,4 +1,4 @@
- compiler.note.proc.messager: RUNNING - lastRound = false
-TestImportStar.java:39:1: compiler.err.doesnt.exist: xxx
+TestImportStar.java:14:1: compiler.err.doesnt.exist: xxx
- compiler.note.proc.messager: RUNNING - lastRound = true
-1 error
\ No newline at end of file
+1 error
diff --git a/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.java b/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.java
index 88e87a6ab28..40949cbbf23 100644
--- a/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.java
+++ b/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.java
@@ -1,34 +1,10 @@
/*
- * Copyright (c) 2002, 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
+ * @test /nodynamiccopyright/
* @bug 4094658
* @summary Test enforcement of JLS 6.6.1 and 6.6.2 rules requiring that
* the type to which a component member belongs be accessible in qualified
* names.
- *
- * @compile/fail QualifiedAccess_4.java
+ * @compile/fail/ref=QualifiedAccess_4.out -XDrawDiagnostics QualifiedAccess_4.java
*/
import pack1.P1;
@@ -38,8 +14,5 @@ class CMain {
class Foo {
class Bar {}
}
-
- // NOTE: Error localization and recovery is bad here,
- // eliciting two other spurious complaints.
Foo.Bar yy = x.new Foo.Bar(); // ERROR - Type in qualified 'new' must be unqualified
}
diff --git a/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.out b/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.out
new file mode 100644
index 00000000000..6f5caf83f5f
--- /dev/null
+++ b/langtools/test/tools/javac/QualifiedAccess/QualifiedAccess_4.out
@@ -0,0 +1,2 @@
+QualifiedAccess_4.java:17:28: compiler.err.expected: '('
+1 error
diff --git a/langtools/test/tools/javac/T4848619/T4848619a.java b/langtools/test/tools/javac/T4848619/T4848619a.java
index d61f7f6b8ab..859c3b4e1f7 100644
--- a/langtools/test/tools/javac/T4848619/T4848619a.java
+++ b/langtools/test/tools/javac/T4848619/T4848619a.java
@@ -1,32 +1,9 @@
/*
- * Copyright (c) 2005, 2006, 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
+ * @test /nodynamiccopyright/
* @bug 4848619
* @summary static final variable declared after use and self initialized
* @author Peter von der Ah\u00e9
- * @compile/fail T4848619a.java
+ * @compile/fail/ref=T4848619a.out -XDrawDiagnostics T4848619a.java
*/
public class T4848619a {
diff --git a/langtools/test/tools/javac/T4848619/T4848619a.out b/langtools/test/tools/javac/T4848619/T4848619a.out
new file mode 100644
index 00000000000..ce4486bcbd7
--- /dev/null
+++ b/langtools/test/tools/javac/T4848619/T4848619a.out
@@ -0,0 +1,2 @@
+T4848619a.java:11:37: compiler.err.illegal.self.ref
+1 error
diff --git a/langtools/test/tools/javac/T4848619/T4848619b.java b/langtools/test/tools/javac/T4848619/T4848619b.java
index 3c9e6ba3d36..b1677c60091 100644
--- a/langtools/test/tools/javac/T4848619/T4848619b.java
+++ b/langtools/test/tools/javac/T4848619/T4848619b.java
@@ -1,32 +1,9 @@
/*
- * Copyright (c) 2005, 2006, 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
+ * @test /nodynamiccopyright/
* @bug 4848619
* @summary static final variable declared after use and self initialized
* @author Peter von der Ah\u00e9
- * @compile/fail T4848619b.java
+ * @compile/fail/ref=T4848619b.out -XDrawDiagnostics T4848619b.java
*/
public class T4848619b {
diff --git a/langtools/test/tools/javac/T4848619/T4848619b.out b/langtools/test/tools/javac/T4848619/T4848619b.out
new file mode 100644
index 00000000000..8358f891bf5
--- /dev/null
+++ b/langtools/test/tools/javac/T4848619/T4848619b.out
@@ -0,0 +1,2 @@
+T4848619b.java:11:13: compiler.err.illegal.self.ref
+1 error
diff --git a/langtools/test/tools/javac/scope/6225935/Estatico4.java b/langtools/test/tools/javac/scope/6225935/Estatico4.java
index 30da1412390..c2b17d6cc00 100644
--- a/langtools/test/tools/javac/scope/6225935/Estatico4.java
+++ b/langtools/test/tools/javac/scope/6225935/Estatico4.java
@@ -1,31 +1,8 @@
/*
- * Copyright (c) 2006, 2007, 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
+ * @test /nodynamiccopyright/
* @bug 6214959
- * @summary Compiler fails do produce error message with ODD number of import static
- * @compile/fail Estatico4.java
+ * @summary Compiler fails to produce error message with ODD number of import static
+ * @compile/fail/ref=Estatico4.out -XDrawDiagnostics Estatico4.java
*/
diff --git a/langtools/test/tools/javac/scope/6225935/Estatico4.out b/langtools/test/tools/javac/scope/6225935/Estatico4.out
new file mode 100644
index 00000000000..2105cec25e0
--- /dev/null
+++ b/langtools/test/tools/javac/scope/6225935/Estatico4.out
@@ -0,0 +1,2 @@
+Estatico4.java:16:24: compiler.err.ref.ambiguous: CENTER, kindname.variable, CENTER, java.awt.FlowLayout, kindname.variable, CENTER, javax.swing.SwingConstants
+1 error
diff --git a/langtools/test/tools/javac/scope/6225935/T6214959.java b/langtools/test/tools/javac/scope/6225935/T6214959.java
index b7be5050a12..96a9478f33c 100644
--- a/langtools/test/tools/javac/scope/6225935/T6214959.java
+++ b/langtools/test/tools/javac/scope/6225935/T6214959.java
@@ -1,32 +1,9 @@
/*
- * Copyright (c) 2006, 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
+ * @test /nodynamiccopyright/
* @bug 6214959
- * @summary Compiler fails do produce error message with ODD number of import static
+ * @summary Compiler fails to produce error message with ODD number of import static
* @author Peter von der Ah\u00e9
- * @compile/fail T6214959.java
+ * @compile/fail/ref=T6214959.out -XDrawDiagnostics T6214959.java
*/
import static a.Star.*;
diff --git a/langtools/test/tools/javac/scope/6225935/T6214959.out b/langtools/test/tools/javac/scope/6225935/T6214959.out
new file mode 100644
index 00000000000..e3f7bd98b6d
--- /dev/null
+++ b/langtools/test/tools/javac/scope/6225935/T6214959.out
@@ -0,0 +1,2 @@
+T6214959.java:15:7: compiler.err.ref.ambiguous: y, kindname.method, y(), a.Star, kindname.method, y(), a.Ambiguous
+1 error
diff --git a/langtools/test/tools/javac/warnings/DepAnn.java b/langtools/test/tools/javac/warnings/DepAnn.java
index 92a0d550a96..4f25d290e7b 100644
--- a/langtools/test/tools/javac/warnings/DepAnn.java
+++ b/langtools/test/tools/javac/warnings/DepAnn.java
@@ -1,35 +1,7 @@
/*
- * Copyright (c) 2005, 2006, 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
+ * @test /nodynamiccopyright/
* @bug 4986256
- * @compile DepAnn.java
- * @compile -Xlint:dep-ann DepAnn.java
- * @compile -Xlint:all DepAnn.java
- * @compile -Werror DepAnn.java
- * @compile/fail -Werror -Xlint:dep-ann DepAnn.java
- * @compile/fail -Werror -Xlint:all,-path DepAnn.java
+ * @compile/ref=DepAnn.out -XDrawDiagnostics -Xlint:all DepAnn.java
*/
// control: this class should generate warnings
diff --git a/langtools/test/tools/javac/warnings/DepAnn.out b/langtools/test/tools/javac/warnings/DepAnn.out
new file mode 100644
index 00000000000..c8c29eca134
--- /dev/null
+++ b/langtools/test/tools/javac/warnings/DepAnn.out
@@ -0,0 +1,5 @@
+DepAnn.java:12:10: compiler.warn.missing.deprecated.annotation
+DepAnn.java:9:1: compiler.warn.missing.deprecated.annotation
+DepAnn.java:59:10: compiler.warn.missing.deprecated.annotation
+DepAnn.java:56:1: compiler.warn.missing.deprecated.annotation
+4 warnings
diff --git a/langtools/test/tools/javac/warnings/Finally.java b/langtools/test/tools/javac/warnings/Finally.java
index 105d5bec934..dd6aeee5824 100644
--- a/langtools/test/tools/javac/warnings/Finally.java
+++ b/langtools/test/tools/javac/warnings/Finally.java
@@ -1,35 +1,7 @@
/*
- * Copyright (c) 2005, 2006, 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
+ * @test /nodynamiccopyright/
* @bug 4986256
- * @compile Finally.java
- * @compile -Xlint:finally Finally.java
- * @compile -Xlint:all Finally.java
- * @compile -Werror Finally.java
- * @compile/fail -Werror -Xlint:finally Finally.java
- * @compile/fail -Werror -Xlint:all,-path Finally.java
+ * @compile/ref=Finally.out -XDrawDiagnostics -Xlint:all Finally.java
*/
// control: this class should generate a warning
diff --git a/langtools/test/tools/javac/warnings/Finally.out b/langtools/test/tools/javac/warnings/Finally.out
new file mode 100644
index 00000000000..cfb4e654491
--- /dev/null
+++ b/langtools/test/tools/javac/warnings/Finally.out
@@ -0,0 +1,2 @@
+Finally.java:16:9: compiler.warn.finally.cannot.complete
+1 warning
diff --git a/langtools/test/tools/javac/warnings/Serial.java b/langtools/test/tools/javac/warnings/Serial.java
index 3d5cc464ca4..c9c3d6b7c06 100644
--- a/langtools/test/tools/javac/warnings/Serial.java
+++ b/langtools/test/tools/javac/warnings/Serial.java
@@ -1,34 +1,7 @@
/*
- * Copyright (c) 2005, 2006, 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
+ * @test /nodynamiccopyright/
* @bug 4986256
- * @compile Serial.java
- * @compile -Xlint:serial Serial.java
- * @compile -Xlint:all Serial.java
- * @compile -Werror Serial.java
- * @compile/fail -Werror -Xlint:serial Serial.java
+ * @compile/ref=Serial.out -XDrawDiagnostics -Xlint:all Serial.java
*/
import java.io.Serializable;
diff --git a/langtools/test/tools/javac/warnings/Serial.out b/langtools/test/tools/javac/warnings/Serial.out
new file mode 100644
index 00000000000..05e727adee1
--- /dev/null
+++ b/langtools/test/tools/javac/warnings/Serial.out
@@ -0,0 +1,5 @@
+Serial.java:12:12: compiler.warn.missing.SVUID: Serial.Inner
+Serial.java:10:1: compiler.warn.missing.SVUID: Serial
+Serial.java:51:12: compiler.warn.missing.SVUID: Serial3.Inner
+Serial.java:49:1: compiler.warn.missing.SVUID: Serial3
+4 warnings
From 4fcc6c8f4f0c42b0c07ec323c87fe88da6b40fbd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?=
Date: Mon, 13 Oct 2014 17:16:32 +0200
Subject: [PATCH 42/82] 8060011: Concatenating an array and converting it to
Java gives wrong result
Reviewed-by: lagergren, attila
---
.../arrays/DeletedRangeArrayFilter.java | 12 ++--
.../internal/runtime/arrays/IntArrayData.java | 8 +--
.../runtime/arrays/LongArrayData.java | 12 ++--
.../runtime/arrays/NumberArrayData.java | 8 +--
.../runtime/arrays/ObjectArrayData.java | 3 +-
.../runtime/arrays/SparseArrayData.java | 2 +-
nashorn/test/script/basic/JDK-8060011.js | 58 +++++++++++++++++++
7 files changed, 81 insertions(+), 22 deletions(-)
create mode 100644 nashorn/test/script/basic/JDK-8060011.js
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java
index 8732add9348..cd5cadb962e 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java
@@ -66,9 +66,9 @@ final class DeletedRangeArrayFilter extends ArrayFilter {
public Object[] asObjectArray() {
final Object[] value = super.asObjectArray();
- if (lo <= Integer.MAX_VALUE) {
- final int intHi = (int)Math.min(hi, Integer.MAX_VALUE);
- for (int i = (int)lo; i <= intHi; i++) {
+ if (lo < Integer.MAX_VALUE) {
+ final int end = (int)Math.min(hi + 1, Integer.MAX_VALUE);
+ for (int i = (int)lo; i < end; i++) {
value[i] = ScriptRuntime.UNDEFINED;
}
}
@@ -81,9 +81,9 @@ final class DeletedRangeArrayFilter extends ArrayFilter {
final Object value = super.asArrayOfType(componentType);
final Object undefValue = convertUndefinedValue(componentType);
- if (lo <= Integer.MAX_VALUE) {
- final int intHi = (int)Math.min(hi, Integer.MAX_VALUE);
- for (int i = (int)lo; i <= intHi; i++) {
+ if (lo < Integer.MAX_VALUE) {
+ final int end = (int)Math.min(hi + 1, Integer.MAX_VALUE);
+ for (int i = (int)lo; i < end; i++) {
Array.set(value, i, undefValue);
}
}
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java
index 48dd088e01c..fece3a6ef64 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java
@@ -73,7 +73,7 @@ final class IntArrayData extends ContinuousArrayData implements IntElements {
@Override
public Object[] asObjectArray() {
- return toObjectArray();
+ return toObjectArray(true);
}
@SuppressWarnings("unused")
@@ -116,9 +116,9 @@ final class IntArrayData extends ContinuousArrayData implements IntElements {
return super.asArrayOfType(componentType);
}
- private Object[] toObjectArray() {
+ private Object[] toObjectArray(final boolean trim) {
assert length <= array.length : "length exceeds internal array size";
- final Object[] oarray = new Object[array.length];
+ final Object[] oarray = new Object[trim ? (int)length : array.length];
for (int index = 0; index < length; index++) {
oarray[index] = Integer.valueOf(array[index]);
@@ -158,7 +158,7 @@ final class IntArrayData extends ContinuousArrayData implements IntElements {
}
private ObjectArrayData convertToObject() {
- return new ObjectArrayData(toObjectArray(), (int)length);
+ return new ObjectArrayData(toObjectArray(false), (int)length);
}
@Override
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java
index ad050d69170..31a4484e2ae 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java
@@ -67,12 +67,12 @@ final class LongArrayData extends ContinuousArrayData implements IntOrLongElemen
@Override
public Object[] asObjectArray() {
- return toObjectArray(array, (int)length);
+ return toObjectArray(true);
}
- private static Object[] toObjectArray(final long[] array, final int length) {
+ private Object[] toObjectArray(final boolean trim) {
assert length <= array.length : "length exceeds internal array size";
- final Object[] oarray = new Object[array.length];
+ final Object[] oarray = new Object[trim ? (int)length : array.length];
for (int index = 0; index < length; index++) {
oarray[index] = Long.valueOf(array[index]);
@@ -89,7 +89,7 @@ final class LongArrayData extends ContinuousArrayData implements IntOrLongElemen
return super.asArrayOfType(componentType);
}
- private static double[] toDoubleArray(final long[] array, final int length) {
+ private double[] toDoubleArray() {
assert length <= array.length : "length exceeds internal array size";
final double[] darray = new double[array.length];
@@ -107,9 +107,9 @@ final class LongArrayData extends ContinuousArrayData implements IntOrLongElemen
}
final int len = (int)length;
if (type == Double.class) {
- return new NumberArrayData(LongArrayData.toDoubleArray(array, len), len);
+ return new NumberArrayData(toDoubleArray(), len);
}
- return new ObjectArrayData(LongArrayData.toObjectArray(array, len), len);
+ return new ObjectArrayData(toObjectArray(false), len);
}
@Override
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java
index b2d843e6fb4..4d27f51df3c 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java
@@ -66,12 +66,12 @@ final class NumberArrayData extends ContinuousArrayData implements NumericElemen
@Override
public Object[] asObjectArray() {
- return toObjectArray(array, (int)length);
+ return toObjectArray(true);
}
- private static Object[] toObjectArray(final double[] array, final int length) {
+ private Object[] toObjectArray(final boolean trim) {
assert length <= array.length : "length exceeds internal array size";
- final Object[] oarray = new Object[array.length];
+ final Object[] oarray = new Object[trim ? (int)length : array.length];
for (int index = 0; index < length; index++) {
oarray[index] = Double.valueOf(array[index]);
@@ -91,7 +91,7 @@ final class NumberArrayData extends ContinuousArrayData implements NumericElemen
public ArrayData convert(final Class> type) {
if (type != Double.class && type != Integer.class && type != Long.class) {
final int len = (int)length;
- return new ObjectArrayData(NumberArrayData.toObjectArray(array, len), len);
+ return new ObjectArrayData(toObjectArray(false), len);
}
return this;
}
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
index 8fd1a453077..001ea61c7c8 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
@@ -155,7 +155,8 @@ final class ObjectArrayData extends ContinuousArrayData {
@Override
public ArrayData setEmpty(final long lo, final long hi) {
- Arrays.fill(array, (int)Math.max(lo, 0L), (int)Math.min(hi, Integer.MAX_VALUE), ScriptRuntime.EMPTY);
+ // hi parameter is inclusive, but Arrays.fill toIndex parameter is exclusive
+ Arrays.fill(array, (int)Math.max(lo, 0L), (int)Math.min(hi + 1, Integer.MAX_VALUE), ScriptRuntime.EMPTY);
return this;
}
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java
index d28b731c44c..ef47345173f 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java
@@ -78,7 +78,7 @@ class SparseArrayData extends ArrayData {
for (final Map.Entry entry : sparseMap.entrySet()) {
final long key = entry.getKey();
- if (key <= Integer.MAX_VALUE) {
+ if (key < Integer.MAX_VALUE) {
objArray[(int)key] = entry.getValue();
} else {
break; // ascending key order
diff --git a/nashorn/test/script/basic/JDK-8060011.js b/nashorn/test/script/basic/JDK-8060011.js
new file mode 100644
index 00000000000..7514ff290b6
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8060011.js
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+/**
+ * JDK-8060011: Concatenating an array and converting it to Java gives wrong result
+ *
+ * @test
+ * @run
+ */
+
+
+function compareAsJavaArrays(a1, a2) {
+ var ja1 = Java.to(a1);
+ var ja2 = Java.to(a2);
+ if (ja1.length !== ja2.length) {
+ throw "different length";
+ }
+ for (var i = 0; i < ja1.length; i++) {
+ if (ja1[i] !== ja2[i]) {
+ throw "different element at " + i;
+ }
+ }
+ if (java.util.Arrays.toString(ja1) !== java.util.Arrays.toString(ja2)) {
+ throw "different string representation";
+ }
+}
+
+compareAsJavaArrays([0, 1, 2, 3],
+ [0].concat([1, 2, 3]));
+compareAsJavaArrays([1000000000, 2000000000, 3000000000, 4000000000],
+ [1000000000].concat([2000000000, 3000000000, 4000000000]));
+compareAsJavaArrays([0.5, 1.5, 2.5, 3.5],
+ [0.5].concat([1.5, 2.5, 3.5]));
+compareAsJavaArrays(["0", "1", "2", "3"],
+ ["0"].concat(["1", "2", "3"]));
+
+
+
From f3201874bc9f96eded67bda60ea91d0f035ea170 Mon Sep 17 00:00:00 2001
From: Paul Govereau
Date: Mon, 13 Oct 2014 11:21:51 -0400
Subject: [PATCH 43/82] 8058243: Reduce size of bytecode for large switch
statements
Reviewed-by: jjg, vromero
---
.../classes/com/sun/tools/javac/jvm/Gen.java | 19 ++++++++-----------
1 file changed, 8 insertions(+), 11 deletions(-)
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
index 553bf403469..959a76201fe 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
@@ -1220,17 +1220,14 @@ public class Gen extends JCTree.Visitor {
}
// Determine whether to issue a tableswitch or a lookupswitch
- // instruction.
- long table_space_cost = 4 + ((long) hi - lo + 1); // words
- long table_time_cost = 3; // comparisons
- long lookup_space_cost = 3 + 2 * (long) nlabels;
- long lookup_time_cost = nlabels;
- int opcode =
- nlabels > 0 &&
- table_space_cost + 3 * table_time_cost <=
- lookup_space_cost + 3 * lookup_time_cost
- ?
- tableswitch : lookupswitch;
+ // instruction. The difference in computation cost is
+ // proportional to log(#cases), which is negligable, so we only
+ // consider the size of the bytecode.
+ // A discussion of the metric can be found here:
+ // http://mail.openjdk.java.net/pipermail/compiler-dev/2014-September/008987.html
+ int table_cost = 4 + (hi - lo + 1); // words
+ int lookup_cost = 3 + 2 * nlabels;
+ int opcode = table_cost <= lookup_cost ? tableswitch : lookupswitch;
int startpc = code.curCP(); // the position of the selector operation
code.emitop0(opcode);
From 1eb03e49bfdb332c45c39a38922094d398d56d37 Mon Sep 17 00:00:00 2001
From: Jan Lahoda
Date: Mon, 13 Oct 2014 17:22:47 +0200
Subject: [PATCH 44/82] 8054956: Javac reports wrong error offset for unknown
identifier of annotation element/value pair
When reporting an error about unresolvable annotation attribute, use the position of the explicit left-hand-side of the assignment if available, otherwise use the position of the right-hand-side.
Reviewed-by: jfranck
---
.../share/classes/com/sun/tools/javac/comp/Annotate.java | 4 +++-
langtools/test/tools/javac/annotations/neg/Recovery1.out | 2 +-
langtools/test/tools/javac/positions/TreeEndPosTest.java | 8 +++++++-
3 files changed, 11 insertions(+), 3 deletions(-)
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java
index de6383a051c..d3d3eecced9 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java
@@ -315,8 +315,10 @@ public class Annotate {
isError = true;
}
List args = a.args;
+ boolean elidedValue = false;
if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
// special case: elided "value=" assumed
+ elidedValue = true;
args.head = make.at(args.head.pos).
Assign(make.Ident(names.value), args.head);
}
@@ -336,7 +338,7 @@ public class Annotate {
continue;
}
JCIdent left = (JCIdent)assign.lhs;
- Symbol method = rs.resolveQualifiedMethod(assign.rhs.pos(),
+ Symbol method = rs.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(),
env,
a.type,
left.name,
diff --git a/langtools/test/tools/javac/annotations/neg/Recovery1.out b/langtools/test/tools/javac/annotations/neg/Recovery1.out
index 1f7ec2df0c2..ba6a327dd65 100644
--- a/langtools/test/tools/javac/annotations/neg/Recovery1.out
+++ b/langtools/test/tools/javac/annotations/neg/Recovery1.out
@@ -1,4 +1,4 @@
Recovery1.java:14:5: compiler.err.cant.resolve.location: kindname.class, Marker, , , (compiler.misc.location: kindname.annotation, recovery1.MyAnnotation, null)
Recovery1.java:14:30: compiler.err.cant.resolve.location: kindname.class, Marker, , , (compiler.misc.location: kindname.annotation, recovery1.MyAnnotation, null)
-Recovery1.java:18:43: compiler.err.cant.resolve.location.args: kindname.method, markerToo, , , (compiler.misc.location: kindname.annotation, recovery1.MyAnnotation, null)
+Recovery1.java:18:33: compiler.err.cant.resolve.location.args: kindname.method, markerToo, , , (compiler.misc.location: kindname.annotation, recovery1.MyAnnotation, null)
3 errors
diff --git a/langtools/test/tools/javac/positions/TreeEndPosTest.java b/langtools/test/tools/javac/positions/TreeEndPosTest.java
index 961803762e1..e8c6c8689d0 100644
--- a/langtools/test/tools/javac/positions/TreeEndPosTest.java
+++ b/langtools/test/tools/javac/positions/TreeEndPosTest.java
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 8017216 8019422 8019421
+ * @bug 8017216 8019422 8019421 8054956
* @summary verify start and end positions
* @run main TreeEndPosTest
*/
@@ -102,6 +102,7 @@ public class TreeEndPosTest {
public static void main(String... args) throws IOException {
testUninitializedVariable();
testMissingAnnotationValue();
+ testUnresolvableAnnotationAttribute();
testFinalVariableWithDefaultConstructor();
testFinalVariableWithConstructor();
}
@@ -115,6 +116,11 @@ public class TreeEndPosTest {
null, "@interface Foo { }", "\"vvvv\""));
}
+ static void testUnresolvableAnnotationAttribute() throws IOException {
+ compile(JavaSource.createJavaSource("@Foo(value=\"vvvv\")",
+ null, "@interface Foo { }", "value"));
+ }
+
static void testFinalVariableWithDefaultConstructor() throws IOException {
compile(JavaSource.createJavaSource("private static final String Foo; public void bar() { }",
"private static final String Foo;"));
From ef05cafd6b910c21cf9e262170dfd70336f2e65a Mon Sep 17 00:00:00 2001
From: Paul Govereau
Date: Mon, 13 Oct 2014 12:12:06 -0400
Subject: [PATCH 45/82] 8060234: Fix push for JDK-8058243
Reviewed-by: jjg, vromero
---
.../classes/com/sun/tools/javac/jvm/Gen.java | 4 +-
.../test/tools/javac/SwitchMetricTest.java | 88 +++++++++++++++++++
2 files changed, 90 insertions(+), 2 deletions(-)
create mode 100644 langtools/test/tools/javac/SwitchMetricTest.java
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
index 959a76201fe..b5ed1f5aedb 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
@@ -1225,8 +1225,8 @@ public class Gen extends JCTree.Visitor {
// consider the size of the bytecode.
// A discussion of the metric can be found here:
// http://mail.openjdk.java.net/pipermail/compiler-dev/2014-September/008987.html
- int table_cost = 4 + (hi - lo + 1); // words
- int lookup_cost = 3 + 2 * nlabels;
+ long table_cost = 4 + ((long)hi - lo + 1); // words
+ long lookup_cost = 3 + 2 * (long)nlabels;
int opcode = table_cost <= lookup_cost ? tableswitch : lookupswitch;
int startpc = code.curCP(); // the position of the selector operation
diff --git a/langtools/test/tools/javac/SwitchMetricTest.java b/langtools/test/tools/javac/SwitchMetricTest.java
new file mode 100644
index 00000000000..74ac6f7dba4
--- /dev/null
+++ b/langtools/test/tools/javac/SwitchMetricTest.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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 8058243
+ * @summary Reduce size of bytecode for large switch statements
+ * @library /tools/lib
+ * @build ToolBox
+ * @run main SwitchMetricTest
+ */
+
+import java.net.URL;
+import java.util.List;
+
+public class SwitchMetricTest {
+ public static void main(String... args) throws Exception {
+ new SwitchMetricTest().run();
+ }
+
+ // This code should produce a tableswitch
+ class Test1 {
+ int m(int x) {
+ switch (x) {
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5: return 1;
+ default: return 0;
+ }
+ }
+ }
+
+ // This code should produce a lookupswitch
+ class Test2 {
+ int m(int x) {
+ switch (x) {
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 50: return 1;
+ default: return 0;
+ }
+ }
+ }
+
+ void check(String classfile, String bytecode) throws Exception {
+ ToolBox tb = new ToolBox();
+ URL url = SwitchMetricTest.class.getResource(classfile);
+ List result = tb.new JavapTask()
+ .options("-c")
+ .classes(url.getFile())
+ .run()
+ .write(ToolBox.OutputKind.DIRECT)
+ .getOutputLines(ToolBox.OutputKind.DIRECT);
+
+ List matches = tb.grep(bytecode, result);
+ if (matches.isEmpty())
+ throw new Exception(bytecode + " not found");
+ }
+
+ void run() throws Exception {
+ check("SwitchMetricTest$Test1.class", "tableswitch");
+ check("SwitchMetricTest$Test2.class", "lookupswitch");
+ }
+}
From 2d6eed916f15524814cd0db806ce35a36654b543 Mon Sep 17 00:00:00 2001
From: Athijegannathan Sundararajan
Date: Mon, 13 Oct 2014 23:38:49 +0530
Subject: [PATCH 46/82] 8050977: Java8 Javascript Nashorn exception: no current
Global instance for nashorn
Reviewed-by: attila, lagergren, hannesw
---
.../api/scripting/NashornScriptEngine.java | 28 +-----
.../nashorn/api/scripting/ScriptUtils.java | 20 ++--
.../internal/codegen/MethodEmitter.java | 10 +-
.../nashorn/internal/objects/NativeJava.java | 6 +-
.../linker/JavaAdapterBytecodeGenerator.java | 33 ++++++-
.../linker/JavaAdapterClassLoader.java | 3 +-
.../runtime/linker/JavaAdapterServices.java | 3 +-
.../runtime/linker/NashornBeansLinker.java | 91 ++++++++++++++++---
.../runtime/linker/NashornLinker.java | 2 +-
.../runtime/resources/mozilla_compat.js | 4 +-
nashorn/test/script/basic/convert.js | 2 +-
nashorn/test/script/nosecurity/JDK-8044798.js | 2 +
.../scripting/ScriptEngineSecurityTest.java | 36 --------
.../api/scripting/ScriptEngineTest.java | 35 +++++++
14 files changed, 177 insertions(+), 98 deletions(-)
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngine.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngine.java
index bbf1eecfb49..2f000954815 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngine.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngine.java
@@ -229,6 +229,8 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
}
private T getInterfaceInner(final Object thiz, final Class clazz) {
+ assert !(thiz instanceof ScriptObject) : "raw ScriptObject not expected here";
+
if (clazz == null || !clazz.isInterface()) {
throw new IllegalArgumentException(getMessage("interface.class.expected"));
}
@@ -251,17 +253,6 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
final ScriptObjectMirror mirror = (ScriptObjectMirror)thiz;
realSelf = mirror.getScriptObject();
realGlobal = mirror.getHomeGlobal();
- if (! isOfContext(realGlobal, nashornContext)) {
- throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
- }
- } else if (thiz instanceof ScriptObject) {
- // called from script code.
- realSelf = (ScriptObject)thiz;
- realGlobal = Context.getGlobal();
- if (realGlobal == null) {
- throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
- }
-
if (! isOfContext(realGlobal, nashornContext)) {
throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
}
@@ -368,6 +359,7 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
name.getClass(); // null check
+ assert !(selfObject instanceof ScriptObject) : "raw ScriptObject not expected here";
Global invokeGlobal = null;
ScriptObjectMirror selfMirror = null;
@@ -377,20 +369,6 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
}
invokeGlobal = selfMirror.getHomeGlobal();
- } else if (selfObject instanceof ScriptObject) {
- // invokeMethod called from script code - in which case we may get 'naked' ScriptObject
- // Wrap it with oldGlobal to make a ScriptObjectMirror for the same.
- final Global oldGlobal = Context.getGlobal();
- invokeGlobal = oldGlobal;
- if (oldGlobal == null) {
- throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
- }
-
- if (! isOfContext(oldGlobal, nashornContext)) {
- throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
- }
-
- selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(selfObject, oldGlobal);
} else if (selfObject == null) {
// selfObject is null => global function call
final Global ctxtGlobal = getNashornGlobalFrom(context);
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java
index 4de2cbf5516..b6c4c97e547 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java
@@ -75,11 +75,8 @@ public final class ScriptUtils {
* @param sync the object to synchronize on
* @return a synchronizing wrapper function
*/
- public static Object makeSynchronizedFunction(final Object func, final Object sync) {
- if (func instanceof ScriptFunction) {
- return ((ScriptFunction)func).makeSynchronizedFunction(sync);
- }
- throw typeError("not.a.function", ScriptRuntime.safeToString(func));
+ public static Object makeSynchronizedFunction(final ScriptFunction func, final Object sync) {
+ return func.makeSynchronizedFunction(unwrap(sync));
}
/**
@@ -88,12 +85,8 @@ public final class ScriptUtils {
* @param obj object to be wrapped
* @return wrapped object
*/
- public static Object wrap(final Object obj) {
- if (obj instanceof ScriptObject) {
- return ScriptObjectMirror.wrap(obj, Context.getGlobal());
- }
-
- return obj;
+ public static ScriptObjectMirror wrap(final ScriptObject obj) {
+ return (ScriptObjectMirror) ScriptObjectMirror.wrap(obj, Context.getGlobal());
}
/**
@@ -160,14 +153,15 @@ public final class ScriptUtils {
}
final LinkerServices linker = Bootstrap.getLinkerServices();
- final MethodHandle converter = linker.getTypeConverter(obj.getClass(), clazz);
+ final Object objToConvert = unwrap(obj);
+ final MethodHandle converter = linker.getTypeConverter(objToConvert.getClass(), clazz);
if (converter == null) {
// no supported conversion!
throw new UnsupportedOperationException("conversion not supported");
}
try {
- return converter.invoke(obj);
+ return converter.invoke(objToConvert);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/MethodEmitter.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/MethodEmitter.java
index 20914472ce6..2df1ae90b88 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/MethodEmitter.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/MethodEmitter.java
@@ -98,6 +98,7 @@ import jdk.nashorn.internal.ir.LocalVariableConversion;
import jdk.nashorn.internal.ir.RuntimeNode;
import jdk.nashorn.internal.ir.Symbol;
import jdk.nashorn.internal.ir.TryNode;
+import jdk.nashorn.internal.objects.NativeArray;
import jdk.nashorn.internal.runtime.ArgumentSetter;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.Debug;
@@ -2125,7 +2126,14 @@ public class MethodEmitter implements Emitter {
int pos = 0;
for (int i = argCount - 1; i >= 0; i--) {
- paramTypes[i] = stack.peek(pos++);
+ Type pt = stack.peek(pos++);
+ // "erase" specific ScriptObject subtype info - except for NativeArray.
+ // NativeArray is used for array/List/Deque conversion for Java calls.
+ if (ScriptObject.class.isAssignableFrom(pt.getTypeClass()) &&
+ !NativeArray.class.isAssignableFrom(pt.getTypeClass())) {
+ pt = Type.SCRIPT_OBJECT;
+ }
+ paramTypes[i] = pt;
}
final String descriptor = Type.getMethodDescriptor(returnType, paramTypes);
for (int i = 0; i < argCount; i++) {
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
index 4395e081e70..7c6e60a967d 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
@@ -90,7 +90,11 @@ public final class NativeJava {
*/
@Function(name="synchronized", attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object synchronizedFunc(final Object self, final Object func, final Object obj) {
- return ScriptUtils.makeSynchronizedFunction(func, obj);
+ if (func instanceof ScriptFunction) {
+ return ((ScriptFunction)func).makeSynchronizedFunction(obj);
+ }
+
+ throw typeError("not.a.function", ScriptRuntime.safeToString(func));
}
/**
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java
index 44ea184656d..7986b8b4c7c 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java
@@ -152,6 +152,7 @@ final class JavaAdapterBytecodeGenerator {
static final String SET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE, OBJECT_TYPE);
static final String VOID_NOARG_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE);
+ private static final Type SCRIPT_OBJECT_TYPE = Type.getType(ScriptObject.class);
private static final Type SCRIPT_FUNCTION_TYPE = Type.getType(ScriptFunction.class);
private static final Type STRING_TYPE = Type.getType(String.class);
private static final Type METHOD_TYPE_TYPE = Type.getType(MethodType.class);
@@ -536,8 +537,8 @@ final class JavaAdapterBytecodeGenerator {
final int argLen = originalArgTypes.length;
final Type[] newArgTypes = new Type[argLen + 1];
- // Insert ScriptFunction|Object as the last argument to the constructor
- final Type extraArgumentType = fromFunction ? SCRIPT_FUNCTION_TYPE : OBJECT_TYPE;
+ // Insert ScriptFunction|ScriptObject as the last argument to the constructor
+ final Type extraArgumentType = fromFunction ? SCRIPT_FUNCTION_TYPE : SCRIPT_OBJECT_TYPE;
newArgTypes[argLen] = extraArgumentType;
System.arraycopy(originalArgTypes, 0, newArgTypes, 0, argLen);
@@ -588,6 +589,34 @@ final class JavaAdapterBytecodeGenerator {
// Initialize converters
generateConverterInit(mv, fromFunction);
endInitMethod(mv);
+
+ if (! fromFunction) {
+ newArgTypes[argLen] = OBJECT_TYPE;
+ final InstructionAdapter mv2 = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC, INIT,
+ Type.getMethodDescriptor(originalCtorType.getReturnType(), newArgTypes), null, null));
+ generateOverridingConstructorWithObjectParam(mv2, ctor, originalCtorType.getDescriptor());
+ }
+ }
+
+ // Object additional param accepting constructor - generated to handle null and undefined value
+ // for script adapters. This is effectively to throw TypeError on such script adapters. See
+ // JavaAdapterServices.getHandle as well.
+ private void generateOverridingConstructorWithObjectParam(final InstructionAdapter mv, final Constructor> ctor, final String ctorDescriptor) {
+ mv.visitCode();
+ mv.visitVarInsn(ALOAD, 0);
+ final Class>[] argTypes = ctor.getParameterTypes();
+ int offset = 1; // First arg is at position 1, after this.
+ for (int i = 0; i < argTypes.length; ++i) {
+ final Type argType = Type.getType(argTypes[i]);
+ mv.load(offset, argType);
+ offset += argType.getSize();
+ }
+ mv.invokespecial(superClassName, INIT, ctorDescriptor, false);
+ mv.visitVarInsn(ALOAD, offset);
+ mv.visitInsn(ACONST_NULL);
+ mv.visitInsn(ACONST_NULL);
+ mv.invokestatic(SERVICES_CLASS_TYPE_NAME, "getHandle", GET_HANDLE_OBJECT_DESCRIPTOR, false);
+ endInitMethod(mv);
}
private static void endInitMethod(final InstructionAdapter mv) {
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterClassLoader.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterClassLoader.java
index f5ba8b12c6d..77004978eb7 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterClassLoader.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterClassLoader.java
@@ -39,6 +39,7 @@ import jdk.nashorn.internal.codegen.DumpBytecode;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptFunction;
+import jdk.nashorn.internal.runtime.ScriptObject;
/**
* This class encapsulates the bytecode of the adapter class and can be used to load it into the JVM as an actual Class.
@@ -51,7 +52,7 @@ final class JavaAdapterClassLoader {
private static final AccessControlContext CREATE_LOADER_ACC_CTXT = ClassAndLoader.createPermAccCtxt("createClassLoader");
private static final AccessControlContext GET_CONTEXT_ACC_CTXT = ClassAndLoader.createPermAccCtxt(Context.NASHORN_GET_CONTEXT);
private static final Collection VISIBLE_INTERNAL_CLASS_NAMES = Collections.unmodifiableCollection(new HashSet<>(
- Arrays.asList(JavaAdapterServices.class.getName(), ScriptFunction.class.getName(), JSType.class.getName())));
+ Arrays.asList(JavaAdapterServices.class.getName(), ScriptObject.class.getName(), ScriptFunction.class.getName(), JSType.class.getName())));
private final String className;
private final byte[] classBytes;
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java
index ef91f35c097..08e4682181d 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java
@@ -47,7 +47,6 @@ import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.commons.InstructionAdapter;
-import jdk.nashorn.api.scripting.ScriptUtils;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
@@ -220,7 +219,7 @@ public final class JavaAdapterServices {
* @return the filtered return value.
*/
public static Object exportReturnValue(final Object obj) {
- return ScriptUtils.wrap(NashornBeansLinker.exportArgument(obj));
+ return NashornBeansLinker.exportArgument(obj, true);
}
/**
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java
index f802e039607..25ba619b7ad 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java
@@ -35,17 +35,28 @@ import jdk.internal.dynalink.linker.GuardingDynamicLinker;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.internal.dynalink.support.Lookup;
+import jdk.nashorn.api.scripting.ScriptUtils;
+import jdk.nashorn.internal.objects.NativeArray;
import jdk.nashorn.internal.runtime.ConsString;
+import jdk.nashorn.internal.runtime.ScriptObject;
+import jdk.nashorn.internal.runtime.options.Options;
/**
* This linker delegates to a {@code BeansLinker} but passes it a special linker services object that has a modified
* {@code asType} method that will ensure that we never pass internal engine objects that should not be externally
- * observable (currently only ConsString) to Java APIs, but rather that we flatten it into a String. We can't just add
+ * observable (currently ConsString and ScriptObject) to Java APIs, but rather that we flatten it into a String. We can't just add
* this functionality as custom converters via {@code GuaardingTypeConverterFactory}, since they are not consulted when
* the target method handle parameter signature is {@code Object}.
*/
public class NashornBeansLinker implements GuardingDynamicLinker {
+ // System property to control whether to wrap ScriptObject->ScriptObjectMirror for
+ // Object type arguments of Java method calls, field set and array set.
+ private static final boolean MIRROR_ALWAYS = Options.getBooleanProperty("nashorn.mirror.always", true);
+
private static final MethodHandle EXPORT_ARGUMENT = new Lookup(MethodHandles.lookup()).findOwnStatic("exportArgument", Object.class, Object.class);
+ private static final MethodHandle EXPORT_NATIVE_ARRAY = new Lookup(MethodHandles.lookup()).findOwnStatic("exportNativeArray", Object.class, NativeArray.class);
+ private static final MethodHandle EXPORT_SCRIPT_OBJECT = new Lookup(MethodHandles.lookup()).findOwnStatic("exportScriptObject", Object.class, ScriptObject.class);
+ private static final MethodHandle IMPORT_RESULT = new Lookup(MethodHandles.lookup()).findOwnStatic("importResult", Object.class, Object.class);
private final BeansLinker beansLinker = new BeansLinker();
@@ -67,8 +78,39 @@ public class NashornBeansLinker implements GuardingDynamicLinker {
return delegateLinker.getGuardedInvocation(linkRequest, new NashornBeansLinkerServices(linkerServices));
}
- static Object exportArgument(final Object arg) {
- return arg instanceof ConsString ? arg.toString() : arg;
+ @SuppressWarnings("unused")
+ private static Object exportArgument(final Object arg) {
+ return exportArgument(arg, MIRROR_ALWAYS);
+ }
+
+ @SuppressWarnings("unused")
+ private static Object exportNativeArray(final NativeArray arg) {
+ return exportArgument(arg, MIRROR_ALWAYS);
+ }
+
+ @SuppressWarnings("unused")
+ private static Object exportScriptObject(final ScriptObject arg) {
+ return exportArgument(arg, MIRROR_ALWAYS);
+ }
+
+ @SuppressWarnings("unused")
+ private static Object exportScriptArray(final NativeArray arg) {
+ return exportArgument(arg, MIRROR_ALWAYS);
+ }
+
+ static Object exportArgument(final Object arg, final boolean mirrorAlways) {
+ if (arg instanceof ConsString) {
+ return arg.toString();
+ } else if (mirrorAlways && arg instanceof ScriptObject) {
+ return ScriptUtils.wrap((ScriptObject)arg);
+ } else {
+ return arg;
+ }
+ }
+
+ @SuppressWarnings("unused")
+ private static Object importResult(final Object arg) {
+ return ScriptUtils.unwrap(arg);
}
private static class NashornBeansLinkerServices implements LinkerServices {
@@ -80,23 +122,50 @@ public class NashornBeansLinker implements GuardingDynamicLinker {
@Override
public MethodHandle asType(final MethodHandle handle, final MethodType fromType) {
- final MethodHandle typed = linkerServices.asType(handle, fromType);
-
final MethodType handleType = handle.type();
final int paramCount = handleType.parameterCount();
assert fromType.parameterCount() == handleType.parameterCount();
+ MethodType newFromType = fromType;
MethodHandle[] filters = null;
for(int i = 0; i < paramCount; ++i) {
- if(shouldConvert(handleType.parameterType(i), fromType.parameterType(i))) {
- if(filters == null) {
+ final MethodHandle filter = argConversionFilter(handleType.parameterType(i), fromType.parameterType(i));
+ if (filter != null) {
+ if (filters == null) {
filters = new MethodHandle[paramCount];
}
- filters[i] = EXPORT_ARGUMENT;
+ // "erase" specific type with Object type or else we'll get filter mismatch
+ newFromType = newFromType.changeParameterType(i, Object.class);
+ filters[i] = filter;
}
}
- return filters != null ? MethodHandles.filterArguments(typed, 0, filters) : typed;
+ final MethodHandle typed = linkerServices.asType(handle, newFromType);
+ MethodHandle result = filters != null ? MethodHandles.filterArguments(typed, 0, filters) : typed;
+ // Filter Object typed return value for possible ScriptObjectMirror. We convert
+ // ScriptObjectMirror as ScriptObject (if it is mirror from current global).
+ if (MIRROR_ALWAYS && areBothObjects(handleType.returnType(), fromType.returnType())) {
+ result = MethodHandles.filterReturnValue(result, IMPORT_RESULT);
+ }
+
+ return result;
+ }
+
+ private static MethodHandle argConversionFilter(final Class> handleType, final Class> fromType) {
+ if (handleType == Object.class) {
+ if (fromType == Object.class) {
+ return EXPORT_ARGUMENT;
+ } else if (fromType == NativeArray.class) {
+ return EXPORT_NATIVE_ARRAY;
+ } else if (fromType == ScriptObject.class) {
+ return EXPORT_SCRIPT_OBJECT;
+ }
+ }
+ return null;
+ }
+
+ private static boolean areBothObjects(final Class> handleType, final Class> fromType) {
+ return handleType == Object.class && fromType == Object.class;
}
@Override
@@ -104,10 +173,6 @@ public class NashornBeansLinker implements GuardingDynamicLinker {
return Implementation.asTypeLosslessReturn(this, handle, fromType);
}
- private static boolean shouldConvert(final Class> handleType, final Class> fromType) {
- return handleType == Object.class && fromType == Object.class;
- }
-
@Override
public MethodHandle getTypeConverter(final Class> sourceType, final Class> targetType) {
return linkerServices.getTypeConverter(sourceType, targetType);
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java
index bde01567aa1..75af367f08d 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java
@@ -292,7 +292,7 @@ final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTyp
@SuppressWarnings("unused")
private static Object createMirror(final Object obj) {
- return ScriptUtils.wrap(obj);
+ return obj instanceof ScriptObject? ScriptUtils.wrap((ScriptObject)obj) : obj;
}
private static MethodHandle findOwnMH(final String name, final Class> rtype, final Class>... types) {
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/mozilla_compat.js b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/mozilla_compat.js
index 85e2161c004..6c27e2a6fbc 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/mozilla_compat.js
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/mozilla_compat.js
@@ -105,7 +105,7 @@ Object.defineProperty(this, "sync", {
if (arguments.length < 1 || arguments.length > 2 ) {
throw "sync(function [,object]) parameter count mismatch";
}
- return Packages.jdk.nashorn.api.scripting.ScriptUtils.makeSynchronizedFunction(func, syncobj);
+ return Java.synchronized(func, syncobj);
}
});
@@ -160,7 +160,7 @@ Object.defineProperty(Object.prototype, "toSource", {
configurable: true, enumerable: false, writable: true,
value: function(state) {
if (! state) {
- state = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap());
+ state = java.util.Collections.newSetFromMap(new java.util.HashMap());
}
if (state.contains(this)) {
return "{}";
diff --git a/nashorn/test/script/basic/convert.js b/nashorn/test/script/basic/convert.js
index 3a1bca08771..2c87661c74a 100644
--- a/nashorn/test/script/basic/convert.js
+++ b/nashorn/test/script/basic/convert.js
@@ -42,7 +42,7 @@ print(list);
// object to Map
obj = { foo: 333, bar: 'hello'};
-var map = ScriptUtils.convert(obj, java.util.Map.class);
+var map = ScriptUtils.wrap(obj);
print(map instanceof java.util.Map);
for (m in map) {
print(m + " " + map[m]);
diff --git a/nashorn/test/script/nosecurity/JDK-8044798.js b/nashorn/test/script/nosecurity/JDK-8044798.js
index c3b6d4cb945..c24edf2181b 100644
--- a/nashorn/test/script/nosecurity/JDK-8044798.js
+++ b/nashorn/test/script/nosecurity/JDK-8044798.js
@@ -25,6 +25,8 @@
* JDK-8044798: API for debugging Nashorn
*
* @test
+ * @option -Dnashorn.mirror.always=false
+ * @fork
* @run
*/
diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineSecurityTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineSecurityTest.java
index 09199a52703..226832e7d82 100644
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineSecurityTest.java
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineSecurityTest.java
@@ -168,42 +168,6 @@ public class ScriptEngineSecurityTest {
}
}
- @Test
- /**
- * Check that script can't implement sensitive package interfaces.
- */
- public void checkSensitiveInterfaceImplTest() throws ScriptException {
- if (System.getSecurityManager() == null) {
- // pass vacuously
- return;
- }
-
- final ScriptEngineManager m = new ScriptEngineManager();
- final ScriptEngine e = m.getEngineByName("nashorn");
- final Object[] holder = new Object[1];
- e.put("holder", holder);
- // put an empty script object into array
- e.eval("holder[0] = {}");
- // holder[0] is an object of some subclass of ScriptObject
- final Class> ScriptObjectClass = holder[0].getClass().getSuperclass();
- final Class> PropertyAccessClass = ScriptObjectClass.getInterfaces()[0];
- // implementation methods for PropertyAccess class
- e.eval("function set() {}; function get() {}; function getInt(){} " +
- "function getDouble(){}; function getLong() {}; " +
- "this.delete = function () {}; function has() {}; " +
- "function hasOwnProperty() {}");
-
- // get implementation of a restricted package interface
- try {
- log(Objects.toString(((Invocable)e).getInterface((Class>)PropertyAccessClass)));
- fail("should have thrown SecurityException");
- } catch (final Exception exp) {
- if (! (exp instanceof SecurityException)) {
- fail("SecurityException expected, got " + exp);
- }
- }
- }
-
// @bug 8032948: Nashorn linkages awry
public static class FakeProxy extends Proxy {
public FakeProxy(final InvocationHandler ih) {
diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java
index 291e8d424c4..124b5a92a80 100644
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java
@@ -38,6 +38,7 @@ import java.lang.reflect.Proxy;
import java.util.concurrent.Callable;
import javax.script.Compilable;
import javax.script.CompiledScript;
+import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
@@ -629,6 +630,40 @@ public class ScriptEngineTest {
assertEquals(enumerable, Boolean.FALSE);
}
+ public static class Context {
+ private Object myobj;
+
+ public void set(Object o) {
+ myobj = o;
+ }
+
+ public Object get() {
+ return myobj;
+ }
+ }
+
+ // @bug 8050977: Java8 Javascript Nashorn exception:
+ // no current Global instance for nashorn
+ @Test
+ public void currentGlobalMissingTest() throws Exception {
+ final ScriptEngineManager manager = new ScriptEngineManager();
+ final ScriptEngine e = manager.getEngineByName("nashorn");
+
+ final Context ctx = new Context();
+ e.put("ctx", ctx);
+ e.eval("var obj = { foo: function(str) { return str.toUpperCase() } }");
+ e.eval("ctx.set(obj)");
+ final Invocable inv = (Invocable)e;
+ assertEquals("HELLO", inv.invokeMethod(ctx.get(), "foo", "hello"));
+ // try object literal
+ e.eval("ctx.set({ bar: function(str) { return str.toLowerCase() } })");
+ assertEquals("hello", inv.invokeMethod(ctx.get(), "bar", "HELLO"));
+ // try array literal
+ e.eval("var arr = [ 'hello', 'world' ]");
+ e.eval("ctx.set(arr)");
+ assertEquals("helloworld", inv.invokeMethod(ctx.get(), "join", ""));
+ }
+
private static void checkProperty(final ScriptEngine e, final String name)
throws ScriptException {
final String value = System.getProperty(name);
From c03284412182d24d955ff53b1e54f8a33ef63e29 Mon Sep 17 00:00:00 2001
From: Attila Szegedi
Date: Mon, 13 Oct 2014 20:10:14 +0200
Subject: [PATCH 47/82] 8059842: Creating symbols for declared functions
shouldn't be a special case
Reviewed-by: hannesw, lagergren
---
.../internal/codegen/AssignSymbols.java | 34 ++++++++++++-------
.../jdk/nashorn/internal/ir/VarNode.java | 8 +++++
2 files changed, 30 insertions(+), 12 deletions(-)
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java
index fa2b8a198bd..f83dc9ccdd1 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java
@@ -511,16 +511,6 @@ final class AssignSymbols extends NodeVisitor implements Loggabl
thisProperties.push(new HashSet());
- if (functionNode.isDeclared()) {
- // Can't use lc.getCurrentBlock() as we can have an outermost function in our lexical context that
- // is not a program - it is a function being compiled on-demand.
- final Iterator blocks = lc.getBlocks();
- if (blocks.hasNext()) {
- final IdentNode ident = functionNode.getIdent();
- defineSymbol(blocks.next(), ident.getName(), ident, IS_VAR | (functionNode.isAnonymous()? IS_INTERNAL : 0));
- }
- }
-
// Every function has a body, even the ones skipped on reparse (they have an empty one). We're
// asserting this as even for those, enterBlock() must be invoked to correctly process symbols that
// are used in them.
@@ -532,16 +522,36 @@ final class AssignSymbols extends NodeVisitor implements Loggabl
@Override
public boolean enterVarNode(final VarNode varNode) {
start(varNode);
+ // Normally, a symbol assigned in a var statement is not live for its RHS. Since we also represent function
+ // declarations as VarNodes, they are exception to the rule, as they need to have the symbol visible to the
+ // body of the declared function for self-reference.
+ if (varNode.isFunctionDeclaration()) {
+ defineVarIdent(varNode);
+ }
return true;
}
@Override
public Node leaveVarNode(final VarNode varNode) {
- final IdentNode ident = varNode.getName();
- defineSymbol(lc.getCurrentBlock(), ident.getName(), ident, varNode.getSymbolFlags() | (lc.getCurrentFunction().isProgram() ? IS_SCOPE : 0));
+ if (!varNode.isFunctionDeclaration()) {
+ defineVarIdent(varNode);
+ }
return super.leaveVarNode(varNode);
}
+ private void defineVarIdent(final VarNode varNode) {
+ final IdentNode ident = varNode.getName();
+ final int flags;
+ if (varNode.isAnonymousFunctionDeclaration()) {
+ flags = IS_INTERNAL;
+ } else if (lc.getCurrentFunction().isProgram()) {
+ flags = IS_SCOPE;
+ } else {
+ flags = 0;
+ }
+ defineSymbol(lc.getCurrentBlock(), ident.getName(), ident, varNode.getSymbolFlags() | flags);
+ }
+
private Symbol exceptionSymbol() {
return newObjectInternal(EXCEPTION_PREFIX);
}
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/VarNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/VarNode.java
index f9aef826fe6..a8db410042e 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/VarNode.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/VarNode.java
@@ -272,4 +272,12 @@ public final class VarNode extends Statement implements Assignment {
public boolean isFunctionDeclaration() {
return init instanceof FunctionNode && ((FunctionNode)init).isDeclared();
}
+
+ /**
+ * Returns true if this is an anonymous function declaration.
+ * @return true if this is an anonymous function declaration.
+ */
+ public boolean isAnonymousFunctionDeclaration() {
+ return isFunctionDeclaration() && ((FunctionNode)init).isAnonymous();
+ }
}
From 8cc03657e9b976696230b3e925743b7cf319aae1 Mon Sep 17 00:00:00 2001
From: Paul Govereau
Date: Mon, 13 Oct 2014 17:09:12 -0400
Subject: [PATCH 48/82] 8060249: Backout fix for JDK-8058243
Reviewed-by: vromero
---
.../classes/com/sun/tools/javac/jvm/Gen.java | 19 ++--
.../test/tools/javac/SwitchMetricTest.java | 88 -------------------
2 files changed, 11 insertions(+), 96 deletions(-)
delete mode 100644 langtools/test/tools/javac/SwitchMetricTest.java
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
index b5ed1f5aedb..553bf403469 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
@@ -1220,14 +1220,17 @@ public class Gen extends JCTree.Visitor {
}
// Determine whether to issue a tableswitch or a lookupswitch
- // instruction. The difference in computation cost is
- // proportional to log(#cases), which is negligable, so we only
- // consider the size of the bytecode.
- // A discussion of the metric can be found here:
- // http://mail.openjdk.java.net/pipermail/compiler-dev/2014-September/008987.html
- long table_cost = 4 + ((long)hi - lo + 1); // words
- long lookup_cost = 3 + 2 * (long)nlabels;
- int opcode = table_cost <= lookup_cost ? tableswitch : lookupswitch;
+ // instruction.
+ long table_space_cost = 4 + ((long) hi - lo + 1); // words
+ long table_time_cost = 3; // comparisons
+ long lookup_space_cost = 3 + 2 * (long) nlabels;
+ long lookup_time_cost = nlabels;
+ int opcode =
+ nlabels > 0 &&
+ table_space_cost + 3 * table_time_cost <=
+ lookup_space_cost + 3 * lookup_time_cost
+ ?
+ tableswitch : lookupswitch;
int startpc = code.curCP(); // the position of the selector operation
code.emitop0(opcode);
diff --git a/langtools/test/tools/javac/SwitchMetricTest.java b/langtools/test/tools/javac/SwitchMetricTest.java
deleted file mode 100644
index 74ac6f7dba4..00000000000
--- a/langtools/test/tools/javac/SwitchMetricTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * 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 8058243
- * @summary Reduce size of bytecode for large switch statements
- * @library /tools/lib
- * @build ToolBox
- * @run main SwitchMetricTest
- */
-
-import java.net.URL;
-import java.util.List;
-
-public class SwitchMetricTest {
- public static void main(String... args) throws Exception {
- new SwitchMetricTest().run();
- }
-
- // This code should produce a tableswitch
- class Test1 {
- int m(int x) {
- switch (x) {
- case 1:
- case 2:
- case 3:
- case 4:
- case 5: return 1;
- default: return 0;
- }
- }
- }
-
- // This code should produce a lookupswitch
- class Test2 {
- int m(int x) {
- switch (x) {
- case 1:
- case 2:
- case 3:
- case 4:
- case 50: return 1;
- default: return 0;
- }
- }
- }
-
- void check(String classfile, String bytecode) throws Exception {
- ToolBox tb = new ToolBox();
- URL url = SwitchMetricTest.class.getResource(classfile);
- List result = tb.new JavapTask()
- .options("-c")
- .classes(url.getFile())
- .run()
- .write(ToolBox.OutputKind.DIRECT)
- .getOutputLines(ToolBox.OutputKind.DIRECT);
-
- List matches = tb.grep(bytecode, result);
- if (matches.isEmpty())
- throw new Exception(bytecode + " not found");
- }
-
- void run() throws Exception {
- check("SwitchMetricTest$Test1.class", "tableswitch");
- check("SwitchMetricTest$Test2.class", "lookupswitch");
- }
-}
From 8f96799dd526960efdde91cbc80e99c94d0557da Mon Sep 17 00:00:00 2001
From: Maurizio Cimadamore
Date: Tue, 14 Oct 2014 12:00:39 +0100
Subject: [PATCH 49/82] 8058199: Code generation problem with javac skipping a
checkcast instruction
TransTypes sometimes ignores inferred signatures when emitting synthetic casts
Reviewed-by: vromero
---
.../com/sun/tools/javac/comp/TransTypes.java | 34 +++++++--
.../generics/inference/8058199/T8058199.java | 75 +++++++++++++++++++
2 files changed, 101 insertions(+), 8 deletions(-)
create mode 100644 langtools/test/tools/javac/generics/inference/8058199/T8058199.java
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
index 9b7a6c6784a..3c60e5ff5f4 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
@@ -67,12 +67,16 @@ public class TransTypes extends TreeTranslator {
private Symtab syms;
private TreeMaker make;
private Enter enter;
- private boolean allowInterfaceBridges;
private Types types;
private final Resolve resolve;
-
private final CompileStates compileStates;
+ /** Switch: is complex graph inference supported? */
+ private final boolean allowGraphInference;
+
+ /** Switch: are default methods supported? */
+ private final boolean allowInterfaceBridges;
+
protected TransTypes(Context context) {
context.put(transTypesKey, this);
compileStates = CompileStates.instance(context);
@@ -81,11 +85,12 @@ public class TransTypes extends TreeTranslator {
syms = Symtab.instance(context);
enter = Enter.instance(context);
overridden = new HashMap<>();
- Source source = Source.instance(context);
- allowInterfaceBridges = source.allowDefaultMethods();
types = Types.instance(context);
make = TreeMaker.instance(context);
resolve = Resolve.instance(context);
+ Source source = Source.instance(context);
+ allowInterfaceBridges = source.allowDefaultMethods();
+ allowGraphInference = source.allowGraphInference();
}
/** A hashtable mapping bridge methods to the methods they override after
@@ -654,7 +659,11 @@ public class TransTypes extends TreeTranslator {
tree.meth = translate(tree.meth, null);
Symbol meth = TreeInfo.symbol(tree.meth);
Type mt = meth.erasure(types);
- List argtypes = mt.getParameterTypes();
+ boolean useInstantiatedPtArgs =
+ allowGraphInference && !types.isSignaturePolymorphic((MethodSymbol)meth.baseSymbol());
+ List argtypes = useInstantiatedPtArgs ?
+ tree.meth.type.getParameterTypes() :
+ mt.getParameterTypes();
if (meth.name == names.init && meth.owner == syms.enumSym)
argtypes = argtypes.tail.tail;
if (tree.varargsElement != null)
@@ -675,14 +684,23 @@ public class TransTypes extends TreeTranslator {
public void visitNewClass(JCNewClass tree) {
if (tree.encl != null)
tree.encl = translate(tree.encl, erasure(tree.encl.type));
+
+ Type erasedConstructorType = tree.constructorType != null ?
+ erasure(tree.constructorType) :
+ null;
+
+ List argtypes = erasedConstructorType != null && allowGraphInference ?
+ erasedConstructorType.getParameterTypes() :
+ tree.constructor.erasure(types).getParameterTypes();
+
tree.clazz = translate(tree.clazz, null);
if (tree.varargsElement != null)
tree.varargsElement = types.erasure(tree.varargsElement);
tree.args = translateArgs(
- tree.args, tree.constructor.erasure(types).getParameterTypes(), tree.varargsElement);
+ tree.args, argtypes, tree.varargsElement);
tree.def = translate(tree.def, null);
- if (tree.constructorType != null)
- tree.constructorType = erasure(tree.constructorType);
+ if (erasedConstructorType != null)
+ tree.constructorType = erasedConstructorType;
tree.type = erasure(tree.type);
result = tree;
}
diff --git a/langtools/test/tools/javac/generics/inference/8058199/T8058199.java b/langtools/test/tools/javac/generics/inference/8058199/T8058199.java
new file mode 100644
index 00000000000..98ee2c49e0a
--- /dev/null
+++ b/langtools/test/tools/javac/generics/inference/8058199/T8058199.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+/**
+ * @test
+ * @bug 8058199
+ * @summary Code generation problem with javac skipping a checkcast instruction
+ */
+public class T8058199 {
+
+ final static String SYNTHETIC_CAST_TYPE = "[Ljava.lang.String;";
+
+ @SuppressWarnings("unchecked")
+ Z[] makeArr(Z z) { return (Z[])new Object[1]; }
+
+ void check(U u) { }
+
+ void testMethod() {
+ test(() -> check(makeArr("")));
+ }
+
+ void testNewDiamond() {
+ class Check {
+ Check(X x) { }
+ }
+ test(()-> new Check<>(makeArr("")));
+ }
+
+ void testNewGeneric() {
+ class Check {
+ Check(Z z) { }
+ }
+ test(()-> new Check(makeArr("")));
+ }
+
+ private void test(Runnable r) {
+ try {
+ r.run();
+ throw new AssertionError("Missing synthetic cast");
+ } catch (ClassCastException cce) {
+ if (!cce.getMessage().contains(SYNTHETIC_CAST_TYPE)) {
+ throw new AssertionError("Bad type in synthetic cast", cce);
+ }
+ }
+ }
+
+ public static void main(String[] args) {
+ T8058199 test = new T8058199();
+ test.testMethod();
+ test.testNewDiamond();
+ test.testNewGeneric();
+ }
+}
From 2756ed20d76abc5eeb036d2bbf59c1119fbce24a Mon Sep 17 00:00:00 2001
From: Maurizio Cimadamore
Date: Tue, 14 Oct 2014 12:01:05 +0100
Subject: [PATCH 50/82] 8058511: StackOverflowError at
com.sun.tools.javac.code.Types.lub
Lub crashes when handling typevar with array bound
Reviewed-by: vromero, dlsmith
---
.../com/sun/tools/javac/code/Types.java | 75 ++++++++++++-------
.../generics/inference/8058511/T8058511a.java | 38 ++++++++++
.../generics/inference/8058511/T8058511b.java | 36 +++++++++
.../generics/inference/8058511/T8058511c.java | 38 ++++++++++
4 files changed, 159 insertions(+), 28 deletions(-)
create mode 100644 langtools/test/tools/javac/generics/inference/8058511/T8058511a.java
create mode 100644 langtools/test/tools/javac/generics/inference/8058511/T8058511b.java
create mode 100644 langtools/test/tools/javac/generics/inference/8058511/T8058511c.java
diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
index 97e6ba47991..f09ca031f35 100644
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
@@ -1889,7 +1889,12 @@ public class Types {
* Mapping to take element type of an arraytype
*/
private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
- public Type apply(Type t) { return elemtype(t); }
+ public Type apply(Type t) {
+ while (t.hasTag(TYPEVAR)) {
+ t = t.getUpperBound();
+ }
+ return elemtype(t);
+ }
};
/**
@@ -3531,40 +3536,46 @@ public class Types {
}
/**
- * Return the least upper bound of pair of types. if the lub does
+ * Return the least upper bound of list of types. if the lub does
* not exist return null.
*/
- public Type lub(Type t1, Type t2) {
- return lub(List.of(t1, t2));
+ public Type lub(List ts) {
+ return lub(ts.toArray(new Type[ts.length()]));
}
/**
* Return the least upper bound (lub) of set of types. If the lub
* does not exist return the type of null (bottom).
*/
- public Type lub(List ts) {
+ public Type lub(Type... ts) {
+ final int UNKNOWN_BOUND = 0;
final int ARRAY_BOUND = 1;
final int CLASS_BOUND = 2;
- int boundkind = 0;
- for (Type t : ts) {
+
+ int[] kinds = new int[ts.length];
+
+ int boundkind = UNKNOWN_BOUND;
+ for (int i = 0 ; i < ts.length ; i++) {
+ Type t = ts[i];
switch (t.getTag()) {
case CLASS:
- boundkind |= CLASS_BOUND;
+ boundkind |= kinds[i] = CLASS_BOUND;
break;
case ARRAY:
- boundkind |= ARRAY_BOUND;
+ boundkind |= kinds[i] = ARRAY_BOUND;
break;
case TYPEVAR:
do {
t = t.getUpperBound();
} while (t.hasTag(TYPEVAR));
if (t.hasTag(ARRAY)) {
- boundkind |= ARRAY_BOUND;
+ boundkind |= kinds[i] = ARRAY_BOUND;
} else {
- boundkind |= CLASS_BOUND;
+ boundkind |= kinds[i] = CLASS_BOUND;
}
break;
default:
+ kinds[i] = UNKNOWN_BOUND;
if (t.isPrimitive())
return syms.errType;
}
@@ -3575,15 +3586,16 @@ public class Types {
case ARRAY_BOUND:
// calculate lub(A[], B[])
- List elements = Type.map(ts, elemTypeFun);
- for (Type t : elements) {
- if (t.isPrimitive()) {
+ Type[] elements = new Type[ts.length];
+ for (int i = 0 ; i < ts.length ; i++) {
+ Type elem = elements[i] = elemTypeFun.apply(ts[i]);
+ if (elem.isPrimitive()) {
// if a primitive type is found, then return
// arraySuperType unless all the types are the
// same
- Type first = ts.head;
- for (Type s : ts.tail) {
- if (!isSameType(first, s)) {
+ Type first = ts[0];
+ for (int j = 1 ; j < ts.length ; j++) {
+ if (!isSameType(first, ts[j])) {
// lub(int[], B[]) is Cloneable & Serializable
return arraySuperType();
}
@@ -3598,13 +3610,20 @@ public class Types {
case CLASS_BOUND:
// calculate lub(A, B)
- while (!ts.head.hasTag(CLASS) && !ts.head.hasTag(TYPEVAR)) {
- ts = ts.tail;
+ int startIdx = 0;
+ for (int i = 0; i < ts.length ; i++) {
+ Type t = ts[i];
+ if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) {
+ break;
+ } else {
+ startIdx++;
+ }
}
- Assert.check(!ts.isEmpty());
+ Assert.check(startIdx < ts.length);
//step 1 - compute erased candidate set (EC)
- List cl = erasedSupertypes(ts.head);
- for (Type t : ts.tail) {
+ List cl = erasedSupertypes(ts[startIdx]);
+ for (int i = startIdx + 1 ; i < ts.length ; i++) {
+ Type t = ts[i];
if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
cl = intersect(cl, erasedSupertypes(t));
}
@@ -3613,9 +3632,9 @@ public class Types {
//step 3 - for each element G in MEC, compute lci(Inv(G))
List candidates = List.nil();
for (Type erasedSupertype : mec) {
- List lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
- for (Type t : ts) {
- lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
+ List lci = List.of(asSuper(ts[startIdx], erasedSupertype.tsym));
+ for (int i = startIdx + 1 ; i < ts.length ; i++) {
+ lci = intersect(lci, List.of(asSuper(ts[i], erasedSupertype.tsym)));
}
candidates = candidates.appendList(lci);
}
@@ -3626,9 +3645,9 @@ public class Types {
default:
// calculate lub(A, B[])
List classes = List.of(arraySuperType());
- for (Type t : ts) {
- if (!t.hasTag(ARRAY)) // Filter out any arrays
- classes = classes.prepend(t);
+ for (int i = 0 ; i < ts.length ; i++) {
+ if (kinds[i] != ARRAY_BOUND) // Filter out any arrays
+ classes = classes.prepend(ts[i]);
}
// lub(A, B[]) is lub(A, arraySuperType)
return lub(classes);
diff --git a/langtools/test/tools/javac/generics/inference/8058511/T8058511a.java b/langtools/test/tools/javac/generics/inference/8058511/T8058511a.java
new file mode 100644
index 00000000000..6c1ffeb89aa
--- /dev/null
+++ b/langtools/test/tools/javac/generics/inference/8058511/T8058511a.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+/**
+ * @test
+ * @bug 8058511
+ * @summary StackOverflowError at com.sun.tools.javac.code.Types.lub
+ * @compile T8058511a.java
+ */
+class T8058511a {
+ void choose(Z z1, Z z2) { }
+
+ void test(Class cd, Class extends double[]> cdarr) {
+ choose(cd, cdarr);
+ }
+}
diff --git a/langtools/test/tools/javac/generics/inference/8058511/T8058511b.java b/langtools/test/tools/javac/generics/inference/8058511/T8058511b.java
new file mode 100644
index 00000000000..0dd5aef44a2
--- /dev/null
+++ b/langtools/test/tools/javac/generics/inference/8058511/T8058511b.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+/**
+ * @test
+ * @bug 8058511
+ * @summary StackOverflowError at com.sun.tools.javac.code.Types.lub
+ * @compile T8058511b.java
+ */
+class T8058511b {
+ void test(Class cd, Class extends double[]> cdarr) {
+ ((false) ? cd : cdarr).toString();
+ }
+}
diff --git a/langtools/test/tools/javac/generics/inference/8058511/T8058511c.java b/langtools/test/tools/javac/generics/inference/8058511/T8058511c.java
new file mode 100644
index 00000000000..c2ed03e0a98
--- /dev/null
+++ b/langtools/test/tools/javac/generics/inference/8058511/T8058511c.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+/**
+ * @test
+ * @bug 8058511
+ * @summary StackOverflowError at com.sun.tools.javac.code.Types.lub
+ * @compile T8058511c.java
+ */
+import java.util.List;
+
+class T8058511c {
+ void test(List extends double[]> l) {
+ (true ? l.get(0) : l.get(0)).toString();
+ }
+}
From a891de31140740b036bd75ac5a1c063d3456829a Mon Sep 17 00:00:00 2001
From: Attila Szegedi
Date: Tue, 14 Oct 2014 13:04:56 +0200
Subject: [PATCH 51/82] 8060238: Reports for optimistic test run overwrite
those for pessimistic run
Reviewed-by: hannesw, lagergren, sundar
---
nashorn/make/build.xml | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml
index 27ae1b319fc..9e6f5b5558e 100644
--- a/nashorn/make/build.xml
+++ b/nashorn/make/build.xml
@@ -408,7 +408,7 @@ grant codeBase "file:/${basedir}/test/script/markdown.js" {
-
@@ -431,7 +431,7 @@ grant codeBase "file:/${basedir}/test/script/markdown.js" {
-
@@ -457,9 +457,11 @@ grant codeBase "file:/${basedir}/test/script/markdown.js" {
+
+
@@ -467,9 +469,11 @@ grant codeBase "file:/${basedir}/test/script/markdown.js" {
+
+
From fab85d4210cd99e9901a8bbfac85c9a9bdfc32ae Mon Sep 17 00:00:00 2001
From: Andreas Gabrielsson
Date: Tue, 14 Oct 2014 15:28:24 +0200
Subject: [PATCH 52/82] 8012518: Reengineer Parser.java to make it play well
with the copy-on-write IR
Remove the kludges introduced to make the parser work with the copy on write IR. Now everything is done bottom up, finshing node children completely before node parents. The repeated non-functional pattern 'node = node.setSomething(something);' is gone. Resulting code is much more readable, and extensible for future work. The parser is now also consistent with the rest of the stateless copy-on-write world in code generation.
Reviewed-by: lagergren, attila, hannesw, shade
---
nashorn/.hgignore | 2 +
nashorn/bin/runopt.sh | 137 +++++
.../nashorn/api/scripting/ScriptUtils.java | 2 -
.../jdk/nashorn/internal/ir/Block.java | 48 +-
.../jdk/nashorn/internal/ir/ForNode.java | 61 +--
.../jdk/nashorn/internal/ir/FunctionNode.java | 77 +--
.../jdk/nashorn/internal/ir/LoopNode.java | 5 +-
.../classes/jdk/nashorn/internal/ir/Node.java | 22 +-
.../jdk/nashorn/internal/ir/WhileNode.java | 12 +-
.../jdk/nashorn/internal/ir/WithNode.java | 14 +-
.../jdk/nashorn/internal/objects/Global.java | 2 -
.../nashorn/internal/objects/NativeError.java | 2 -
.../nashorn/internal/objects/NativeJava.java | 2 -
.../jdk/nashorn/internal/parser/Parser.java | 487 ++++++++++--------
.../internal/parser/ParserContext.java | 334 ++++++++++++
.../parser/ParserContextBaseNode.java | 109 ++++
.../parser/ParserContextBlockNode.java | 56 ++
.../parser/ParserContextBreakableNode.java | 40 ++
.../parser/ParserContextFunctionNode.java | 197 +++++++
.../parser/ParserContextLabelNode.java | 52 ++
.../parser/ParserContextLoopNode.java | 37 ++
.../internal/parser/ParserContextNode.java | 67 +++
.../parser/ParserContextSwitchNode.java | 36 ++
.../jdk/nashorn/internal/runtime/Context.java | 35 +-
24 files changed, 1466 insertions(+), 370 deletions(-)
create mode 100644 nashorn/bin/runopt.sh
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContext.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextBaseNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextBlockNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextBreakableNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextFunctionNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextLabelNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextLoopNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextNode.java
create mode 100644 nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/ParserContextSwitchNode.java
diff --git a/nashorn/.hgignore b/nashorn/.hgignore
index 02ec40d7e8d..7ee241994a9 100644
--- a/nashorn/.hgignore
+++ b/nashorn/.hgignore
@@ -26,3 +26,5 @@ jcov2/*
test/lib/testng.jar
test/script/external/*
.project
+.externalToolBuilders/*
+.settings/*
diff --git a/nashorn/bin/runopt.sh b/nashorn/bin/runopt.sh
new file mode 100644
index 00000000000..0a61491e624
--- /dev/null
+++ b/nashorn/bin/runopt.sh
@@ -0,0 +1,137 @@
+#!/bin/sh
+#
+# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# 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.
+#
+
+###########################################################################################
+# This is a helper script to evaluate nashorn with optimistic types
+# it produces a flight recording for every run, and uses the best
+# known flags for performance for the current configration
+###########################################################################################
+
+# Flags to enable assertions, we need the system assertions too, since
+# this script runs Nashorn in the BCP to override any nashorn.jar that might
+# reside in your $JAVA_HOME/jre/lib/ext/nashorn.jar
+#
+ENABLE_ASSERTIONS_FLAGS="-ea -esa"
+
+# Flags to instrument lambdaform computation, caching, interpretation and compilation
+# Default compile threshold for lambdaforms is 30
+#
+#LAMBDAFORM_FLAGS="\
+# -Djava.lang.invoke.MethodHandle.COMPILE_THRESHOLD=3 \
+# -Djava.lang.invoke.MethodHandle.DUMP_CLASS_FILES=true \
+# -Djava.lang.invoke.MethodHandle.TRACE_METHOD_LINKAGE=true \
+# -Djava.lang.invoke.MethodHandle.TRACE_INTERPRETER=true"
+
+# Flags to run trusted tests from the Nashorn test suite
+#
+#TRUSTED_TEST_FLAGS="\
+#-Djava.security.manager \
+#-Djava.security.policy=../build/nashorn.policy -Dnashorn.debug"
+
+# Testing out new code optimizations using the generic hotspot "new code" parameter
+#
+#USE_NEW_CODE_FLAGS=-XX:+UnlockDiagnosticVMOptions -XX:+UseNewCode
+
+#
+#-Dnashorn.typeInfo.disabled=false \
+# and for Nashorn options:
+# --class-cache-size=0 --persistent-code-cache=false
+
+# Unique timestamped file name for JFR recordings. For JFR, we also have to
+# crank up the stack cutoff depth to 1024, because of ridiculously long lambda form
+# stack traces.
+#
+# It is also recommended that you go into $JAVA_HOME/jre/lib/jfr/default.jfc and
+# set the "method-sampling-interval" Normal and Maximum sample time as low as you
+# can go (10 ms on most platforms). The default is normally higher. The increased
+# sampling overhead is usually negligible for Nashorn runs, but the data is better
+
+if [ -z $JFR_FILENAME ]; then
+ JFR_FILENAME="./nashorn_$(date|sed "s/ /_/g"|sed "s/:/_/g").jfr"
+ echo "Using default JFR filename: ${JFR_FILENAME}..."
+fi
+
+# Flight recorder
+#
+# see above - already in place, copy the flags down here to disable
+ENABLE_FLIGHT_RECORDER_FLAGS="\
+ -XX:+UnlockCommercialFeatures \
+ -XX:+FlightRecorder \
+ -XX:FlightRecorderOptions=defaultrecording=true,disk=true,dumponexit=true,dumponexitpath=$JFR_FILENAME,stackdepth=1024"
+
+# Type specialization and math intrinsic replacement should be enabled by default in 8u20 and nine,
+# keeping this flag around for experimental reasons. Replace + with - to switch it off
+#
+#ENABLE_TYPE_SPECIALIZATION_FLAGS=-XX:+UseTypeSpeculation
+
+# Same with math intrinsics. They should be enabled by default in 8u20 and 9, so
+# this disables them if needed
+#
+#DISABLE_MATH_INTRINSICS_FLAGS=-XX:-UseMathExactIntrinsics
+
+# Add timing to time the compilation phases.
+#ENABLE_TIME_FLAGS=--log=time
+
+# Add ShowHiddenFrames to get lambda form internals on the stack traces
+#ENABLE_SHOW_HIDDEN_FRAMES_FLAGS=-XX:+ShowHiddenFrames
+
+# Add print optoassembly to get an asm dump. This requires 1) a debug build, not product,
+# That tired compilation is switched off, for C2 only output and that the number of
+# compiler threads is set to 1 for determinsm.
+#
+#PRINT_ASM_FLAGS=-XX:+PrintOptoAssembly -XX:-TieredCompilation -XX:CICompilerCount=1 \
+
+# Tier compile threasholds. Default value is 10. (1-100 is useful for experiments)
+#TIER_COMPILATION_THRESHOLD_FLAGS=-XX:IncreaseFirstTierCompileThresholdAt=10
+
+# Directory where to look for nashorn.jar in a dist folder. The default is "..", assuming
+# that we run the script from the make dir
+DIR=..
+NASHORN_JAR=$DIR/dist/nashorn.jar
+
+
+# The built Nashorn jar is placed first in the bootclasspath to override the JDK
+# nashorn.jar in $JAVA_HOME/jre/lib/ext. Thus, we also need -esa, as assertions in
+# nashorn count as system assertions in this configuration
+
+# Type profiling default level is 111, 222 adds some compile time, but is faster
+
+$JAVA_HOME/bin/java \
+$ENABLE_ASSERTIONS_FLAGS \
+$LAMBDAFORM_FLAGS \
+$TRUSTED_FLAGS \
+$USE_NEW_CODE_FLAGS \
+$ENABLE_SHOW_HIDDEN_FRAMES_FLAGS \
+$ENABLE_FLIGHT_RECORDER_FLAGS \
+$ENABLE_TYPE_SPECIALIZATION_FLAGS \
+$TIERED_COMPILATION_THRESOLD_FLAGS \
+$DISABLE_MATH_INTRINSICS_FLAGS \
+$PRINT_ASM_FLAGS \
+-Xbootclasspath/p:$NASHORN_JAR \
+-Xms2G -Xmx2G \
+-XX:TypeProfileLevel=222 \
+-cp $CLASSPATH:../build/test/classes/ \
+jdk.nashorn.tools.Shell $ENABLE_TIME_FLAGS ${@}
+
+
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java
index b6c4c97e547..e6e3915ab29 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptUtils.java
@@ -25,8 +25,6 @@
package jdk.nashorn.api.scripting;
-import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
-
import java.lang.invoke.MethodHandle;
import jdk.internal.dynalink.beans.StaticClass;
import jdk.internal.dynalink.linker.LinkerServices;
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Block.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Block.java
index 86a84ca6de8..e3a26893cb5 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Block.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Block.java
@@ -80,11 +80,12 @@ public class Block extends Node implements BreakableNode, Terminal, Flags
/**
* Constructor
*
- * @param token token
- * @param finish finish
- * @param statements statements
+ * @param token The first token of the block
+ * @param finish The index of the last character
+ * @param flags The flags of the block
+ * @param statements All statements in the block
*/
- public Block(final long token, final int finish, final Statement... statements) {
+ public Block(final long token, final int finish, final int flags, final Statement... statements) {
super(token, finish);
this.statements = Arrays.asList(statements);
@@ -92,29 +93,52 @@ public class Block extends Node implements BreakableNode, Terminal, Flags
this.entryLabel = new Label("block_entry");
this.breakLabel = new Label("block_break");
final int len = statements.length;
- this.flags = len > 0 && statements[len - 1].hasTerminalFlags() ? IS_TERMINAL : 0;
+ final int terminalFlags = len > 0 && statements[len - 1].hasTerminalFlags() ? IS_TERMINAL : 0;
+ this.flags = terminalFlags | flags;
this.conversion = null;
}
+ /**
+ * Constructs a new block
+ *
+ * @param token The first token of the block
+ * @param finish The index of the last character
+ * @param statements All statements in the block
+ */
+ public Block(final long token, final int finish, final Statement...statements){
+ this(token, finish, 0, statements);
+ }
+
+ /**
+ * Constructs a new block
+ *
+ * @param token The first token of the block
+ * @param finish The index of the last character
+ * @param statements All statements in the block
+ */
+ public Block(final long token, final int finish, final List statements){
+ this(token, finish, 0, statements);
+ }
+
/**
* Constructor
*
- * @param token token
- * @param finish finish
- * @param statements statements
+ * @param token The first token of the block
+ * @param finish The index of the last character
+ * @param flags The flags of the block
+ * @param statements All statements in the block
*/
- public Block(final long token, final int finish, final List statements) {
- this(token, finish, statements.toArray(new Statement[statements.size()]));
+ public Block(final long token, final int finish, final int flags, final List statements) {
+ this(token, finish, flags, statements.toArray(new Statement[statements.size()]));
}
private Block(final Block block, final int finish, final List statements, final int flags, final Map symbols, final LocalVariableConversion conversion) {
- super(block);
+ super(block, finish);
this.statements = statements;
this.flags = flags;
this.symbols = new LinkedHashMap<>(symbols); //todo - symbols have no dependencies on any IR node and can as far as we understand it be shallow copied now
this.entryLabel = new Label(block.entryLabel);
this.breakLabel = new Label(block.breakLabel);
- this.finish = finish;
this.conversion = conversion;
}
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/ForNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/ForNode.java
index 9b4cb6d6e1c..bc864eb68bb 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/ForNode.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/ForNode.java
@@ -54,20 +54,37 @@ public final class ForNode extends LoopNode {
private final int flags;
+ /**
+ * Constructs a ForNode
+ *
+ * @param lineNumber The line number of header
+ * @param token The for token
+ * @param finish The last character of the for node
+ * @param body The body of the for node
+ * @param flags The flags
+ */
+ public ForNode(final int lineNumber, final long token, final int finish, final Block body, final int flags){
+ this(lineNumber, token, finish, body, flags, null, null, null);
+ }
+
/**
* Constructor
*
- * @param lineNumber line number
- * @param token token
- * @param finish finish
- * @param body body
- * @param flags flags
+ * @param lineNumber The line number of header
+ * @param token The for token
+ * @param finish The last character of the for node
+ * @param body The body of the for node
+ * @param flags The flags
+ * @param init The initial expression
+ * @param test The test expression
+ * @param modify The modify expression
*/
- public ForNode(final int lineNumber, final long token, final int finish, final Block body, final int flags) {
- super(lineNumber, token, finish, body, false);
+ public ForNode(final int lineNumber, final long token, final int finish, final Block body, final int flags, final Expression init, final JoinPredecessorExpression test, final JoinPredecessorExpression modify) {
+ super(lineNumber, token, finish, body, test, false);
this.flags = flags;
- this.init = null;
- this.modify = null;
+ this.init = init;
+ this.modify = modify;
+
}
private ForNode(final ForNode forNode, final Expression init, final JoinPredecessorExpression test,
@@ -166,16 +183,6 @@ public final class ForNode extends LoopNode {
public boolean isForIn() {
return (flags & IS_FOR_IN) != 0;
}
-
- /**
- * Flag this to be a for in construct
- * @param lc lexical context
- * @return new for node if changed or existing if not
- */
- public ForNode setIsForIn(final LexicalContext lc) {
- return setFlags(lc, flags | IS_FOR_IN);
- }
-
/**
* Is this a for each construct, known from e.g. Rhino. This will be a for of construct
* in ECMAScript 6
@@ -185,15 +192,6 @@ public final class ForNode extends LoopNode {
return (flags & IS_FOR_EACH) != 0;
}
- /**
- * Flag this to be a for each construct
- * @param lc lexical context
- * @return new for node if changed or existing if not
- */
- public ForNode setIsForEach(final LexicalContext lc) {
- return setFlags(lc, flags | IS_FOR_EACH);
- }
-
/**
* If this is a for in or for each construct, there is an iterator symbol
* @return the symbol for the iterator to be used, or null if none exists
@@ -260,13 +258,6 @@ public final class ForNode extends LoopNode {
return Node.replaceInLexicalContext(lc, this, new ForNode(this, init, test, body, modify, flags, controlFlowEscapes, conversion));
}
- private ForNode setFlags(final LexicalContext lc, final int flags) {
- if (this.flags == flags) {
- return this;
- }
- return Node.replaceInLexicalContext(lc, this, new ForNode(this, init, test, body, modify, flags, controlFlowEscapes, conversion));
- }
-
@Override
JoinPredecessor setLocalVariableConversionChanged(final LexicalContext lc, final LocalVariableConversion conversion) {
return Node.replaceInLexicalContext(lc, this, new ForNode(this, init, test, body, modify, flags, controlFlowEscapes, conversion));
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/FunctionNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/FunctionNode.java
index 1bbc7ab0834..ad19f8d53a8 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/FunctionNode.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/FunctionNode.java
@@ -31,7 +31,6 @@ import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALL
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE_ENTEREXIT;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE_MISSES;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE_VALUES;
-
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
@@ -46,6 +45,7 @@ import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.ir.annotations.Ignore;
import jdk.nashorn.internal.ir.annotations.Immutable;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
+import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.Source;
@@ -299,12 +299,16 @@ public final class FunctionNode extends LexicalContextExpression implements Flag
* @param token token
* @param finish finish
* @param firstToken first token of the function node (including the function declaration)
+ * @param lastToken lastToken
* @param namespace the namespace
* @param ident the identifier
* @param name the name of the function
* @param parameters parameter list
* @param kind kind of function as in {@link FunctionNode.Kind}
* @param flags initial flags
+ * @param body body of the function
+ * @param state The initial state from the parser. Must be one of {@link CompilationState#PARSED} and {@link CompilationState#PARSE_ERROR}
+ * @param endParserState The parser state at the end of the parsing.
*/
public FunctionNode(
final Source source,
@@ -312,12 +316,16 @@ public final class FunctionNode extends LexicalContextExpression implements Flag
final long token,
final int finish,
final long firstToken,
+ final long lastToken,
final Namespace namespace,
final IdentNode ident,
final String name,
final List parameters,
final FunctionNode.Kind kind,
- final int flags) {
+ final int flags,
+ final Block body,
+ final CompilationState state,
+ final Object endParserState) {
super(token, finish);
this.source = source;
@@ -327,15 +335,15 @@ public final class FunctionNode extends LexicalContextExpression implements Flag
this.kind = kind;
this.parameters = parameters;
this.firstToken = firstToken;
- this.lastToken = token;
+ this.lastToken = lastToken;
this.namespace = namespace;
- this.compilationState = EnumSet.of(CompilationState.INITIALIZED);
+ this.compilationState = EnumSet.of(CompilationState.INITIALIZED, state);
this.flags = flags;
this.compileUnit = null;
- this.body = null;
+ this.body = body;
this.thisProperties = 0;
this.rootClass = null;
- this.endParserState = null;
+ this.endParserState = endParserState;
}
private FunctionNode(
@@ -439,7 +447,7 @@ public final class FunctionNode extends LexicalContextExpression implements Flag
* @return the id
*/
public int getId() {
- return position();
+ return isProgram() ? -1: Token.descPosition(firstToken);
}
/**
@@ -902,34 +910,6 @@ public final class FunctionNode extends LexicalContextExpression implements Flag
return lastToken;
}
- /**
- * Set the last token for this function's code
- * @param lc lexical context
- * @param lastToken the last token
- * @return function node or a new one if state was changed
- */
- public FunctionNode setLastToken(final LexicalContext lc, final long lastToken) {
- if (this.lastToken == lastToken) {
- return this;
- }
- return Node.replaceInLexicalContext(
- lc,
- this,
- new FunctionNode(
- this,
- lastToken,
- endParserState,
- flags,
- name,
- returnType,
- compileUnit,
- compilationState,
- body,
- parameters,
- thisProperties,
- rootClass));
- }
-
/**
* Returns the end parser state for this function.
* @return the end parser state for this function.
@@ -938,33 +918,6 @@ public final class FunctionNode extends LexicalContextExpression implements Flag
return endParserState;
}
- /**
- * Set the end parser state for this function.
- * @param lc lexical context
- * @param endParserState the parser state to set
- * @return function node or a new one if state was changed
- */
- public FunctionNode setEndParserState(final LexicalContext lc, final Object endParserState) {
- if (this.endParserState == endParserState) {
- return this;
- }
- return Node.replaceInLexicalContext(
- lc,
- this,
- new FunctionNode(
- this,
- lastToken,
- endParserState,
- flags,
- name,
- returnType,
- compileUnit,
- compilationState,
- body,
- parameters,
- thisProperties, rootClass));
- }
-
/**
* Get the name of this function
* @return the name
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LoopNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LoopNode.java
index 86ef3cdad49..bfc86a69a43 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LoopNode.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LoopNode.java
@@ -53,14 +53,15 @@ public abstract class LoopNode extends BreakableStatement {
* @param token token
* @param finish finish
* @param body loop body
+ * @param test test
* @param controlFlowEscapes controlFlowEscapes
*/
- protected LoopNode(final int lineNumber, final long token, final int finish, final Block body, final boolean controlFlowEscapes) {
+ protected LoopNode(final int lineNumber, final long token, final int finish, final Block body, final JoinPredecessorExpression test, final boolean controlFlowEscapes) {
super(lineNumber, token, finish, new Label("while_break"));
this.continueLabel = new Label("while_continue");
- this.test = null;
this.body = body;
this.controlFlowEscapes = controlFlowEscapes;
+ this.test = test;
}
/**
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Node.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Node.java
index 37ec4b96a39..861f12a05ff 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Node.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Node.java
@@ -39,7 +39,7 @@ public abstract class Node implements Cloneable {
protected final int start;
/** End of source range. */
- protected int finish;
+ protected final int finish;
/** Token descriptor. */
private final long token;
@@ -80,6 +80,18 @@ public abstract class Node implements Cloneable {
this.finish = node.finish;
}
+ /**
+ * Copy constructor that overrides finish
+ *
+ * @param node source node
+ * @param finish Last character
+ */
+ protected Node(final Node node, final int finish) {
+ this.token = node.token;
+ this.start = node.start;
+ this.finish = finish;
+ }
+
/**
* Is this a loop node?
*
@@ -151,14 +163,6 @@ public abstract class Node implements Cloneable {
return finish;
}
- /**
- * Set finish position for this node in the source string
- * @param finish finish
- */
- public void setFinish(final int finish) {
- this.finish = finish;
- }
-
/**
* Get start position for node
* @return start position
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WhileNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WhileNode.java
index 0cced567fbc..99bdce87c19 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WhileNode.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WhileNode.java
@@ -45,9 +45,11 @@ public final class WhileNode extends LoopNode {
* @param token token
* @param finish finish
* @param isDoWhile is this a do while loop?
+ * @param test test expression
+ * @param body body of the while loop
*/
- public WhileNode(final int lineNumber, final long token, final int finish, final boolean isDoWhile) {
- super(lineNumber, token, finish, null, false);
+ public WhileNode(final int lineNumber, final long token, final int finish, final boolean isDoWhile, final JoinPredecessorExpression test, final Block body) {
+ super(lineNumber, token, finish, body, test, false);
this.isDoWhile = isDoWhile;
}
@@ -55,10 +57,10 @@ public final class WhileNode extends LoopNode {
* Internal copy constructor
*
* @param whileNode while node
- * @param test test
- * @param body body
+ * @param test Test expression
+ * @param body body of the while loop
* @param controlFlowEscapes control flow escapes?
- * @param conversion TODO
+ * @param conversion local variable conversion info
*/
private WhileNode(final WhileNode whileNode, final JoinPredecessorExpression test, final Block body, final boolean controlFlowEscapes, final LocalVariableConversion conversion) {
super(whileNode, test, body, controlFlowEscapes, conversion);
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WithNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WithNode.java
index 0ea52c98bb4..20e319294d2 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WithNode.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/WithNode.java
@@ -42,14 +42,16 @@ public final class WithNode extends LexicalContextStatement {
/**
* Constructor
*
- * @param lineNumber line number
- * @param token token
- * @param finish finish
+ * @param lineNumber Line number of the header
+ * @param token First token
+ * @param finish Character index of the last token
+ * @param expression With expression
+ * @param body Body of with node
*/
- public WithNode(final int lineNumber, final long token, final int finish) {
+ public WithNode(final int lineNumber, final long token, final int finish, final Expression expression, final Block body) {
super(lineNumber, token, finish);
- this.expression = null;
- this.body = null;
+ this.expression = expression;
+ this.body = body;
}
private WithNode(final WithNode node, final Expression expression, final Block body) {
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java
index eb56de0e18f..61d7948f621 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java
@@ -561,7 +561,6 @@ public final class Global extends ScriptObject implements Scope {
*
* @param engine ScriptEngine to initialize
*/
- @SuppressWarnings("hiding")
public void initBuiltinObjects(final ScriptEngine engine) {
if (this.builtinObject != null) {
// already initialized, just return
@@ -1718,7 +1717,6 @@ public final class Global extends ScriptObject implements Scope {
return func;
}
- @SuppressWarnings("hiding")
private void init(final ScriptEngine engine) {
assert Context.getGlobal() == this : "this global is not set as current";
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeError.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeError.java
index e1d95ce097f..41ea9a5f4e2 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeError.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeError.java
@@ -27,7 +27,6 @@ package jdk.nashorn.internal.objects;
import static jdk.nashorn.internal.lookup.Lookup.MH;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
-
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import jdk.nashorn.api.scripting.NashornException;
@@ -131,7 +130,6 @@ public final class NativeError extends ScriptObject {
// This is called NativeError, NativeTypeError etc. to
// associate a ECMAException with the ECMA Error object.
- @SuppressWarnings("unused")
static void initException(final ScriptObject self) {
// ECMAException constructor has side effects
new ECMAException(self, null);
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
index 7c6e60a967d..e9a4380dadc 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
@@ -27,7 +27,6 @@ package jdk.nashorn.internal.objects;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
-
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Array;
import java.util.Collection;
@@ -36,7 +35,6 @@ import java.util.List;
import jdk.internal.dynalink.beans.StaticClass;
import jdk.internal.dynalink.support.TypeUtilities;
import jdk.nashorn.api.scripting.JSObject;
-import jdk.nashorn.api.scripting.ScriptUtils;
import jdk.nashorn.internal.objects.annotations.Attribute;
import jdk.nashorn.internal.objects.annotations.Function;
import jdk.nashorn.internal.objects.annotations.ScriptClass;
diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java
index 3162e184468..32f1df63895 100644
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java
@@ -53,7 +53,6 @@ import static jdk.nashorn.internal.parser.TokenType.RPAREN;
import static jdk.nashorn.internal.parser.TokenType.SEMICOLON;
import static jdk.nashorn.internal.parser.TokenType.TERNARY;
import static jdk.nashorn.internal.parser.TokenType.WHILE;
-
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -71,10 +70,8 @@ import jdk.nashorn.internal.ir.AccessNode;
import jdk.nashorn.internal.ir.BaseNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
-import jdk.nashorn.internal.ir.BlockLexicalContext;
import jdk.nashorn.internal.ir.BlockStatement;
import jdk.nashorn.internal.ir.BreakNode;
-import jdk.nashorn.internal.ir.BreakableNode;
import jdk.nashorn.internal.ir.CallNode;
import jdk.nashorn.internal.ir.CaseNode;
import jdk.nashorn.internal.ir.CatchNode;
@@ -90,9 +87,7 @@ import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.JoinPredecessorExpression;
import jdk.nashorn.internal.ir.LabelNode;
-import jdk.nashorn.internal.ir.LexicalContext;
import jdk.nashorn.internal.ir.LiteralNode;
-import jdk.nashorn.internal.ir.LoopNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ObjectNode;
import jdk.nashorn.internal.ir.PropertyKey;
@@ -138,8 +133,8 @@ public class Parser extends AbstractParser implements Loggable {
private List functionDeclarations;
- private final BlockLexicalContext lc = new BlockLexicalContext();
- private final Deque