Merge 'jetbrains-master-mirror' into studio-master-dev

This adds upstream's latest changes from branch 884, see
https://github.com/JetBrains/jdk8u_jaxp/compare/736...884
diff --git a/.hgtags b/.hgtags
index e7129e5..0575ee8 100644
--- a/.hgtags
+++ b/.hgtags
@@ -386,6 +386,7 @@
 56f6ca79467d04eb95383102046836b6ac7d2811 jdk8u40-b27
 7e43d4e20a33b8b6bd06112e39d367b51de921a7 jdk8u40-b31
 8facbe662ec106f1aae271f5c59909e124938c40 jdk8u40-b32
+b02301aeab79b1ee7859aeeb994fa5ba31105734 jdk8u40-b33
 9286acc600a779acb8bcfab38e82d4f50704afe3 jdk8u45-b00
 9fded65e1d36e3388111955d50ebf8511dd0345e jdk8u45-b01
 62566a3dbe5982565ce3e468ee3980b7937a86cc jdk8u45-b02
@@ -544,10 +545,24 @@
 aa9485a887b7e983f9743c9c114de2055055300d jdk8u74-b01
 b3325c0526621f9ddf82738373cc8f8947dab195 jdk8u74-b02
 2b3d0e6f3cd179e2346679af2a8881bb6b20f968 jdk8u72-b31
+aeecbaa27f807ce0656a108cd0e81669724b8d1b jdk8u73-b00
+9009a8b2b55256764dd304902b04a3dea2597684 jdk8u73-b01
+7a021985ef009c3a88a206d6f295f17e382f98b9 jdk8u73-b02
+2e7b89c7f79794b872e73708fdaa3ed9331ec45d jdk8u74-b00
+aa9485a887b7e983f9743c9c114de2055055300d jdk8u74-b01
+b3325c0526621f9ddf82738373cc8f8947dab195 jdk8u74-b02
+c583ac51e2c78d6c59786b447986baf7b961518d jdk8u74-b31
+4c8fd0814bf0bcbc9666a29e1daa35c64c7bb57a jdk8u74-b32
+8cc52edbb741c42e09f4b132ca0a759d3de6f848 jdk8u77-b00
+8f0ed89698a28138065b6b941769650627636745 jdk8u77-b01
+27f1130320a55b6b89024cb8baa93c8767c516d2 jdk8u77-b02
+1c71899e85662239085fab94ad5c26441e7a80cd jdk8u77-b03
+a49d8c7db1e5b3ab84561069bd4ae63579139878 jdk8u77-b31
 eca165c0654ac2e1926b50655e5ed5e9b73ca674 jdk8u75-b00
 06cdf5dc679e0fef7c8e37c5c712b2c5891c1444 jdk8u75-b01
 26c297e9f11b78b55cdefd22849ae4fe55042a5b jdk8u75-b02
 2a292503c55704cb7f898fa195d76682c0ea6a72 jdk8u75-b03
+cb072b12f5dbe3a249d596078d98a34ec9364187 jdk8u101-b00
 cb072b12f5dbe3a249d596078d98a34ec9364187 jdk8u75-b04
 40ccc40d58450eb4518348f6b34885c5a711675a jdk8u75-b05
 e77acebebfdc2f84b1217be3a6a2eb4c205afda5 jdk8u75-b06
@@ -563,6 +578,7 @@
 6b0d1f04c4808aaab32771e0892ac83e66714ecb jdk8u91-b00
 817898d53814da42f567995c921f3ea90016dccc jdk8u91-b13
 f6bda5729ff86e9691cd51f04261c3942974cecc jdk8u91-b14
+8b0bf55a041ae5657b1ae9e74e68258e8d36dda4 jdk8u91-b15
 acbcb6682c9b3e66f9cc61a6a62e8cb5f24c75d3 jdk8u76-b00
 b3c914ad842d61818e0c5850409f77478b13acc6 jdk8u76-b01
 7711933ec18462ece8a1b9a9527ec873c520b1ab jdk8u76-b02
@@ -579,6 +595,24 @@
 7e43e115dfafee70152a01b99aa9de25b4410570 jdk8u92-b00
 1bce84411d37ecf9a4335d1348f4b2f0b7ab6e08 jdk8u92-b13
 fb9f98ed6ef2505a424864f0a9468e59298fede6 jdk8u92-b14
+ac887193179bae82fd1cdf4d8c463457163a6535 jdk8u92-b31
+edce55dd16423b70ebdb36a14b3e6c62d223637b jdk8u92-b32
+69550dfee4b1adb5c73175f0555dd69e7436ca8b jdk8u92-b33
+75757308d2785ab9dc36fddf022e6d3f6e9246a6 jdk8u92-b34
+cb072b12f5dbe3a249d596078d98a34ec9364187 jdk8u81-b00
+fb5e0a18ad7d49134616879d1a500b1356e12fd4 jdk8u101-b01
+c7aeb4e55b0f7de8c5bd2a6e41dc5c54c4239271 jdk8u101-b02
+c678c1a31a553ebe7a8fd3888acc282dbd975e3b jdk8u101-b03
+a6a032a5490f4000bdfb25a2f604b22bcdf95ecf jdk8u101-b04
+80f389596bfaa22d4d2282b8417b98a53241f2aa jdk8u101-b05
+03f2bf9410ef2aad8d8a5ab0432ae0dbdf8bfd62 jdk8u101-b06
+39e620ddf0bb8c6a6d6f0588c71d5f43d8bcc987 jdk8u101-b07
+20b4715976338d4307c2d70e205ce88f31fbd7e7 jdk8u101-b08
+97939d061a0e492c6c2b464df44373165ecc15d2 jdk8u101-b09
+0066fe71b1203e103f7e1a2354bd94f65fdf38fd jdk8u101-b10
+0878a0a5fdabeec872e878f4737d96edee8b1393 jdk8u101-b11
+ddcc10eeb9d3367eb4b3fa0cd4d118e6dbc8850e jdk8u101-b12
+8ee36eca2124f4ea14d0b7ef844d5d7070eb0dd1 jdk8u101-b13
 acbcb6682c9b3e66f9cc61a6a62e8cb5f24c75d3 jdk8u76-b00
 b3c914ad842d61818e0c5850409f77478b13acc6 jdk8u76-b01
 7711933ec18462ece8a1b9a9527ec873c520b1ab jdk8u76-b02
@@ -590,6 +624,76 @@
 760d26dbaa27603ee94a746e47f166e6470290c2 jdk8u102-b02
 9be3e75c8f466e69f21a0894731a3863d48bcf43 jdk8u102-b03
 58469c50677dfcf88b7b2f740ac71c7e1d1dd1d2 jdk8u102-b04
+f5cb21e3a36196f1c8c224d6b17d88dec37f7e49 jdk8u102-b05
+545ae88cd091d1e362537971b0c6f1b8d4327b9e jdk8u102-b06
+f563e46f3083e1c542a6bf3e11547d297c9da8fa jdk8u102-b07
+c9f8318eb6315719d79a3fa4791d73da42e73fe2 jdk8u102-b08
+8f5ebb91ab3a341a6f7db7ede8113a4f52a6ab26 jdk8u102-b09
+018c7ebb858c5cd3af8e9b11b03e4e05663250b4 jdk8u102-b10
+429621d25778abb1ab7a0ede8dc48d5606f76108 jdk8u102-b11
+fef62f7eb59982f2c92a3bb135c6ae4d6a466328 jdk8u102-b12
+e9de037c3b4c7691662d996c49b42f3e639e65ee jdk8u102-b13
+1f032000ff4b70c3adc02669b6324880199f8db8 jdk8u102-b14
+ff603463199f8a2140cb97fd3ff98046dfeecb3f jdk8u102-b31
+58dea534c1d49731a40de645cfa3450949f31d26 jdk8u102-b32
+d31aad84c2727e40792cba85073713424b6b209f jdk8u102-b33
+6d28aaf99e9383e968654867e9fd2195046f33f4 jdk8u102-b34
+d3c5785df6b5aacdba20221b2f819aae93becac7 jdk8u102-b35
+a6a032a5490f4000bdfb25a2f604b22bcdf95ecf jdk8u111-b00
+4389b3cda88c98df36b36116999c4591a9b8e12c jdk8u111-b01
+1ffc284c45e0fb86c066b832d7be50766b68eb25 jdk8u111-b02
+f518fa45f0f04dbadd026a390254b57169a0c8ab jdk8u111-b03
+4daccb30c04496252bf7d43de8e2ee0471e4319f jdk8u111-b04
+9bbba018c96a17c5b5583e26a38d3c1e910178ef jdk8u111-b05
+bd3773524c2de38524496097d7d8bc2c1cc39e96 jdk8u111-b06
+9c8856c6b82e4b9773896322146c3b1d6d12a6ec jdk8u111-b07
+76e3e209e51c17546b484b0ac95e77cbb949e4cf jdk8u111-b08
+c4301c045c79b8984346d705999d08475792418b jdk8u111-b09
+ea4555b9d9130771e228fdf0f33b783bcbc3172c jdk8u111-b10
+d80acd543dcb4ddb011dec05da364727da907ec2 jdk8u111-b11
+59b4011136ae60b43855f99d316119ca61d84460 jdk8u111-b12
+41ed5205949c82e729533e897382b39342029cff jdk8u111-b13
+f1d0b6e8107011c46fca3621bcf8c0a873f379f7 jdk8u111-b14
 4e861d8430460a72ee3e5c79a85e772b06684adc jdk8u112-b00
 664dd77016540cb9cee7b1bfa27a0a6970f7cf1f jdk8u112-b01
 80ce57123e23ff53f19c034ea5892b186730ddf3 jdk8u112-b02
+fa8960424b5baf4aa0c1e0172115e85317f04127 jdk8u112-b03
+cfc0c92fdbac159ab3434b96d650324cf6dc91dd jdk8u112-b04
+e677228a078a680d8761b3fd22938effe9f7e18d jdk8u112-b06
+7ebdc1fa55fa3f0c21cc009bf1bb8cfd39a92099 jdk8u112-b07
+6ee652d363bb2e0a9f7f0ea7d0d8f4de727aec7c jdk8u112-b08
+45d7c35417517939a600614f0dd0cb16a3098937 jdk8u112-b09
+17cfa0cd7c3c621236f4dd891f8808c3a03c3542 jdk8u112-b10
+ed365ea4cf5fb4d9407e9484f0cb5cd2e2c7786c jdk8u112-b11
+382516531501b0136ae56e9bccc6d09de805ce39 jdk8u112-b12
+eca53abf6800f86146fbcc0e81af4346526e3ad0 jdk8u112-b13
+15749f6d0d05bc1acc005643ba494ff09387cbdc jdk8u112-b14
+b07754d40ea6415af3b267327e748522ea17b131 jdk8u112-b15
+66ef33852d93fe8469724cbdbbdd57dd0e506a6f jdk8u112-b16
+376ba5ed85cc43ef8f13eddc592126e42887ac60 jdk8u112-b31
+9bbba018c96a17c5b5583e26a38d3c1e910178ef jdk8u121-b00
+21da1526aeaf09fde06ec0a5504b564b591f7d03 jdk8u121-b01
+a0ad630d453b3b3c5b1185056a9216281f3085cd jdk8u121-b02
+e76bf2e89efd4b98fa399e4c7db489fc86275257 jdk8u121-b03
+05ac2cb9826a084578dd3b52582323b2473da631 jdk8u121-b04
+49e1091960832ddb247de2825414577d398ba15f jdk8u121-b05
+e31f5ceba6bf5ab6ddfdd1bffef3536e6af8f78b jdk8u121-b06
+d12a9b165b4789915a6ef267099db9721a9887f8 jdk8u121-b07
+c7325d95eaba9e5ef329527107bafc68346d4264 jdk8u121-b08
+f805dcb18704a7028b9d193e8fe661381d473213 jdk8u121-b09
+989c624fdc1f306f1b6068b0529268a46e21ee6b jdk8u121-b10
+77c3d617ae4c28c6e29d51411ab2b2c9eb24683f jdk8u121-b11
+f9cb265fd35fc60dccd75075614f8e897af92ab3 jdk8u121-b12
+b8d4e47240711ff66f9347483d20c84466d75c89 jdk8u121-b13
+2e5a470691f23ebf8d1f0f0dea8ef7de9a70a943 jdk8u122-b00
+cbb8efe139275a4e7c541f9e45eb410c27a5ea61 jdk8u122-b01
+e279f24557d43d8edfe313cb1a53add7ac6ceb2c jdk8u122-b02
+4d0371f160495cc61e3b57ca2d57884c2b9f9068 jdk8u122-b03
+4d0371f160495cc61e3b57ca2d57884c2b9f9068 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+95728234c69f848fda20c3d107a2a14405e8e8bd jdk8u122-b03
+540ca507f5e33ad46c85750f5df110522454cb2d jdk8u122-b04
+7f6d0e9a119670bb83ab2961503471d73f8a5f7e jdk8u132-b00
+4203c092a35355406709027827e9130f79dd96ca jdk8u152-b00
+bedfdbc290ac3c771c107a644250c1985f26fb2f jdk8u152-b01
diff --git a/ASSEMBLY_EXCEPTION b/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/ASSEMBLY_EXCEPTION
+++ b/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/src/com/sun/org/apache/xalan/internal/XalanConstants.java b/src/com/sun/org/apache/xalan/internal/XalanConstants.java
index e35d775..d77dfb0 100644
--- a/src/com/sun/org/apache/xalan/internal/XalanConstants.java
+++ b/src/com/sun/org/apache/xalan/internal/XalanConstants.java
@@ -81,6 +81,14 @@
      */
     public static final String JDK_GENERAL_ENTITY_SIZE_LIMIT =
             ORACLE_JAXP_PROPERTY_PREFIX + "maxGeneralEntitySizeLimit";
+
+    /**
+     * JDK node count limit in entities that limits the total number of nodes
+     * in all of entity references.
+     */
+    public static final String JDK_ENTITY_REPLACEMENT_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "entityReplacementLimit";
+
     /**
      * JDK maximum parameter entity size limit
      */
@@ -137,6 +145,13 @@
      * JDK maximum general entity size limit
      */
     public static final String SP_GENERAL_ENTITY_SIZE_LIMIT = "jdk.xml.maxGeneralEntitySizeLimit";
+
+    /**
+     * JDK node count limit in entities that limits the total number of nodes
+     * in all of entity references.
+     */
+    public static final String SP_ENTITY_REPLACEMENT_LIMIT = "jdk.xml.entityReplacementLimit";
+
     /**
      * JDK maximum parameter entity size limit
      */
diff --git a/src/com/sun/org/apache/xalan/internal/res/XSLTErrorResources_zh_TW.java b/src/com/sun/org/apache/xalan/internal/res/XSLTErrorResources_zh_TW.java
index 80e0a34..ee8a11b 100644
--- a/src/com/sun/org/apache/xalan/internal/res/XSLTErrorResources_zh_TW.java
+++ b/src/com/sun/org/apache/xalan/internal/res/XSLTErrorResources_zh_TW.java
@@ -1265,7 +1265,7 @@
       "\u627E\u4E0D\u5230\u5341\u9032\u4F4D\u683C\u5F0F\u7684\u5BA3\u544A: {0}"},
 
     { WG_OLD_XSLT_NS,
-     "\u907A\u6F0F\u6216\u4E0D\u6B63\u78BA\u7684 XSLT \u547D\u540D\u7A7A\u9593\u3002 "},
+     "\u907A\u6F0F\u6216\u4E0D\u6B63\u78BA\u7684 XSLT \u547D\u540D\u7A7A\u9593\u3002"},
 
     { WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED,
       "\u53EA\u5141\u8A31\u4E00\u500B\u9810\u8A2D\u7684 xsl:decimal-format \u5BA3\u544A\u3002"},
diff --git a/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java b/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java
index d11c50b..96bb46c 100644
--- a/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java
+++ b/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -82,7 +82,9 @@
         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);
