changeset 1365:fe931343ad6a

8086733: Improve namespace handling Reviewed-by: dfuchs, lancea, ahgross
author aefimov
date Sun, 12 Jul 2015 22:35:12 +0300
parents ba508fc2eeb6
children ab72c17cd492
files src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java src/com/sun/xml/internal/stream/Entity.java
diffstat 18 files changed, 287 insertions(+), 254 deletions(-) [+]
line wrap: on
line diff
--- a/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java	Sun Jul 12 22:35:12 2015 +0300
@@ -65,27 +65,31 @@
      */
     public static enum Limit {
 
-        ENTITY_EXPANSION_LIMIT(XalanConstants.JDK_ENTITY_EXPANSION_LIMIT,
+        ENTITY_EXPANSION_LIMIT("EntityExpansionLimit", XalanConstants.JDK_ENTITY_EXPANSION_LIMIT,
                 XalanConstants.SP_ENTITY_EXPANSION_LIMIT, 0, 64000),
-        MAX_OCCUR_NODE_LIMIT(XalanConstants.JDK_MAX_OCCUR_LIMIT,
+        MAX_OCCUR_NODE_LIMIT("MaxOccurLimit", XalanConstants.JDK_MAX_OCCUR_LIMIT,
                 XalanConstants.SP_MAX_OCCUR_LIMIT, 0, 5000),
-        ELEMENT_ATTRIBUTE_LIMIT(XalanConstants.JDK_ELEMENT_ATTRIBUTE_LIMIT,
+        ELEMENT_ATTRIBUTE_LIMIT("ElementAttributeLimit", XalanConstants.JDK_ELEMENT_ATTRIBUTE_LIMIT,
                 XalanConstants.SP_ELEMENT_ATTRIBUTE_LIMIT, 0, 10000),
-        TOTAL_ENTITY_SIZE_LIMIT(XalanConstants.JDK_TOTAL_ENTITY_SIZE_LIMIT,
+        TOTAL_ENTITY_SIZE_LIMIT("TotalEntitySizeLimit", XalanConstants.JDK_TOTAL_ENTITY_SIZE_LIMIT,
                 XalanConstants.SP_TOTAL_ENTITY_SIZE_LIMIT, 0, 50000000),
-        GENEAL_ENTITY_SIZE_LIMIT(XalanConstants.JDK_GENEAL_ENTITY_SIZE_LIMIT,
+        GENEAL_ENTITY_SIZE_LIMIT("MaxEntitySizeLimit", XalanConstants.JDK_GENEAL_ENTITY_SIZE_LIMIT,
                 XalanConstants.SP_GENEAL_ENTITY_SIZE_LIMIT, 0, 0),
-        PARAMETER_ENTITY_SIZE_LIMIT(XalanConstants.JDK_PARAMETER_ENTITY_SIZE_LIMIT,
+        PARAMETER_ENTITY_SIZE_LIMIT("MaxEntitySizeLimit", XalanConstants.JDK_PARAMETER_ENTITY_SIZE_LIMIT,
                 XalanConstants.SP_PARAMETER_ENTITY_SIZE_LIMIT, 0, 1000000),
-        MAX_ELEMENT_DEPTH_LIMIT(XalanConstants.JDK_MAX_ELEMENT_DEPTH,
-                XalanConstants.SP_MAX_ELEMENT_DEPTH, 0, 0);
+        MAX_ELEMENT_DEPTH_LIMIT("MaxElementDepthLimit", XalanConstants.JDK_MAX_ELEMENT_DEPTH,
+                XalanConstants.SP_MAX_ELEMENT_DEPTH, 0, 0),
+        MAX_NAME_LIMIT("MaxXMLNameLimit", XalanConstants.JDK_XML_NAME_LIMIT,
+                XalanConstants.SP_XML_NAME_LIMIT, 1000, 1000);
 
+        final String key;
         final String apiProperty;
         final String systemProperty;
         final int defaultValue;
         final int secureValue;
 
-        Limit(String apiProperty, String systemProperty, int value, int secureValue) {
+        Limit(String key, String apiProperty, String systemProperty, int value, int secureValue) {
+            this.key = key;
             this.apiProperty = apiProperty;
             this.systemProperty = systemProperty;
             this.defaultValue = value;
@@ -100,6 +104,10 @@
             return (propertyName == null) ? false : systemProperty.equals(propertyName);
         }
 
+        public String key() {
+            return key;
+        }
+
         public String apiProperty() {
             return apiProperty;
         }
@@ -108,7 +116,7 @@
             return systemProperty;
         }
 
-        int defaultValue() {
+        public int defaultValue() {
             return defaultValue;
         }
 
@@ -160,7 +168,7 @@
     /**
      * Index of the special entityCountInfo property
      */
-    private int indexEntityCountInfo = 10000;
+    private final int indexEntityCountInfo = 10000;
     private String printEntityCountInfo = "";
 
     /**
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java	Sun Jul 12 22:35:12 2015 +0300
@@ -332,7 +332,7 @@
                                                          new Object[]{entityName});
                                     }
                                 }
-                                fEntityManager.startEntity(entityName, true);
+                                fEntityManager.startEntity(false, entityName, true);
                             }
                         }
                     }
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1,62 +1,21 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
 /*
- * The Apache Software License, Version 1.1
- *
- *
- * 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.
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ */
+
+/*
+ * Copyright 2005 The Apache Software Foundation.
  *
- * 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.
+ * 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
  *
- * 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.
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
- * 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
- * <http://www.apache.org/>.
+ * 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;
@@ -65,6 +24,8 @@
 import com.sun.org.apache.xerces.internal.util.XML11Char;
 import com.sun.org.apache.xerces.internal.util.XMLChar;
 import com.sun.org.apache.xerces.internal.util.XMLStringBuffer;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager.Limit;
 import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.xni.XMLString;
 import java.io.IOException;
@@ -690,9 +651,13 @@
                         break;
                     }
                     index = fCurrentEntity.position;
+                    //check prefix before further read
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, index - offset);
                 }
                 if (++fCurrentEntity.position == fCurrentEntity.count) {
                     int length = fCurrentEntity.position - offset;
+                    //check localpart before loading more data
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length - index - 1);
                     invokeListeners(length);
                     if (length == fCurrentEntity.ch.length) {
                         // bad luck we have to resize our buffer
@@ -786,6 +751,8 @@
                                                     offset, length);
             if (index != -1) {
                 int prefixLength = index - offset;
+                //check the result: prefix
+                checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, prefixLength);
                 prefix = fSymbolTable.addSymbol(fCurrentEntity.ch,
                                                     offset, prefixLength);
                 int len = length - prefixLength - 1;
@@ -798,12 +765,16 @@
                                                null,
                                                XMLErrorReporter.SEVERITY_FATAL_ERROR);
                 }
+                //check the result: localpart
+                checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, index + 1, len);
                 localpart = fSymbolTable.addSymbol(fCurrentEntity.ch,
                                                    index + 1, len);
 
             }
             else {
                 localpart = rawname;
+                //check the result: localpart
+                checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
             }
             qname.setValues(prefix, localpart, rawname, null);
             return true;
@@ -934,6 +905,9 @@
         }
         int length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length - newlines;
+        if (fCurrentEntity.reference) {
+            checkLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fCurrentEntity, offset, length);
+        }
         content.setValues(fCurrentEntity.ch, offset, length);
 
         // return next character
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1,62 +1,21 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
 /*
- * The Apache Software License, Version 1.1
- *
- *
- * Copyright (c) 1999-2003 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.
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ */
+
+/*
+ * Copyright 2005 The Apache Software Foundation.
  *
- * 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.
+ * 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
  *
- * 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.
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
- * 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) 2002, International
- * Business Machines, Inc., http://www.apache.org.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
+ * 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;
@@ -67,6 +26,7 @@
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl;
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
 import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.xni.XMLDocumentHandler;
@@ -340,36 +300,37 @@
         }
 
         // call handler
-
-            if (empty) {
-
-                //decrease the markup depth..
-                fMarkupDepth--;
+        if (empty) {
+            //decrease the markup depth..
+            fMarkupDepth--;
 
-                // check that this element was opened in the same entity
-                if (fMarkupDepth < fEntityStack[fEntityDepth - 1]) {
-                    reportFatalError(
-                        "ElementEntityMismatch",
-                        new Object[] { fCurrentElement.rawname });
-                }
+            // check that this element was opened in the same entity
+            if (fMarkupDepth < fEntityStack[fEntityDepth - 1]) {
+                reportFatalError(
+                    "ElementEntityMismatch",
+                    new Object[] { fCurrentElement.rawname });
+            }
 
+            if (fDocumentHandler != null) {
                 fDocumentHandler.emptyElement(fElementQName, fAttributes, null);
+            }
 
-                /*if (fBindNamespaces) {
-                    fNamespaceContext.popContext();
-                }*/
-                fScanEndElement = true;
+            /*if (fBindNamespaces) {
+                fNamespaceContext.popContext();
+            }*/
+            fScanEndElement = true;
 
-                //pop the element off the stack..
-                fElementStack.popElement();
-            } else {
+            //pop the element off the stack..
+            fElementStack.popElement();
+        } else {
+            if(dtdGrammarUtil != null) {
+                dtdGrammarUtil.startElement(fElementQName, fAttributes);
+            }
 
-                if(dtdGrammarUtil != null)
-                    dtdGrammarUtil.startElement(fElementQName, fAttributes);
-
-                if (fDocumentHandler != null)
+            if (fDocumentHandler != null) {
                 fDocumentHandler.startElement(fElementQName, fAttributes, null);
             }
+        }
 
         if (DEBUG_START_END_ELEMENT)
             System.out.println("<<< scanStartElement(): " + empty);
@@ -679,7 +640,13 @@
             if (prefix == XMLSymbols.PREFIX_XMLNS
                 || prefix == XMLSymbols.EMPTY_STRING
                 && localpart == XMLSymbols.PREFIX_XMLNS) {
-
+                if (value.length() > fXMLNameLimit) {
+                    fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
+                            "MaxXMLNameLimit",
+                            new Object[]{value, value.length(), fXMLNameLimit,
+                            fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.MAX_NAME_LIMIT)},
+                            XMLErrorReporter.SEVERITY_FATAL_ERROR);
+                }
                 // get the internalized value of this attribute
                 String uri = fSymbolTable.addSymbol(value);
 
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -369,6 +369,8 @@
                 }
                 // we're done, set starting state for external subset
                 setScannerState(SCANNER_STATE_TEXT_DECL);
+                // we're done scanning DTD.
+                fLimitAnalyzer.reset(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT);
                 return false;
             }
         } while (complete);
@@ -704,7 +706,7 @@
             fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN,"EntityNotDeclared",
             new Object[]{name}, XMLErrorReporter.SEVERITY_ERROR);
         }
-        fEntityManager.startEntity(fSymbolTable.addSymbol(pName),
+        fEntityManager.startEntity(false, fSymbolTable.addSymbol(pName),
         literal);
         // if we actually got a new entity and it's external
         // parse text decl if there is any
@@ -1632,7 +1634,7 @@
         XMLString literal2 = fString;
         int countChar = 0;
         if (fLimitAnalyzer == null ) {
-            fLimitAnalyzer = new XMLLimitAnalyzer();
+            fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
          }
             fLimitAnalyzer.startEntity(entityName);
 
@@ -1640,9 +1642,7 @@
             fStringBuffer.clear();
             fStringBuffer2.clear();
             do {
-                if (isPEDecl && fLimitAnalyzer != null) {
-                    checkLimit("%" + entityName, fString.length + countChar);
-                }
+                checkEntityLimit(isPEDecl, entityName, fString.length + countChar);
                 countChar = 0;
                 fStringBuffer.append(fString);
                 fStringBuffer2.append(fString);
@@ -1728,9 +1728,7 @@
             literal = fStringBuffer;
             literal2 = fStringBuffer2;
         } else {
-            if (isPEDecl) {
-                checkLimit("%" + entityName, literal);
-        }
+            checkEntityLimit(isPEDecl, entityName, literal);
         }
         value.setValues(literal);
         nonNormalizedValue.setValues(literal2);
@@ -2152,35 +2150,49 @@
         setScannerState(SCANNER_STATE_TEXT_DECL);
         //new SymbolTable());
 
-        fLimitAnalyzer = new XMLLimitAnalyzer();
+        fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
+        fSecurityManager = fEntityManager.fSecurityManager;
     }
 
     /**
      * Add the count of the content buffer and check if the accumulated
      * value exceeds the limit
+     * @param isPEDecl a flag to indicate whether the entity is parameter
      * @param entityName entity name
      * @param buffer content buffer
      */
-    private void checkLimit(String entityName, XMLString buffer) {
-        checkLimit(entityName, buffer.length);
+    private void checkEntityLimit(boolean isPEDecl, String entityName, XMLString buffer) {
+        checkEntityLimit(isPEDecl, entityName, buffer.length);
     }
 
     /**
      * Add the count and check limit
+     * @param isPEDecl a flag to indicate whether the entity is parameter
      * @param entityName entity name
      * @param len length of the buffer
      */
-    private void checkLimit(String entityName, int len) {
+    private void checkEntityLimit(boolean isPEDecl, String entityName, int len) {
         if (fLimitAnalyzer == null) {
-            fLimitAnalyzer = new XMLLimitAnalyzer();
+            fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
         }
-        fLimitAnalyzer.addValue(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, entityName, len);
-        if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
-                    fSecurityManager.debugPrint(fLimitAnalyzer);
-            reportFatalError("MaxEntitySizeLimit", new Object[]{entityName,
-                fLimitAnalyzer.getValue(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT),
-                fSecurityManager.getLimit(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT),
-                fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT)});
+        if (isPEDecl) {
+            fLimitAnalyzer.addValue(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, "%" + entityName, len);
+            if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
+                        fSecurityManager.debugPrint(fLimitAnalyzer);
+                reportFatalError("MaxEntitySizeLimit", new Object[]{"%" + entityName,
+                    fLimitAnalyzer.getValue(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT),
+                    fSecurityManager.getLimit(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT),
+                    fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT)});
+            }
+        } else {
+            fLimitAnalyzer.addValue(XMLSecurityManager.Limit.GENEAL_ENTITY_SIZE_LIMIT, entityName, len);
+            if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.GENEAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
+                        fSecurityManager.debugPrint(fLimitAnalyzer);
+                reportFatalError("MaxEntitySizeLimit", new Object[]{entityName,
+                    fLimitAnalyzer.getValue(XMLSecurityManager.Limit.GENEAL_ENTITY_SIZE_LIMIT),
+                    fSecurityManager.getLimit(XMLSecurityManager.Limit.GENEAL_ENTITY_SIZE_LIMIT),
+                    fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.GENEAL_ENTITY_SIZE_LIMIT)});
+            }
         }
         if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
             fSecurityManager.debugPrint(fLimitAnalyzer);
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java	Sun Jul 12 22:35:12 2015 +0300
@@ -89,7 +89,7 @@
     // Constants
     //
 