+                XalanConstants.SP_XML_NAME_LIMIT, 1000, 1000),
+        ENTITY_REPLACEMENT_LIMIT("EntityReplacementLimit", XalanConstants.JDK_ENTITY_REPLACEMENT_LIMIT,
+                XalanConstants.SP_ENTITY_REPLACEMENT_LIMIT, 0, 3000000);
 
         final String key;
         final String apiProperty;
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
index e136357..c392cbe 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -9,7 +9,7 @@
  * (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
+ *     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,
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: LiteralElement.java,v 1.2.4.1 2005/09/13 12:38:33 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -58,8 +55,6 @@
     // names are not known at compile time.
     private boolean _allAttributesUnique = false;
 
-    private final static String XMLNS_STRING = "xmlns";
-
     /**
      * Returns the QName for this literal element
      */
@@ -140,8 +135,8 @@
         // Treat default namespace as "" and not null
         if (prefix == null)
             prefix = Constants.EMPTYSTRING;
-        else if (prefix.equals(XMLNS_STRING))
-            return(XMLNS_STRING);
+        else if (prefix.equals(XMLNS_PREFIX))
+            return(XMLNS_PREFIX);
 
         // Check if we must translate the prefix
         final String alternative = stable.lookupPrefixAlias(prefix);
@@ -266,7 +261,7 @@
                 // Ignore special attributes (e.g. xmlns:prefix and xmlns)
                 final String prefix = qname.getPrefix();
                 if (prefix != null && prefix.equals(XMLNS_PREFIX) ||
-                    prefix == null && qname.getLocalPart().equals("xmlns") ||
+                    prefix == null && qname.getLocalPart().equals(XMLNS_PREFIX) ||
                     uri != null && uri.equals(XSLT_URI))
                 {
                     continue;
@@ -339,9 +334,9 @@
         il.append(methodGen.startElement());
 
         // The value of an attribute may depend on a (sibling) variable
-        int j=0;
+        int j = 0;
         while (j < elementCount())  {
-            final SyntaxTreeNode item = (SyntaxTreeNode) elementAt(j);
+            final SyntaxTreeNode item = elementAt(j);
             if (item instanceof Variable) {
                 item.translate(classGen, methodGen);
             }
@@ -350,35 +345,12 @@
 
         // Compile code to emit namespace attributes
         if (_accessedPrefixes != null) {
-            boolean declaresDefaultNS = false;
-
             for (Map.Entry<String, String> entry : _accessedPrefixes.entrySet()) {
                 final String prefix = entry.getKey();
                 final String uri = entry.getValue();
-
-                if (uri != Constants.EMPTYSTRING ||
-                        prefix != Constants.EMPTYSTRING)
-                {
-                    if (prefix == Constants.EMPTYSTRING) {
-                        declaresDefaultNS = true;
-                    }
-                    il.append(methodGen.loadHandler());
-                    il.append(new PUSH(cpg,prefix));
-                    il.append(new PUSH(cpg,uri));
-                    il.append(methodGen.namespace());
-                }
-            }
-
-            /*
-             * If our XslElement parent redeclares the default NS, and this
-             * element doesn't, it must be redeclared one more time.
-             */
-            if (!declaresDefaultNS && (_parent instanceof XslElement)
-                    && ((XslElement) _parent).declaresDefaultNS())
-            {
                 il.append(methodGen.loadHandler());
-                il.append(new PUSH(cpg, Constants.EMPTYSTRING));
-                il.append(new PUSH(cpg, Constants.EMPTYSTRING));
+                il.append(new PUSH(cpg, prefix));
+                il.append(new PUSH(cpg, uri));
                 il.append(methodGen.namespace());
             }
         }
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
index d15d90e..7088850 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: Parser.java,v 1.2.4.1 2005/09/13 12:14:32 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -37,6 +34,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.StringReader;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -44,7 +42,6 @@
 import java.util.Properties;
 import java.util.Stack;
 import java.util.StringTokenizer;
-import java.util.Vector;
 import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
@@ -68,20 +65,20 @@
  */
 public class Parser implements Constants, ContentHandler {
 
-    private static final String XSL = "xsl";            // standard prefix
+    private static final String XSL = "xsl";           // standard prefix
     private static final String TRANSLET = "translet"; // extension prefix
 
     private Locator _locator = null;
 
-    private XSLTC _xsltc;             // Reference to the compiler object.
-    private XPathParser _xpathParser; // Reference to the XPath parser.
-    private Vector _errors;           // Contains all compilation errors
-    private Vector _warnings;         // Contains all compilation errors
+    private XSLTC _xsltc;                  // Reference to the compiler object.
+    private XPathParser _xpathParser;      // Reference to the XPath parser.
+    private ArrayList<ErrorMsg> _errors;   // Contains all compilation errors
+    private ArrayList<ErrorMsg> _warnings; // Contains all compilation warnings
 
     private Map<String, String>   _instructionClasses; // Maps instructions to classes
     private Map<String, String[]> _instructionAttrs;  // reqd and opt attrs
-    private Map<String, QName>   _qNames;
-    private Map<String, Map>     _namespaces;
+    private Map<String, QName>    _qNames;
+    private Map<String, Map<String, QName>> _namespaces;
     private QName       _useAttributeSets;
     private QName       _excludeResultPrefixes;
     private QName       _extensionElementPrefixes;
@@ -113,8 +110,8 @@
         _instructionAttrs    = new HashMap<>();
         _variableScope       = new HashMap<>();
         _template            = null;
-        _errors              = new Vector();
-        _warnings            = new Vector();
+        _errors              = new ArrayList<>();
+        _warnings            = new ArrayList<>();
         _symbolTable         = new SymbolTable();
         _xpathParser         = new XPathParser(this);
         _currentStylesheet   = null;
@@ -139,7 +136,6 @@
     public void setOutput(Output output) {
         if (_output != null) {
             if (_output.getImportPrecedence() <= output.getImportPrecedence()) {
-                String cdata = _output.getCdata();
                 output.mergeOutput(_output);
                 _output.disable();
                 _output = output;
@@ -173,12 +169,13 @@
         Object existing = _variableScope.get(var.getName().getStringRep());
         if (existing != null) {
             if (existing instanceof Stack) {
-                Stack stack = (Stack)existing;
+                @SuppressWarnings("unchecked")
+                Stack<VariableBase> stack = (Stack<VariableBase>)existing;
                 stack.push(var);
             }
             else if (existing instanceof VariableBase) {
-                Stack stack = new Stack();
-                stack.push(existing);
+                Stack<VariableBase> stack = new Stack<>();
+                stack.push((VariableBase)existing);
                 stack.push(var);
                 _variableScope.put(var.getName().getStringRep(), stack);
             }
@@ -191,7 +188,8 @@
     public void removeVariable(QName name) {
         Object existing = _variableScope.get(name.getStringRep());
         if (existing instanceof Stack) {
-            Stack stack = (Stack)existing;
+            @SuppressWarnings("unchecked")
+            Stack<VariableBase> stack = (Stack<VariableBase>)existing;
             if (!stack.isEmpty()) stack.pop();
             if (!stack.isEmpty()) return;
         }
@@ -201,13 +199,14 @@
     public VariableBase lookupVariable(QName name) {
         Object existing = _variableScope.get(name.getStringRep());
         if (existing instanceof VariableBase) {
-            return((VariableBase)existing);
+            return (VariableBase)existing;
         }
         else if (existing instanceof Stack) {
-            Stack stack = (Stack)existing;
-            return((VariableBase)stack.peek());
+            @SuppressWarnings("unchecked")
+            Stack<VariableBase> stack = (Stack<VariableBase>)existing;
+            return stack.peek();
         }
-        return(null);
+        return null;
     }
 
     public void setXSLTC(XSLTC xsltc) {
@@ -397,7 +396,6 @@
         try {
             if (stylesheet != null) {
                 stylesheet.parseContents(this);
-                final int precedence = stylesheet.getImportPrecedence();
                 final Iterator<SyntaxTreeNode> elements = stylesheet.elements();
                 while (elements.hasNext()) {
                     SyntaxTreeNode child = elements.next();
@@ -704,8 +702,6 @@
            new String[] {"stylesheet-prefix", "result-prefix"});
     }
 
-
-
     /**
      * Initialize the _instructionClasses map, which maps XSL element
      * names to Java classes in this package.
@@ -779,6 +775,7 @@
     /**
      * Add primops and base functions to the symbol table.
      */
+    @SuppressWarnings("unused")
     private void initSymbolTable() {
         MethodType I_V  = new MethodType(Type.Int, Type.Void);
         MethodType I_R  = new MethodType(Type.Int, Type.Real);
@@ -971,12 +968,12 @@
         String local, Attributes attributes)
     {
         SyntaxTreeNode node = null;
-        QName  qname = getQName(uri, prefix, local);
+        QName qname = getQName(uri, prefix, local);
         String className = _instructionClasses.get(qname.getStringRep());
 
         if (className != null) {
             try {
-                final Class clazz = ObjectFactory.findProviderClass(className, true);
+                final Class<?> clazz = ObjectFactory.findProviderClass(className, true);
                 node = (SyntaxTreeNode)clazz.newInstance();
                 node.setQName(qname);
                 node.setParser(this);
@@ -1023,7 +1020,7 @@
                 else {
                     Stylesheet sheet = _xsltc.getStylesheet();
                     if ((sheet != null) && (sheet.isExtension(uri))) {
-                        if (sheet != (SyntaxTreeNode)_parentStack.peek()) {
+                        if (sheet != _parentStack.peek()) {
                             node = new UnsupportedElement(uri, prefix, local, true);
                             UnsupportedElement elem = (UnsupportedElement)node;
                             ErrorMsg msg =
@@ -1156,7 +1153,6 @@
                     node.setParser(this);
                     node.setParent(parent);
                     node.setLineNumber(line);
-// System.out.println("e = " + text + " " + node);
                     return node;
                 }
             }
@@ -1191,7 +1187,7 @@
         if (size > 0) {
             System.err.println(new ErrorMsg(ErrorMsg.COMPILER_ERROR_KEY));
             for (int i = 0; i < size; i++) {
-                System.err.println("  " + _errors.elementAt(i));
+                System.err.println("  " + _errors.get(i));
             }
         }
     }
@@ -1204,7 +1200,7 @@
         if (size > 0) {
             System.err.println(new ErrorMsg(ErrorMsg.COMPILER_WARNING_KEY));
             for (int i = 0; i < size; i++) {
-                System.err.println("  " + _warnings.elementAt(i));
+                System.err.println("  " + _warnings.get(i));
             }
         }
     }
@@ -1217,42 +1213,42 @@
         case Constants.INTERNAL:
             // Unexpected internal errors, such as null-ptr exceptions, etc.
             // Immediately terminates compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.UNSUPPORTED:
             // XSLT elements that are not implemented and unsupported ext.
             // Immediately terminates compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.FATAL:
             // Fatal error in the stylesheet input (parsing or content)
             // Immediately terminates compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.ERROR:
             // Other error in the stylesheet input (parsing or content)
             // Does not terminate compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.WARNING:
             // Other error in the stylesheet input (content errors only)
             // Does not terminate compilation, a translet is produced
-            _warnings.addElement(error);
+            _warnings.add(error);
             break;
         }
     }
 
-    public Vector getErrors() {
+    public ArrayList<ErrorMsg> getErrors() {
         return _errors;
     }
 
-    public Vector getWarnings() {
+    public ArrayList<ErrorMsg> getWarnings() {
         return _warnings;
     }
 
     /************************ SAX2 ContentHandler INTERFACE *****************/
 
-    private Stack _parentStack = null;
+    private Stack<SyntaxTreeNode> _parentStack = null;
     private Map<String, String> _prefixMapping = null;
 
     /**
@@ -1262,7 +1258,7 @@
         _root = null;
         _target = null;
         _prefixMapping = null;
-        _parentStack = new Stack();
+        _parentStack = new Stack<>();
     }
 
     /**
@@ -1318,7 +1314,7 @@
             _root = element;
         }
         else {
-            SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
+            SyntaxTreeNode parent = _parentStack.peek();
             parent.addElement(element);
             element.setParent(parent);
         }
@@ -1349,7 +1345,7 @@
      */
     public void characters(char[] ch, int start, int length) {
         String string = new String(ch, start, length);
-        SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
+        SyntaxTreeNode parent = _parentStack.peek();
 
         if (string.length() == 0) return;
 
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java
index 5894996..09061ea 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -31,6 +31,7 @@
 import com.sun.org.apache.bcel.internal.generic.GETSTATIC;
 import com.sun.org.apache.bcel.internal.generic.INVOKEINTERFACE;
 import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
+import com.sun.org.apache.bcel.internal.generic.INVOKESTATIC;
 import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
 import com.sun.org.apache.bcel.internal.generic.ISTORE;
 import com.sun.org.apache.bcel.internal.generic.InstructionHandle;
@@ -1252,6 +1253,10 @@
                                 classGen.getConstantPool());
         transf.addException("com.sun.org.apache.xalan.internal.xsltc.TransletException");
 
+        // call resetPrefixIndex at the beginning of transform
+        final int check = cpg.addMethodref(BASIS_LIBRARY_CLASS, "resetPrefixIndex", "()V");
+        il.append(new INVOKESTATIC(check));
+
         // Define and initialize current with the root node
         final LocalVariableGen current =
             transf.addLocalVariable("current",
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
index 1e8ad86..01ef38b 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
@@ -73,7 +73,7 @@
     protected QName _qname;                    // The element QName
     private int _line;                         // Source file line number
     protected AttributesImpl _attributes = null;   // Attributes of this element
-    private   Map<String, String> _prefixMapping = null; // Namespace declarations
+    private Map<String, String> _prefixMapping = null; // Namespace declarations
 
     // Sentinel - used to denote unrecognised syntaxt tree nodes.
     protected static final SyntaxTreeNode Dummy = new AbsolutePathPattern(null);
@@ -829,7 +829,7 @@
      * @param pos The child node's position.
      * @return The child node.
      */
-    protected final Object elementAt(int pos) {
+    protected final SyntaxTreeNode elementAt(int pos) {
         return _contents.get(pos);
     }
 
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java
index fc2b202..37d4cf9 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java
@@ -128,8 +128,7 @@
                 parser.reportError(Constants.ERROR, err);
             }
             setName(parser.getQNameIgnoreDefaultNs(name));
-        }
-        else {
+        } else {
             reportError(this, parser, ErrorMsg.REQUIRED_ATTR_ERR, "name");
         }
 
@@ -151,8 +150,7 @@
             if (tselect instanceof ReferenceType == false) {
                 _select = new CastExpr(_select, Type.Reference);
             }
-        }
-        else {
+        } else {
             typeCheckContents(stable);
         }
         return Type.Void;
@@ -163,23 +161,24 @@
      * a 'select' attribute, or in the with-param element's body
      */
     public void translateValue(ClassGenerator classGen,
-                               MethodGenerator methodGen) {
+                               MethodGenerator methodGen)
+    {
         // Compile expression is 'select' attribute if present
         if (_select != null) {
             _select.translate(classGen, methodGen);
             _select.startIterator(classGen, methodGen);
-        }
         // If not, compile result tree from parameter body if present.
         // Store result tree into local variable for releasing it later
-        else if (hasContents()) {
+        } else if (hasContents()) {
             final InstructionList il = methodGen.getInstructionList();
             compileResultTree(classGen, methodGen);
-            _domAdapter = methodGen.addLocalVariable2("@" + _escapedName, Type.ResultTree.toJCType(), il.getEnd());
+            _domAdapter = methodGen.addLocalVariable2("@" + _escapedName,
+                                                      Type.ResultTree.toJCType(),
+                                                      il.getEnd());
             il.append(DUP);
             il.append(new ASTORE(_domAdapter.getIndex()));
-        }
         // If neither are present then store empty string in parameter slot
-        else {
+        } else {
             final ConstantPoolGen cpg = classGen.getConstantPool();
             final InstructionList il = methodGen.getInstructionList();
             il.append(new PUSH(cpg, Constants.EMPTYSTRING));
@@ -223,22 +222,31 @@
     /**
      * Release the compiled result tree.
      */
-    public void releaseResultTree(ClassGenerator classGen, MethodGenerator methodGen) {
+    public void releaseResultTree(ClassGenerator classGen,
+                                  MethodGenerator methodGen)
+    {
         if (_domAdapter != null) {
             final ConstantPoolGen cpg = classGen.getConstantPool();
             final InstructionList il = methodGen.getInstructionList();
-            if (classGen.getStylesheet().callsNodeset() && classGen.getDOMClass().equals(MULTI_DOM_CLASS)) {
-                final int removeDA = cpg.addMethodref(MULTI_DOM_CLASS, "removeDOMAdapter", "(" + DOM_ADAPTER_SIG + ")V");
+            if (classGen.getStylesheet().callsNodeset() &&
+                classGen.getDOMClass().equals(MULTI_DOM_CLASS))
+            {
+                final int removeDA =
+                    cpg.addMethodref(MULTI_DOM_CLASS, "removeDOMAdapter",
+                                     "(" + DOM_ADAPTER_SIG + ")V");
                 il.append(methodGen.loadDOM());
                 il.append(new CHECKCAST(cpg.addClass(MULTI_DOM_CLASS)));
                 il.append(new ALOAD(_domAdapter.getIndex()));
                 il.append(new CHECKCAST(cpg.addClass(DOM_ADAPTER_CLASS)));
                 il.append(new INVOKEVIRTUAL(removeDA));
             }
-            final int release = cpg.addInterfaceMethodref(DOM_IMPL_CLASS, "release", "()V");
+            final int release =
+                cpg.addInterfaceMethodref(DOM_IMPL_CLASS, "release", "()V");
             il.append(new ALOAD(_domAdapter.getIndex()));
             il.append(new INVOKEINTERFACE(release, 1));
+            _domAdapter.setEnd(il.getEnd());
+            methodGen.removeLocalVariable(_domAdapter);
             _domAdapter = null;
-         }
-     }
+        }
+    }
 }
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
index 3218181..631edbd 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XSLTC.java,v 1.2.4.1 2005/09/05 09:51:38 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -39,6 +36,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Date;
 import java.util.Enumeration;
@@ -283,7 +281,7 @@
     }
 
     /*
-     * Function loads an external extension functions.
+     * Function loads an external extension function.
      * The filtering of function types (external,internal) takes place in FunctionCall class
      *
      */
@@ -598,18 +596,18 @@
     }
 
     /**
-     * Get a Vector containing all compile error messages
-     * @return A Vector containing all compile error messages
+     * Get a list of all compile error messages
+     * @return A List containing all compile error messages
      */
-    public Vector getErrors() {
+    public ArrayList<ErrorMsg> getErrors() {
         return _parser.getErrors();
     }
 
     /**
-     * Get a Vector containing all compile warning messages
-     * @return A Vector containing all compile error messages
+     * Get a list of all compile warning messages
+     * @return A List containing all compile error messages
      */
-    public Vector getWarnings() {
+    public ArrayList<ErrorMsg> getWarnings() {
         return _parser.getWarnings();
     }
 
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
index e04bab7..e94ebb1 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XslElement.java,v 1.2.4.1 2005/09/12 11:39:55 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -60,14 +57,6 @@
         displayContents(indent + IndentIncrement);
     }
 
-    /**
-     * This method is now deprecated. The new implemation of this class
-     * never declares the default NS.
-     */
-    public boolean declaresDefaultNS() {
-        return false;
-    }
-
     public void parseContents(Parser parser) {
         final SymbolTable stable = parser.getSymbolTable();
 
@@ -210,7 +199,6 @@
      * on the handler (vii) evaluates the contents (viii) calls endElement().
      */
     public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
-        LocalVariableGen local = null;
         final ConstantPoolGen cpg = classGen.getConstantPool();
         final InstructionList il = methodGen.getInstructionList();
 
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/util/ErrorMessages_zh_TW.java b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/util/ErrorMessages_zh_TW.java
index 2b73cd2..7cae67a 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/compiler/util/ErrorMessages_zh_TW.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/compiler/util/ErrorMessages_zh_TW.java
@@ -682,7 +682,7 @@
          * documentation.
          */
         {ErrorMsg.COMPILE_USAGE_STR,
-        "\u6982\u8981\n   java com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile [-o <output>]\n      [-d <directory>] [-j <jarfile>] [-p <package>]\n      [-n] [-x] [-u] [-v] [-h] { <stylesheet> | -i }\n\n\u9078\u9805\n   -o <output>    \u6307\u6D3E\u540D\u7A31 <output> \u81F3\u7522\u751F\u7684\n                  translet\u3002\u6839\u64DA\u9810\u8A2D\uFF0Ctranslet \u540D\u7A31\n                  \u884D\u751F\u81EA <stylesheet> \u540D\u7A31\u3002  \u82E5\u7DE8\u8B6F\n                  \u591A\u500B\u6A23\u5F0F\u8868\uFF0C\u5C07\u5FFD\u7565\u6B64\u9078\u9805\u3002\n   -d <directory> \u6307\u5B9A translet \u7684\u76EE\u7684\u5730\u76EE\u9304\n   -j <jarfile>   \u5C01\u88DD translet \u985E\u5225\u6210\u70BA jar \u6A94\u6848\uFF0C\n                  \u540D\u7A31\u6307\u5B9A\u70BA <jarfile>\n   -p <package>   \u6307\u5B9A\u6240\u6709\u7522\u751F\u7684 translet \u985E\u5225\u7684\u5957\u88DD\u7A0B\u5F0F\n                  \u540D\u7A31\u524D\u7F6E\u78BC\u3002\n   -n             \u555F\u7528\u6A23\u677F\u5167\u5D4C (\u9810\u8A2D\u884C\u70BA\u4E00\u822C\u800C\u8A00\n                  \u8F03\u4F73)\u3002\n   -x             \u958B\u555F\u984D\u5916\u7684\u9664\u932F\u8A0A\u606F\u8F38\u51FA\n   -u             \u89E3\u8B6F <stylesheet> \u5F15\u6578\u70BA URL\n   -i             \u5F37\u5236\u7DE8\u8B6F\u5668\u5F9E stdin \u8B80\u53D6\u6A23\u5F0F\u8868\n   -v             \u5217\u5370\u7DE8\u8B6F\u5668\u7248\u672C\n   -h             \u5217\u5370\u6B64\u7528\u6CD5\u6558\u8FF0\n"},
+        "\u6982\u8981\n   java com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile [-o <output>]\n      [-d <directory>] [-j <jarfile>] [-p <package>]\n      [-n] [-x] [-u] [-v] [-h] { <stylesheet> | -i }\n\n\u9078\u9805\n   -o <output>    \u6307\u6D3E\u540D\u7A31 <output> \u81F3\u7522\u751F\u7684\n                  translet\u3002\u6839\u64DA\u9810\u8A2D\uFF0Ctranslet \u540D\u7A31\n                  \u884D\u751F\u81EA <stylesheet> \u540D\u7A31\u3002\u82E5\u7DE8\u8B6F\n                  \u591A\u500B\u6A23\u5F0F\u8868\uFF0C\u5C07\u5FFD\u7565\u6B64\u9078\u9805\u3002\n   -d <directory> \u6307\u5B9A translet \u7684\u76EE\u7684\u5730\u76EE\u9304\n   -j <jarfile>   \u5C01\u88DD translet \u985E\u5225\u6210\u70BA jar \u6A94\u6848\uFF0C\n                  \u540D\u7A31\u6307\u5B9A\u70BA <jarfile>\n   -p <package>   \u6307\u5B9A\u6240\u6709\u7522\u751F\u7684 translet \u985E\u5225\u7684\u5957\u88DD\u7A0B\u5F0F\n                  \u540D\u7A31\u524D\u7F6E\u78BC\u3002\n   -n             \u555F\u7528\u6A23\u677F\u5167\u5D4C (\u9810\u8A2D\u884C\u70BA\u4E00\u822C\u800C\u8A00\n                  \u8F03\u4F73)\u3002\n   -x             \u958B\u555F\u984D\u5916\u7684\u9664\u932F\u8A0A\u606F\u8F38\u51FA\n   -u             \u89E3\u8B6F <stylesheet> \u5F15\u6578\u70BA URL\n   -i             \u5F37\u5236\u7DE8\u8B6F\u5668\u5F9E stdin \u8B80\u53D6\u6A23\u5F0F\u8868\n   -v             \u5217\u5370\u7DE8\u8B6F\u5668\u7248\u672C\n   -h             \u5217\u5370\u6B64\u7528\u6CD5\u6558\u8FF0\n"},
 
         /*
          * Note to translators:  This message contains usage information for a
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java b/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java
index dc3a3ce..804b154 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -48,6 +48,7 @@
 import java.text.NumberFormat;
 import java.util.Locale;
 import java.util.ResourceBundle;
+import java.util.concurrent.atomic.AtomicInteger;
 import javax.xml.transform.dom.DOMSource;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
@@ -1530,16 +1531,25 @@
     }
 
     /**
-     * This function is used in the execution of xsl:element
+     * These functions are used in the execution of xsl:element to generate
+     * and reset namespace prefix index local to current transformation process
      */
-    private static int prefixIndex = 0;
-
     public static String generatePrefix() {
-        synchronized (BasisLibrary.class) {
-            return ("ns" + prefixIndex++);
-        }
+        return ("ns" + threadLocalPrefixIndex.get().getAndIncrement());
     }
 
+    public static void resetPrefixIndex() {
+        threadLocalPrefixIndex.get().set(0);
+    }
+
+    private static final ThreadLocal<AtomicInteger> threadLocalPrefixIndex =
+        new ThreadLocal<AtomicInteger>() {
+            @Override
+            protected AtomicInteger initialValue() {
+                return new AtomicInteger();
+            }
+        };
+
     public static final String RUN_TIME_INTERNAL_ERR =
                                            "RUN_TIME_INTERNAL_ERR";
     public static final String RUN_TIME_COPY_ERR =
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java b/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
index 8bbc541..bce2c3a 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2007, 2016, 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
  *
@@ -17,18 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: TemplatesHandlerImpl.java,v 1.2.4.1 2005/09/06 12:09:03 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
-import javax.xml.XMLConstants;
-import javax.xml.transform.Source;
-import javax.xml.transform.Templates;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.URIResolver;
-import javax.xml.transform.sax.TemplatesHandler;
 import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.CompilerException;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
@@ -37,15 +28,19 @@
 import com.sun.org.apache.xalan.internal.xsltc.compiler.SyntaxTreeNode;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
-
+import java.util.ArrayList;
+import javax.xml.XMLConstants;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.sax.TemplatesHandler;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.Locator;
 import org.xml.sax.SAXException;
 import org.xml.sax.Attributes;
 
-import java.util.Vector;
-
 /**
  * Implementation of a JAXP1.1 TemplatesHandler
  * @author Morten Jorgensen
@@ -268,13 +263,13 @@
                 }
             }
             else {
-                StringBuffer errorMessage = new StringBuffer();
-                Vector errors = _parser.getErrors();
+                StringBuilder errorMessage = new StringBuilder();
+                ArrayList<ErrorMsg> errors = _parser.getErrors();
                 final int count = errors.size();
                 for (int i = 0; i < count; i++) {
                     if (errorMessage.length() > 0)
                         errorMessage.append('\n');
-                    errorMessage.append(errors.elementAt(i).toString());
+                    errorMessage.append(errors.get(i).toString());
                 }
                 throw new SAXException(ErrorMsg.JAXP_COMPILE_ERR, new TransformerException(errorMessage.toString()));
             }
diff --git a/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java b/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
index b37c8f4..e30fffd 100644
--- a/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
+++ b/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: TransformerFactoryImpl.java,v 1.8 2007/04/09 21:30:41 joehw Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
@@ -48,6 +45,7 @@
 import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.Map;
 import java.util.Properties;
@@ -592,7 +590,7 @@
         }
 
         // Inefficient, but array is small
-        for (int i =0; i < features.length; i++) {
+        for (int i = 0; i < features.length; i++) {
             if (name.equals(features[i])) {
                 return true;
             }
@@ -799,7 +797,7 @@
     /**
      * Pass warning messages from the compiler to the error listener
      */
-    private void passWarningsToListener(Vector messages)
+    private void passWarningsToListener(ArrayList<ErrorMsg> messages)
         throws TransformerException
     {
         if (_errorListener == null || messages == null) {
@@ -808,7 +806,7 @@
         // Pass messages to listener, one by one
         final int count = messages.size();
         for (int pos = 0; pos < count; pos++) {
-            ErrorMsg msg = (ErrorMsg)messages.elementAt(pos);
+            ErrorMsg msg = messages.get(pos);
             // Workaround for the TCK failure ErrorListener.errorTests.error001.
             if (msg.isWarningError())
                 _errorListener.error(
@@ -822,7 +820,7 @@
     /**
      * Pass error messages from the compiler to the error listener
      */
-    private void passErrorsToListener(Vector messages) {
+    private void passErrorsToListener(ArrayList<ErrorMsg> messages) {
         try {
             if (_errorListener == null || messages == null) {
                 return;
@@ -830,7 +828,7 @@
             // Pass messages to listener, one by one
             final int count = messages.size();
             for (int pos = 0; pos < count; pos++) {
-                String message = messages.elementAt(pos).toString();
+                String message = messages.get(pos).toString();
                 _errorListener.error(new TransformerException(message));
             }
         }
@@ -1004,40 +1002,39 @@
         }
 
         // Check that the transformation went well before returning
-    if (bytecodes == null) {
-        Vector errs = xsltc.getErrors();
-        ErrorMsg err;
-        if (errs != null) {
-            err = (ErrorMsg)errs.elementAt(errs.size()-1);
-        } else {
-            err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
-        }
-        Throwable cause = err.getCause();
-        TransformerConfigurationException exc;
-        if (cause != null) {
-            exc =  new TransformerConfigurationException(cause.getMessage(), cause);
-        } else {
-            exc =  new TransformerConfigurationException(err.toString());
-        }
-
-        // Pass compiler errors to the error listener
-        if (_errorListener != null) {
-            passErrorsToListener(xsltc.getErrors());
-
-            // As required by TCK 1.2, send a fatalError to the
-            // error listener because compilation of the stylesheet
-            // failed and no further processing will be possible.
-            try {
-                _errorListener.fatalError(exc);
-            } catch (TransformerException te) {
-                // well, we tried.
+        if (bytecodes == null) {
+            ArrayList<ErrorMsg> errs = xsltc.getErrors();
+            ErrorMsg err;
+            if (errs != null) {
+                err = errs.get(errs.size() - 1);
+            } else {
+                err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
             }
+            Throwable cause = err.getCause();
+            TransformerConfigurationException exc;
+            if (cause != null) {
+                exc =  new TransformerConfigurationException(cause.getMessage(), cause);
+            } else {
+                exc =  new TransformerConfigurationException(err.toString());
+            }
+
+            // Pass compiler errors to the error listener
+            if (_errorListener != null) {
+                passErrorsToListener(xsltc.getErrors());
+
+                // As required by TCK 1.2, send a fatalError to the
+                // error listener because compilation of the stylesheet
+                // failed and no further processing will be possible.
+                try {
+                    _errorListener.fatalError(exc);
+                } catch (TransformerException te) {
+                    // well, we tried.
+                }
+            } else {
+                xsltc.printErrors();
+            }
+            throw exc;
         }
-        else {
-            xsltc.printErrors();
-        }
-        throw exc;
-    }
 
         return new TemplatesImpl(bytecodes, transletName,
             xsltc.getOutputProperties(), _indentNumber, this);
diff --git a/src/com/sun/org/apache/xerces/internal/dom/AbortException.java b/src/com/sun/org/apache/xerces/internal/dom/AbortException.java
new file mode 100644
index 0000000..3e178dd
--- /dev/null
+++ b/src/com/sun/org/apache/xerces/internal/dom/AbortException.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.org.apache.xerces.internal.dom;
+
+public class AbortException extends RuntimeException {
+
+        private static final long serialVersionUID = 2608302175475740417L;
+
+        /**
+         * Constructor AbortException
+         */
+        public AbortException() { super(null, null, false, false); }
+}
diff --git a/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java b/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
index 3758f39..c4268dc 100644
--- a/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
+++ b/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
@@ -26,6 +26,7 @@
 import java.io.StringReader;
 import java.util.Vector;
 
+import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.RevalidationHandler;
 import com.sun.org.apache.xerces.internal.impl.dtd.DTDGrammar;
@@ -158,11 +159,6 @@
     // attribute value normalization
     final XMLString fNormalizedValue = new XMLString(new char[16], 0, 0);
 
-    /**
-     * If the user stops the process, this exception will be thrown.
-     */
-    public static final RuntimeException abort = new RuntimeException();
-
     //DTD validator
     private XMLDTDValidator fDTDValidator;
 
@@ -243,11 +239,10 @@
                                         XMLGrammarDescription.XML_SCHEMA, fValidationHandler);
                                 fValidationHandler = null;
                         }
-                }
-                catch (RuntimeException e) {
-            if( e==abort )
-                return; // processing aborted by the user
-            throw e;    // otherwise re-throw.
+                } catch (AbortException e) {
+                    return;
+                } catch (RuntimeException e) {
+                    throw e;    // otherwise re-throw.
                 }
 
         }
@@ -1372,10 +1367,10 @@
             error.fRelatedData = locator.fRelatedNode;
 
             if(!errorHandler.handleError(error))
-                throw abort;
+                throw new AbortException();
         }
         if( severity==DOMError.SEVERITY_FATAL_ERROR )
-            throw abort;
+            throw new AbortException();
     }
 
     protected final void updateQName (Node node, QName qname){
@@ -2044,5 +2039,4 @@
         return null;
     }
 
-
 }  // DOMNormalizer class
diff --git a/src/com/sun/org/apache/xerces/internal/impl/Constants.java b/src/com/sun/org/apache/xerces/internal/impl/Constants.java
index 1f67a9f..c5355a0 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/Constants.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/Constants.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -242,6 +242,14 @@
      */
     public static final String JDK_GENERAL_ENTITY_SIZE_LIMIT =
             ORACLE_JAXP_PROPERTY_PREFIX + "maxGeneralEntitySizeLimit";
+
+    /**
+     * JDK node count limit in entities that limits the total number of nodes
+     * in all of entity references.
+     */
+    public static final String JDK_ENTITY_REPLACEMENT_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "entityReplacementLimit";
+
     /**
      * JDK maximum parameter entity size limit
      */
@@ -295,6 +303,13 @@
      * JDK maximum general entity size limit
      */
     public static final String SP_GENERAL_ENTITY_SIZE_LIMIT = "jdk.xml.maxGeneralEntitySizeLimit";
+
+    /**
+     * JDK node count limit in entities that limits the total number of nodes
+     * in all of entity references.
+     */
+    public static final String SP_ENTITY_REPLACEMENT_LIMIT = "jdk.xml.entityReplacementLimit";
+
     /**
      * JDK maximum parameter entity size limit
      */
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XML11DTDScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XML11DTDScannerImpl.java
index d6648b7..a4361b2 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11DTDScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11DTDScannerImpl.java
@@ -1,62 +1,21 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2016, 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-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
- * <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;
@@ -146,7 +105,7 @@
     protected boolean scanPubidLiteral(XMLString literal)
         throws IOException, XNIException
     {
-        int quote = fEntityScanner.scanChar();
+        int quote = fEntityScanner.scanChar(null);
         if (quote != '\'' && quote != '"') {
             reportFatalError("QuoteRequiredInPublicID", null);
             return false;
@@ -157,7 +116,7 @@
         boolean skipSpace = true;
         boolean dataok = true;
         while (true) {
-            int c = fEntityScanner.scanChar();
+            int c = fEntityScanner.scanChar(null);
             // REVISIT:  it could really only be \n or 0x20; all else is normalized, no?  - neilg
             if (c == ' ' || c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) {
                 if (!skipSpace) {
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java
index 5276454..cea629a 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java
@@ -1,74 +1,32 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2016, 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-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
- * <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;
 
-import java.io.IOException;
-
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
 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.xni.XMLString;
 import com.sun.org.apache.xerces.internal.xni.XNIException;
+import java.io.IOException;
 
 /**
  * This class is responsible for scanning XML document structure
@@ -135,7 +93,7 @@
             // happens when there is the character reference &#13;
             // but scanContent doesn't do entity expansions...
             // is this *really* necessary???  - NG
-            fEntityScanner.scanChar();
+            fEntityScanner.scanChar(null);
             content.append((char)c);
             c = -1;
         }
@@ -144,7 +102,7 @@
         } */
 
         if (c == ']') {
-            content.append((char)fEntityScanner.scanChar());
+            content.append((char)fEntityScanner.scanChar(null));
             // remember where we are in case we get an endEntity before we
             // could flush the buffer out - this happens when we're parsing an
             // entity which ends with a ]
@@ -153,12 +111,12 @@
             // We work on a single character basis to handle cases such as:
             // ']]]>' which we might otherwise miss.
             //
-            if (fEntityScanner.skipChar(']')) {
+            if (fEntityScanner.skipChar(']', null)) {
                 content.append(']');
-                while (fEntityScanner.skipChar(']')) {
+                while (fEntityScanner.skipChar(']', null)) {
                     content.append(']');
                 }
-                if (fEntityScanner.skipChar('>')) {
+                if (fEntityScanner.skipChar('>', null)) {
                     reportFatalError("CDEndInContent", null);
                 }
             }
@@ -185,6 +143,7 @@
      * @param checkEntities true if undeclared entities should be reported as VC violation,
      *                      false if undeclared entities should be reported as WFC violation.
      * @param eleName The name of element to which this attribute belongs.
+     * @param isNSURI The flag indicating whether the content is a namespace URI
      *
      * @return true if the non-normalized and normalized value are the same
      *
@@ -194,7 +153,7 @@
     protected boolean scanAttributeValue(XMLString value,
                                       XMLString nonNormalizedValue,
                                       String atName,
-                                      boolean checkEntities,String eleName)
+                                      boolean checkEntities,String eleName, boolean isNSURI)
         throws IOException, XNIException
     {
         // quote
@@ -203,10 +162,10 @@
             reportFatalError("OpenQuoteExpected", new Object[]{eleName,atName});
         }
 
-        fEntityScanner.scanChar();
+        fEntityScanner.scanChar(NameType.ATTRIBUTE);
         int entityDepth = fEntityDepth;
 
-        int c = fEntityScanner.scanLiteral(quote, value);
+        int c = fEntityScanner.scanLiteral(quote, value, isNSURI);
         if (DEBUG_ATTR_NORMALIZATION) {
             System.out.println("** scanLiteral -> \""
                                + value.toString() + "\"");
@@ -216,7 +175,7 @@
         if (c == quote && (fromIndex = isUnchangedByNormalization(value)) == -1) {
             /** Both the non-normalized and normalized attribute values are equal. **/
             nonNormalizedValue.setValues(value);
-            int cquote = fEntityScanner.scanChar();
+            int cquote = fEntityScanner.scanChar(NameType.ATTRIBUTE);
             if (cquote != quote) {
                 reportFatalError("CloseQuoteExpected", new Object[]{eleName,atName});
             }
@@ -239,11 +198,11 @@
                                        + fStringBuffer.toString() + "\"");
                 }
                 if (c == '&') {
-                    fEntityScanner.skipChar('&');
+                    fEntityScanner.skipChar('&', NameType.REFERENCE);
                     if (entityDepth == fEntityDepth) {
                         fStringBuffer2.append('&');
                     }
-                    if (fEntityScanner.skipChar('#')) {
+                    if (fEntityScanner.skipChar('#', NameType.REFERENCE)) {
                         if (entityDepth == fEntityDepth) {
                             fStringBuffer2.append('#');
                         }
@@ -257,59 +216,22 @@
                         }
                     }
                     else {
-                        String entityName = fEntityScanner.scanName();
+                        String entityName = fEntityScanner.scanName(NameType.REFERENCE);
                         if (entityName == null) {
                             reportFatalError("NameRequiredInReference", null);
                         }
                         else if (entityDepth == fEntityDepth) {
                             fStringBuffer2.append(entityName);
                         }
-                        if (!fEntityScanner.skipChar(';')) {
+                        if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
                             reportFatalError("SemicolonRequiredInReference",
                                              new Object []{entityName});
                         }
                         else if (entityDepth == fEntityDepth) {
                             fStringBuffer2.append(';');
                         }
-                        if (entityName == fAmpSymbol) {
-                            fStringBuffer.append('&');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** value5: \""
-                                                   + fStringBuffer.toString()
-                                                   + "\"");
-                            }
-                        }
-                        else if (entityName == fAposSymbol) {
-                            fStringBuffer.append('\'');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** value7: \""
-                                                   + fStringBuffer.toString()
-                                                   + "\"");
-                            }
-                        }
-                        else if (entityName == fLtSymbol) {
-                            fStringBuffer.append('<');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** value9: \""
-                                                   + fStringBuffer.toString()
-                                                   + "\"");
-                            }
-                        }
-                        else if (entityName == fGtSymbol) {
-                            fStringBuffer.append('>');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** valueB: \""
-                                                   + fStringBuffer.toString()
-                                                   + "\"");
-                            }
-                        }
-                        else if (entityName == fQuotSymbol) {
-                            fStringBuffer.append('"');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** valueD: \""
-                                                   + fStringBuffer.toString()
-                                                   + "\"");
-                            }
+                        if (resolveCharacter(entityName, fStringBuffer)) {
+                            checkEntityLimit(false, fEntityScanner.fCurrentEntity.name, 1);
                         }
                         else {
                             if (fEntityManager.isExternalEntity(entityName)) {
@@ -340,13 +262,13 @@
                 else if (c == '<') {
                     reportFatalError("LessthanInAttValue",
                                      new Object[] { eleName, atName });
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     if (entityDepth == fEntityDepth) {
                         fStringBuffer2.append((char)c);
                     }
                 }
                 else if (c == '%' || c == ']') {
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     fStringBuffer.append((char)c);
                     if (entityDepth == fEntityDepth) {
                         fStringBuffer2.append((char)c);
@@ -360,7 +282,7 @@
                 // XML11EntityScanner.  Not sure why
                 // this check was originally necessary.  - NG
                 else if (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) {
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     fStringBuffer.append(' ');
                     if (entityDepth == fEntityDepth) {
                         fStringBuffer2.append('\n');
@@ -383,12 +305,12 @@
                 else if (c != -1 && isInvalidLiteral(c)) {
                     reportFatalError("InvalidCharInAttValue",
                                      new Object[] {eleName, atName, Integer.toString(c, 16)});
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     if (entityDepth == fEntityDepth) {
                         fStringBuffer2.append((char)c);
                     }
                 }
-                c = fEntityScanner.scanLiteral(quote, value);
+                c = fEntityScanner.scanLiteral(quote, value, isNSURI);
                 if (entityDepth == fEntityDepth) {
                     fStringBuffer2.append(value);
                 }
@@ -405,7 +327,7 @@
         nonNormalizedValue.setValues(fStringBuffer2);
 
         // quote
-        int cquote = fEntityScanner.scanChar();
+        int cquote = fEntityScanner.scanChar(null);
         if (cquote != quote) {
             reportFatalError("CloseQuoteExpected", new Object[]{eleName,atName});
         }
@@ -440,7 +362,7 @@
     protected boolean scanPubidLiteral(XMLString literal)
         throws IOException, XNIException
     {
-        int quote = fEntityScanner.scanChar();
+        int quote = fEntityScanner.scanChar(null);
         if (quote != '\'' && quote != '"') {
             reportFatalError("QuoteRequiredInPublicID", null);
             return false;
@@ -451,7 +373,7 @@
         boolean skipSpace = true;
         boolean dataok = true;
         while (true) {
-            int c = fEntityScanner.scanChar();
+            int c = fEntityScanner.scanChar(null);
             // REVISIT:  none of these except \n and 0x20 should make it past the entity scanner
             if (c == ' ' || c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) {
                 if (!skipSpace) {
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java b/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
index bf72247..e29d296 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
@@ -1,7 +1,6 @@
 /*
  * Copyright (c) 2015, 2016, 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
@@ -10,7 +9,7 @@
  * (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
+ *      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,
@@ -21,6 +20,7 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+import com.sun.org.apache.xerces.internal.impl.XMLScanner.NameType;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
 import com.sun.org.apache.xerces.internal.util.XML11Char;
 import com.sun.org.apache.xerces.internal.util.XMLChar;
@@ -28,6 +28,7 @@
 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 com.sun.xml.internal.stream.Entity;
 import java.io.IOException;
 
 /**
@@ -93,7 +94,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public int scanChar() throws IOException {
+    protected int scanChar(NameType nt) throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -101,6 +102,7 @@
         }
 
         // scan character
+        int offset = fCurrentEntity.position;
         int c = fCurrentEntity.ch[fCurrentEntity.position++];
         boolean external = false;
         if (c == '\n' ||
@@ -111,6 +113,7 @@
                 invokeListeners(1);
                 fCurrentEntity.ch[0] = (char)c;
                 load(1, false, false);
+                offset = 0;
             }
             if (c == '\r' && external) {
                 int cc = fCurrentEntity.ch[fCurrentEntity.position++];
@@ -123,6 +126,9 @@
 
         // return character that was scanned
         fCurrentEntity.columnNumber++;
+        if (!detectingVersion) {
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
+        }
         return c;
 
     } // scanChar():int
@@ -142,7 +148,7 @@
      * @see com.sun.org.apache.xerces.internal.util.SymbolTable
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11Name
      */
-    public String scanNmtoken() throws IOException {
+    protected String scanNmtoken() throws IOException {
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
             load(0, true, true);
@@ -249,6 +255,8 @@
      * <strong>Note:</strong> The string returned must be a symbol. The
      * SymbolTable can be used for this purpose.
      *
+     * @param nt The type of the name (element or attribute)
+     *
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      *
@@ -256,7 +264,7 @@
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11Name
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11NameStart
      */
-    public String scanName() throws IOException {
+    protected String scanName(NameType nt) throws IOException {
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
             load(0, true, true);
@@ -311,23 +319,11 @@
             return null;
         }
 
+        int length = 0;
         do {
             ch = fCurrentEntity.ch[fCurrentEntity.position];
             if (XML11Char.isXML11Name(ch)) {
-                if (++fCurrentEntity.position == fCurrentEntity.count) {
-                    int length = fCurrentEntity.position - offset;
-                    invokeListeners(length);
-                    if (length == fCurrentEntity.ch.length) {
-                        // bad luck we have to resize our buffer
-                        char[] tmp = new char[fCurrentEntity.ch.length << 1];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                    }
-                    else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, offset)) > 0) {
                     offset = 0;
                     if (load(length, false, false)) {
                         break;
@@ -335,20 +331,7 @@
                 }
             }
             else if (XML11Char.isXML11NameHighSurrogate(ch)) {
-                if (++fCurrentEntity.position == fCurrentEntity.count) {
-                    int length = fCurrentEntity.position - offset;
-                    invokeListeners(length);
-                    if (length == fCurrentEntity.ch.length) {
-                        // bad luck we have to resize our buffer
-                        char[] tmp = new char[fCurrentEntity.ch.length << 1];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                    }
-                    else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, offset)) > 0) {
                     offset = 0;
                     if (load(length, false, false)) {
                         --fCurrentEntity.position;
@@ -362,20 +345,7 @@
                     --fCurrentEntity.position;
                     break;
                 }
-                if (++fCurrentEntity.position == fCurrentEntity.count) {
-                    int length = fCurrentEntity.position - offset;
-                    invokeListeners(length);
-                    if (length == fCurrentEntity.ch.length) {
-                        // bad luck we have to resize our buffer
-                        char[] tmp = new char[fCurrentEntity.ch.length << 1];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                    }
-                    else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, offset)) > 0) {
                     offset = 0;
                     if (load(length, false, false)) {
                         break;
@@ -388,12 +358,14 @@
         }
         while (true);
 
-        int length = fCurrentEntity.position - offset;
+        length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length;
 
         // return name
         String symbol = null;
         if (length > 0) {
+            checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
+            checkEntityLimit(nt, fCurrentEntity, offset, length);
             symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length);
         }
         return symbol;
@@ -416,7 +388,7 @@
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11NCName
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11NCNameStart
      */
-    public String scanNCName() throws IOException {
+    protected String scanNCName() throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -572,6 +544,7 @@
      * this purpose.
      *
      * @param qname The qualified name structure to fill.
+     * @param nt The type of the name (element or attribute)
      *
      * @return Returns true if a qualified name appeared immediately on
      *         the input and was scanned, false otherwise.
@@ -583,7 +556,7 @@
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11Name
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11NameStart
      */
-    public boolean scanQName(QName qname) throws IOException {
+    protected boolean scanQName(QName qname, XMLScanner.NameType nt) throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -603,6 +576,7 @@
                     fCurrentEntity.columnNumber++;
                     String name = fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1);
                     qname.setValues(null, name, name, null);
+                    checkEntityLimit(nt, fCurrentEntity, 0, 1);
                     return true;
                 }
             }
@@ -633,6 +607,7 @@
                     fCurrentEntity.columnNumber += 2;
                     String name = fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 2);
                     qname.setValues(null, name, name, null);
+                    checkEntityLimit(nt, fCurrentEntity, 0, 2);
                     return true;
                 }
             }
@@ -642,6 +617,7 @@
         }
 
         int index = -1;
+        int length = 0;
         boolean sawIncompleteSurrogatePair = false;
         do {
             ch = fCurrentEntity.ch[fCurrentEntity.position];
@@ -654,22 +630,7 @@
                     //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
-                        char[] tmp = new char[fCurrentEntity.ch.length << 1];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                    }
-                    else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, index)) > 0) {
                     if (index != -1) {
                         index = index - offset;
                     }
@@ -680,20 +641,7 @@
                 }
             }
             else if (XML11Char.isXML11NameHighSurrogate(ch)) {
-                if (++fCurrentEntity.position == fCurrentEntity.count) {
-                    int length = fCurrentEntity.position - offset;
-                    invokeListeners(length);
-                    if (length == fCurrentEntity.ch.length) {
-                        // bad luck we have to resize our buffer
-                        char[] tmp = new char[fCurrentEntity.ch.length << 1];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                    }
-                    else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, index)) > 0) {
                     if (index != -1) {
                         index = index - offset;
                     }
@@ -712,20 +660,7 @@
                     --fCurrentEntity.position;
                     break;
                 }
-                if (++fCurrentEntity.position == fCurrentEntity.count) {
-                    int length = fCurrentEntity.position - offset;
-                    invokeListeners(length);
-                    if (length == fCurrentEntity.ch.length) {
-                        // bad luck we have to resize our buffer
-                        char[] tmp = new char[fCurrentEntity.ch.length << 1];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                    }
-                    else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                         fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, index)) > 0) {
                     if (index != -1) {
                         index = index - offset;
                     }
@@ -741,7 +676,7 @@
         }
         while (true);
 
-        int length = fCurrentEntity.position - offset;
+        length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length;
 
         if (length > 0) {
@@ -777,6 +712,7 @@
                 checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
             }
             qname.setValues(prefix, localpart, rawname, null);
+            checkEntityLimit(nt, fCurrentEntity, offset, length);
             return true;
         }
         return false;
@@ -809,7 +745,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public int scanContent(XMLString content) throws IOException {
+    protected int scanContent(XMLString content) throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -827,6 +763,7 @@
         int offset = fCurrentEntity.position;
         int c = fCurrentEntity.ch[offset];
         int newlines = 0;
+        boolean counted = false;
         boolean external = fCurrentEntity.isExternal();
         if (c == '\n' || ((c == '\r' || c == 0x85 || c == 0x2028) && external)) {
             do {
@@ -836,11 +773,13 @@
                     fCurrentEntity.lineNumber++;
                     fCurrentEntity.columnNumber = 1;
                     if (fCurrentEntity.position == fCurrentEntity.count) {
+                        checkEntityLimit(null, fCurrentEntity, offset, newlines);
                         offset = 0;
                         fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
                         fCurrentEntity.position = newlines;
                         fCurrentEntity.startPosition = newlines;
                         if (load(newlines, false, true)) {
+                            counted = true;
                             break;
                         }
                     }
@@ -859,11 +798,13 @@
                     fCurrentEntity.lineNumber++;
                     fCurrentEntity.columnNumber = 1;
                     if (fCurrentEntity.position == fCurrentEntity.count) {
+                        checkEntityLimit(null, fCurrentEntity, offset, newlines);
                         offset = 0;
                         fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
                         fCurrentEntity.position = newlines;
                         fCurrentEntity.startPosition = newlines;
                         if (load(newlines, false, true)) {
+                            counted = true;
                             break;
                         }
                     }
@@ -878,6 +819,7 @@
             }
             int length = fCurrentEntity.position - offset;
             if (fCurrentEntity.position == fCurrentEntity.count - 1) {
+                checkEntityLimit(null, fCurrentEntity, offset, length);
                 content.setValues(fCurrentEntity.ch, offset, length);
                 return -1;
             }
@@ -905,8 +847,8 @@
         }
         int length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length - newlines;
-        if (fCurrentEntity.isGE) {
-            checkLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fCurrentEntity, offset, length);
+        if (!counted) {
+            checkEntityLimit(null, fCurrentEntity, offset, length);
         }
         content.setValues(fCurrentEntity.ch, offset, length);
 
@@ -946,6 +888,7 @@
      * @param quote   The quote character that signifies the end of the
      *                attribute value data.
      * @param content The content structure to fill.
+     * @param isNSURI a flag indicating whether the content is a Namespace URI
      *
      * @return Returns the next character on the input, if known. This
      *         value may be -1 but this does <em>note</em> designate
@@ -954,7 +897,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public int scanLiteral(int quote, XMLString content)
+    protected int scanLiteral(int quote, XMLString content, boolean isNSURI)
         throws IOException {
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -1052,8 +995,10 @@
         }
         int length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length - newlines;
-        if (fCurrentEntity.isGE) {
-            checkLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fCurrentEntity, offset, length);
+
+        checkEntityLimit(null, fCurrentEntity, offset, length);
+        if (isNSURI) {
+            checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
         }
         content.setValues(fCurrentEntity.ch, offset, length);
 
@@ -1104,7 +1049,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public boolean scanData(String delimiter, XMLStringBuffer buffer)
+    protected boolean scanData(String delimiter, XMLStringBuffer buffer)
         throws IOException {
 
         boolean done = false;
@@ -1136,6 +1081,7 @@
             if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
                 // something must be wrong with the input:  e.g., file ends  an unterminated comment
                 int length = fCurrentEntity.count - fCurrentEntity.position;
+                checkEntityLimit(NameType.COMMENT, fCurrentEntity, fCurrentEntity.position, length);
                 buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length);
                 fCurrentEntity.columnNumber += fCurrentEntity.count;
                 fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
@@ -1200,6 +1146,7 @@
                 }
                 int length = fCurrentEntity.position - offset;
                 if (fCurrentEntity.position == fCurrentEntity.count - 1) {
+                    checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
                     buffer.append(fCurrentEntity.ch, offset, length);
                     return true;
                 }
@@ -1238,6 +1185,7 @@
                         fCurrentEntity.position--;
                         int length = fCurrentEntity.position - offset;
                         fCurrentEntity.columnNumber += length - newlines;
+                        checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
                         buffer.append(fCurrentEntity.ch, offset, length);
                         return true;
                     }
@@ -1275,6 +1223,7 @@
                         fCurrentEntity.position--;
                         int length = fCurrentEntity.position - offset;
                         fCurrentEntity.columnNumber += length - newlines;
+                        checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
                         buffer.append(fCurrentEntity.ch, offset, length);
                         return true;
                     }
@@ -1282,6 +1231,7 @@
             }
             int length = fCurrentEntity.position - offset;
             fCurrentEntity.columnNumber += length - newlines;
+            checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
             if (done) {
                 length -= delimLen;
             }
@@ -1306,7 +1256,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public boolean skipChar(int c) throws IOException {
+    protected boolean skipChar(int c, NameType nt) throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -1314,6 +1264,7 @@
         }
 
         // skip character
+        int offset = fCurrentEntity.position;
         int cc = fCurrentEntity.ch[fCurrentEntity.position];
         if (cc == c) {
             fCurrentEntity.position++;
@@ -1324,12 +1275,14 @@
             else {
                 fCurrentEntity.columnNumber++;
             }
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
         }
         else if (c == '\n' && ((cc == 0x2028 || cc == 0x85) && fCurrentEntity.isExternal())) {
             fCurrentEntity.position++;
             fCurrentEntity.lineNumber++;
             fCurrentEntity.columnNumber = 1;
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
         }
         else if (c == '\n' && (cc == '\r' ) && fCurrentEntity.isExternal()) {
@@ -1345,6 +1298,7 @@
             }
             fCurrentEntity.lineNumber++;
             fCurrentEntity.columnNumber = 1;
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
         }
 
@@ -1367,7 +1321,7 @@
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isSpace
      * @see com.sun.org.apache.xerces.internal.util.XML11Char#isXML11Space
      */
-    public boolean skipSpaces() throws IOException {
+    protected boolean skipSpaces() throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -1387,7 +1341,7 @@
 
         // skip spaces
         int c = fCurrentEntity.ch[fCurrentEntity.position];
-
+        int offset = fCurrentEntity.position - 1;
         // External --  Match: S + 0x85 + 0x2028, and perform end of line normalization
         if (fCurrentEntity.isExternal()) {
             if (XML11Char.isXML11Space(c)) {
@@ -1423,6 +1377,11 @@
                     else {
                         fCurrentEntity.columnNumber++;
                     }
+
+                    //If this is a general entity, spaces within a start element should be counted
+                    checkEntityLimit(null, fCurrentEntity, offset, fCurrentEntity.position - offset);
+                    offset = fCurrentEntity.position;
+
                     // load more characters, if needed
                     if (!entityChanged)
                         fCurrentEntity.position++;
@@ -1463,6 +1422,11 @@
                 else {
                     fCurrentEntity.columnNumber++;
                 }
+
+                //If this is a general entity, spaces within a start element should be counted
+                checkEntityLimit(null, fCurrentEntity, offset, fCurrentEntity.position - offset);
+                offset = fCurrentEntity.position;
+
                 // load more characters, if needed
                 if (!entityChanged)
                     fCurrentEntity.position++;
@@ -1496,7 +1460,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public boolean skipString(String s) throws IOException {
+    protected boolean skipString(String s) throws IOException {
 
         // load more characters, if needed
         if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -1505,6 +1469,7 @@
 
         // skip string
         final int length = s.length();
+        final int beforeSkip = fCurrentEntity.position ;
         for (int i = 0; i < length; i++) {
             char c = fCurrentEntity.ch[fCurrentEntity.position++];
             if (c != s.charAt(i)) {
@@ -1524,6 +1489,9 @@
             }
         }
         fCurrentEntity.columnNumber += length;
+        if (!detectingVersion) {
+            checkEntityLimit(null, fCurrentEntity, beforeSkip, length);
+        }
         return true;
 
     } // skipString(String):boolean
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
index a3dd4d1..ae7d7b8 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -136,7 +136,7 @@
         if (DEBUG_START_END_ELEMENT)
             System.out.println(">>> scanStartElementNS()");
                 // Note: namespace processing is on by default
-        fEntityScanner.scanQName(fElementQName);
+        fEntityScanner.scanQName(fElementQName, NameType.ATTRIBUTE);
         // REVISIT - [Q] Why do we need this local variable? -- mrglavas
         String rawname = fElementQName.rawname;
         if (fBindNamespaces) {
@@ -174,11 +174,11 @@
             // end tag?
             int c = fEntityScanner.peekChar();
             if (c == '>') {
-                fEntityScanner.scanChar();
+                fEntityScanner.scanChar(null);
                 break;
             } else if (c == '/') {
-                fEntityScanner.scanChar();
-                if (!fEntityScanner.skipChar('>')) {
+                fEntityScanner.scanChar(null);
+                if (!fEntityScanner.skipChar('>', null)) {
                     reportFatalError(
                         "ElementUnterminated",
                         new Object[] { rawname });
@@ -346,7 +346,7 @@
     protected void scanStartElementName ()
         throws IOException, XNIException {
         // Note: namespace processing is on by default
-        fEntityScanner.scanQName(fElementQName);
+        fEntityScanner.scanQName(fElementQName, NameType.ATTRIBUTE);
         // Must skip spaces here because the DTD scanner
         // would consume them at the end of the external subset.
         fSawSpace = fEntityScanner.skipSpaces();
@@ -396,11 +396,11 @@
             // end tag?
             int c = fEntityScanner.peekChar();
             if (c == '>') {
-                fEntityScanner.scanChar();
+                fEntityScanner.scanChar(null);
                 break;
             } else if (c == '/') {
-                fEntityScanner.scanChar();
-                if (!fEntityScanner.skipChar('>')) {
+                fEntityScanner.scanChar(null);
+                if (!fEntityScanner.skipChar('>', null)) {
                     reportFatalError(
                         "ElementUnterminated",
                         new Object[] { rawname });
@@ -572,11 +572,11 @@
             System.out.println(">>> scanAttribute()");
 
         // name
-        fEntityScanner.scanQName(fAttributeQName);
+        fEntityScanner.scanQName(fAttributeQName, NameType.ATTRIBUTE);
 
         // equals
         fEntityScanner.skipSpaces();
-        if (!fEntityScanner.skipChar('=')) {
+        if (!fEntityScanner.skipChar('=', NameType.ATTRIBUTE)) {
             reportFatalError(
                 "EqRequiredInAttribute",
                 new Object[] {
@@ -615,13 +615,20 @@
         //REVISIT: one more case needs to be included: external PE and standalone is no
         boolean isVC = fHasExternalDTD && !fStandalone;
 
-        // REVISIT: it seems that this function should not take attributes, and length
-        scanAttributeValue(
-            this.fTempString,
-            fTempString2,
-            fAttributeQName.rawname,
-            isVC,
-            fCurrentElement.rawname);
+        /**
+         * Determine whether this is a namespace declaration that will be subject
+         * to the name limit check in the scanAttributeValue operation.
+         * Namespace declaration format: xmlns="..." or xmlns:prefix="..."
+         * Note that prefix:xmlns="..." isn't a namespace.
+         */
+        String localpart = fAttributeQName.localpart;
+        String prefix = fAttributeQName.prefix != null
+                ? fAttributeQName.prefix : XMLSymbols.EMPTY_STRING;
+        boolean isNSDecl = fBindNamespaces & (prefix == XMLSymbols.PREFIX_XMLNS ||
+                    prefix == XMLSymbols.EMPTY_STRING && localpart == XMLSymbols.PREFIX_XMLNS);
+
+        scanAttributeValue(this.fTempString, fTempString2, fAttributeQName.rawname,
+            isVC, fCurrentElement.rawname, isNSDecl);
         String value = fTempString.toString();
         attributes.setValue(attrIndex, value);
         attributes.setNonNormalizedValue(attrIndex, fTempString2.toString());
@@ -629,17 +636,7 @@
 
         // record namespace declarations if any.
         if (fBindNamespaces) {
-
-            String localpart = fAttributeQName.localpart;
-            String prefix =
-                fAttributeQName.prefix != null
-                    ? fAttributeQName.prefix
-                    : XMLSymbols.EMPTY_STRING;
-            // when it's of form xmlns="..." or xmlns:prefix="...",
-            // it's a namespace declaration. but prefix:xmlns="..." isn't.
-            if (prefix == XMLSymbols.PREFIX_XMLNS
-                || prefix == XMLSymbols.EMPTY_STRING
-                && localpart == XMLSymbols.PREFIX_XMLNS) {
+            if (isNSDecl) {
                 if (value.length() > fXMLNameLimit) {
                     fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
                             "MaxXMLNameLimit",
@@ -759,7 +756,7 @@
 
         // end
         fEntityScanner.skipSpaces();
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', NameType.ELEMENTEND)) {
             reportFatalError(
                 "ETagUnterminated",
                 new Object[] { endElementName.rawname });
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
index 8ea89de..d63df64 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
@@ -9,8 +9,9 @@
  * 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
+ *      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,
@@ -23,12 +24,14 @@
 
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
+
 import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
 import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl;
 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.xni.XMLDTDContentModelHandler;
@@ -368,6 +371,7 @@
                 // we're done, set starting state for external subset
                 setScannerState(SCANNER_STATE_TEXT_DECL);
                 // we're done scanning DTD.
+                fLimitAnalyzer.reset(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT);
                 fLimitAnalyzer.reset(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT);
                 return false;
             }
@@ -400,7 +404,7 @@
                 if (isInvalidLiteral(c)) {
                     reportFatalError("InvalidCharInDTD",
                         new Object[] { Integer.toHexString(c) });
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                 }
             }
         }
@@ -768,7 +772,7 @@
                 fStringBuffer.clear();
                 fStringBuffer.append("xml");
                 while (isValidNameChar(fEntityScanner.peekChar())) {
-                    fStringBuffer.append((char)fEntityScanner.scanChar());
+                    fStringBuffer.append((char)fEntityScanner.scanChar(null));
                 }
                 String target =
                 fSymbolTable.addSymbol(fStringBuffer.ch,
@@ -868,7 +872,7 @@
         }
 
         // element name
-        String name = fEntityScanner.scanName();
+        String name = fEntityScanner.scanName(NameType.ELEMENTSTART);
         if (name == null) {
             reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL",
             null);
@@ -901,7 +905,7 @@
             }
         }
         else {
-            if (!fEntityScanner.skipChar('(')) {
+            if (!fEntityScanner.skipChar('(', null)) {
                 reportFatalError("MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN",
                 new Object[]{name});
             }
@@ -931,7 +935,7 @@
         fReportEntity = false;
         skipSeparator(false, !scanningInternalSubset());
         // end
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', null)) {
             reportFatalError("ElementDeclUnterminated", new Object[]{name});
         }
         fReportEntity = true;
@@ -968,7 +972,7 @@
             fDTDContentModelHandler.pcdata(null);
         }
         skipSeparator(false, !scanningInternalSubset());
-        while (fEntityScanner.skipChar('|')) {
+        while (fEntityScanner.skipChar('|', null)) {
             fStringBuffer.append('|');
             // call handler
             if (fDTDContentModelHandler != null) {
@@ -977,7 +981,7 @@
             }
             skipSeparator(false, !scanningInternalSubset());
 
-            childName = fEntityScanner.scanName();
+            childName = fEntityScanner.scanName(NameType.ENTITY);
             if (childName == null) {
                 reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_MIXED_CONTENT",
                 new Object[]{elName});
@@ -1006,7 +1010,7 @@
             reportFatalError("MixedContentUnterminated",
             new Object[]{elName});
         }
-        else if (fEntityScanner.skipChar(')')){
+        else if (fEntityScanner.skipChar(')', null)){
             fStringBuffer.append(')');
             // call handler
             if (fDTDContentModelHandler != null) {
@@ -1044,7 +1048,7 @@
         int currentOp = 0;
         int c;
         while (true) {
-            if (fEntityScanner.skipChar('(')) {
+            if (fEntityScanner.skipChar('(', null)) {
                 fMarkUpDepth++;
                 fStringBuffer.append('(');
                 // call handler
@@ -1058,7 +1062,7 @@
                 continue;
             }
             skipSeparator(false, !scanningInternalSubset());
-            String childName = fEntityScanner.scanName();
+            String childName = fEntityScanner.scanName(NameType.ELEMENTSTART);
             if (childName == null) {
                 reportFatalError("MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN",
                 new Object[]{elName});
@@ -1085,7 +1089,7 @@
                     }
                     fDTDContentModelHandler.occurrence(oc, null);
                 }
-                fEntityScanner.scanChar();
+                fEntityScanner.scanChar(null);
                 fStringBuffer.append((char)c);
             }
             while (true) {
@@ -1098,7 +1102,7 @@
                         fDTDContentModelHandler.separator(XMLDTDContentModelHandler.SEPARATOR_SEQUENCE,
                         null);
                     }
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     fStringBuffer.append(',');
                     break;
                 }
@@ -1109,7 +1113,7 @@
                         fDTDContentModelHandler.separator(XMLDTDContentModelHandler.SEPARATOR_CHOICE,
                         null);
                     }
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     fStringBuffer.append('|');
                     break;
                 }
@@ -1155,7 +1159,7 @@
                 }
                 else {
                     // no occurrence specified
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     fStringBuffer.append(')');
                 }
                 fMarkUpDepth--;
@@ -1187,7 +1191,7 @@
         }
 
         // element name
-        String elName = fEntityScanner.scanName();
+        String elName = fEntityScanner.scanName(NameType.ELEMENTSTART);
         if (elName == null) {
             reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_ATTLISTDECL",
             null);
@@ -1201,7 +1205,7 @@
         // spaces
         if (!skipSeparator(true, !scanningInternalSubset())) {
             // no space, is it the end yet?
-            if (fEntityScanner.skipChar('>')) {
+            if (fEntityScanner.skipChar('>', null)) {
                 // yes, stop here
                 // call handler
                 if (fDTDHandler != null) {
@@ -1217,8 +1221,8 @@
         }
 
         // definitions
-        while (!fEntityScanner.skipChar('>')) {
-            String name = fEntityScanner.scanName();
+        while (!fEntityScanner.skipChar('>', null)) {
+            String name = fEntityScanner.scanName(NameType.ATTRIBUTE);
             if (name == null) {
                 reportFatalError("AttNameRequiredInAttDef",
                 new Object[]{elName});
@@ -1354,7 +1358,7 @@
                 new Object[]{elName, atName});
             }
             // open paren
-            int c = fEntityScanner.scanChar();
+            int c = fEntityScanner.scanChar(null);
             if (c != '(') {
                 reportFatalError("MSG_OPEN_PAREN_REQUIRED_IN_NOTATIONTYPE",
                 new Object[]{elName, atName});
@@ -1362,7 +1366,7 @@
             fMarkUpDepth++;
             do {
                 skipSeparator(false, !scanningInternalSubset());
-                String aName = fEntityScanner.scanName();
+                String aName = fEntityScanner.scanName(NameType.ATTRIBUTE);
                 if (aName == null) {
                     reportFatalError("MSG_NAME_REQUIRED_IN_NOTATIONTYPE",
                     new Object[]{elName, atName});
@@ -1370,7 +1374,7 @@
                 ensureEnumerationSize(fEnumerationCount + 1);
                 fEnumeration[fEnumerationCount++] = aName;
                 skipSeparator(false, !scanningInternalSubset());
-                c = fEntityScanner.scanChar();
+                c = fEntityScanner.scanChar(null);
             } while (c == '|');
             if (c != ')') {
                 reportFatalError("NotationTypeUnterminated",
@@ -1381,7 +1385,7 @@
         else {              // Enumeration
             type = "ENUMERATION";
             // open paren
-            int c = fEntityScanner.scanChar();
+            int c = fEntityScanner.scanChar(null);
             if (c != '(') {
                 //                       "OPEN_PAREN_REQUIRED_BEFORE_ENUMERATION_IN_ATTRDECL",
                 reportFatalError("AttTypeRequiredInAttDef",
@@ -1398,7 +1402,7 @@
                 ensureEnumerationSize(fEnumerationCount + 1);
                 fEnumeration[fEnumerationCount++] = token;
                 skipSeparator(false, !scanningInternalSubset());
-                c = fEntityScanner.scanChar();
+                c = fEntityScanner.scanChar(null);
             } while (c == '|');
             if (c != ')') {
                 reportFatalError("EnumerationUnterminated",
@@ -1448,7 +1452,7 @@
             // AttValue
             boolean isVC = !fStandalone  &&  (fSeenExternalDTD || fSeenExternalPE) ;
             scanAttributeValue(defaultVal, nonNormalizedDefaultVal, atName,
-            fAttributes, 0, isVC, elName);
+            fAttributes, 0, isVC, elName, false);
         }
         return defaultType;
 
@@ -1476,7 +1480,7 @@
         boolean sawPERef = false;
         fReportEntity = false;
         if (fEntityScanner.skipSpaces()) {
-            if (!fEntityScanner.skipChar('%')) {
+            if (!fEntityScanner.skipChar('%', NameType.REFERENCE)) {
                 isPEDecl = false; // <!ENTITY x "x">
             }
             else if (skipSeparator(true, !scanningInternalSubset())) {
@@ -1497,7 +1501,7 @@
                 sawPERef = true;
             }
         }
-        else if (scanningInternalSubset() || !fEntityScanner.skipChar('%')) {
+        else if (scanningInternalSubset() || !fEntityScanner.skipChar('%', NameType.REFERENCE)) {
             // <!ENTITY[^ ]...> or <!ENTITY[^ %]...>
             reportFatalError("MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_ENTITYDECL",
             null);
@@ -1514,11 +1518,11 @@
         }
         if (sawPERef) {
             while (true) {
-                String peName = fEntityScanner.scanName();
+                String peName = fEntityScanner.scanName(NameType.REFERENCE);
                 if (peName == null) {
                     reportFatalError("NameRequiredInPEReference", null);
                 }
-                else if (!fEntityScanner.skipChar(';')) {
+                else if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
                     reportFatalError("SemicolonRequiredInPEReference",
                     new Object[]{peName});
                 }
@@ -1526,20 +1530,20 @@
                     startPE(peName, false);
                 }
                 fEntityScanner.skipSpaces();
-                if (!fEntityScanner.skipChar('%'))
+                if (!fEntityScanner.skipChar('%', NameType.REFERENCE))
                     break;
                 if (!isPEDecl) {
                     if (skipSeparator(true, !scanningInternalSubset())) {
                         isPEDecl = true;
                         break;
                     }
-                    isPEDecl = fEntityScanner.skipChar('%');
+                    isPEDecl = fEntityScanner.skipChar('%', NameType.REFERENCE);
                 }
             }
         }
 
         // name
-        String name = fEntityScanner.scanName();
+        String name = fEntityScanner.scanName(NameType.ENTITY);
         if (name == null) {
             reportFatalError("MSG_ENTITY_NAME_REQUIRED_IN_ENTITYDECL", null);
         }
@@ -1574,7 +1578,7 @@
                 reportFatalError("MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_UNPARSED_ENTITYDECL",
                 new Object[]{name});
             }
-            notation = fEntityScanner.scanName();
+            notation = fEntityScanner.scanName(NameType.NOTATION);
             if (notation == null) {
                 reportFatalError("MSG_NOTATION_NAME_REQUIRED_FOR_UNPARSED_ENTITYDECL",
                 new Object[]{name});
@@ -1596,7 +1600,7 @@
         skipSeparator(false, !scanningInternalSubset());
 
         // end
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', null)) {
             reportFatalError("EntityDeclUnterminated", new Object[]{name});
         }
         fMarkUpDepth--;
@@ -1651,7 +1655,7 @@
     protected final void scanEntityValue(String entityName, boolean isPEDecl, XMLString value,
     XMLString nonNormalizedValue)
     throws IOException, XNIException {
-        int quote = fEntityScanner.scanChar();
+        int quote = fEntityScanner.scanChar(null);
         if (quote != '\'' && quote != '"') {
             reportFatalError("OpenQuoteMissingInDecl", null);
         }
@@ -1666,23 +1670,24 @@
          }
         fLimitAnalyzer.startEntity(entityName);
 
-        if (fEntityScanner.scanLiteral(quote, fString) != quote) {
+        if (fEntityScanner.scanLiteral(quote, fString, false) != quote) {
             fStringBuffer.clear();
             fStringBuffer2.clear();
+            int offset;
             do {
-                checkEntityLimit(isPEDecl, entityName, fString.length + countChar);
                 countChar = 0;
+                offset = fStringBuffer.length;
                 fStringBuffer.append(fString);
                 fStringBuffer2.append(fString);
-                if (fEntityScanner.skipChar('&')) {
-                    if (fEntityScanner.skipChar('#')) {
+                if (fEntityScanner.skipChar('&', NameType.REFERENCE)) {
+                    if (fEntityScanner.skipChar('#', NameType.REFERENCE)) {
                         fStringBuffer2.append("&#");
                         scanCharReferenceValue(fStringBuffer, fStringBuffer2);
                     }
                     else {
                         fStringBuffer.append('&');
                         fStringBuffer2.append('&');
-                        String eName = fEntityScanner.scanName();
+                        String eName = fEntityScanner.scanName(NameType.REFERENCE);
                         if (eName == null) {
                             reportFatalError("NameRequiredInReference",
                             null);
@@ -1691,7 +1696,7 @@
                             fStringBuffer.append(eName);
                             fStringBuffer2.append(eName);
                         }
-                        if (!fEntityScanner.skipChar(';')) {
+                        if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
                             reportFatalError("SemicolonRequiredInReference",
                             new Object[]{eName});
                         }
@@ -1701,15 +1706,15 @@
                         }
                     }
                 }
-                else if (fEntityScanner.skipChar('%')) {
+                else if (fEntityScanner.skipChar('%', NameType.REFERENCE)) {
                     while (true) {
                         fStringBuffer2.append('%');
-                        String peName = fEntityScanner.scanName();
+                        String peName = fEntityScanner.scanName(NameType.REFERENCE);
                         if (peName == null) {
                             reportFatalError("NameRequiredInPEReference",
                             null);
                         }
-                        else if (!fEntityScanner.skipChar(';')) {
+                        else if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
                             reportFatalError("SemicolonRequiredInPEReference",
                             new Object[]{peName});
                         }
@@ -1726,20 +1731,20 @@
                         // REVISIT: This will make returning the non-
                         //          normalized value harder. -Ac
                         fEntityScanner.skipSpaces();
-                        if (!fEntityScanner.skipChar('%'))
+                        if (!fEntityScanner.skipChar('%', NameType.REFERENCE))
                             break;
                     }
                 }
                 else {
-                    countChar++;
                     int c = fEntityScanner.peekChar();
                     if (XMLChar.isHighSurrogate(c)) {
+                        countChar++;
                         scanSurrogates(fStringBuffer2);
                     }
                     else if (isInvalidLiteral(c)) {
                         reportFatalError("InvalidCharInLiteral",
                         new Object[]{Integer.toHexString(c)});
-                        fEntityScanner.scanChar();
+                        fEntityScanner.scanChar(null);
                     }
                     // if it's not the delimiting quote or if it is but from a
                     // different entity than the one this literal started from,
@@ -1747,10 +1752,12 @@
                     else if (c != quote || entityDepth != fEntityDepth) {
                         fStringBuffer.append((char)c);
                         fStringBuffer2.append((char)c);
-                        fEntityScanner.scanChar();
+                        fEntityScanner.scanChar(null);
                     }
                 }
-            } while (fEntityScanner.scanLiteral(quote, fString) != quote);
+                checkEntityLimit(isPEDecl, entityName, fStringBuffer.length - offset + countChar);
+            } while (fEntityScanner.scanLiteral(quote, fString, false) != quote);
+            checkEntityLimit(isPEDecl, entityName, fString.length);
             fStringBuffer.append(fString);
             fStringBuffer2.append(fString);
             literal = fStringBuffer;
@@ -1761,10 +1768,14 @@
         value.setValues(literal);
         nonNormalizedValue.setValues(literal2);
         if (fLimitAnalyzer != null) {
-            fLimitAnalyzer.endEntity(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, entityName);
+            if (isPEDecl) {
+                fLimitAnalyzer.endEntity(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, entityName);
+            } else {
+                fLimitAnalyzer.endEntity(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT, entityName);
+            }
         }
 
-        if (!fEntityScanner.skipChar(quote)) {
+        if (!fEntityScanner.skipChar(quote, null)) {
             reportFatalError("CloseQuoteMissingInDecl", null);
         }
     } // scanEntityValue(XMLString,XMLString):void
@@ -1789,7 +1800,7 @@
         }
 
         // notation name
-        String name = fEntityScanner.scanName();
+        String name = fEntityScanner.scanName(NameType.NOTATION);
         if (name == null) {
             reportFatalError("MSG_NOTATION_NAME_REQUIRED_IN_NOTATIONDECL",
             null);
@@ -1816,7 +1827,7 @@
         skipSeparator(false, !scanningInternalSubset());
 
         // end
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', null)) {
             reportFatalError("NotationDeclUnterminated", new Object[]{name});
         }
         fMarkUpDepth--;
@@ -1864,7 +1875,7 @@
                 XMLErrorReporter.SEVERITY_ERROR);
             }
             // call handler
-            if (!fEntityScanner.skipChar('[')) {
+            if (!fEntityScanner.skipChar('[', null)) {
                 reportFatalError("MSG_MARKUP_NOT_RECOGNIZED_IN_DTD", null);
             }
 
@@ -1889,7 +1900,7 @@
                 fDTDHandler.startConditional(XMLDTDHandler.CONDITIONAL_IGNORE,
                 null);
             }
-            if (!fEntityScanner.skipChar('[')) {
+            if (!fEntityScanner.skipChar('[', null)) {
                 reportFatalError("MSG_MARKUP_NOT_RECOGNIZED_IN_DTD", null);
             }
             fReportEntity = true;
@@ -1898,7 +1909,7 @@
                 fIgnoreConditionalBuffer.clear();
             }
             while (true) {
-                if (fEntityScanner.skipChar('<')) {
+                if (fEntityScanner.skipChar('<', null)) {
                     if (fDTDHandler != null) {
                         fIgnoreConditionalBuffer.append('<');
                     }
@@ -1906,8 +1917,8 @@
                     // These tests are split so that we handle cases like
                     // '<<![' and '<!<![' which we might otherwise miss.
                     //
-                    if (fEntityScanner.skipChar('!')) {
-                        if(fEntityScanner.skipChar('[')) {
+                    if (fEntityScanner.skipChar('!', null)) {
+                        if(fEntityScanner.skipChar('[', null)) {
                             if (fDTDHandler != null) {
                                 fIgnoreConditionalBuffer.append("![");
                             }
@@ -1919,24 +1930,24 @@
                         }
                     }
                 }
-                else if (fEntityScanner.skipChar(']')) {
+                else if (fEntityScanner.skipChar(']', null)) {
                     if (fDTDHandler != null) {
                         fIgnoreConditionalBuffer.append(']');
                     }
                     //
                     // The same thing goes for ']<![' and '<]]>', etc.
                     //
-                    if (fEntityScanner.skipChar(']')) {
+                    if (fEntityScanner.skipChar(']', null)) {
                         if (fDTDHandler != null) {
                             fIgnoreConditionalBuffer.append(']');
                         }
-                        while (fEntityScanner.skipChar(']')) {
+                        while (fEntityScanner.skipChar(']', null)) {
                             /* empty loop body */
                             if (fDTDHandler != null) {
                                 fIgnoreConditionalBuffer.append(']');
                             }
                         }
-                        if (fEntityScanner.skipChar('>')) {
+                        if (fEntityScanner.skipChar('>', null)) {
                             if (fIncludeSectDepth-- == initialDepth) {
                                 fMarkUpDepth--;
                                 // call handler
@@ -1954,7 +1965,7 @@
                     }
                 }
                 else {
-                    int c = fEntityScanner.scanChar();
+                    int c = fEntityScanner.scanChar(null);
                     if (fScannerState == SCANNER_STATE_END_OF_INPUT) {
                         reportFatalError("IgnoreSectUnterminated", null);
                         return;
@@ -1991,16 +2002,16 @@
         //System.out.println("scanDecls"+fScannerState);
         while (again && fScannerState == SCANNER_STATE_MARKUP_DECL) {
             again = complete;
-            if (fEntityScanner.skipChar('<')) {
+            if (fEntityScanner.skipChar('<', null)) {
                 fMarkUpDepth++;
-                if (fEntityScanner.skipChar('?')) {
+                if (fEntityScanner.skipChar('?', null)) {
                     fStringBuffer.clear();
                     scanPI(fStringBuffer);
                     fMarkUpDepth--; // we're done with this decl
                 }
-                else if (fEntityScanner.skipChar('!')) {
-                    if (fEntityScanner.skipChar('-')) {
-                        if (!fEntityScanner.skipChar('-')) {
+                else if (fEntityScanner.skipChar('!', null)) {
+                    if (fEntityScanner.skipChar('-', null)) {
+                        if (!fEntityScanner.skipChar('-', null)) {
                             reportFatalError("MSG_MARKUP_NOT_RECOGNIZED_IN_DTD",
                             null);
                         } else {
@@ -2019,7 +2030,7 @@
                     else if (fEntityScanner.skipString("NOTATION")) {
                         scanNotationDecl();
                     }
-                    else if (fEntityScanner.skipChar('[') &&
+                    else if (fEntityScanner.skipChar('[', null) &&
                     !scanningInternalSubset()) {
                         scanConditionalSect(fPEDepth);
                     }
@@ -2034,10 +2045,10 @@
                     reportFatalError("MSG_MARKUP_NOT_RECOGNIZED_IN_DTD", null);
                 }
             }
-            else if (fIncludeSectDepth > 0 && fEntityScanner.skipChar(']')) {
+            else if (fIncludeSectDepth > 0 && fEntityScanner.skipChar(']', null)) {
                 // end of conditional section?
-                if (!fEntityScanner.skipChar(']')
-                || !fEntityScanner.skipChar('>')) {
+                if (!fEntityScanner.skipChar(']', null)
+                || !fEntityScanner.skipChar('>', null)) {
                     reportFatalError("IncludeSectUnterminated", null);
                 }
                 // call handler
@@ -2084,21 +2095,21 @@
     throws IOException, XNIException {
         int depth = fPEDepth;
         boolean sawSpace = fEntityScanner.skipSpaces();
-        if (!lookForPERefs || !fEntityScanner.skipChar('%')) {
+        if (!lookForPERefs || !fEntityScanner.skipChar('%', NameType.REFERENCE)) {
             return !spaceRequired || sawSpace || (depth != fPEDepth);
         }
         while (true) {
-            String name = fEntityScanner.scanName();
+            String name = fEntityScanner.scanName(NameType.ENTITY);
             if (name == null) {
                 reportFatalError("NameRequiredInPEReference", null);
             }
-            else if (!fEntityScanner.skipChar(';')) {
+            else if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
                 reportFatalError("SemicolonRequiredInPEReference",
                 new Object[]{name});
             }
             startPE(name, false);
             fEntityScanner.skipSpaces();
-            if (!fEntityScanner.skipChar('%'))
+            if (!fEntityScanner.skipChar('%', NameType.REFERENCE))
                 return true;
         }
     }
@@ -2182,56 +2193,6 @@
         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 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 checkEntityLimit(boolean isPEDecl, String entityName, int len) {
-        if (fLimitAnalyzer == null) {
-            fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
-        }
-        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.GENERAL_ENTITY_SIZE_LIMIT, entityName, len);
-            if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
-                        fSecurityManager.debugPrint(fLimitAnalyzer);
-                reportFatalError("MaxEntitySizeLimit", new Object[]{entityName,
-                    fLimitAnalyzer.getValue(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT),
-                    fSecurityManager.getLimit(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT),
-                    fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT)});
-            }
-        }
-        if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
-            fSecurityManager.debugPrint(fLimitAnalyzer);
-            reportFatalError("TotalEntitySizeLimit",
-                new Object[]{fLimitAnalyzer.getTotalValue(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT),
-                fSecurityManager.getLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT),
-                fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT)});
-        }
-
-    }
-
     public DTDGrammar getGrammar(){
         return nvGrammarInfo;
     }
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
index 529e38b..6d197c5 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
@@ -21,20 +21,17 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
-import com.sun.xml.internal.stream.XMLBufferListener;
-import com.sun.xml.internal.stream.XMLEntityStorage;
-import com.sun.xml.internal.stream.dtd.DTDGrammarUtil;
-
-import java.io.EOFException;
-import java.io.IOException;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.events.XMLEvent;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
 import com.sun.org.apache.xerces.internal.util.AugmentationsImpl;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesIteratorImpl;
 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.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.XMLSecurityManager.Limit;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
+import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.xni.XMLAttributes;
 import com.sun.org.apache.xerces.internal.xni.XMLDocumentHandler;
@@ -46,14 +43,15 @@
 import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentScanner;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
-import com.sun.org.apache.xerces.internal.xni.Augmentations;
-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.utils.SecuritySupport;
-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.utils.XMLSecurityPropertyManager;
+import com.sun.xml.internal.stream.XMLBufferListener;
+import com.sun.xml.internal.stream.XMLEntityStorage;
+import com.sun.xml.internal.stream.dtd.DTDGrammarUtil;
+import java.io.EOFException;
+import java.io.IOException;
+import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.events.XMLEvent;
+
 
 /**
  *
@@ -453,6 +451,7 @@
                     //fDocumentHandler.startElement(getElementQName(),fAttributes,null);
                     break;
                 case XMLStreamConstants.CHARACTERS :
+                    fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity);
                     fDocumentHandler.characters(getCharacterData(),null);
                     break;
                 case XMLStreamConstants.SPACE:
@@ -461,13 +460,15 @@
                     //fDocumentHandler.ignorableWhitespace(getCharacterData(), null);
                     break;
                 case XMLStreamConstants.ENTITY_REFERENCE :
+                    fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity);
                     //entity reference callback are given in startEntity
                     break;
                 case XMLStreamConstants.PROCESSING_INSTRUCTION :
+                    fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity);
                     fDocumentHandler.processingInstruction(getPITarget(),getPIData(),null);
                     break;
                 case XMLStreamConstants.COMMENT :
-                    //System.out.println(" in COMMENT of the XMLNSDocumentScannerImpl");
+                    fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity);
                     fDocumentHandler.comment(getCharacterData(),null);
                     break;
                 case XMLStreamConstants.DTD :
@@ -476,6 +477,7 @@
                     //therefore we don't need to take care of anything here. So Just break;
                     break;
                 case XMLStreamConstants.CDATA:
+                    fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity);
                     fDocumentHandler.startCDATA(null);
                     //xxx: check if CDATA values comes from getCharacterData() function
                     fDocumentHandler.characters(getCharacterData(),null);
@@ -1272,9 +1274,9 @@
             fElementQName = fElementStack.nextElement();
             // name
             if (fNamespaces) {
-                fEntityScanner.scanQName(fElementQName);
+                fEntityScanner.scanQName(fElementQName, NameType.ELEMENTSTART);
             } else {
-                String name = fEntityScanner.scanName();
+                String name = fEntityScanner.scanName(NameType.ELEMENTSTART);
                 fElementQName.setValues(null, name, name, null);
             }
 
@@ -1375,11 +1377,11 @@
         // end tag?
         final int c = fEntityScanner.peekChar();
         if (c == '>') {
-            fEntityScanner.scanChar();
+            fEntityScanner.scanChar(null);
             return true;
         } else if (c == '/') {
-            fEntityScanner.scanChar();
-            if (!fEntityScanner.skipChar('>')) {
+            fEntityScanner.scanChar(null);
+            if (!fEntityScanner.skipChar('>', NameType.ELEMENTEND)) {
                 reportFatalError("ElementUnterminated",
                         new Object[]{fElementQName.rawname});
             }
@@ -1517,15 +1519,15 @@
 
         // name
         if (fNamespaces) {
-            fEntityScanner.scanQName(fAttributeQName);
+            fEntityScanner.scanQName(fAttributeQName, NameType.ATTRIBUTENAME);
         } else {
-            String name = fEntityScanner.scanName();
+            String name = fEntityScanner.scanName(NameType.ATTRIBUTENAME);
             fAttributeQName.setValues(null, name, name, null);
         }
 
         // equals
         fEntityScanner.skipSpaces();
-        if (!fEntityScanner.skipChar('=')) {
+        if (!fEntityScanner.skipChar('=', NameType.ATTRIBUTE)) {
             reportFatalError("EqRequiredInAttribute",
                 new Object[] {fCurrentElement.rawname, fAttributeQName.rawname});
         }
@@ -1543,9 +1545,8 @@
         //can safely add the attribute later..
         XMLString tmpStr = getString();
 
-        scanAttributeValue(tmpStr, fTempString2,
-                fAttributeQName.rawname, attributes,
-                attIndex, isVC, fCurrentElement.rawname);
+        scanAttributeValue(tmpStr, fTempString2, fAttributeQName.rawname, attributes,
+                attIndex, isVC, fCurrentElement.rawname, false);
 
         // content
         int oldLen = attributes.getLength();
@@ -1593,13 +1594,13 @@
         if (c == '\r') {
             // happens when there is the character reference &#13;
             //xxx: We know the next chracter.. we should just skip it and add ']' directlry
-            fEntityScanner.scanChar();
+            fEntityScanner.scanChar(null);
             content.append((char)c);
             c = -1;
         } else if (c == ']') {
             //fStringBuffer.clear();
             //xxx: We know the next chracter.. we should just skip it and add ']' directlry
-            content.append((char)fEntityScanner.scanChar());
+            content.append((char)fEntityScanner.scanChar(null));
             // remember where we are in case we get an endEntity before we
             // could flush the buffer out - this happens when we're parsing an
             // entity which ends with a ]
@@ -1608,12 +1609,12 @@
             // We work on a single character basis to handle cases such as:
             // ']]]>' which we might otherwise miss.
             //
-            if (fEntityScanner.skipChar(']')) {
+            if (fEntityScanner.skipChar(']', null)) {
                 content.append(']');
-                while (fEntityScanner.skipChar(']')) {
+                while (fEntityScanner.skipChar(']', null)) {
                     content.append(']');
                 }
-                if (fEntityScanner.skipChar('>')) {
+                if (fEntityScanner.skipChar('>', null)) {
                     reportFatalError("CDEndInContent", null);
                 }
             }
@@ -1688,7 +1689,7 @@
                     } else {
                         reportFatalError("InvalidCharInCDSect",
                                 new Object[]{Integer.toString(c,16)});
-                                fEntityScanner.scanChar();
+                                fEntityScanner.scanChar(null);
                     }
                 }
                 //by this time we have also read surrogate contents if any...
@@ -1750,7 +1751,7 @@
 
         // end
         fEntityScanner.skipSpaces();
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', NameType.ELEMENTEND)) {
             reportFatalError("ETagUnterminated",
                     new Object[]{rawname});
         }
@@ -1840,12 +1841,12 @@
      *                      notification.
      */
     protected void scanEntityReference(XMLStringBuffer content) throws IOException, XNIException {
-        String name = fEntityScanner.scanName();
+        String name = fEntityScanner.scanName(NameType.REFERENCE);
         if (name == null) {
             reportFatalError("NameRequiredInReference", null);
             return;
         }
-        if (!fEntityScanner.skipChar(';')) {
+        if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
             reportFatalError("SemicolonRequiredInReference", new Object []{name});
         }
         if (fEntityStore.isUnparsedEntity(name)) {
@@ -1942,6 +1943,7 @@
      */
     private void handleCharacter(char c, String entity, XMLStringBuffer content) throws XNIException {
         foundBuiltInRefs = true;
+        checkEntityLimit(false, fEntityScanner.fCurrentEntity.name, 1);
         content.append(c);
         if (fDocumentHandler != null) {
             fSingleChar[0] = c;
@@ -2598,19 +2600,20 @@
         private void startOfMarkup() throws IOException {
             fMarkupDepth++;
             final int ch = fEntityScanner.peekChar();
+
             if (isValidNameStartChar(ch) || isValidNameStartHighSurrogate(ch)) {
                 setScannerState(SCANNER_STATE_START_ELEMENT_TAG);
             } else {
                 switch(ch){
                     case '?' :{
                         setScannerState(SCANNER_STATE_PI);
-                        fEntityScanner.skipChar(ch);
+                        fEntityScanner.skipChar(ch, null);
                         break;
                     }
                     case '!' :{
-                        fEntityScanner.skipChar(ch);
-                        if (fEntityScanner.skipChar('-')) {
-                            if (!fEntityScanner.skipChar('-')) {
+                        fEntityScanner.skipChar(ch, null);
+                        if (fEntityScanner.skipChar('-', null)) {
+                            if (!fEntityScanner.skipChar('-', NameType.COMMENT)) {
                                 reportFatalError("InvalidCommentStart",
                                         null);
                             }
@@ -2625,7 +2628,7 @@
                     }
                     case '/' :{
                         setScannerState(SCANNER_STATE_END_ELEMENT_TAG);
-                        fEntityScanner.skipChar(ch);
+                        fEntityScanner.skipChar(ch, NameType.ELEMENTEND);
                         break;
                     }
                     default :{
@@ -2637,9 +2640,9 @@
         }//startOfMarkup
 
         private void startOfContent() throws IOException {
-            if (fEntityScanner.skipChar('<')) {
+            if (fEntityScanner.skipChar('<', null)) {
                 setScannerState(SCANNER_STATE_START_OF_MARKUP);
-            } else if (fEntityScanner.skipChar('&')) {
+            } else if (fEntityScanner.skipChar('&', NameType.REFERENCE)) {
                 setScannerState(SCANNER_STATE_REFERENCE) ; //XMLEvent.ENTITY_REFERENCE ); //SCANNER_STATE_REFERENCE
             } else {
                 //element content is there..
@@ -2712,10 +2715,10 @@
                     case SCANNER_STATE_CONTENT: {
                         final int ch = fEntityScanner.peekChar();
                         if (ch == '<') {
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(null);
                             setScannerState(SCANNER_STATE_START_OF_MARKUP);
                         } else if (ch == '&') {
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(NameType.REFERENCE);
                             setScannerState(SCANNER_STATE_REFERENCE) ; //XMLEvent.ENTITY_REFERENCE ); //SCANNER_STATE_REFERENCE
                             break;
                         } else {
@@ -2815,9 +2818,9 @@
                         if(DEBUG){
                             System.out.println("fTempString = " + fTempString);
                         }
-                        if(fEntityScanner.skipChar('<')){
+                        if(fEntityScanner.skipChar('<', null)){
                             //check if we have reached end of element
-                            if(fEntityScanner.skipChar('/')){
+                            if(fEntityScanner.skipChar('/', NameType.ELEMENTEND)){
                                 //increase the mark up depth
                                 fMarkupDepth++;
                                 fLastSectionWasCharacterData = false;
@@ -2867,7 +2870,7 @@
                             }
                             // happens when there is the character reference &#13;
                             //xxx: We know the next chracter.. we should just skip it and add ']' directlry
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(null);
                             fUsebuffer = true;
                             fContentBuffer.append((char)c);
                             c = -1 ;
@@ -2875,7 +2878,7 @@
                             //fStringBuffer.clear();
                             //xxx: We know the next chracter.. we should just skip it and add ']' directlry
                             fUsebuffer = true;
-                            fContentBuffer.append((char)fEntityScanner.scanChar());
+                            fContentBuffer.append((char)fEntityScanner.scanChar(null));
                             // remember where we are in case we get an endEntity before we
                             // could flush the buffer out - this happens when we're parsing an
                             // entity which ends with a ]
@@ -2884,12 +2887,12 @@
                             // We work on a single character basis to handle cases such as:
                             // ']]]>' which we might otherwise miss.
                             //
-                            if (fEntityScanner.skipChar(']')) {
+                            if (fEntityScanner.skipChar(']', null)) {
                                 fContentBuffer.append(']');
-                                while (fEntityScanner.skipChar(']')) {
+                                while (fEntityScanner.skipChar(']', null)) {
                                     fContentBuffer.append(']');
                                 }
-                                if (fEntityScanner.skipChar('>')) {
+                                if (fEntityScanner.skipChar('>', null)) {
                                     reportFatalError("CDEndInContent", null);
                                 }
                             }
@@ -2902,12 +2905,12 @@
                             // we need not to grow the buffer only when isCoalesce() is not true;
 
                             if (c == '<') {
-                                fEntityScanner.scanChar();
+                                fEntityScanner.scanChar(null);
                                 setScannerState(SCANNER_STATE_START_OF_MARKUP);
                                 break;
                             }//xxx what should be the behavior if entity reference is present in the content ?
                             else if (c == '&') {
-                                fEntityScanner.scanChar();
+                                fEntityScanner.scanChar(NameType.REFERENCE);
                                 setScannerState(SCANNER_STATE_REFERENCE);
                                 break;
                             }///xxx since this part is also characters, it should be merged...
@@ -2920,7 +2923,7 @@
                                     reportFatalError("InvalidCharInContent",
                                             new Object[] {
                                         Integer.toString(c, 16)});
-                                        fEntityScanner.scanChar();
+                                        fEntityScanner.scanChar(null);
                                 }
                                 break;
                             }
@@ -3046,7 +3049,7 @@
                         }
                         fUsebuffer = true ;
                         //take care of character reference
-                        if (fEntityScanner.skipChar('#')) {
+                        if (fEntityScanner.skipChar('#', NameType.REFERENCE)) {
                             scanCharReferenceValue(fContentBuffer, null);
                             fMarkupDepth--;
                             if(!fIsCoalesce){
@@ -3097,11 +3100,11 @@
 
                                 if (fNamespaces) {
                                     while (isValidNCName(fEntityScanner.peekChar())) {
-                                        fStringBuffer.append((char)fEntityScanner.scanChar());
+                                        fStringBuffer.append((char)fEntityScanner.scanChar(null));
                                     }
                                 } else {
                                     while (isValidNameChar(fEntityScanner.peekChar())) {
-                                        fStringBuffer.append((char)fEntityScanner.scanChar());
+                                        fStringBuffer.append((char)fEntityScanner.scanChar(null));
                                     }
                                 }
                                 String target = fSymbolTable.addSymbol(fStringBuffer.ch, fStringBuffer.offset, fStringBuffer.length);
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java
index 97e9d29..6c62345 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java
@@ -632,7 +632,7 @@
         }
 
         // root element name
-        fDoctypeName = fEntityScanner.scanName();
+        fDoctypeName = fEntityScanner.scanName(NameType.DOCTYPE);
         if (fDoctypeName == null) {
             reportFatalError("MSG_ROOT_ELEMENT_TYPE_REQUIRED", null);
         }
@@ -672,10 +672,10 @@
 
         // is there an internal subset?
         boolean internalSubset = true;
-        if (!fEntityScanner.skipChar('[')) {
+        if (!fEntityScanner.skipChar('[', null)) {
             internalSubset = false;
             fEntityScanner.skipSpaces();
-            if (!fEntityScanner.skipChar('>')) {
+            if (!fEntityScanner.skipChar('>', null)) {
                 reportFatalError("DoctypedeclUnterminated", new Object[]{fDoctypeName});
             }
             fMarkupDepth--;
@@ -754,7 +754,7 @@
                         fStringBuffer.clear();
                         fStringBuffer.append("xml");
                         while (XMLChar.isName(fEntityScanner.peekChar())) {
-                            fStringBuffer.append((char)fEntityScanner.scanChar());
+                            fStringBuffer.append((char)fEntityScanner.scanChar(null));
                         }
                         String target = fSymbolTable.addSymbol(fStringBuffer.ch, fStringBuffer.offset, fStringBuffer.length);
                         //this function should fill the data.. and set the fEvent object to this event.
@@ -832,9 +832,9 @@
                     switch (fScannerState) {
                         case SCANNER_STATE_PROLOG: {
                             fEntityScanner.skipSpaces();
-                            if (fEntityScanner.skipChar('<')) {
+                            if (fEntityScanner.skipChar('<', null)) {
                                 setScannerState(SCANNER_STATE_START_OF_MARKUP);
-                            } else if (fEntityScanner.skipChar('&')) {
+                            } else if (fEntityScanner.skipChar('&', NameType.REFERENCE)) {
                                 setScannerState(SCANNER_STATE_REFERENCE);
                             } else {
                                 setScannerState(SCANNER_STATE_CONTENT);
@@ -850,9 +850,9 @@
                                 setDriver(fContentDriver);
                                 //from now onwards this would be handled by fContentDriver,in the same next() call
                                 return fContentDriver.next();
-                            } else if (fEntityScanner.skipChar('!')) {
-                                if (fEntityScanner.skipChar('-')) {
-                                    if (!fEntityScanner.skipChar('-')) {
+                            } else if (fEntityScanner.skipChar('!', null)) {
+                                if (fEntityScanner.skipChar('-', null)) {
+                                    if (!fEntityScanner.skipChar('-', null)) {
                                         reportFatalError("InvalidCommentStart",
                                                 null);
                                     }
@@ -872,7 +872,7 @@
                                     reportFatalError("MarkupNotRecognizedInProlog",
                                             null);
                                 }
-                            } else if (fEntityScanner.skipChar('?')) {
+                            } else if (fEntityScanner.skipChar('?', null)) {
                                 setScannerState(SCANNER_STATE_PI);
                             } else {
                                 reportFatalError("MarkupNotRecognizedInProlog",
@@ -992,7 +992,7 @@
 
                     case SCANNER_STATE_CONTENT: {
                         reportFatalError("ContentIllegalInProlog", null);
-                        fEntityScanner.scanChar();
+                        fEntityScanner.scanChar(null);
                     }
                     case SCANNER_STATE_REFERENCE: {
                         reportFatalError("ReferenceIllegalInProlog", null);
@@ -1106,11 +1106,11 @@
                             fReadingDTD=false;
                             if (!moreToScan) {
                                 // end doctype declaration
-                                if (!fEntityScanner.skipChar(']')) {
+                                if (!fEntityScanner.skipChar(']', null)) {
                                     reportFatalError("DoctypedeclNotClosed", new Object[]{fDoctypeName});
                                 }
                                 fEntityScanner.skipSpaces();
-                                if (!fEntityScanner.skipChar('>')) {
+                                if (!fEntityScanner.skipChar('>', null)) {
                                     reportFatalError("DoctypedeclUnterminated", new Object[]{fDoctypeName});
                                 }
                                 fMarkupDepth--;
@@ -1374,7 +1374,7 @@
                             if(fScannerState == SCANNER_STATE_TERMINATED ){
                                 return XMLEvent.END_DOCUMENT ;
                             }
-                            if (fEntityScanner.skipChar('<')) {
+                            if (fEntityScanner.skipChar('<', null)) {
                                 setScannerState(SCANNER_STATE_START_OF_MARKUP);
                             } else {
                                 setScannerState(SCANNER_STATE_CONTENT);
@@ -1383,11 +1383,11 @@
                         }
                         case SCANNER_STATE_START_OF_MARKUP: {
                             fMarkupDepth++;
-                            if (fEntityScanner.skipChar('?')) {
+                            if (fEntityScanner.skipChar('?', null)) {
                                 setScannerState(SCANNER_STATE_PI);
-                            } else if (fEntityScanner.skipChar('!')) {
+                            } else if (fEntityScanner.skipChar('!', null)) {
                                 setScannerState(SCANNER_STATE_COMMENT);
-                            } else if (fEntityScanner.skipChar('/')) {
+                            } else if (fEntityScanner.skipChar('/', null)) {
                                 reportFatalError("MarkupNotRecognizedInMisc",
                                         null);
                             } else if (isValidNameStartChar(fEntityScanner.peekChar()) ||
@@ -1430,7 +1430,7 @@
                         } else{
                             reportFatalError("ContentIllegalInTrailingMisc",
                                     null);
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(null);
                             setScannerState(SCANNER_STATE_TRAILING_MISC);
                             return XMLEvent.CHARACTERS;
                         }
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java b/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
index b792231..ff02bba 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
@@ -1,7 +1,6 @@
 /*
  * Copyright (c) 2003, 2016, 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
@@ -10,7 +9,7 @@
  * (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
+ *      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,
@@ -21,6 +20,8 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+
+import com.sun.org.apache.xerces.internal.impl.XMLScanner.NameType;
 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;
@@ -144,6 +145,9 @@
     // so that XMLStreamReader.getVersion() can find that out.
     protected boolean xmlVersionSetExplicitly = false;
 
+    // indicates that the operation is for detecting XML version
+    boolean detectingVersion = false;
+
     //
     // Constructors
     //
@@ -530,10 +534,12 @@
      * <p>
      * <strong>Note:</strong> The character is consumed.
      *
+     * @param nt The type of the name (element or attribute)
+     *
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public int scanChar() throws IOException {
+    protected int scanChar(NameType nt) throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(scanChar: ");
             print();
@@ -546,6 +552,7 @@
         }
 
         // scan character
+        int offset = fCurrentEntity.position;
         int c = fCurrentEntity.ch[fCurrentEntity.position++];
         if (c == '\n' || (c == '\r' && isExternal)) {
             fCurrentEntity.lineNumber++;
@@ -554,6 +561,7 @@
                 invokeListeners(1);
                 fCurrentEntity.ch[0] = (char)c;
                 load(1, false, false);
+                offset = 0;
             }
             if (c == '\r' && isExternal) {
                 if (fCurrentEntity.ch[fCurrentEntity.position++] != '\n') {
@@ -570,6 +578,9 @@
             System.out.println(" -> '"+(char)c+"'");
         }
         fCurrentEntity.columnNumber++;
+        if (!detectingVersion) {
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
+        }
         return c;
 
     } // scanChar():int
@@ -589,7 +600,7 @@
      * @see com.sun.org.apache.xerces.internal.util.SymbolTable
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isName
      */
-    public String scanNmtoken() throws IOException {
+    protected String scanNmtoken() throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(scanNmtoken: ");
             print();
@@ -661,6 +672,8 @@
      * <strong>Note:</strong> The string returned must be a symbol. The
      * SymbolTable can be used for this purpose.
      *
+     * @param nt The type of the name (element or attribute)
+     *
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      *
@@ -668,7 +681,7 @@
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isName
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isNameStart
      */
-    public String scanName() throws IOException {
+    protected String scanName(NameType nt) throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(scanName: ");
             print();
@@ -682,6 +695,7 @@
 
         // scan name
         int offset = fCurrentEntity.position;
+        int length;
         if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) {
             if (++fCurrentEntity.position == fCurrentEntity.count) {
                 invokeListeners(1);
@@ -709,20 +723,7 @@
                     vc = XMLChar.isName(c);
                 }
                 if(!vc)break;
-                if (++fCurrentEntity.position == fCurrentEntity.count) {
-                    int length = fCurrentEntity.position - offset;
-                    invokeListeners(length);
-                    if (length == fCurrentEntity.fBufferSize) {
-                        // bad luck we have to resize our buffer
-                        char[] tmp = new char[fCurrentEntity.fBufferSize * 2];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                        fCurrentEntity.fBufferSize *= 2;
-                    } else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, offset)) > 0) {
                     offset = 0;
                     if (load(length, false, false)) {
                         break;
@@ -730,12 +731,14 @@
                 }
             }
         }
-        int length = fCurrentEntity.position - offset;
+        length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length;
 
         // return name
         String symbol;
         if (length > 0) {
+            checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
+            checkEntityLimit(nt, fCurrentEntity, offset, length);
             symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length);
         } else
             symbol = null;
@@ -759,6 +762,7 @@
      * this purpose.
      *
      * @param qname The qualified name structure to fill.
+     * @param nt The type of the name (element or attribute)
      *
      * @return Returns true if a qualified name appeared immediately on
      *         the input and was scanned, false otherwise.
@@ -770,7 +774,7 @@
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isName
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isNameStart
      */
-    public boolean scanQName(QName qname) throws IOException {
+    protected boolean scanQName(QName qname, NameType nt) throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(scanQName, "+qname+": ");
             print();
@@ -806,11 +810,13 @@
                         print();
                         System.out.println(" -> true");
                     }
+                    checkEntityLimit(nt, fCurrentEntity, 0, 1);
                     return true;
                 }
             }
             int index = -1;
             boolean vc = false;
+            int length;
             while ( true){
 
                 //XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) ;
@@ -829,22 +835,7 @@
                     //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
-                        char[] tmp = new char[fCurrentEntity.fBufferSize * 2];
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                tmp, 0, length);
-                        fCurrentEntity.ch = tmp;
-                        fCurrentEntity.fBufferSize *= 2;
-                    } else {
-                        System.arraycopy(fCurrentEntity.ch, offset,
-                                fCurrentEntity.ch, 0, length);
-                    }
+                if ((length = checkBeforeLoad(fCurrentEntity, offset, index)) > 0) {
                     if (index != -1) {
                         index = index - offset;
                     }
@@ -854,7 +845,7 @@
                     }
                 }
             }
-            int length = fCurrentEntity.position - offset;
+            length = fCurrentEntity.position - offset;
             fCurrentEntity.columnNumber += length;
             if (length > 0) {
                 String prefix = null;
@@ -885,6 +876,7 @@
                     print();
                     System.out.println(" -> true");
                 }
+                checkEntityLimit(nt, fCurrentEntity, offset, length);
                 return true;
             }
         }
@@ -900,22 +892,104 @@
     } // scanQName(QName):boolean
 
     /**
+     * Checks whether the end of the entity buffer has been reached. If yes,
+     * checks against the limit and buffer size before loading more characters.
+     *
+     * @param entity the current entity
+     * @param offset the offset from which the current read was started
+     * @param nameOffset the offset from which the current name starts
+     * @return the length of characters scanned before the end of the buffer,
+     * zero if there is more to be read in the buffer
+     */
+    protected int checkBeforeLoad(Entity.ScannedEntity entity, int offset,
+            int nameOffset) throws IOException {
+        int length = 0;
+        if (++entity.position == entity.count) {
+            length = entity.position - offset;
+            int nameLength = length;
+            if (nameOffset != -1) {
+                nameOffset = nameOffset - offset;
+                nameLength = length - nameOffset;
+            } else {
+                nameOffset = offset;
+            }
+            //check limit before loading more data
+            checkLimit(Limit.MAX_NAME_LIMIT, entity, nameOffset, nameLength);
+            invokeListeners(length);
+            if (length == entity.ch.length) {
+                // bad luck we have to resize our buffer
+                char[] tmp = new char[entity.fBufferSize * 2];
+                System.arraycopy(entity.ch, offset, tmp, 0, length);
+                entity.ch = tmp;
+                entity.fBufferSize *= 2;
+            }
+            else {
+                System.arraycopy(entity.ch, offset, entity.ch, 0, length);
+            }
+        }
+        return length;
+    }
+
+    /**
+     * If the current entity is an Entity reference, check the accumulated size
+     * against the limit.
+     *
+     * @param nt type of name (element, attribute or entity)
+     * @param entity The current entity
+     * @param offset The index of the first byte
+     * @param length The length of the entity scanned
+     */
+    protected void checkEntityLimit(NameType nt, ScannedEntity entity, int offset, int length) {
+        if (entity == null || !entity.isGE) {
+            return;
+        }
+
+        if (nt != NameType.REFERENCE) {
+            checkLimit(Limit.GENERAL_ENTITY_SIZE_LIMIT, entity, offset, length);
+        }
+        if (nt == NameType.ELEMENTSTART || nt == NameType.ATTRIBUTENAME) {
+            checkNodeCount(entity);
+        }
+    }
+
+    /**
+     * If the current entity is an Entity reference, counts the total nodes in
+     * the entity and checks the accumulated value against the limit.
+     *
+     * @param entity The current entity
+     */
+    protected void checkNodeCount(ScannedEntity entity) {
+        if (entity != null && entity.isGE) {
+            checkLimit(Limit.ENTITY_REPLACEMENT_LIMIT, entity, 0, 1);
+        }
+    }
+
+    /**
      * Checks whether the value of the specified Limit exceeds its limit
      *
-     * @param limit The Limit to be checked.
-     * @param entity The current entity.
+     * @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.
+     * @param length The length of the entity scanned
      */
     protected void checkLimit(Limit limit, ScannedEntity entity, int offset, int length) {
-        fLimitAnalyzer.addValue(limit, null, length);
+        fLimitAnalyzer.addValue(limit, entity.name, length);
         if (fSecurityManager.isOverLimit(limit, fLimitAnalyzer)) {
             fSecurityManager.debugPrint(fLimitAnalyzer);
+            Object[] e = (limit == Limit.ENTITY_REPLACEMENT_LIMIT) ?
+                    new Object[]{fLimitAnalyzer.getValue(limit),
+                        fSecurityManager.getLimit(limit), fSecurityManager.getStateLiteral(limit)} :
+                    new Object[]{entity.name, fLimitAnalyzer.getValue(limit),
+                        fSecurityManager.getLimit(limit), fSecurityManager.getStateLiteral(limit)};
             fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, limit.key(),
-                    new Object[]{new String(entity.ch, offset, length),
-                fLimitAnalyzer.getTotalValue(limit),
-                fSecurityManager.getLimit(limit),
-                fSecurityManager.getStateLiteral(limit)},
+                    e, XMLErrorReporter.SEVERITY_FATAL_ERROR);
+        }
+        if (fSecurityManager.isOverLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
+            fSecurityManager.debugPrint(fLimitAnalyzer);
+            fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, "TotalEntitySizeLimit",
+                    new Object[]{fLimitAnalyzer.getTotalValue(Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getStateLiteral(Limit.TOTAL_ENTITY_SIZE_LIMIT)},
                     XMLErrorReporter.SEVERITY_FATAL_ERROR);
         }
     }
@@ -942,7 +1016,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public int scanContent(XMLString content) throws IOException {
+    protected int scanContent(XMLString content) throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(scanContent: ");
             print();
@@ -963,6 +1037,7 @@
         int offset = fCurrentEntity.position;
         int c = fCurrentEntity.ch[offset];
         int newlines = 0;
+        boolean counted = false;
         if (c == '\n' || (c == '\r' && isExternal)) {
             if (DEBUG_BUFFER) {
                 System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
@@ -976,9 +1051,11 @@
                     fCurrentEntity.lineNumber++;
                     fCurrentEntity.columnNumber = 1;
                     if (fCurrentEntity.position == fCurrentEntity.count) {
+                        checkEntityLimit(null, fCurrentEntity, offset, newlines);
                         offset = 0;
                         fCurrentEntity.position = newlines;
                         if (load(newlines, false, true)) {
+                            counted = true;
                             break;
                         }
                     }
@@ -995,9 +1072,11 @@
                     fCurrentEntity.lineNumber++;
                     fCurrentEntity.columnNumber = 1;
                     if (fCurrentEntity.position == fCurrentEntity.count) {
+                        checkEntityLimit(null, fCurrentEntity, offset, newlines);
                         offset = 0;
                         fCurrentEntity.position = newlines;
                         if (load(newlines, false, true)) {
+                            counted = true;
                             break;
                         }
                     }
@@ -1011,6 +1090,7 @@
             }
             int length = fCurrentEntity.position - offset;
             if (fCurrentEntity.position == fCurrentEntity.count - 1) {
+                checkEntityLimit(null, fCurrentEntity, offset, length);
                 //CHANGED: dont replace the value.. append to the buffer. This gives control to the callee
                 //on buffering the data..
                 content.setValues(fCurrentEntity.ch, offset, length);
@@ -1038,8 +1118,8 @@
         }
         int length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length - newlines;
-        if (fCurrentEntity.isGE) {
-            checkLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fCurrentEntity, offset, length);
+        if (!counted) {
+            checkEntityLimit(null, fCurrentEntity, offset, length);
         }
 
         //CHANGED: dont replace the value.. append to the buffer. This gives control to the callee
@@ -1086,6 +1166,7 @@
      * @param quote   The quote character that signifies the end of the
      *                attribute value data.
      * @param content The content structure to fill.
+     * @param isNSURI a flag indicating whether the content is a Namespace URI
      *
      * @return Returns the next character on the input, if known. This
      *         value may be -1 but this does <em>note</em> designate
@@ -1094,7 +1175,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public int scanLiteral(int quote, XMLString content)
+    protected int scanLiteral(int quote, XMLString content, boolean isNSURI)
     throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(scanLiteral, '"+(char)quote+"': ");
@@ -1205,8 +1286,10 @@
         }
         int length = fCurrentEntity.position - offset;
         fCurrentEntity.columnNumber += length - newlines;
-        if (fCurrentEntity.isGE) {
-            checkLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT, fCurrentEntity, offset, length);
+
+        checkEntityLimit(null, fCurrentEntity, offset, length);
+        if (isNSURI) {
+            checkLimit(Limit.MAX_NAME_LIMIT, fCurrentEntity, offset, length);
         }
         content.setValues(fCurrentEntity.ch, offset, length);
 
@@ -1273,7 +1356,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public boolean scanData(String delimiter, XMLStringBuffer buffer)
+    protected boolean scanData(String delimiter, XMLStringBuffer buffer)
     throws IOException {
 
         boolean done = false;
@@ -1311,6 +1394,7 @@
             if (fCurrentEntity.position > fCurrentEntity.count - delimLen) {
                 // something must be wrong with the input:  e.g., file ends in an unterminated comment
                 int length = fCurrentEntity.count - fCurrentEntity.position;
+                checkEntityLimit(NameType.COMMENT, fCurrentEntity, fCurrentEntity.position, length);
                 buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length);
                 fCurrentEntity.columnNumber += fCurrentEntity.count;
                 fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
@@ -1373,6 +1457,7 @@
                 }
                 int length = fCurrentEntity.position - offset;
                 if (fCurrentEntity.position == fCurrentEntity.count - 1) {
+                    checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
                     buffer.append(fCurrentEntity.ch, offset, length);
                     if (DEBUG_BUFFER) {
                         System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
@@ -1416,12 +1501,14 @@
                     fCurrentEntity.position--;
                     int length = fCurrentEntity.position - offset;
                     fCurrentEntity.columnNumber += length - newlines;
+                    checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
                     buffer.append(fCurrentEntity.ch, offset, length);
                     return true;
                 }
             }
             int length = fCurrentEntity.position - offset;
             fCurrentEntity.columnNumber += length - newlines;
+            checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
             if (done) {
                 length -= delimLen;
             }
@@ -1445,13 +1532,14 @@
      * the specified character.
      *
      * @param c The character to skip.
+     * @param nt The type of the name (element or attribute)
      *
      * @return Returns true if the character was skipped.
      *
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public boolean skipChar(int c) throws IOException {
+    protected boolean skipChar(int c, NameType nt) throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(skipChar, '"+(char)c+"': ");
             print();
@@ -1464,6 +1552,7 @@
         }
 
         // skip character
+        int offset = fCurrentEntity.position;
         int cc = fCurrentEntity.ch[fCurrentEntity.position];
         if (cc == c) {
             fCurrentEntity.position++;
@@ -1478,6 +1567,7 @@
                 print();
                 System.out.println(" -> true");
             }
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
         } else if (c == '\n' && cc == '\r' && isExternal) {
             // handle newlines
@@ -1497,6 +1587,7 @@
                 print();
                 System.out.println(" -> true");
             }
+            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
         }
 
@@ -1526,7 +1617,7 @@
      *
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isSpace
      */
-    public boolean skipSpaces() throws IOException {
+    protected boolean skipSpaces() throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(skipSpaces: ");
             print();
@@ -1550,6 +1641,7 @@
 
         // skip spaces
         int c = fCurrentEntity.ch[fCurrentEntity.position];
+        int offset = fCurrentEntity.position - 1;
         if (XMLChar.isSpace(c)) {
             do {
                 boolean entityChanged = false;
@@ -1579,6 +1671,11 @@
                 } else {
                     fCurrentEntity.columnNumber++;
                 }
+
+                //If this is a general entity, spaces within a start element should be counted
+                checkEntityLimit(null, fCurrentEntity, offset, fCurrentEntity.position - offset);
+                offset = fCurrentEntity.position;
+
                 // load more characters, if needed
                 if (!entityChanged){
                     fCurrentEntity.position++;
@@ -1620,7 +1717,7 @@
 
 
     /**
-     * @param legnth This function checks that following number of characters are available.
+     * @param length This function checks that following number of characters are available.
      * to the underlying buffer.
      * @return This function returns true if capacity asked is available.
      */
@@ -1629,9 +1726,9 @@
     }
 
     /**
-     * @param legnth This function checks that following number of characters are available.
+     * @param length This function checks that following number of characters are available.
      * to the underlying buffer.
-     * @param if the underlying function should change the entity
+     * @param changeEntity a flag to indicate that the underlying function should change the entity
      * @return This function returns true if capacity asked is available.
      *
      */
@@ -1694,7 +1791,7 @@
      * @throws IOException  Thrown if i/o error occurs.
      * @throws EOFException Thrown on end of file.
      */
-    public boolean skipString(String s) throws IOException {
+    protected boolean skipString(String s) throws IOException {
 
         final int length = s.length();
 
@@ -1714,6 +1811,9 @@
                 if(afterSkip-- == beforeSkip){
                     fCurrentEntity.position = fCurrentEntity.position + length ;
                     fCurrentEntity.columnNumber += length;
+                    if (!detectingVersion) {
+                        checkEntityLimit(null, fCurrentEntity, beforeSkip, length);
+                    }
                     return true;
                 }
             }
@@ -1722,7 +1822,7 @@
         return false;
     } // skipString(String):boolean
 
-    public boolean skipString(char [] s) throws IOException {
+    protected boolean skipString(char [] s) throws IOException {
 
         final int length = s.length;
         //first make sure that required capacity is avaible
@@ -1741,6 +1841,9 @@
             }
             fCurrentEntity.position = fCurrentEntity.position + length ;
             fCurrentEntity.columnNumber += length;
+            if (!detectingVersion) {
+                checkEntityLimit(null, fCurrentEntity, beforeSkip, length);
+            }
             return true;
 
         }
@@ -2138,7 +2241,7 @@
      *
      * @see com.sun.org.apache.xerces.internal.util.XMLChar#isSpace
      */
-    public final boolean skipDeclSpaces() throws IOException {
+    protected final boolean skipDeclSpaces() throws IOException {
         if (DEBUG_BUFFER) {
             System.out.print("(skipDeclSpaces: ");
             //XMLEntityManager.print(fCurrentEntity);
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java b/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java
index cbc93b8..264b908 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java
@@ -190,9 +190,9 @@
             // There are two variables,fNamespaces and fBindNamespaces
             //StAX uses XMLNSDocumentScannerImpl so this distinction needs to be maintained
             if (fNamespaces) {
-                fEntityScanner.scanQName(fElementQName);
+                fEntityScanner.scanQName(fElementQName, NameType.ELEMENTSTART);
             } else {
-                String name = fEntityScanner.scanName();
+                String name = fEntityScanner.scanName(NameType.ELEMENTSTART);
                 fElementQName.setValues(null, name, name, null);
             }
 
@@ -405,11 +405,11 @@
         if (DEBUG_START_END_ELEMENT) System.out.println(this.getClass().toString() +">>> scanAttribute()");
 
         // name
-        fEntityScanner.scanQName(fAttributeQName);
+        fEntityScanner.scanQName(fAttributeQName, NameType.ATTRIBUTE);
 
         // equals
         fEntityScanner.skipSpaces();
-        if (!fEntityScanner.skipChar('=')) {
+        if (!fEntityScanner.skipChar('=', NameType.ATTRIBUTE)) {
             reportFatalError("EqRequiredInAttribute",
                     new Object[]{fCurrentElement.rawname,fAttributeQName.rawname});
         }
@@ -431,23 +431,28 @@
         //since scanAttributeValue doesn't use attIndex parameter therefore we
         //can safely add the attribute later..
         XMLString tmpStr = getString();
-        scanAttributeValue(tmpStr, fTempString2,
-                fAttributeQName.rawname, attributes,
-                attrIndex, isVC, fCurrentElement.rawname);
+
+        /**
+         * Determine whether this is a namespace declaration that will be subject
+         * to the name limit check in the scanAttributeValue operation.
+         * Namespace declaration format: xmlns="..." or xmlns:prefix="..."
+         * Note that prefix:xmlns="..." isn't a namespace.
+         */
+        String localpart = fAttributeQName.localpart;
+        String prefix = fAttributeQName.prefix != null
+                ? fAttributeQName.prefix : XMLSymbols.EMPTY_STRING;
+        boolean isNSDecl = fBindNamespaces & (prefix == XMLSymbols.PREFIX_XMLNS ||
+                    prefix == XMLSymbols.EMPTY_STRING && localpart == XMLSymbols.PREFIX_XMLNS);
+
+        scanAttributeValue(tmpStr, fTempString2, fAttributeQName.rawname, attributes,
+                attrIndex, isVC, fCurrentElement.rawname, isNSDecl);
 
         String value = null;
         //fTempString.toString();
 
         // record namespace declarations if any.
         if (fBindNamespaces) {
-
-            String localpart = fAttributeQName.localpart;
-            String prefix = fAttributeQName.prefix != null
-                    ? fAttributeQName.prefix : XMLSymbols.EMPTY_STRING;
-            // when it's of form xmlns="..." or xmlns:prefix="...",
-            // it's a namespace declaration. but prefix:xmlns="..." isn't.
-            if (prefix == XMLSymbols.PREFIX_XMLNS ||
-                    prefix == XMLSymbols.EMPTY_STRING && localpart == XMLSymbols.PREFIX_XMLNS) {
+            if (isNSDecl) {
                 //check the length of URI
                 if (tmpStr.length > fXMLNameLimit) {
                     fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java b/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
index d926d78..fb12b42 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
@@ -115,6 +115,30 @@
     /** Debug attribute normalization. */
     protected static final boolean DEBUG_ATTR_NORMALIZATION = false;
 
+    /**
+     * Type of names
+     */
+    public static enum NameType {
+        ATTRIBUTE("attribute"),
+        ATTRIBUTENAME("attribute name"),
+        COMMENT("comment"),
+        DOCTYPE("doctype"),
+        ELEMENTSTART("startelement"),
+        ELEMENTEND("endelement"),
+        ENTITY("entity"),
+        NOTATION("notation"),
+        PI("pi"),
+        REFERENCE("reference");
+
+        final String literal;
+        NameType(String literal) {
+            this.literal = literal;
+        }
+
+        String literal() {
+            return literal;
+        }
+    }
 
     //xxx: setting the default value as false, as we dont need to calculate this value
     //we should have a feature when set to true computes this value
@@ -145,7 +169,7 @@
     protected boolean fNotifyCharRefs = false;
 
     /** Internal parser-settings feature */
-        protected boolean fParserSettings = true;
+    protected boolean fParserSettings = true;
 
     // properties
 
@@ -174,13 +198,13 @@
     /** event type */
     protected XMLEvent fEvent ;
 
-    /** Entity scanner, this alwasy works on last entity that was opened. */
+    /** Entity scanner, this always works on last entity that was opened. */
     protected XMLEntityScanner fEntityScanner = null;
 
     /** Entity depth. */
     protected int fEntityDepth;
 
-    /** Literal value of the last character refence scanned. */
+    /** Literal value of the last character reference scanned. */
     protected String fCharRefLiteral = null;
 
     /** Scanning attribute. */
@@ -548,10 +572,10 @@
         }
 
         // end
-        if (!fEntityScanner.skipChar('?')) {
+        if (!fEntityScanner.skipChar('?', null)) {
             reportFatalError("XMLDeclUnterminated", null);
         }
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', null)) {
             reportFatalError("XMLDeclUnterminated", null);
 
         }
@@ -578,7 +602,7 @@
      * <strong>Note:</strong> This method uses fStringBuffer2, anything in it
      * at the time of calling is lost.
      */
-    public String scanPseudoAttribute(boolean scanningTextDecl,
+    protected String scanPseudoAttribute(boolean scanningTextDecl,
             XMLString value)
             throws IOException, XNIException {
 
@@ -589,7 +613,7 @@
             reportFatalError("PseudoAttrNameExpected", null);
         }
         fEntityScanner.skipSpaces();
-        if (!fEntityScanner.skipChar('=')) {
+        if (!fEntityScanner.skipChar('=', null)) {
             reportFatalError(scanningTextDecl ? "EqRequiredInTextDecl"
                     : "EqRequiredInXMLDecl", new Object[]{name});
         }
@@ -599,15 +623,15 @@
             reportFatalError(scanningTextDecl ? "QuoteRequiredInTextDecl"
                     : "QuoteRequiredInXMLDecl" , new Object[]{name});
         }
-        fEntityScanner.scanChar();
-        int c = fEntityScanner.scanLiteral(quote, value);
+        fEntityScanner.scanChar(NameType.ATTRIBUTE);
+        int c = fEntityScanner.scanLiteral(quote, value, false);
         if (c != quote) {
             fStringBuffer2.clear();
             do {
                 fStringBuffer2.append(value);
                 if (c != -1) {
                     if (c == '&' || c == '%' || c == '<' || c == ']') {
-                        fStringBuffer2.append((char)fEntityScanner.scanChar());
+                        fStringBuffer2.append((char)fEntityScanner.scanChar(NameType.ATTRIBUTE));
                     } else if (XMLChar.isHighSurrogate(c)) {
                         scanSurrogates(fStringBuffer2);
                     } else if (isInvalidLiteral(c)) {
@@ -615,15 +639,15 @@
                                 ? "InvalidCharInTextDecl" : "InvalidCharInXMLDecl";
                         reportFatalError(key,
                                 new Object[] {Integer.toString(c, 16)});
-                                fEntityScanner.scanChar();
+                                fEntityScanner.scanChar(null);
                     }
                 }
-                c = fEntityScanner.scanLiteral(quote, value);
+                c = fEntityScanner.scanLiteral(quote, value, false);
             } while (c != quote);
             fStringBuffer2.append(value);
             value.setValues(fStringBuffer2);
         }
-        if (!fEntityScanner.skipChar(quote)) {
+        if (!fEntityScanner.skipChar(quote, null)) {
             reportFatalError(scanningTextDecl ? "CloseQuoteMissingInTextDecl"
                     : "CloseQuoteMissingInXMLDecl",
                     new Object[]{name});
@@ -681,7 +705,7 @@
 
         // target
         fReportEntity = false;
-        String target = fEntityScanner.scanName();
+        String target = fEntityScanner.scanName(NameType.PI);
         if (target == null) {
             reportFatalError("PITargetRequired", null);
         }
@@ -746,7 +770,7 @@
                     } else if (isInvalidLiteral(c)) {
                         reportFatalError("InvalidCharInPI",
                                 new Object[]{Integer.toHexString(c)});
-                                fEntityScanner.scanChar();
+                                fEntityScanner.scanChar(null);
                     }
                 }
             } while (fEntityScanner.scanData("?>", data));
@@ -787,11 +811,11 @@
                 else if (isInvalidLiteral(c)) {
                     reportFatalError("InvalidCharInComment",
                             new Object[] { Integer.toHexString(c) });
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(NameType.COMMENT);
                 }
             }
         }
-        if (!fEntityScanner.skipChar('>')) {
+        if (!fEntityScanner.skipChar('>', NameType.COMMENT)) {
             reportFatalError("DashDashInComment", null);
         }
 
@@ -812,15 +836,14 @@
      * @param checkEntities true if undeclared entities should be reported as VC violation,
      *                      false if undeclared entities should be reported as WFC violation.
      * @param eleName The name of element to which this attribute belongs.
+     * @param isNSURI a flag indicating whether the content is a Namespace URI
      *
      * <strong>Note:</strong> This method uses fStringBuffer2, anything in it
      * at the time of calling is lost.
      **/
-    protected void scanAttributeValue(XMLString value,
-            XMLString nonNormalizedValue,
-            String atName,
-            XMLAttributes attributes, int attrIndex,
-            boolean checkEntities, String eleName)
+    protected void scanAttributeValue(XMLString value, XMLString nonNormalizedValue,
+            String atName, XMLAttributes attributes, int attrIndex, boolean checkEntities,
+            String eleName, boolean isNSURI)
             throws IOException, XNIException {
         XMLStringBuffer stringBuffer = null;
         // quote
@@ -829,10 +852,10 @@
             reportFatalError("OpenQuoteExpected", new Object[]{eleName, atName});
         }
 
-        fEntityScanner.scanChar();
+        fEntityScanner.scanChar(NameType.ATTRIBUTE);
         int entityDepth = fEntityDepth;
 
-        int c = fEntityScanner.scanLiteral(quote, value);
+        int c = fEntityScanner.scanLiteral(quote, value, isNSURI);
         if (DEBUG_ATTR_NORMALIZATION) {
             System.out.println("** scanLiteral -> \""
                     + value.toString() + "\"");
@@ -858,11 +881,11 @@
                             + stringBuffer.toString() + "\"");
                 }
                 if (c == '&') {
-                    fEntityScanner.skipChar('&');
+                    fEntityScanner.skipChar('&', NameType.REFERENCE);
                     if (entityDepth == fEntityDepth && fNeedNonNormalizedValue ) {
                         fStringBuffer2.append('&');
                     }
-                    if (fEntityScanner.skipChar('#')) {
+                    if (fEntityScanner.skipChar('#', NameType.REFERENCE)) {
                         if (entityDepth == fEntityDepth && fNeedNonNormalizedValue ) {
                             fStringBuffer2.append('#');
                         }
@@ -880,53 +903,20 @@
                             }
                         }
                     } else {
-                        String entityName = fEntityScanner.scanName();
+                        String entityName = fEntityScanner.scanName(NameType.ENTITY);
                         if (entityName == null) {
                             reportFatalError("NameRequiredInReference", null);
                         } else if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                             fStringBuffer2.append(entityName);
                         }
-                        if (!fEntityScanner.skipChar(';')) {
+                        if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
                             reportFatalError("SemicolonRequiredInReference",
                                     new Object []{entityName});
                         } else if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                             fStringBuffer2.append(';');
                         }
-                        if (entityName == fAmpSymbol) {
-                            stringBuffer.append('&');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** value5: \""
-                                        + stringBuffer.toString()
-                                        + "\"");
-                            }
-                        } else if (entityName == fAposSymbol) {
-                            stringBuffer.append('\'');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** value7: \""
-                                        + stringBuffer.toString()
-                                        + "\"");
-                            }
-                        } else if (entityName == fLtSymbol) {
-                            stringBuffer.append('<');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** value9: \""
-                                        + stringBuffer.toString()
-                                        + "\"");
-                            }
-                        } else if (entityName == fGtSymbol) {
-                            stringBuffer.append('>');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** valueB: \""
-                                        + stringBuffer.toString()
-                                        + "\"");
-                            }
-                        } else if (entityName == fQuotSymbol) {
-                            stringBuffer.append('"');
-                            if (DEBUG_ATTR_NORMALIZATION) {
-                                System.out.println("** valueD: \""
-                                        + stringBuffer.toString()
-                                        + "\"");
-                            }
+                        if (resolveCharacter(entityName, stringBuffer)) {
+                            checkEntityLimit(false, fEntityScanner.fCurrentEntity.name, 1);
                         } else {
                             if (fEntityStore.isExternalEntity(entityName)) {
                                 reportFatalError("ReferenceToExternalEntity",
@@ -953,12 +943,12 @@
                 } else if (c == '<') {
                     reportFatalError("LessthanInAttValue",
                             new Object[] { eleName, atName });
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(null);
                             if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                                 fStringBuffer2.append((char)c);
                             }
                 } else if (c == '%' || c == ']') {
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     stringBuffer.append((char)c);
                     if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                         fStringBuffer2.append((char)c);
@@ -968,7 +958,7 @@
                                 + stringBuffer.toString() + "\"");
                     }
                 } else if (c == '\n' || c == '\r') {
-                    fEntityScanner.scanChar();
+                    fEntityScanner.scanChar(null);
                     stringBuffer.append(' ');
                     if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                         fStringBuffer2.append('\n');
@@ -989,12 +979,12 @@
                 } else if (c != -1 && isInvalidLiteral(c)) {
                     reportFatalError("InvalidCharInAttValue",
                             new Object[] {eleName, atName, Integer.toString(c, 16)});
-                            fEntityScanner.scanChar();
+                            fEntityScanner.scanChar(null);
                             if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                                 fStringBuffer2.append((char)c);
                             }
                 }
-                c = fEntityScanner.scanLiteral(quote, value);
+                c = fEntityScanner.scanLiteral(quote, value, isNSURI);
                 if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
                     fStringBuffer2.append(value);
                 }
@@ -1015,7 +1005,7 @@
             nonNormalizedValue.setValues(fStringBuffer2);
 
         // quote
-        int cquote = fEntityScanner.scanChar();
+        int cquote = fEntityScanner.scanChar(NameType.ATTRIBUTE);
         if (cquote != quote) {
             reportFatalError("CloseQuoteExpected", new Object[]{eleName, atName});
         }
@@ -1023,6 +1013,39 @@
 
 
     /**
+     * Resolves character entity references.
+     * @param entityName the name of the entity
+     * @param stringBuffer the current XMLStringBuffer to append the character to.
+     * @return true if resolved, false otherwise
+     */
+    protected boolean resolveCharacter(String entityName, XMLStringBuffer stringBuffer) {
+        /**
+         * entityNames (symbols) are interned. The equals method would do the same,
+         * but I'm leaving it as comparisons by references are common in the impl
+         * and it made it explicit to others who read this code.
+         */
+        if (entityName == fAmpSymbol) {
+            stringBuffer.append('&');
+            return true;
+        } else if (entityName == fAposSymbol) {
+            stringBuffer.append('\'');
+            return true;
+        } else if (entityName == fLtSymbol) {
+            stringBuffer.append('<');
+            return true;
+        } else if (entityName == fGtSymbol) {
+            checkEntityLimit(false, fEntityScanner.fCurrentEntity.name, 1);
+            stringBuffer.append('>');
+            return true;
+        } else if (entityName == fQuotSymbol) {
+            checkEntityLimit(false, fEntityScanner.fCurrentEntity.name, 1);
+            stringBuffer.append('"');
+            return true;
+        }
+        return false;
+    }
+
+    /**
      * Scans External ID and return the public and system IDs.
      *
      * @param identifiers An array of size 2 to return the system id,
@@ -1065,25 +1088,25 @@
                 }
                 reportFatalError("QuoteRequiredInSystemID", null);
             }
-            fEntityScanner.scanChar();
+            fEntityScanner.scanChar(null);
             XMLString ident = fString;
-            if (fEntityScanner.scanLiteral(quote, ident) != quote) {
+            if (fEntityScanner.scanLiteral(quote, ident, false) != quote) {
                 fStringBuffer.clear();
                 do {
                     fStringBuffer.append(ident);
                     int c = fEntityScanner.peekChar();
                     if (XMLChar.isMarkup(c) || c == ']') {
-                        fStringBuffer.append((char)fEntityScanner.scanChar());
+                        fStringBuffer.append((char)fEntityScanner.scanChar(null));
                     } else if (c != -1 && isInvalidLiteral(c)) {
                         reportFatalError("InvalidCharInSystemID",
                             new Object[] {Integer.toString(c, 16)});
                     }
-                } while (fEntityScanner.scanLiteral(quote, ident) != quote);
+                } while (fEntityScanner.scanLiteral(quote, ident, false) != quote);
                 fStringBuffer.append(ident);
                 ident = fStringBuffer;
             }
             systemId = ident.toString();
-            if (!fEntityScanner.skipChar(quote)) {
+            if (!fEntityScanner.skipChar(quote, null)) {
                 reportFatalError("SystemIDUnterminated", null);
             }
         }
@@ -1115,7 +1138,7 @@
      */
     protected boolean scanPubidLiteral(XMLString literal)
     throws IOException, XNIException {
-        int quote = fEntityScanner.scanChar();
+        int quote = fEntityScanner.scanChar(null);
         if (quote != '\'' && quote != '"') {
             reportFatalError("QuoteRequiredInPublicID", null);
             return false;
@@ -1126,7 +1149,7 @@
         boolean skipSpace = true;
         boolean dataok = true;
         while (true) {
-            int c = fEntityScanner.scanChar();
+            int c = fEntityScanner.scanChar(null);
             if (c == ' ' || c == '\n' || c == '\r') {
                 if (!skipSpace) {
                     // take the first whitespace as a space and skip the others
@@ -1242,9 +1265,10 @@
      */
     protected int scanCharReferenceValue(XMLStringBuffer buf, XMLStringBuffer buf2)
     throws IOException, XNIException {
+        int initLen = buf.length;
         // scan hexadecimal value
         boolean hex = false;
-        if (fEntityScanner.skipChar('x')) {
+        if (fEntityScanner.skipChar('x', NameType.REFERENCE)) {
             if (buf2 != null) { buf2.append('x'); }
             hex = true;
             fStringBuffer3.clear();
@@ -1256,7 +1280,7 @@
                     (c >= 'A' && c <= 'F');
             if (digit) {
                 if (buf2 != null) { buf2.append((char)c); }
-                fEntityScanner.scanChar();
+                fEntityScanner.scanChar(NameType.REFERENCE);
                 fStringBuffer3.append((char)c);
 
                 do {
@@ -1266,7 +1290,7 @@
                             (c >= 'A' && c <= 'F');
                     if (digit) {
                         if (buf2 != null) { buf2.append((char)c); }
-                        fEntityScanner.scanChar();
+                        fEntityScanner.scanChar(NameType.REFERENCE);
                         fStringBuffer3.append((char)c);
                     }
                 } while (digit);
@@ -1284,7 +1308,7 @@
             digit = c >= '0' && c <= '9';
             if (digit) {
                 if (buf2 != null) { buf2.append((char)c); }
-                fEntityScanner.scanChar();
+                fEntityScanner.scanChar(NameType.REFERENCE);
                 fStringBuffer3.append((char)c);
 
                 do {
@@ -1292,7 +1316,7 @@
                     digit = c >= '0' && c <= '9';
                     if (digit) {
                         if (buf2 != null) { buf2.append((char)c); }
-                        fEntityScanner.scanChar();
+                        fEntityScanner.scanChar(NameType.REFERENCE);
                         fStringBuffer3.append((char)c);
                     }
                 } while (digit);
@@ -1302,7 +1326,7 @@
         }
 
         // end
-        if (!fEntityScanner.skipChar(';')) {
+        if (!fEntityScanner.skipChar(';', NameType.REFERENCE)) {
             reportFatalError("SemicolonRequiredInCharRef", null);
         }
         if (buf2 != null) { buf2.append(';'); }
@@ -1348,6 +1372,9 @@
             }
         }
 
+        if (fEntityScanner.fCurrentEntity.isGE) {
+            checkEntityLimit(false, fEntityScanner.fCurrentEntity.name, buf.length - initLen);
+        }
         return value;
     }
     // returns true if the given character is not
@@ -1409,14 +1436,14 @@
     protected boolean scanSurrogates(XMLStringBuffer buf)
     throws IOException, XNIException {
 
-        int high = fEntityScanner.scanChar();
+        int high = fEntityScanner.scanChar(null);
         int low = fEntityScanner.peekChar();
         if (!XMLChar.isLowSurrogate(low)) {
             reportFatalError("InvalidCharInContent",
                     new Object[] {Integer.toString(high, 16)});
                     return false;
         }
-        fEntityScanner.scanChar();
+        fEntityScanner.scanChar(null);
 
         // convert surrogates to supplemental character
         int c = XMLChar.supplemental((char)high, (char)low);
@@ -1479,5 +1506,52 @@
         }
     }
 
+    /**
+     * 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
+     */
+    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
+     */
+    void checkEntityLimit(boolean isPEDecl, String entityName, int len) {
+        if (fLimitAnalyzer == null) {
+            fLimitAnalyzer = fEntityManager.fLimitAnalyzer;
+        }
+        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.GENERAL_ENTITY_SIZE_LIMIT, entityName, len);
+            if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
+                        fSecurityManager.debugPrint(fLimitAnalyzer);
+                reportFatalError("MaxEntitySizeLimit", new Object[]{entityName,
+                    fLimitAnalyzer.getValue(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT),
+                    fSecurityManager.getLimit(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT),
+                    fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.GENERAL_ENTITY_SIZE_LIMIT)});
+            }
+        }
+        if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT, fLimitAnalyzer)) {
+            fSecurityManager.debugPrint(fLimitAnalyzer);
+            reportFatalError("TotalEntitySizeLimit",
+                new Object[]{fLimitAnalyzer.getTotalValue(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT)});
+        }
+    }
 } // class XMLScanner
diff --git a/src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java b/src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java
index 437cc30..a7ab027 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java
+++ b/src/com/sun/org/apache/xerces/internal/impl/XMLVersionDetector.java
@@ -1,62 +1,21 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2016, 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-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.
- *
- * 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) 2003, 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;
@@ -192,40 +151,46 @@
         // in the XML declaration.
         fEntityManager.setScannerVersion(Constants.XML_VERSION_1_0);
         XMLEntityScanner scanner = fEntityManager.getEntityScanner();
+        scanner.detectingVersion = true;
         try {
             if (!scanner.skipString("<?xml")) {
                 // definitely not a well-formed 1.1 doc!
+                scanner.detectingVersion = false;
                 return Constants.XML_VERSION_1_0;
             }
             if (!scanner.skipDeclSpaces()) {
                 fixupCurrentEntity(fEntityManager, fExpectedVersionString, 5);
+                scanner.detectingVersion = false;
                 return Constants.XML_VERSION_1_0;
             }
             if (!scanner.skipString("version")) {
                 fixupCurrentEntity(fEntityManager, fExpectedVersionString, 6);
+                scanner.detectingVersion = false;
                 return Constants.XML_VERSION_1_0;
             }
             scanner.skipDeclSpaces();
             // Check if the next character is '='. If it is then consume it.
             if (scanner.peekChar() != '=') {
                 fixupCurrentEntity(fEntityManager, fExpectedVersionString, 13);
+                scanner.detectingVersion = false;
                 return Constants.XML_VERSION_1_0;
             }
-            scanner.scanChar();
+            scanner.scanChar(null);
             scanner.skipDeclSpaces();
-            int quoteChar = scanner.scanChar();
+            int quoteChar = scanner.scanChar(null);
             fExpectedVersionString[14] = (char) quoteChar;
             for (int versionPos = 0; versionPos < XML11_VERSION.length; versionPos++) {
-                fExpectedVersionString[15 + versionPos] = (char) scanner.scanChar();
+                fExpectedVersionString[15 + versionPos] = (char) scanner.scanChar(null);
             }
             // REVISIT:  should we check whether this equals quoteChar?
-            fExpectedVersionString[18] = (char) scanner.scanChar();
+            fExpectedVersionString[18] = (char) scanner.scanChar(null);
             fixupCurrentEntity(fEntityManager, fExpectedVersionString, 19);
             int matched = 0;
             for (; matched < XML11_VERSION.length; matched++) {
                 if (fExpectedVersionString[15 + matched] != XML11_VERSION[matched])
                     break;
             }
+            scanner.detectingVersion = false;
             if (matched == XML11_VERSION.length)
                 return Constants.XML_VERSION_1_1;
             return Constants.XML_VERSION_1_0;
@@ -237,10 +202,9 @@
                 "PrematureEOF",
                 null,
                 XMLErrorReporter.SEVERITY_FATAL_ERROR);
+            scanner.detectingVersion = false;
             return Constants.XML_VERSION_1_0;
-
         }
-
     }
 
     // This method prepends "length" chars from the char array,
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/DatatypeMessages_zh_TW.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/DatatypeMessages_zh_TW.properties
index 675be50..2cb7ffe 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/DatatypeMessages_zh_TW.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/DatatypeMessages_zh_TW.properties
@@ -9,9 +9,9 @@
 FieldCannotBeNull=\u7121\u6CD5\u4F7F\u7528 ''null'' \u53C3\u6578\u547C\u53EB {0}
 UnknownField=\u4F7F\u7528\u4E0D\u660E\u7684\u6B04\u4F4D\u547C\u53EB {0}:{1}
 #There are two similar keys 'InvalidXMLGreogorianCalendarValue' . Suffix (year, month) has been added and are used as per the context.
-InvalidXGCValue-milli=\u5E74 = {0}\u3001\u6708 = {1}\uFF0C\u65E5 = {2}\uFF0C\u5C0F\u6642 = {3}\uFF0C\u5206\u9418\uFF0C = {4}\uFF0C\u79D2 = {5}\uFF0C\u5C0F\u6578\u79D2 = {6}\uFF0C\u6642\u5340\uFF0C = {7}\uFF0C\u4E0D\u662F XML \u516C\u66C6\u503C\u7684\u6709\u6548\u8868\u793A\u6CD5\u3002
+InvalidXGCValue-milli=\u5E74 = {0}\u3001\u6708 = {1}\u3001\u65E5 = {2}\u3001\u5C0F\u6642 = {3}\u3001\u5206\u9418 = {4}\u3001\u79D2 = {5}\u3001\u5C0F\u6578\u79D2 = {6}\u3001\u6642\u5340 = {7}\uFF0C\u4E0D\u662F XML \u516C\u66C6\u503C\u7684\u6709\u6548\u8868\u793A\u6CD5\u3002
 #There are two similar keys 'InvalidXMLGreogorianCalendarValue' . Suffix (year, month) has been added and are used as per the context.
-InvalidXGCValue-fractional=\u5E74 = {0}\u3001\u6708 = {1}\uFF0C\u65E5 = {2}\uFF0C\u5C0F\u6642 = {3}\uFF0C\u5206\u9418\uFF0C = {4}\uFF0C\u79D2 = {5}\uFF0C\u5C0F\u6578\u79D2 = {6}\uFF0C\u6642\u5340\uFF0C = {7}\uFF0C\u4E0D\u662F XML \u516C\u66C6\u503C\u7684\u6709\u6548\u8868\u793A\u6CD5\u3002
+InvalidXGCValue-fractional=\u5E74 = {0}\u3001\u6708 = {1}\u3001\u65E5 = {2}\u3001\u5C0F\u6642 = {3}\u3001\u5206\u9418 = {4}\u3001\u79D2 = {5}\u3001\u5C0F\u6578\u79D2 = {6}\u3001\u6642\u5340 = {7}\uFF0C\u4E0D\u662F XML \u516C\u66C6\u503C\u7684\u6709\u6548\u8868\u793A\u6CD5\u3002
 
 InvalidXGCFields=XMLGregorianCalendar \u8A2D\u5B9A\u4E86\u7121\u6548\u7684\u6B04\u4F4D\u96C6
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
index 46caccb..01531f7 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
@@ -298,7 +298,8 @@
         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 of entities is \"{1}\" that exceeded the \"{2}\" limit set by \"{3}\".
+        TotalEntitySizeLimit=JAXP00010004: The accumulated size of entities is \"{0}\" that exceeded the \"{1}\" limit set by \"{2}\".
         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}\".
+        EntityReplacementLimit=JAXP00010007: The total number of nodes in entity references is \"{0}\" that is over the limit \"{1}\" set by \"{2}\".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties
index 9575319..0848270 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties
@@ -145,7 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Leerstelle nach "<!DOCTYPE" in der Dokumenttypdeklaration erforderlich.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Root-Elementtyp muss nach "<!DOCTYPE" in der Dokumenttypdeklaration enthalten sein.
         DoctypedeclUnterminated = Dokumenttypdeklaration f\u00FCr Root-Elementtyp "{0}" muss mit ">" enden.
-        DoctypedeclNotClosed = Dokumenttypdeklaration f\u00FCr Root-Elementtyp "{0}" muss mit "]" abgeschlossen werden.
+        DoctypedeclNotClosed = Dokumenttypdeklaration f\u00FCr Root-Elementtyp "{0}" muss mit '']'' enden.
         PEReferenceWithinMarkup = Parameterentityreferenz "%{0};" darf nicht in Markup in der internen Teilmenge der DTD vorkommen.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Die Markup-Deklarationen, die in der Dokumenttypdeklaration enthalten sind bzw. auf die von der Dokumenttypdeklaration verwiesen wird, m\u00FCssen ordnungsgem\u00E4\u00DF formatiert sein.
 # 2.10 White Space Handling
@@ -298,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: Der Parser hat mehr als {0} Entityerweiterungen in diesem Dokument gefunden. Dies ist der von JDK vorgeschriebene Grenzwert.
         ElementAttributeLimit=JAXP00010002: Element "{0}" hat mehr als {1} Attribute. "{1}" ist der von JDK vorgeschriebene Grenzwert.
         MaxEntitySizeLimit=JAXP00010003: Die L\u00E4nge von Entity "{0}" ist "{1}" und \u00FCberschreitet den Grenzwert "{2}", der von "{3}" festgelegt wurde.
-        TotalEntitySizeLimit=JAXP00010004: Die akkumulierte Gr\u00F6\u00DFe von Entitys ist "{1}" und \u00FCberschreitet den Grenzwert "{2}", der von "{3}" festgelegt wurde.
+        TotalEntitySizeLimit=JAXP00010004: Die akkumulierte Gr\u00F6\u00DFe von Entitys ist "{0}" und \u00FCberschreitet den Grenzwert "{1}", der von "{2}" festgelegt wurde.
         MaxXMLNameLimit=JAXP00010005: Die L\u00E4nge von Entity "{0}" ist "{1}" und \u00FCberschreitet den Grenzwert "{2}", der von "{3}" festgelegt wurde.
         MaxElementDepthLimit=JAXP00010006: Die Tiefe von Element "{0}" ist "{1}" und \u00FCberschreitet den Grenzwert "{2}", der von "{3}" festgelegt wurde.
+        EntityReplacementLimit=JAXP00010007: Die Gesamtanzahl von Knoten in Entityreferenzen betr\u00E4gt "{0}". Das liegt \u00FCber dem von "{2}" festgelegten Grenzwert "{1}".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties
index 80b1d61..108eeeb 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties
@@ -145,7 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Es necesario un espacio en blanco despu\u00E9s de "<!DOCTYPE" en la declaraci\u00F3n de tipo de documento.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = El tipo de elemento ra\u00EDz debe aparecer despu\u00E9s de "<!DOCTYPE" en la declaraci\u00F3n de tipo de documento.
         DoctypedeclUnterminated = La declaraci\u00F3n de tipo de documento para el tipo de elemento ra\u00EDz "{0}" debe finalizar en ''>''.
-        DoctypedeclNotClosed = La declaraci\u00F3n de tipo de documento para el tipo de elemento ra\u00EDz "{0}" debe cerrar en '']''.
+        DoctypedeclNotClosed = La declaraci\u00F3n de tipo de documento para el tipo de elemento ra\u00EDz "{0}" debe finalizar en '']''.
         PEReferenceWithinMarkup = La referencia de entidad del par\u00E1metro "%{0};" no puede producirse en el marcador en el subconjunto interno del DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Las declaraciones de marcador que se incluyen o a las que apunta la declaraci\u00F3n de tipo de documento deben tener el formato correcto.
 # 2.10 White Space Handling
@@ -298,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: el analizador ha encontrado m\u00E1s de "{0}"ampliaciones de entidad en este documento; \u00E9ste es el l\u00EDmite impuesto por el JDK.
         ElementAttributeLimit=JAXP00010002: el elemento "{0}" tiene m\u00E1s de "{1}" atributos, "{1}" es el l\u00EDmite impuesto por el JDK.
         MaxEntitySizeLimit=JAXP00010003: la longitud de la entidad "{0}" es "{1}", que excede el l\u00EDmite de "{2}" que ha definido "{3}".
-        TotalEntitySizeLimit=JAXP00010004: el tama\u00F1o acumulado de las entidades es "{1}" y excede el l\u00EDmite de "{2}" definido por "{3}".
+        TotalEntitySizeLimit=JAXP00010004: el tama\u00F1o acumulado de las entidades es "{0}" y excede el l\u00EDmite de "{1}" definido por "{2}".
         MaxXMLNameLimit=JAXP00010005: la longitud de la entidad "{0}" es "{1}" y excede el l\u00EDmite de "{2}" definido por "{3}".
         MaxElementDepthLimit=JAXP00010006: El elemento "{0}" tiene una profundidad de "{1}" que excede el l\u00EDmite "{2}" definido por "{3}".
+        EntityReplacementLimit=JAXP00010007: El n\u00FAmero total de nodos en las referencias de entidad es de "{0}" que supera el l\u00EDmite de "{1}" definido por "{2}".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties
index f536437..c9c31bb 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties
@@ -145,7 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Un espace est obligatoire apr\u00E8s "<!DOCTYPE" dans la d\u00E9claration de type de document.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Le type d'\u00E9l\u00E9ment racine doit figurer apr\u00E8s "<!DOCTYPE" dans la d\u00E9claration de type de document.
         DoctypedeclUnterminated = La d\u00E9claration de type de document pour le type d''\u00E9l\u00E9ment racine "{0}" doit se terminer par ''>''.
-        DoctypedeclNotClosed = La d\u00E9claration de type de document pour le type d''\u00E9l\u00E9ment racine "{0}" doit se conclure par '']''.
+        DoctypedeclNotClosed = La d\u00E9claration de type de document pour le type d''\u00E9l\u00E9ment racine "{0}" doit se terminer par '']''.
         PEReferenceWithinMarkup = La r\u00E9f\u00E9rence d''entit\u00E9 de param\u00E8tre "%{0};" ne peut pas survenir dans le balisage du sous-ensemble interne de la DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Les d\u00E9clarations de balisage contenues dans la d\u00E9claration de type de document ou sur lesquelles pointe cette derni\u00E8re doivent avoir un format correct.
 # 2.10 White Space Handling
@@ -298,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001 : L''analyseur a rencontr\u00E9 plus de "{0}" d\u00E9veloppements d''entit\u00E9 dans ce document. Il s''agit de la limite impos\u00E9e par le JDK.
         ElementAttributeLimit=JAXP00010002 : L''\u00E9l\u00E9ment "{0}" a plus de "{1}" attributs. "{1}" est la limite impos\u00E9e par le JDK.
         MaxEntitySizeLimit=JAXP00010003 : La longueur de l''entit\u00E9 "{0}" est de "{1}". Cette valeur d\u00E9passe la limite de "{2}" d\u00E9finie par "{3}".
-        TotalEntitySizeLimit=JAXP00010004 : La taille cumul\u00E9e des entit\u00E9s est "{1}" et d\u00E9passe la limite de "{2}" d\u00E9finie par "{3}".
+        TotalEntitySizeLimit=JAXP00010004 : La taille cumul\u00E9e des entit\u00E9s est "{0}" et d\u00E9passe la limite de "{1}" d\u00E9finie par "{2}".
         MaxXMLNameLimit=JAXP00010005 : La longueur de l''entit\u00E9 "{0}" est de "{1}". Cette valeur d\u00E9passe la limite de "{2}" d\u00E9finie par "{3}".
         MaxElementDepthLimit=JAXP00010006 : l''\u00E9l\u00E9ment "{0}" a une profondeur de "{1}" qui d\u00E9passe la limite de "{2}" d\u00E9finie par "{3}".
+        EntityReplacementLimit=JAXP00010007 : Le nombre total de noeuds dans les r\u00E9f\u00E9rences d''entit\u00E9 est "{0}", soit plus que la limite de "{1}" d\u00E9finie par "{2}".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties
index 7a68939..1cca604 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties
@@ -145,7 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u00C8 richiesto uno spazio dopo "<!DOCTYPE" nella dichiarazione del tipo di documento.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Il tipo di elemento radice deve comparire dopo "<!DOCTYPE" nella dichiarazione del tipo di documento.
         DoctypedeclUnterminated = La dichiarazione del tipo di documento per il tipo di elemento radice "{0}" deve terminare con ''>''.
-        DoctypedeclNotClosed = La dichiarazione del tipo di documento per il tipo di elemento radice "{0}" deve chiudere con '']''.
+        DoctypedeclNotClosed = La dichiarazione del tipo di documento per il tipo di elemento radice "{0}" deve terminare con '']''.
         PEReferenceWithinMarkup = Il riferimento di entit\u00E0 di parametro "%{0};" non pu\u00F2 essere presente nel markup del set secondario interno del DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Le dichiarazioni di markup contenute o indicate dalla dichiarazione del tipo di documento devono avere un formato corretto.
 # 2.10 White Space Handling
@@ -298,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: il parser ha rilevato pi\u00F9 "{0}" espansioni di entit\u00E0 nel documento. Questo \u00E8 il limite imposto dal kit JDK.
         ElementAttributeLimit=JAXP00010002: l''elemento "{0}" contiene pi\u00F9 di "{1}" attributi. "{1}" \u00E8 il limite imposto dal kit JDK.
         MaxEntitySizeLimit=JAXP00010003: la lunghezza dell''entit\u00E0 "{0}" \u00E8 "{1}". Tale valore supera il limite "{2}" definito da "{3}".
-        TotalEntitySizeLimit=JAXP00010004: le dimensioni accumulate delle entit\u00E0 sono pari a "{1}". Tale valore supera il limite "{2}" definito da "{3}".
+        TotalEntitySizeLimit=JAXP00010004: le dimensioni accumulate delle entit\u00E0 sono pari a "{0}". Tale valore supera il limite "{1}" definito da "{2}".
         MaxXMLNameLimit=JAXP00010005: la lunghezza dell''entit\u00E0 "{0}" \u00E8 "{1}". Tale valore supera il limite "{2}" definito da "{3}".
         MaxElementDepthLimit=JAXP00010006: la profondit\u00E0 dell''elemento "{0}" \u00E8 "{1}". Tale valore supera il limite "{2}" definito da "{3}".
+        EntityReplacementLimit=JAXP00010007: il numero totale di nodi nei riferimenti entit\u00E0 \u00E8 "{0}". Tale valore supera il limite di "{1}" impostato da "{2}".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties
index aece337..74e0594 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties
@@ -145,6 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u3067\u306F\u3001"<!DOCTYPE"\u306E\u5F8C\u306B\u7A7A\u767D\u304C\u5FC5\u8981\u3067\u3059\u3002
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u3067\u306F\u3001"<!DOCTYPE"\u306E\u5F8C\u306B\u30EB\u30FC\u30C8\u8981\u7D20\u30BF\u30A4\u30D7\u304C\u5FC5\u8981\u3067\u3059\u3002
         DoctypedeclUnterminated = \u30EB\u30FC\u30C8\u8981\u7D20\u30BF\u30A4\u30D7"{0}"\u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u306F''>''\u3067\u7D42\u4E86\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002
+        DoctypedeclNotClosed = \u30EB\u30FC\u30C8\u8981\u7D20\u30BF\u30A4\u30D7"{0}"\u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u306F'']''\u3067\u9589\u3058\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002
         PEReferenceWithinMarkup = \u30D1\u30E9\u30E1\u30FC\u30BF\u30FB\u30A8\u30F3\u30C6\u30A3\u30C6\u30A3\u53C2\u7167"%{0};"\u306F\u3001DTD\u306E\u5185\u90E8\u30B5\u30D6\u30BB\u30C3\u30C8\u306E\u30DE\u30FC\u30AF\u30A2\u30C3\u30D7\u5185\u306B\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u306B\u542B\u307E\u308C\u308B\u304B\u3001\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u304C\u6307\u3057\u3066\u3044\u308B\u30DE\u30FC\u30AF\u30A2\u30C3\u30D7\u5BA3\u8A00\u306F\u6574\u5F62\u5F0F\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002
 # 2.10 White Space Handling
@@ -297,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: \u30D1\u30FC\u30B5\u30FC\u306B\u3088\u3063\u3066\u3001\u3053\u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u5185\u3067"{0}"\u3092\u8D85\u3048\u308B\u30A8\u30F3\u30C6\u30A3\u30C6\u30A3\u62E1\u5F35\u304C\u691C\u51FA\u3055\u308C\u307E\u3057\u305F\u3002\u3053\u308C\u306F\u3001JDK\u306B\u3088\u308B\u5236\u9650\u3067\u3059\u3002
         ElementAttributeLimit=JAXP00010002: \u8981\u7D20"{0}"\u306B"{1}"\u3092\u8D85\u3048\u308B\u5C5E\u6027\u304C\u5B58\u5728\u3057\u307E\u3059\u3002"{1}"\u306F\u3001JDK\u306B\u3088\u308B\u5236\u9650\u3067\u3059\u3002
         MaxEntitySizeLimit=JAXP00010003: \u30A8\u30F3\u30C6\u30A3\u30C6\u30A3"{0}"\u306E\u9577\u3055\u306F"{1}"\u3067\u3001"{3}"\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650"{2}"\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002
-        TotalEntitySizeLimit=JAXP00010004: \u30A8\u30F3\u30C6\u30A3\u30C6\u30A3\u306E\u7D2F\u7A4D\u30B5\u30A4\u30BA"{1}"\u306F\u3001"{3}"\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650"{2}"\u3092\u8D85\u3048\u307E\u3057\u305F\u3002
+        TotalEntitySizeLimit=JAXP00010004: \u30A8\u30F3\u30C6\u30A3\u30C6\u30A3\u306E\u7D2F\u7A4D\u30B5\u30A4\u30BA"{0}"\u306F\u3001"{2}"\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650"{1}"\u3092\u8D85\u3048\u307E\u3057\u305F\u3002
         MaxXMLNameLimit=JAXP00010005: \u30A8\u30F3\u30C6\u30A3\u30C6\u30A3"{0}"\u306E\u9577\u3055\u306F"{1}"\u3067\u3001"{3}"\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650"{2}"\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002
         MaxElementDepthLimit=JAXP00010006: \u8981\u7D20"{0}"\u306E\u6DF1\u3055\u306F"{1}"\u3067\u3001"{3}"\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650"{2}"\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002
+        EntityReplacementLimit=JAXP00010007: \u30A8\u30F3\u30C6\u30A3\u30C6\u30A3\u53C2\u7167\u306E\u5408\u8A08\u30CE\u30FC\u30C9\u6570\u306F"{0}"\u3067\u3001"{2}"\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650"{1}"\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties
index f992166..e90be33 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties
@@ -145,6 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC5D0\uC11C\uB294 "<!DOCTYPE" \uB2E4\uC74C\uC5D0 \uACF5\uBC31\uC774 \uD544\uC694\uD569\uB2C8\uB2E4.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC5D0\uC11C\uB294 "<!DOCTYPE" \uB2E4\uC74C\uC5D0 \uB8E8\uD2B8 \uC694\uC18C \uC720\uD615\uC774 \uB098\uD0C0\uB098\uC57C \uD569\uB2C8\uB2E4.
         DoctypedeclUnterminated = \uB8E8\uD2B8 \uC694\uC18C \uC720\uD615 "{0}"\uC5D0 \uB300\uD55C \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC740 ''>''\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4.
+        DoctypedeclNotClosed = \uB8E8\uD2B8 \uC694\uC18C \uC720\uD615 "{0}"\uC5D0 \uB300\uD55C \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC740 '']''\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4.
         PEReferenceWithinMarkup = \uB9E4\uAC1C\uBCC0\uC218 \uC5D4\uD2F0\uD2F0 \uCC38\uC870 "%{0};"\uC740 DTD\uC758 \uB0B4\uBD80 \uBD80\uBD84 \uC9D1\uD569\uC5D0 \uC788\uB294 \uB9C8\uD06C\uC5C5 \uC548\uC5D0 \uD45C\uC2DC\uB420 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC744 \uD3EC\uD568\uD558\uAC70\uB098 \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC774 \uAC00\uB9AC\uD0A4\uB294 \uB9C8\uD06C\uC5C5 \uC120\uC5B8\uC740 \uC62C\uBC14\uB978 \uD615\uC2DD\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4.
 # 2.10 White Space Handling
@@ -297,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: \uAD6C\uBB38 \uBD84\uC11D\uAE30\uAC00 \uC774 \uBB38\uC11C\uC5D0\uC11C "{0}"\uAC1C\uB97C \uCD08\uACFC\uD558\uB294 \uC5D4\uD2F0\uD2F0 \uD655\uC7A5\uC744 \uBC1C\uACAC\uD588\uC2B5\uB2C8\uB2E4. \uC774\uB294 JDK\uC5D0\uC11C \uC801\uC6A9\uD558\uB294 \uC81C\uD55C\uC785\uB2C8\uB2E4.
         ElementAttributeLimit=JAXP00010002:  "{0}" \uC694\uC18C\uC5D0 "{1}"\uAC1C\uB97C \uCD08\uACFC\uD558\uB294 \uC18D\uC131\uC774 \uC788\uC2B5\uB2C8\uB2E4. "{1}"\uC740(\uB294) JDK\uC5D0\uC11C \uC801\uC6A9\uD558\uB294 \uC81C\uD55C\uC785\uB2C8\uB2E4.
         MaxEntitySizeLimit=JAXP00010003: "{0}" \uC5D4\uD2F0\uD2F0\uC758 \uAE38\uC774\uAC00 "{3}"\uC5D0\uC11C \uC124\uC815\uB41C "{2}" \uC81C\uD55C\uC744 \uCD08\uACFC\uD558\uB294 "{1}"\uC785\uB2C8\uB2E4.
-        TotalEntitySizeLimit=JAXP00010004: \uC5D4\uD2F0\uD2F0\uC758 \uB204\uC801 \uD06C\uAE30\uAC00 "{3}"\uC5D0\uC11C \uC124\uC815\uD55C "{2}" \uC81C\uD55C\uC744 \uCD08\uACFC\uD558\uB294 "{1}"\uC785\uB2C8\uB2E4.
+        TotalEntitySizeLimit=JAXP00010004: \uC5D4\uD2F0\uD2F0\uC758 \uB204\uC801 \uD06C\uAE30\uAC00 "{2}"\uC5D0\uC11C \uC124\uC815\uD55C "{1}" \uC81C\uD55C\uC744 \uCD08\uACFC\uD558\uB294 "{0}"\uC785\uB2C8\uB2E4.
         MaxXMLNameLimit=JAXP00010005: "{0}" \uC5D4\uD2F0\uD2F0\uC758 \uAE38\uC774\uAC00 "{3}"\uC5D0\uC11C \uC124\uC815\uD55C "{2}" \uC81C\uD55C\uC744 \uCD08\uACFC\uD558\uB294 "{1}"\uC785\uB2C8\uB2E4.
         MaxElementDepthLimit=JAXP00010006: "{0}" \uC694\uC18C\uC758 \uAE4A\uC774\uAC00 "{3}"\uC5D0\uC11C \uC124\uC815\uB41C "{2}" \uC81C\uD55C\uC744 \uCD08\uACFC\uD558\uB294 "{1}"\uC785\uB2C8\uB2E4.
+        EntityReplacementLimit=JAXP00010007: \uC5D4\uD2F0\uD2F0 \uCC38\uC870\uC758 \uCD1D \uB178\uB4DC \uC218\uAC00 "{2}"\uC5D0\uC11C \uC124\uC815\uD55C "{1}" \uC81C\uD55C\uC744 \uCD08\uACFC\uD558\uB294 "{0}"\uC785\uB2C8\uB2E4.
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties
index 473ca3e..93ae48e 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties
@@ -145,6 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = O espa\u00E7o em branco \u00E9 necess\u00E1rio ap\u00F3s "<!DOCTYPE" na declara\u00E7\u00E3o do tipo de documento.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = O tipo de elemento-raiz deve aparecer ap\u00F3s "<!DOCTYPE" na declara\u00E7\u00E3o do tipo de documento.
         DoctypedeclUnterminated = A declara\u00E7\u00E3o do tipo de documento do tipo de elemento "{0}" deve terminar com ''>''.
+        DoctypedeclNotClosed = A declara\u00E7\u00E3o do tipo de documento do tipo de elemento "{0}" deve terminar com '']''.
         PEReferenceWithinMarkup = A refer\u00EAncia da entidade do par\u00E2metro "%{0};" n\u00E3o pode ocorrer na marca\u00E7\u00E3o no subconjunto interno do DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = As declara\u00E7\u00F5es de marca\u00E7\u00E3o contidas ou apontadas pela declara\u00E7\u00E3o do tipo de documento devem estar corretas.
 # 2.10 White Space Handling
@@ -297,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: O parser detectou mais de "{0}" expans\u00F5es da entidade neste documento. Este \u00E9 o limite imposto pelo JDK.
         ElementAttributeLimit=JAXP00010002: o elemento "{0}" tem mais de "{1}" atributos. "{1}" \u00E9 o limite imposto pelo JDK.
         MaxEntitySizeLimit=JAXP00010003: o tamanho da entidade "{0}" \u00E9 "{1}", o que excede o limite de "{2}" definido por "{3}".
-        TotalEntitySizeLimit=JAXP00010004: o tamanho acumulado de entidades \u00E9 "{1}", o que excedeu o limite de "{2}" definido por "{3}".
+        TotalEntitySizeLimit=JAXP00010004: o tamanho acumulado de entidades \u00E9 "{0}", o que excedeu o limite de "{1}" definido por "{2}".
         MaxXMLNameLimit=JAXP00010005: o tamanho da entidade "{0}" \u00E9 "{1}", o que excede o limite de "{2}" definido por "{3}".
         MaxElementDepthLimit=JAXP00010006: o elemento "{0}" tem uma profundidade de "{1}" que excede o limite de "{2}" definido por "{3}".
+        EntityReplacementLimit=JAXP00010007: O n\u00FAmero total de n\u00F3s nas refer\u00EAncias da entidade \u00E9 de "{0}", o que est\u00E1 acima do limite de "{1}" definido por "{2}".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties
index 48fd780..4f54e5f 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties
@@ -145,6 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Tomt utrymme kr\u00E4vs efter "<!DOCTYPE" i dokumenttypdeklarationen.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Rotelementtyp m\u00E5ste anges efter "<!DOCTYPE" i dokumenttypdeklarationen.
         DoctypedeclUnterminated = Dokumenttypdeklarationen f\u00F6r rotelementtyp "{0}" m\u00E5ste avslutas med ''>''.
+        DoctypedeclNotClosed = Dokumenttypsdeklarationen f\u00F6r rotelementtypen "{0}" m\u00E5ste st\u00E4ngas med '']''.
         PEReferenceWithinMarkup = Parameterreferensen "%{0};" f\u00E5r inte f\u00F6rekomma i kodtexten i den interna delm\u00E4ngden i DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Kodtextdeklarationerna som finns med eller pekas till fr\u00E5n dokumenttypdeklarationen m\u00E5ste vara v\u00E4lformulerade.
 # 2.10 White Space Handling
@@ -297,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: Parsern har p\u00E5tr\u00E4ffat fler \u00E4n "{0}" enhetstill\u00E4gg i dokumentet - gr\u00E4nsv\u00E4rdet f\u00F6r JDK har uppn\u00E5tts.
         ElementAttributeLimit=JAXP00010002:  Elementet "{0}" har fler \u00E4n "{1}" attribut, "{1}" \u00E4r gr\u00E4nsv\u00E4rdet f\u00F6r JDK.
         MaxEntitySizeLimit=JAXP00010003: L\u00E4ngden p\u00E5 enheten "{0}" \u00E4r "{1}" som \u00F6verskriver gr\u00E4nsv\u00E4rdet p\u00E5 "{2}" som anges av "{3}".
-        TotalEntitySizeLimit=JAXP00010004: Den ackumulerade storleken f\u00F6r enheter \u00E4r "{1}", vilket \u00F6verskrider gr\u00E4nsv\u00E4rdet "{2}" som anges av "{3}".
+        TotalEntitySizeLimit=JAXP00010004: Den ackumulerade storleken f\u00F6r enheter \u00E4r "{0}", vilket \u00F6verskrider gr\u00E4nsv\u00E4rdet "{1}" som anges av "{2}".
         MaxXMLNameLimit=JAXP00010005: L\u00E4ngden p\u00E5 enheten "{0}" \u00E4r "{1}", vilket \u00F6verskrider gr\u00E4nsv\u00E4rdet "{2}" som anges av "{3}".
         MaxElementDepthLimit=JAXP00010006: Elementet "{0}" har djupet "{1}" vilket \u00E4r st\u00F6rre \u00E4n gr\u00E4nsen "{2}" som anges av "{3}".
+        EntityReplacementLimit=JAXP00010007: Det totala antalet noder i enhetsreferenser \u00E4r "{0}", vilket \u00E4r \u00F6ver gr\u00E4nsen "{1}" som har angetts av "{2}".
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties
index 904174d..dc2e1d0 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties
@@ -145,6 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u5728\u6587\u6863\u7C7B\u578B\u58F0\u660E\u4E2D\u7684 "<!DOCTYPE" \u540E\u9762\u9700\u8981\u6709\u7A7A\u683C\u3002
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \u5728\u6587\u6863\u7C7B\u578B\u58F0\u660E\u4E2D, \u6839\u5143\u7D20\u7C7B\u578B\u5FC5\u987B\u51FA\u73B0\u5728 "<!DOCTYPE" \u540E\u9762\u3002
         DoctypedeclUnterminated = \u6839\u5143\u7D20\u7C7B\u578B "{0}" \u7684\u6587\u6863\u7C7B\u578B\u58F0\u660E\u5FC5\u987B\u4EE5 ''>'' \u7ED3\u5C3E\u3002
+        DoctypedeclNotClosed = \u6839\u5143\u7D20\u7C7B\u578B "{0}" \u7684\u6587\u6863\u7C7B\u578B\u58F0\u660E\u5FC5\u987B\u4EE5 '']'' \u7ED3\u5C3E\u3002
         PEReferenceWithinMarkup = \u53C2\u6570\u5B9E\u4F53\u5F15\u7528 "%{0};" \u4E0D\u80FD\u51FA\u73B0\u5728 DTD \u7684\u5185\u90E8\u5B50\u96C6\u4E2D\u7684\u6807\u8BB0\u5185\u3002
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \u6587\u6863\u7C7B\u578B\u58F0\u660E\u5305\u542B\u6216\u6307\u5411\u7684\u6807\u8BB0\u58F0\u660E\u5FC5\u987B\u683C\u5F0F\u6B63\u786E\u3002
 # 2.10 White Space Handling
@@ -297,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: \u89E3\u6790\u5668\u5728\u6B64\u6587\u6863\u4E2D\u9047\u5230\u591A\u4E2A "{0}" \u5B9E\u4F53\u6269\u5C55; \u8FD9\u662F JDK \u65BD\u52A0\u7684\u9650\u5236\u3002
         ElementAttributeLimit=JAXP00010002: \u5143\u7D20 "{0}" \u5177\u6709\u591A\u4E2A "{1}" \u5C5E\u6027, "{1}" \u662F JDK \u65BD\u52A0\u7684\u9650\u5236\u3002
         MaxEntitySizeLimit=JAXP00010003: \u5B9E\u4F53 "{0}" \u7684\u957F\u5EA6\u4E3A "{1}", \u8D85\u8FC7\u4E86 "{3}" \u8BBE\u7F6E\u7684 "{2}" \u9650\u5236\u3002
-        TotalEntitySizeLimit=JAXP00010004: \u5B9E\u4F53\u7684\u7D2F\u8BA1\u5927\u5C0F\u4E3A "{1}", \u8D85\u8FC7\u4E86 "{3}" \u8BBE\u7F6E\u7684 "{2}" \u9650\u5236\u3002
+        TotalEntitySizeLimit=JAXP00010004: \u5B9E\u4F53\u7684\u7D2F\u8BA1\u5927\u5C0F\u4E3A "{0}", \u8D85\u8FC7\u4E86 "{2}" \u8BBE\u7F6E\u7684 "{1}" \u9650\u5236\u3002
         MaxXMLNameLimit=JAXP00010005: \u5B9E\u4F53 "{0}" \u7684\u957F\u5EA6\u4E3A "{1}", \u8D85\u8FC7\u4E86 "{3}" \u8BBE\u7F6E\u7684 "{2}" \u9650\u5236\u3002
         MaxElementDepthLimit=JAXP00010006: \u5143\u7D20 "{0}" \u7684\u6DF1\u5EA6 "{1}" \u8D85\u8FC7\u4E86 "{3}" \u8BBE\u7F6E\u7684\u9650\u5236 "{2}"\u3002
+        EntityReplacementLimit=JAXP00010007: \u5B9E\u4F53\u5F15\u7528\u4E2D\u7684\u8282\u70B9\u603B\u6570\u4E3A "{0}", \u8D85\u8FC7\u4E86 "{2}" \u8BBE\u7F6E\u7684\u9650\u5236 "{1}"\u3002
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties
index 11efb30..80e01f2 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties
@@ -145,6 +145,7 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u5728\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u4E2D "<!DOCTYPE" \u4E4B\u5F8C\u9700\u8981\u7A7A\u683C\u3002
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \u5728\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u4E2D\uFF0C\u6839\u5143\u7D20\u985E\u578B\u5FC5\u9808\u51FA\u73FE\u5728 "<!DOCTYPE" \u4E4B\u5F8C\u3002
         DoctypedeclUnterminated = \u6839\u5143\u7D20\u985E\u578B "{0}" \u7684\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u7D50\u5C3E\u5FC5\u9808\u70BA ''>''\u3002
+        DoctypedeclNotClosed = \u6839\u5143\u7D20\u985E\u578B "{0}" \u7684\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u7D50\u5C3E\u5FC5\u9808\u70BA '']''\u3002
         PEReferenceWithinMarkup = DTD \u5167\u90E8\u5B57\u96C6\u7684\u6A19\u8A18\u5167\u4E0D\u80FD\u51FA\u73FE\u53C3\u6578\u5BE6\u9AD4\u53C3\u7167 "%{0};"\u3002
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \u6587\u4EF6\u985E\u578B\u5BA3\u544A\u5305\u542B\u6216\u6307\u5411\u7684\u6A19\u8A18\u5BA3\u544A\u5FC5\u9808\u683C\u5F0F\u6B63\u78BA\u3002
 # 2.10 White Space Handling
@@ -198,7 +199,7 @@
         MSG_SPACE_REQUIRED_BEFORE_NDATA_IN_UNPARSED_ENTITYDECL = \u5728\u5BE6\u9AD4 "{0}" \u7684\u5BA3\u544A\u4E2D\uFF0C"NDATA" \u4E4B\u524D\u9700\u8981\u7A7A\u683C\u3002
         MSG_NOTATION_NAME_REQUIRED_FOR_UNPARSED_ENTITYDECL = \u5728\u5BE6\u9AD4 "{0}" \u7684\u5BA3\u544A\u4E2D\uFF0C"NDATA" \u4E4B\u5F8C\u9700\u8981\u8868\u793A\u6CD5\u540D\u7A31\u3002
         EntityDeclUnterminated = \u5BE6\u9AD4 "{0}" \u7684\u5BA3\u544A\u7D50\u5C3E\u5FC5\u9808\u70BA ''>''\u3002
-	MSG_DUPLICATE_ENTITY_DEFINITION = \u5BE6\u9AD4 "{0}" \u5BA3\u544A\u8D85\u904E\u4E00\u6B21\u4EE5\u4E0A\u3002        
+	MSG_DUPLICATE_ENTITY_DEFINITION = \u5BE6\u9AD4 "{0}" \u5BA3\u544A\u8D85\u904E\u4E00\u6B21\u4EE5\u4E0A\u3002
 # 4.2.2 External Entities
         ExternalIDRequired = \u5916\u90E8\u5BE6\u9AD4\u5BA3\u544A\u7684\u958B\u982D\u5FC5\u9808\u70BA "SYSTEM" \u6216 "PUBLIC"\u3002
         MSG_SPACE_REQUIRED_BEFORE_PUBIDLITERAL_IN_EXTERNALID = "PUBLIC" \u8207\u516C\u7528 ID \u4E4B\u9593\u9700\u8981\u7A7A\u683C\u3002
@@ -254,7 +255,7 @@
         RootElementTypeMustMatchDoctypedecl = \u6587\u4EF6\u6839\u5143\u7D20 "{1}" \u5FC5\u9808\u914D\u5C0D DOCTYPE \u6839 "{0}"\u3002
         UndeclaredElementInContentSpec = \u5143\u7D20 "{0}" \u7684\u5167\u5BB9\u6A21\u578B\u53C3\u7167\u672A\u5BA3\u544A\u7684\u5143\u7D20 "{1}"\u3002
         UniqueNotationName = \u8868\u793A\u6CD5 "{0}" \u7684\u5BA3\u544A\u4E26\u975E\u552F\u4E00\u3002\u6307\u5B9A\u7684 Name \u4E0D\u80FD\u5728\u4E00\u500B\u4EE5\u4E0A\u7684\u8868\u793A\u6CD5\u5BA3\u544A\u4E2D\u5BA3\u544A\u3002
-        ENTITYFailedInitializeGrammar =  ENTITYDatatype \u9A57\u8B49\u7A0B\u5F0F: \u5931\u6557\u3002\u9700\u8981\u4F7F\u7528\u6709\u6548\u7684\u6587\u6CD5\u53C3\u7167\u4F86\u547C\u53EB\u8D77\u59CB\u65B9\u6CD5\u3002 \t
+        ENTITYFailedInitializeGrammar =  ENTITYDatatype \u9A57\u8B49\u7A0B\u5F0F: \u5931\u6557\u3002\u9700\u8981\u4F7F\u7528\u6709\u6548\u7684\u6587\u6CD5\u53C3\u7167\u4F86\u547C\u53EB\u8D77\u59CB\u65B9\u6CD5\u3002\t
         ENTITYNotUnparsed = ENTITY "{0}" \u4E26\u975E\u672A\u7D93\u5256\u6790\u3002
         ENTITYNotValid = ENTITY "{0}" \u7121\u6548\u3002
         EmptyList = \u985E\u578B ENTITIES\u3001IDREFS \u8207 NMTOKENS \u7684\u503C\u4E0D\u53EF\u70BA\u7A7A\u767D\u6E05\u55AE\u3002
@@ -277,7 +278,7 @@
         
 # Namespaces support
 # 4. Using Qualified Names
-        IllegalQName = \u5143\u7D20\u6216\u5C6C\u6027\u4E0D\u7B26\u5408 QName \u7522\u751F: QName::=(NCName':')?NCName\u3002 
+        IllegalQName = \u5143\u7D20\u6216\u5C6C\u6027\u4E0D\u7B26\u5408 QName \u7522\u751F: QName::=(NCName':')?NCName\u3002
         ElementXMLNSPrefix = \u5143\u7D20 "{0}" \u4E0D\u80FD\u4F7F\u7528 "xmlns" \u4F5C\u70BA\u524D\u7F6E\u78BC\u3002
         ElementPrefixUnbound = \u5143\u7D20 "{1}" \u7684\u524D\u7F6E\u78BC "{0}" \u672A\u9023\u7D50\u3002
         AttributePrefixUnbound = \u95DC\u806F\u5143\u7D20\u985E\u578B "{0}" \u4E4B\u5C6C\u6027 "{1}" \u7684\u524D\u7F6E\u78BC "{2}" \u672A\u9023\u7D50\u3002
@@ -297,7 +298,8 @@
         EntityExpansionLimit=JAXP00010001: \u5256\u6790\u5668\u5728\u6B64\u6587\u4EF6\u4E2D\u9047\u5230 "{0}" \u500B\u4EE5\u4E0A\u7684\u5BE6\u9AD4\u64F4\u5145; \u9019\u662F JDK \u6240\u898F\u5B9A\u7684\u9650\u5236\u3002
         ElementAttributeLimit=JAXP00010002: \u5143\u7D20 "{0}" \u5177\u6709\u8D85\u904E "{1}" \u500B\u4EE5\u4E0A\u7684\u5C6C\u6027\uFF0C"{1}" \u662F JDK \u6240\u898F\u5B9A\u7684\u9650\u5236\u3002
         MaxEntitySizeLimit=JAXP00010003: \u5BE6\u9AD4 "{0}" \u7684\u9577\u5EA6\u70BA "{1}"\uFF0C\u8D85\u904E "{3}" \u6240\u8A2D\u5B9A\u7684 "{2}" \u9650\u5236\u3002
-        TotalEntitySizeLimit=JAXP00010004: \u5BE6\u9AD4\u7684\u7D2F\u7A4D\u5927\u5C0F\u70BA "{1}"\uFF0C\u8D85\u904E "{3}" \u6240\u8A2D\u5B9A\u7684 "{2}" \u9650\u5236\u3002
+        TotalEntitySizeLimit=JAXP00010004: \u5BE6\u9AD4\u7684\u7D2F\u7A4D\u5927\u5C0F\u70BA "{0}"\uFF0C\u8D85\u904E "{2}" \u6240\u8A2D\u5B9A\u7684 "{1}" \u9650\u5236\u3002
         MaxXMLNameLimit=JAXP00010005: \u5BE6\u9AD4 "{0}" \u7684\u9577\u5EA6\u70BA "{1}"\uFF0C\u8D85\u904E "{3}" \u6240\u8A2D\u5B9A\u7684 "{2}" \u9650\u5236\u3002
-        MaxElementDepthLimit=JAXP00010006: \u5143\u7D20 "{0}" \u7684\u6DF1\u5EA6\u70BA "{1}"\uFF0C\u8D85\u904E "{3}" \u8A2D\u5B9A\u7684 "{2}" \u9650\u5236\u3002
+        MaxElementDepthLimit=JAXP00010006: \u5143\u7D20 "{0}" \u7684\u6DF1\u5EA6\u70BA "{1}"\uFF0C\u8D85\u904E "{3}" \u6240\u8A2D\u5B9A\u7684 "{2}" \u9650\u5236\u3002
+        EntityReplacementLimit=JAXP00010007: \u5BE6\u9AD4\u53C3\u7167\u4E2D\u7684\u7BC0\u9EDE\u7E3D\u6578\u70BA "{0}"\uFF0C\u8D85\u904E "{2}" \u6240\u8A2D\u5B9A\u7684 "{1}" \u9650\u5236\u3002
 
diff --git a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages_zh_TW.properties b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages_zh_TW.properties
index 06d8a05..9f170b1 100644
--- a/src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages_zh_TW.properties
+++ b/src/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages_zh_TW.properties
@@ -188,7 +188,7 @@
         e-props-correct.5 = e-props-correct.5: '{'value constraint'}' \u4E0D\u53EF\u51FA\u73FE\u5728\u5143\u7D20 ''{0}'' \u4E0A\uFF0C\u56E0\u70BA\u5143\u7D20\u7684 '{'type definition'}' \u6216 '{'type definition'}' \u7684 '{'content type'}' \u70BA ID\uFF0C\u6216\u884D\u751F\u81EA ID\u3002
         e-props-correct.6 = e-props-correct.6: \u5075\u6E2C\u5230 ''{0}'' \u7684\u5FAA\u74B0\u66FF\u4EE3\u7FA4\u7D44\u3002
         fractionDigits-valid-restriction = fractionDigits-valid-restriction: \u5728 {2} \u7684\u5B9A\u7FA9\u4E2D\uFF0Cfacet ''fractionDigits'' \u7684\u503C ''{0}'' \u7121\u6548\uFF0C\u56E0\u70BA\u5B83\u5FC5\u9808\u5C0F\u65BC\u6216\u7B49\u65BC ''fractionDigits'' \u7684\u503C\uFF0C\u6B64\u503C\u4EE5\u5176\u4E2D\u4E00\u500B\u7956\u7CFB\u985E\u578B\u8A2D\u70BA ''{1}''\u3002
-        fractionDigits-totalDigits = fractionDigits-totalDigits: \u5728 {2} \u7684\u5B9A\u7FA9\u4E2D\uFF0C facet ''fractionDigits'' \u7684\u503C ''{0}'' \u7121\u6548\uFF0C\u56E0\u70BA\u503C\u5FC5\u9808\u5C0F\u65BC\u6216\u7B49\u65BC ''totalDigits'' \u7684\u503C\uFF0C\u4EA6\u5373 ''{1}''\u3002
+        fractionDigits-totalDigits = fractionDigits-totalDigits: \u5728 {2} \u7684\u5B9A\u7FA9\u4E2D\uFF0Cfacet ''fractionDigits'' \u7684\u503C ''{0}'' \u7121\u6548\uFF0C\u56E0\u70BA\u503C\u5FC5\u9808\u5C0F\u65BC\u6216\u7B49\u65BC ''totalDigits'' \u7684\u503C\uFF0C\u4EA6\u5373 ''{1}''\u3002
         length-minLength-maxLength.1.1 = length-minLength-maxLength.1.1: \u91DD\u5C0D\u985E\u578B {0}\uFF0Clength ''{1}'' \u7684\u503C\u5C0F\u65BC minLength ''{2}'' \u7684\u503C\u662F\u4E00\u9805\u932F\u8AA4\u3002
         length-minLength-maxLength.1.2.a = length-minLength-maxLength.1.2.a: \u91DD\u5C0D\u985E\u578B {0}\uFF0C\u82E5\u76EE\u524D\u9650\u5236\u5177\u6709 minLength facet \u4E14\u76EE\u524D\u7684\u9650\u5236\u6216\u57FA\u790E\u5177\u6709 length facet\uFF0C\u5247\u57FA\u790E\u6C92\u6709 minLength facet \u662F\u4E00\u9805\u932F\u8AA4\u3002
         length-minLength-maxLength.1.2.b = length-minLength-maxLength.1.2.b: \u91DD\u5C0D\u985E\u578B {0}\uFF0C\u76EE\u524D\u7684 minLength ''{1}'' \u4E0D\u7B49\u65BC\u57FA\u790E minLength ''{2}'' \u662F\u4E00\u9805\u932F\u8AA4\u3002
diff --git a/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java b/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
index dac7fbf..84543ec 100644
--- a/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
+++ b/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2671,6 +2671,9 @@
             customTimezoneId.append(sign);
             customTimezoneId.append(hour);
             if (minutes != 0) {
+                if (minutes < 10) {
+                    customTimezoneId.append('0');
+                }
                 customTimezoneId.append(minutes);
             }
             result = TimeZone.getTimeZone(customTimezoneId.toString());
diff --git a/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java b/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java
index b2460d9..8dfe6c7 100644
--- a/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java
+++ b/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java
@@ -1,7 +1,7 @@
 /*
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  *
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  *
  * The contents of this file are subject to the terms of either the GNU
  * General Public License Version 2 only ("GPL") or the Common Development
@@ -129,13 +129,15 @@
         if (index == Limit.ENTITY_EXPANSION_LIMIT.ordinal() ||
                 index == Limit.MAX_OCCUR_NODE_LIMIT.ordinal() ||
                 index == Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal() ||
-                index == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal()
+                index == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal() ||
+                index == Limit.ENTITY_REPLACEMENT_LIMIT.ordinal()
                 ) {
             totalValue[index] += value;
             return;
         }
         if (index == Limit.MAX_ELEMENT_DEPTH_LIMIT.ordinal() ||
                 index == Limit.MAX_NAME_LIMIT.ordinal()) {
+            values[index] = value;
             totalValue[index] = value;
             return;
         }
@@ -175,10 +177,13 @@
      * @return the value of the property
      */
     public int getValue(Limit limit) {
-        return values[limit.ordinal()];
+        return getValue(limit.ordinal());
     }
 
     public int getValue(int index) {
+        if (index == Limit.ENTITY_REPLACEMENT_LIMIT.ordinal()) {
+            return totalValue[index];
+        }
         return values[index];
     }
     /**
@@ -233,6 +238,11 @@
     public void reset(Limit limit) {
         if (limit.ordinal() == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal()) {
             totalValue[limit.ordinal()] = 0;
+        } else if (limit.ordinal() == Limit.GENERAL_ENTITY_SIZE_LIMIT.ordinal()) {
+            names[limit.ordinal()] = null;
+            values[limit.ordinal()] = 0;
+            caches[limit.ordinal()] = null;
+            totalValue[limit.ordinal()] = 0;
         }
     }
 
diff --git a/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java b/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java
index 0673db9..6f44177 100644
--- a/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java
+++ b/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -78,7 +78,9 @@
         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);
+                Constants.JDK_XML_NAME_LIMIT, Constants.SP_XML_NAME_LIMIT, 1000, 1000),
+        ENTITY_REPLACEMENT_LIMIT("EntityReplacementLimit",
+                Constants.JDK_ENTITY_REPLACEMENT_LIMIT, Constants.SP_ENTITY_REPLACEMENT_LIMIT, 0, 3000000);
 
         final String key;
         final String apiProperty;
@@ -450,6 +452,7 @@
         if (index == Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal() ||
                 index == Limit.ENTITY_EXPANSION_LIMIT.ordinal() ||
                 index == Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal() ||
+                index == Limit.ENTITY_REPLACEMENT_LIMIT.ordinal() ||
                 index == Limit.MAX_ELEMENT_DEPTH_LIMIT.ordinal() ||
                 index == Limit.MAX_NAME_LIMIT.ordinal()
                 ) {
diff --git a/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java b/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
index d17cf33..8f14d74 100644
--- a/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
+++ b/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
@@ -33,6 +33,7 @@
 import java.util.StringTokenizer;
 import java.util.Vector;
 
+import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMLocatorImpl;
@@ -117,7 +118,6 @@
     private DOMErrorHandler fErrorHandler = null;
     private final DOMErrorImpl fError = new DOMErrorImpl();
     private final DOMLocatorImpl fLocator = new DOMLocatorImpl();
-    private static final RuntimeException abort = new RuntimeException();
 
     /**
      * Constructs a new LSSerializer.
@@ -539,11 +539,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return null;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort){
-                // stopped at user request
-                return null;
-            }
             throw (LSException) new LSException(LSException.SERIALIZE_ERR, e.toString()).initCause(e);
         } catch (IOException ioe) {
             // REVISIT: A generic IOException doesn't provide enough information
@@ -836,11 +834,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return false;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort){
-                // stopped at user request
-                return false;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
@@ -992,11 +988,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return false;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort){
-                // stopped at user request
-                return false;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
diff --git a/src/com/sun/org/apache/xpath/internal/res/XPATHErrorResources_de.java b/src/com/sun/org/apache/xpath/internal/res/XPATHErrorResources_de.java
index 1ddecd6..e7624ef 100644
--- a/src/com/sun/org/apache/xpath/internal/res/XPATHErrorResources_de.java
+++ b/src/com/sun/org/apache/xpath/internal/res/XPATHErrorResources_de.java
@@ -483,7 +483,7 @@
      "Fehler aufgetreten."},
 
   { ER_ILLEGAL_VARIABLE_REFERENCE,
-      "VariableReference au\u00DFerhalb des Kontextes oder ohne Definition f\u00FCr Variable angegeben. Name = {0}"},
+      "VariableReference au\u00DFerhalb des Kontexts oder ohne Definition f\u00FCr Variable angegeben. Name = {0}"},
 
   { ER_AXES_NOT_ALLOWED,
       "Nur \"child::\"- und \"attribute::\"-Achsen sind in Vergleichsmustern zul\u00E4ssig. Betreffende Achsen = {0}"},
@@ -855,7 +855,7 @@
       "Option \"-E\" nicht unterst\u00FCtzt f\u00FCr DTM-Parser"},
 
   { WG_ILLEGAL_VARIABLE_REFERENCE,
-      "VariableReference au\u00DFerhalb des Kontextes oder ohne Definition f\u00FCr Variable angegeben. Name = {0}"},
+      "VariableReference au\u00DFerhalb des Kontexts oder ohne Definition f\u00FCr Variable angegeben. Name = {0}"},
 
   { WG_UNSUPPORTED_ENCODING,
      "Nicht unterst\u00FCtzte Codierung: {0}"},