-    protected int fElementAttributeLimit;
+    protected int fElementAttributeLimit, fXMLNameLimit;
 
     /** External subset resolver. **/
     protected ExternalSubsetResolver fExternalSubsetResolver;
@@ -425,7 +425,7 @@
      */
     public void setInputSource(XMLInputSource inputSource) throws IOException {
         fEntityManager.setEntityHandler(this);
-        fEntityManager.startEntity("$fragment$", inputSource, false, true);
+        fEntityManager.startEntity(false, "$fragment$", inputSource, false, true);
         // fDocumentSystemId = fEntityManager.expandSystemId(inputSource.getSystemId());
     } // setInputSource(XMLInputSource)
 
@@ -660,11 +660,12 @@
 
         if (fSecurityManager != null) {
             fElementAttributeLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.ELEMENT_ATTRIBUTE_LIMIT);
+            fXMLNameLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_NAME_LIMIT);
         } else {
             fElementAttributeLimit = 0;
+            fXMLNameLimit = XMLSecurityManager.Limit.MAX_NAME_LIMIT.defaultValue();
         }
-        fLimitAnalyzer = new XMLLimitAnalyzer();
-        fEntityManager.setLimitAnalyzer(fLimitAnalyzer);
+        fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
     }
 
     /**
@@ -1905,7 +1906,7 @@
         //if that was the case it its taken care in XMLEntityManager.startEntity()
         //we immediately call the endEntity. Application gets to know if there was
         //any entity that was not declared.
-        fEntityManager.startEntity(name, false);
+        fEntityManager.startEntity(true, name, false);
         //set the scaner state to content.. parser will automatically revive itself at any point of time.
         //setScannerState(SCANNER_STATE_CONTENT);
         //return true ;
@@ -2851,8 +2852,6 @@
                             if(DEBUG){
                                 System.out.println("NOT USING THE BUFFER, STRING = " + fTempString.toString());
                             }
-                            //check limit before returning event
-                            checkLimit(fContentBuffer);
                             if(dtdGrammarUtil!= null && dtdGrammarUtil.isIgnorableWhiteSpace(fContentBuffer)){
                                 if(DEBUG)System.out.println("Return SPACE EVENT");
                                 return XMLEvent.SPACE;
@@ -2951,8 +2950,6 @@
                             fLastSectionWasCharacterData = true ;
                             continue;
                         }else{
-                            //check limit before returning event
-                            checkLimit(fContentBuffer);
                             if(dtdGrammarUtil!= null && dtdGrammarUtil.isIgnorableWhiteSpace(fContentBuffer)){
                                 if(DEBUG)System.out.println("Return SPACE EVENT");
                                 return XMLEvent.SPACE;
@@ -3163,31 +3160,6 @@
             } //while loop
         }//next
 
-        /**
-         * Add the count of the content buffer and check if the accumulated
-         * value exceeds the limit
-         * @param buffer content buffer
-         */
-        protected void checkLimit(XMLStringBuffer buffer) {
-            if (fLimitAnalyzer.isTracking(fCurrentEntityName)) {
-                fLimitAnalyzer.addValue(Limit.GENEAL_ENTITY_SIZE_LIMIT, fCurrentEntityName, buffer.length);
-                if (fSecurityManager.isOverLimit(Limit.GENEAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
-                    fSecurityManager.debugPrint(fLimitAnalyzer);
-                    reportFatalError("MaxEntitySizeLimit", new Object[]{fCurrentEntityName,
-                        fLimitAnalyzer.getValue(Limit.GENEAL_ENTITY_SIZE_LIMIT),
-                        fSecurityManager.getLimit(Limit.GENEAL_ENTITY_SIZE_LIMIT),
-                        fSecurityManager.getStateLiteral(Limit.GENEAL_ENTITY_SIZE_LIMIT)});
-                }
-                if (fSecurityManager.isOverLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
-                    fSecurityManager.debugPrint(fLimitAnalyzer);
-                    reportFatalError("TotalEntitySizeLimit",
-                        new Object[]{fLimitAnalyzer.getTotalValue(Limit.TOTAL_ENTITY_SIZE_LIMIT),
-                        fSecurityManager.getLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT),
-                        fSecurityManager.getStateLiteral(Limit.TOTAL_ENTITY_SIZE_LIMIT)});
-                }
-            }
-        }
-
         //
         // Protected methods
         //
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java	Sun Jul 12 22:35:12 2015 +0300
@@ -401,6 +401,8 @@
      * If this constructor is used to create the object, reset() should be invoked on this object
      */
     public XMLEntityManager() {
+        //for entity managers not created by parsers
+        fSecurityManager = new XMLSecurityManager(true);
         fEntityStorage = new XMLEntityStorage(this) ;
         setScannerVersion(Constants.XML_VERSION_1_0);
     } // <init>()
@@ -578,6 +580,8 @@
     /**
      * This method uses the passed-in XMLInputSource to make
      * fCurrentEntity usable for reading.
+     *
+     * @param reference flag to indicate whether the entity is an Entity Reference.
      * @param name  name of the entity (XML is it's the document entity)
      * @param xmlInputSource    the input source, with sufficient information
      *      to begin scanning characters.
@@ -588,7 +592,7 @@
      *  XNIException    If any parser-specific goes wrong.
      * @return the encoding of the new entity or null if a character stream was employed
      */
-    public String setupCurrentEntity(String name, XMLInputSource xmlInputSource,
+    public String setupCurrentEntity(boolean reference, String name, XMLInputSource xmlInputSource,
             boolean literal, boolean isExternal)
             throws IOException, XNIException {
         // get information
@@ -831,7 +835,9 @@
          * in the prolog of the XML document is not considered. Hence, prolog can
          * be read in Chunks of data instead of byte by byte.
          */
-        fCurrentEntity = new com.sun.xml.internal.stream.Entity.ScannedEntity(name,new XMLResourceIdentifierImpl(publicId, literalSystemId, baseSystemId, expandedSystemId),stream, reader, encoding, literal, encodingExternallySpecified, isExternal);
+        fCurrentEntity = new Entity.ScannedEntity(reference, name,
+                new XMLResourceIdentifierImpl(publicId, literalSystemId, baseSystemId, expandedSystemId),
+                stream, reader, encoding, literal, encodingExternallySpecified, isExternal);
         fCurrentEntity.setEncodingExternallySpecified(encodingExternallySpecified);
         fEntityScanner.setCurrentEntity(fCurrentEntity);
         fResourceIdentifier.setValues(publicId, literalSystemId, baseSystemId, expandedSystemId);
@@ -1099,6 +1105,7 @@
     /**
      * Starts a named entity.
      *
+     * @param reference flag to indicate whether the entity is an Entity Reference.
      * @param entityName The name of the entity to start.
      * @param literal    True if this entity is started within a literal
      *                   value.
@@ -1106,7 +1113,7 @@
      * @throws IOException  Thrown on i/o error.
      * @throws XNIException Thrown by entity handler to signal an error.
      */
-    public void startEntity(String entityName, boolean literal)
+    public void startEntity(boolean reference, String entityName, boolean literal)
     throws IOException, XNIException {
 
         // was entity declared?
@@ -1230,7 +1237,7 @@
         }
 
         // start the entity
-        startEntity(entityName, xmlInputSource, literal, external);
+        startEntity(reference, entityName, xmlInputSource, literal, external);
 
     } // startEntity(String,boolean)
 
@@ -1245,7 +1252,7 @@
      */
     public void startDocumentEntity(XMLInputSource xmlInputSource)
     throws IOException, XNIException {
-        startEntity(XMLEntity, xmlInputSource, false, true);
+        startEntity(false, XMLEntity, xmlInputSource, false, true);
     } // startDocumentEntity(XMLInputSource)
 
     //xxx these methods are not required.
@@ -1260,7 +1267,7 @@
      */
     public void startDTDEntity(XMLInputSource xmlInputSource)
     throws IOException, XNIException {
-        startEntity(DTDEntity, xmlInputSource, false, true);
+        startEntity(false, DTDEntity, xmlInputSource, false, true);
     } // startDTDEntity(XMLInputSource)
 
     // indicate start of external subset so that
@@ -1279,6 +1286,7 @@
      * This method can be used to insert an application defined XML
      * entity stream into the parsing stream.
      *
+     * @param reference flag to indicate whether the entity is an Entity Reference.
      * @param name           The name of the entity.
      * @param xmlInputSource The input source of the entity.
      * @param literal        True if this entity is started within a
@@ -1288,12 +1296,12 @@
      * @throws IOException  Thrown on i/o error.
      * @throws XNIException Thrown by entity handler to signal an error.
      */
-    public void startEntity(String name,
+    public void startEntity(boolean reference, String name,
             XMLInputSource xmlInputSource,
             boolean literal, boolean isExternal)
             throws IOException, XNIException {
 
-        String encoding = setupCurrentEntity(name, xmlInputSource, literal, isExternal);
+        String encoding = setupCurrentEntity(reference, name, xmlInputSource, literal, isExternal);
 
         //when entity expansion limit is set by the Application, we need to
         //check for the entity expansion limit set by the parser, if number of entity
@@ -1305,7 +1313,7 @@
         }
         if( fSecurityManager != null && fSecurityManager.isOverLimit(entityExpansionIndex, fLimitAnalyzer)){
             fSecurityManager.debugPrint(fLimitAnalyzer);
-            fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,"EntityExpansionLimitExceeded",
+            fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,"EntityExpansionLimit",
                     new Object[]{fSecurityManager.getLimitValueByIndex(entityExpansionIndex)},
                                              XMLErrorReporter.SEVERITY_FATAL_ERROR );
             // is there anything better to do than reset the counter?
@@ -1421,10 +1429,6 @@
     // XMLComponent methods
     //
     public void reset(PropertyManager propertyManager){
-        //reset fEntityStorage
-        fEntityStorage.reset(propertyManager);
-        //reset XMLEntityReaderImpl
-        fEntityScanner.reset(propertyManager);
         // xerces properties
         fSymbolTable = (SymbolTable)propertyManager.getProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY);
         fErrorReporter = (XMLErrorReporter)propertyManager.getProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY);
@@ -1447,6 +1451,12 @@
 
         fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(SECURITY_MANAGER);
 
+        fLimitAnalyzer = new XMLLimitAnalyzer();
+        //reset fEntityStorage
+        fEntityStorage.reset(propertyManager);
+        //reset XMLEntityReaderImpl
+        fEntityScanner.reset(propertyManager);
+
         // initialize state
         //fStandalone = false;
         fEntities.clear();
@@ -1533,7 +1543,7 @@
     // a class acting as a component manager but not
     // implementing that interface for whatever reason.
     public void reset() {
-
+        fLimitAnalyzer = new XMLLimitAnalyzer();
         // initialize state
         fStandalone = false;
         fEntities.clear();
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -30,10 +30,14 @@
 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.util.XMLStringBuffer;
+import com.sun.org.apache.xerces.internal.utils.XMLLimitAnalyzer;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager.Limit;
 import com.sun.org.apache.xerces.internal.xni.*;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 import com.sun.xml.internal.stream.Entity;
+import com.sun.xml.internal.stream.Entity.ScannedEntity;
 import com.sun.xml.internal.stream.XMLBufferListener;
 import java.io.EOFException;
 import java.io.IOException;
@@ -60,6 +64,12 @@
 
     protected XMLEntityManager fEntityManager ;
 
+    /** Security manager. */
+    protected XMLSecurityManager fSecurityManager = null;
+
+    /** Limit analyzer. */
+    protected XMLLimitAnalyzer fLimitAnalyzer = null;
+
     /** Debug switching readers for encodings. */
     private static final boolean DEBUG_ENCODINGS = false;
     /** Listeners which should know when load is being called */
@@ -174,10 +184,7 @@
     public void reset(PropertyManager propertyManager){
         fSymbolTable = (SymbolTable)propertyManager.getProperty(SYMBOL_TABLE) ;
         fErrorReporter = (XMLErrorReporter)propertyManager.getProperty(ERROR_REPORTER) ;
-        fCurrentEntity = null;
-        whiteSpaceLen = 0;
-        whiteSpaceInfoNeeded = true;
-        listeners.clear();
+        resetCommon();
     }
 
     /**
@@ -196,18 +203,13 @@
      */
     public void reset(XMLComponentManager componentManager)
     throws XMLConfigurationException {
-
-        //System.out.println(" this is being called");
         // xerces features
         fAllowJavaEncodings = componentManager.getFeature(ALLOW_JAVA_ENCODINGS, false);
 
         //xerces properties
         fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
         fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
-        fCurrentEntity = null;
-        whiteSpaceLen = 0;
-        whiteSpaceInfoNeeded = true;
-        listeners.clear();
+        resetCommon();
     } // reset(XMLComponentManager)
 
 
@@ -217,6 +219,17 @@
         fSymbolTable = symbolTable;
         fEntityManager = entityManager;
         fErrorReporter = reporter;
+        fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
+        fSecurityManager = fEntityManager.fSecurityManager;
+    }
+
+    private void resetCommon() {
+        fCurrentEntity = null;
+        whiteSpaceLen = 0;
+        whiteSpaceInfoNeeded = true;
+        listeners.clear();
+        fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
+        fSecurityManager = fEntityManager.fSecurityManager;
     }
 
     /**
@@ -813,9 +826,13 @@
                         break;
                     }
                     index = fCurrentEntity.position;
+                    //check prefix before further read
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, index - offset);
                 }
                 if (++fCurrentEntity.position == fCurrentEntity.count) {
                     int length = fCurrentEntity.position - offset;
+                    //check localpart before loading more data
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length - index - 1);
                     invokeListeners(length);
                     if (length == fCurrentEntity.fBufferSize) {
                         // bad luck we have to resize our buffer
@@ -847,14 +864,20 @@
 
                 if (index != -1) {
                     int prefixLength = index - offset;
+                    //check the result: prefix
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, prefixLength);
                     prefix = fSymbolTable.addSymbol(fCurrentEntity.ch,
                             offset, prefixLength);
                     int len = length - prefixLength - 1;
+                    //check the result: localpart
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, index + 1, len);
                     localpart = fSymbolTable.addSymbol(fCurrentEntity.ch,
                             index + 1, len);
 
                 } else {
                     localpart = rawname;
+                    //check the result: localpart
+                    checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
                 }
                 qname.setValues(prefix, localpart, rawname, null);
                 if (DEBUG_BUFFER) {
@@ -877,6 +900,27 @@
     } // scanQName(QName):boolean
 
     /**
+     * Checks whether the value of the specified Limit exceeds its limit
+     *
+     * @param limit The Limit to be checked.
+     * @param entity The current entity.
+     * @param offset The index of the first byte
+     * @param length The length of the entity scanned.
+     */
+    protected void checkLimit(Limit limit, ScannedEntity entity, int offset, int length) {
+        fLimitAnalyzer.addValue(limit, null, length);
+        if (fSecurityManager.isOverLimit(limit, fLimitAnalyzer)) {
+            fSecurityManager.debugPrint(fLimitAnalyzer);
+            fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, limit.key(),
+                    new Object[]{new String(entity.ch, offset, length),
+                fLimitAnalyzer.getTotalValue(limit),
+                fSecurityManager.getLimit(limit),
+                fSecurityManager.getStateLiteral(limit)},
+                    XMLErrorReporter.SEVERITY_FATAL_ERROR);
+        }
+    }
+
+    /**
      * CHANGED:
      * Scans a range of parsed character data, This function appends the character data to
      * the supplied buffer.
@@ -994,6 +1038,9 @@
         }
         int length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length - newlines;
+        if (fCurrentEntity.reference) {
+            checkLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fCurrentEntity, offset, length);
+        }
 
         //CHANGED: dont replace the value.. append to the buffer. This gives control to the callee
         //on buffering the data..
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -37,6 +37,7 @@
 import com.sun.org.apache.xerces.internal.xni.XMLAttributes;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentSource;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 
 import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLStreamConstants;
@@ -453,7 +454,15 @@
             // it's a namespace declaration. but prefix:xmlns="..." isn't.
             if (prefix == XMLSymbols.PREFIX_XMLNS ||
                     prefix == XMLSymbols.EMPTY_STRING && localpart == XMLSymbols.PREFIX_XMLNS) {
-
+                //check the length of URI
+                if (tmpStr.length > fXMLNameLimit) {
+                    fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
+                            "MaxXMLNameLimit",
+                            new Object[]{new String(tmpStr.ch,tmpStr.offset,tmpStr.length),
+                            tmpStr.length, fXMLNameLimit,
+                            fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.MAX_NAME_LIMIT)},
+                            XMLErrorReporter.SEVERITY_FATAL_ERROR);
+                }
                 // get the internalized value of this attribute
                 String uri = fSymbolTable.addSymbol(tmpStr.ch,tmpStr.offset,tmpStr.length);
                 value = uri;
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java	Sun Jul 12 22:35:12 2015 +0300
@@ -947,7 +947,7 @@
                                                 new Object[]{entityName});
                                     }
                                 }
-                                fEntityManager.startEntity(entityName, true);
+                                fEntityManager.startEntity(false, entityName, true);
                             }
                         }
                     }
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java	Sun Jul 12 22:35:12 2015 +0300
@@ -186,7 +186,7 @@
      * @throws IOException
      */
     public short determineDocVersion(XMLInputSource inputSource) throws IOException {
-        fEncoding = fEntityManager.setupCurrentEntity(fXMLSymbol, inputSource, false, true);
+        fEncoding = fEntityManager.setupCurrentEntity(false, fXMLSymbol, inputSource, false, true);
 
         // Must use XML 1.0 scanner to handle whitespace correctly
         // in the XML declaration.
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties	Sun Jul 12 22:35:12 2015 +0300
@@ -294,10 +294,10 @@
 
 
 # Implementation limits
-        EntityExpansionLimitExceeded=JAXP00010001: The parser has encountered more than \"{0}\" entity expansions in this document; this is the limit imposed by the JDK.
+        EntityExpansionLimit=JAXP00010001: The parser has encountered more than \"{0}\" entity expansions in this document; this is the limit imposed by the JDK.
         ElementAttributeLimit=JAXP00010002:  Element \"{0}\" has more than \"{1}\" attributes, \"{1}\" is the limit imposed by the JDK.
         MaxEntitySizeLimit=JAXP00010003: The length of entity \"{0}\" is \"{1}\" that exceeds the \"{2}\" limit set by \"{3}\".
-        TotalEntitySizeLimit=JAXP00010004: The accumulated size \"{0}\" of entities exceeded the \"{1}\" limit set by \"{2}\".
-        MaxXMLNameLimit=JAXP00010005: The name \"{0}\" exceeded the \"{1}\" limit set by \"{2}\".
+        TotalEntitySizeLimit=JAXP00010004: The accumulated size of entities is \"{1}\" that exceeded the \"{2}\" limit set by \"{3}\".
+        MaxXMLNameLimit=JAXP00010005: The length of entity \"{0}\" is \"{1}\" that exceeds the \"{2}\" limit set by \"{3}\".
         MaxElementDepthLimit=JAXP00010006: The element \"{0}\" has a depth of \"{1}\" that exceeds the limit \"{2}\" set by \"{3}\".
 
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties	Sun Jul 12 22:35:12 2015 +0300
@@ -283,7 +283,7 @@
         FacetValueFromBase = FacetValueFromBase: In the declaration of type ''{0}'', value ''{1}'' of facet ''{2}'' must be from the value space of the base type, ''{3}''.
         FixedFacetValue = FixedFacetValue: In the definition of {3}, the value ''{1}'' for the facet ''{0}'' is invalid, because the value for ''{0}'' has been set to ''{2}'' in one of the ancestor types, and '{'fixed'}' = true.
         InvalidRegex = InvalidRegex: Pattern value ''{0}'' is not a valid regular expression. The reported error was: ''{1}'' at column ''{2}''.
-        maxOccurLimit = Current configuration of the parser doesn''t allow a maxOccurs attribute value to be set greater than the value {0}.
+        MaxOccurLimit = Current configuration of the parser doesn''t allow a maxOccurs attribute value to be set greater than the value {0}.
         PublicSystemOnNotation = PublicSystemOnNotation: At least one of ''public'' and ''system'' must appear in element ''notation''.
         SchemaLocation = SchemaLocation: schemaLocation value = ''{0}'' must have even number of URI''s.
         TargetNamespace.1 = TargetNamespace.1: Expecting namespace ''{0}'', but the target namespace of the schema document is ''{1}''.
--- a/src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java	Sun Jul 12 22:35:12 2015 +0300
@@ -115,7 +115,7 @@
                 System.out.println("nodeCount = " + nodeCount ) ;
                 System.out.println("nodeLimit = " + maxNodeLimit ) ;
             }
-            fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "maxOccurLimit", new Object[]{ new Integer(maxNodeLimit) }, XMLErrorReporter.SEVERITY_FATAL_ERROR);
+            fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "MaxOccurLimit", new Object[]{ new Integer(maxNodeLimit) }, XMLErrorReporter.SEVERITY_FATAL_ERROR);
             // similarly to entity manager behaviour, take into accont
             // behaviour if continue-after-fatal-error is set.
             nodeCount = 0;
--- a/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1193,7 +1193,7 @@
                     // maxOccurNodeLimit.
                     int maxOccurNodeLimit = fSchemaHandler.fSecureProcessing.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT);
                     if (max > maxOccurNodeLimit && !fSchemaHandler.fSecureProcessing.isNoLimit(maxOccurNodeLimit)) {
-                        reportSchemaFatalError("maxOccurLimit", new Object[] {new Integer(maxOccurNodeLimit)}, element);
+                        reportSchemaFatalError("MaxOccurLimit", new Object[] {new Integer(maxOccurNodeLimit)}, element);
 
                         // reset max values in case processing continues on error
                         attrValues[ATTIDX_MAXOCCURS] = fXIntPool.getXInt(maxOccurNodeLimit);
--- a/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java	Sun Jul 12 22:35:12 2015 +0300
@@ -128,18 +128,21 @@
     public void addValue(int index, String entityName, int value) {
         if (index == Limit.ENTITY_EXPANSION_LIMIT.ordinal() ||
                 index == Limit.MAX_OCCUR_NODE_LIMIT.ordinal() ||
-                index == Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal()) {
+                index == Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal() ||
+                index == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal()
+                ) {
             totalValue[index] += value;
             return;
         }
-        if (index == Limit.MAX_ELEMENT_DEPTH_LIMIT.ordinal()) {
+        if (index == Limit.MAX_ELEMENT_DEPTH_LIMIT.ordinal() ||
+                index == Limit.MAX_NAME_LIMIT.ordinal()) {
             totalValue[index] = value;
             return;
         }
 
         Map<String, Integer> cache;
         if (caches[index] == null) {
-            cache = new HashMap<String, Integer>(10);
+            cache = new HashMap<>(10);
             caches[index] = cache;
         } else {
             cache = caches[index];
@@ -147,10 +150,10 @@
 
         int accumulatedValue = value;
         if (cache.containsKey(entityName)) {
-            accumulatedValue += cache.get(entityName).intValue();
-            cache.put(entityName, Integer.valueOf(accumulatedValue));
+            accumulatedValue += cache.get(entityName);
+            cache.put(entityName, accumulatedValue);
         } else {
-            cache.put(entityName, Integer.valueOf(value));
+            cache.put(entityName, value);
         }
 
         if (accumulatedValue > values[index]) {
@@ -223,6 +226,16 @@
         }
     }
 
+    /**
+     * Resets the current value of the specified limit.
+     * @param limit The limit to be reset.
+     */
+    public void reset(Limit limit) {
+        if (limit.ordinal() == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal()) {
+            totalValue[limit.ordinal()] = 0;
+        }
+    }
+
     public void debugPrint(XMLSecurityManager securityManager) {
         Formatter formatter = new Formatter();
         System.out.println(formatter.format("%30s %15s %15s %15s %30s",
--- a/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java	Sun Jul 12 22:35:12 2015 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -61,20 +61,31 @@
      */
     public static enum Limit {
 
-        ENTITY_EXPANSION_LIMIT(Constants.JDK_ENTITY_EXPANSION_LIMIT, Constants.SP_ENTITY_EXPANSION_LIMIT, 0, 64000),
-        MAX_OCCUR_NODE_LIMIT(Constants.JDK_MAX_OCCUR_LIMIT, Constants.SP_MAX_OCCUR_LIMIT, 0, 5000),
-        ELEMENT_ATTRIBUTE_LIMIT(Constants.JDK_ELEMENT_ATTRIBUTE_LIMIT, Constants.SP_ELEMENT_ATTRIBUTE_LIMIT, 0, 10000),
-        TOTAL_ENTITY_SIZE_LIMIT(Constants.JDK_TOTAL_ENTITY_SIZE_LIMIT, Constants.SP_TOTAL_ENTITY_SIZE_LIMIT, 0, 50000000),
-        GENEAL_ENTITY_SIZE_LIMIT(Constants.JDK_GENEAL_ENTITY_SIZE_LIMIT, Constants.SP_GENEAL_ENTITY_SIZE_LIMIT, 0, 0),
-        PARAMETER_ENTITY_SIZE_LIMIT(Constants.JDK_PARAMETER_ENTITY_SIZE_LIMIT, Constants.SP_PARAMETER_ENTITY_SIZE_LIMIT, 0, 1000000),
-        MAX_ELEMENT_DEPTH_LIMIT(Constants.JDK_MAX_ELEMENT_DEPTH, Constants.SP_MAX_ELEMENT_DEPTH, 0, 0);
+        ENTITY_EXPANSION_LIMIT("EntityExpansionLimit",
+                Constants.JDK_ENTITY_EXPANSION_LIMIT, Constants.SP_ENTITY_EXPANSION_LIMIT, 0, 64000),
+        MAX_OCCUR_NODE_LIMIT("MaxOccurLimit",
+                Constants.JDK_MAX_OCCUR_LIMIT, Constants.SP_MAX_OCCUR_LIMIT, 0, 5000),
+        ELEMENT_ATTRIBUTE_LIMIT("ElementAttributeLimit",
+                Constants.JDK_ELEMENT_ATTRIBUTE_LIMIT, Constants.SP_ELEMENT_ATTRIBUTE_LIMIT, 0, 10000),
+        TOTAL_ENTITY_SIZE_LIMIT("TotalEntitySizeLimit",
+                Constants.JDK_TOTAL_ENTITY_SIZE_LIMIT, Constants.SP_TOTAL_ENTITY_SIZE_LIMIT, 0, 50000000),
+        GENEAL_ENTITY_SIZE_LIMIT("MaxEntitySizeLimit",
+                Constants.JDK_GENEAL_ENTITY_SIZE_LIMIT, Constants.SP_GENEAL_ENTITY_SIZE_LIMIT, 0, 0),
+        PARAMETER_ENTITY_SIZE_LIMIT("MaxEntitySizeLimit",
+                Constants.JDK_PARAMETER_ENTITY_SIZE_LIMIT, Constants.SP_PARAMETER_ENTITY_SIZE_LIMIT, 0, 1000000),
+        MAX_ELEMENT_DEPTH_LIMIT("MaxElementDepthLimit",
+                Constants.JDK_MAX_ELEMENT_DEPTH, Constants.SP_MAX_ELEMENT_DEPTH, 0, 0),
+        MAX_NAME_LIMIT("MaxXMLNameLimit",
+                Constants.JDK_XML_NAME_LIMIT, Constants.SP_XML_NAME_LIMIT, 1000, 1000);
 
+        final String key;
         final String apiProperty;
         final String systemProperty;
         final int defaultValue;
         final int secureValue;
 
-        Limit(String apiProperty, String systemProperty, int value, int secureValue) {
+        Limit(String key, String apiProperty, String systemProperty, int value, int secureValue) {
+            this.key = key;
             this.apiProperty = apiProperty;
             this.systemProperty = systemProperty;
             this.defaultValue = value;
@@ -89,6 +100,10 @@
             return (propertyName == null) ? false : systemProperty.equals(propertyName);
         }
 
+        public String key() {
+            return key;
+        }
+
         public String apiProperty() {
             return apiProperty;
         }
@@ -97,7 +112,7 @@
             return systemProperty;
         }
 
-        int defaultValue() {
+        public int defaultValue() {
             return defaultValue;
         }
 
@@ -152,7 +167,7 @@
     /**
      * Index of the special entityCountInfo property
      */
-    private int indexEntityCountInfo = 10000;
+    private final int indexEntityCountInfo = 10000;
     private String printEntityCountInfo = "";
 
     /**
@@ -433,7 +448,9 @@
         if (index == Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal() ||
                 index == Limit.ENTITY_EXPANSION_LIMIT.ordinal() ||
                 index == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal() ||
-                index == Limit.MAX_ELEMENT_DEPTH_LIMIT.ordinal()) {
+                index == Limit.MAX_ELEMENT_DEPTH_LIMIT.ordinal() ||
+                index == Limit.MAX_NAME_LIMIT.ordinal()
+                ) {
             return (limitAnalyzer.getTotalValue(index) > values[index]);
         } else {
             return (limitAnalyzer.getValue(index) > values[index]);
--- a/src/com/sun/xml/internal/stream/Entity.java	Wed Jun 03 17:05:41 2015 +0300
+++ b/src/com/sun/xml/internal/stream/Entity.java	Sun Jul 12 22:35:12 2015 +0300
@@ -344,6 +344,9 @@
         // to know that prolog is read
         public boolean xmlDeclChunkRead = false;
 
+        // flag to indicate whether the Entity is an Entity Reference
+        public boolean reference = false;
+
         /** returns the name of the current encoding
          *  @return current encoding name
          */
@@ -388,10 +391,11 @@
         //
 
         /** Constructs a scanned entity. */
-        public ScannedEntity(String name,
+        public ScannedEntity(boolean reference, String name,
                 XMLResourceIdentifier entityLocation,
                 InputStream stream, Reader reader,
                 String encoding, boolean literal, boolean mayReadChunks, boolean isExternal) {
+            this.reference = reference;
             this.name = name ;
             this.entityLocation = entityLocation;
             this.stream = stream;