Merge
diff --git a/make/conf/version-numbers.conf b/make/conf/version-numbers.conf
index 9ed2976..d25eb17 100644
--- a/make/conf/version-numbers.conf
+++ b/make/conf/version-numbers.conf
@@ -28,12 +28,12 @@
 
 DEFAULT_VERSION_FEATURE=17
 DEFAULT_VERSION_INTERIM=0
-DEFAULT_VERSION_UPDATE=1
+DEFAULT_VERSION_UPDATE=2
 DEFAULT_VERSION_PATCH=0
 DEFAULT_VERSION_EXTRA1=0
 DEFAULT_VERSION_EXTRA2=0
 DEFAULT_VERSION_EXTRA3=0
-DEFAULT_VERSION_DATE=2021-10-19
+DEFAULT_VERSION_DATE=2022-01-18
 DEFAULT_VERSION_CLASSFILE_MAJOR=61  # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`"
 DEFAULT_VERSION_CLASSFILE_MINOR=0
 DEFAULT_VERSION_DOCS_API_SINCE=11
diff --git a/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp b/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp
index ba18ce3..b99f16f 100644
--- a/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp
+++ b/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp
@@ -192,8 +192,32 @@
   LIR_Address* addr;
   if (index_opr->is_constant()) {
     int elem_size = type2aelembytes(type);
-    addr = new LIR_Address(array_opr,
-                           offset_in_bytes + (intx)(index_opr->as_jint()) * elem_size, type);
+#ifdef _LP64
+    jint index = index_opr->as_jint();
+    jlong disp = offset_in_bytes + (jlong)(index) * elem_size;
+    if (disp > max_jint) {
+      // Displacement overflow. Cannot directly use instruction with 32-bit displacement for 64-bit addresses.
+      // Convert array index to long to do array offset computation with 64-bit values.
+      index_opr = new_register(T_LONG);
+      __ move(LIR_OprFact::longConst(index), index_opr);
+      addr = new LIR_Address(array_opr, index_opr, LIR_Address::scale(type), offset_in_bytes, type);
+    } else {
+      addr = new LIR_Address(array_opr, (intx)disp, type);
+    }
+#else
+    // A displacement overflow can also occur for x86 but that is not a problem due to the 32-bit address range!
+    // Let's assume an array 'a' and an access with displacement 'disp'. When disp overflows, then "a + disp" will
+    // always be negative (i.e. underflows the 32-bit address range):
+    // Let N = 2^32: a + signed_overflow(disp) = a + disp - N.
+    // "a + disp" is always smaller than N. If an index was chosen which would point to an address beyond N, then
+    // range checks would catch that and throw an exception. Thus, a + disp < 0 holds which means that it always
+    // underflows the 32-bit address range:
+    // unsigned_underflow(a + signed_overflow(disp)) = unsigned_underflow(a + disp - N)
+    //                                              = (a + disp - N) + N = a + disp
+    // This shows that we still end up at the correct address with a displacement overflow due to the 32-bit address
+    // range limitation. This overflow only needs to be handled if addresses can be larger as on 64-bit platforms.
+    addr = new LIR_Address(array_opr, offset_in_bytes + (intx)(index_opr->as_jint()) * elem_size, type);
+#endif // _LP64
   } else {
 #ifdef _LP64
     if (index_opr->type() == T_INT) {
diff --git a/src/hotspot/share/c1/c1_GraphBuilder.cpp b/src/hotspot/share/c1/c1_GraphBuilder.cpp
index a7a4778..1c93452 100644
--- a/src/hotspot/share/c1/c1_GraphBuilder.cpp
+++ b/src/hotspot/share/c1/c1_GraphBuilder.cpp
@@ -1989,19 +1989,19 @@
         cha_monomorphic_target = target->find_monomorphic_target(calling_klass, declared_interface, singleton);
         if (cha_monomorphic_target != NULL) {
           if (cha_monomorphic_target->holder() != compilation()->env()->Object_klass()) {
-            // If CHA is able to bind this invoke then update the class
-            // to match that class, otherwise klass will refer to the
-            // interface.
-            klass = cha_monomorphic_target->holder();
+            ciInstanceKlass* holder = cha_monomorphic_target->holder();
+            ciInstanceKlass* constraint = (holder->is_subtype_of(singleton) ? holder : singleton); // avoid upcasts
             actual_recv = declared_interface;
 
             // insert a check it's really the expected class.
-            CheckCast* c = new CheckCast(klass, receiver, copy_state_for_exception());
+            CheckCast* c = new CheckCast(constraint, receiver, copy_state_for_exception());
             c->set_incompatible_class_change_check();
-            c->set_direct_compare(klass->is_final());
+            c->set_direct_compare(constraint->is_final());
             // pass the result of the checkcast so that the compiler has
             // more accurate type info in the inlinee
             better_receiver = append_split(c);
+
+            dependency_recorder()->assert_unique_implementor(declared_interface, singleton);
           } else {
             cha_monomorphic_target = NULL; // subtype check against Object is useless
           }
diff --git a/src/hotspot/share/classfile/classFileParser.cpp b/src/hotspot/share/classfile/classFileParser.cpp
index 0999d7d..052d013 100644
--- a/src/hotspot/share/classfile/classFileParser.cpp
+++ b/src/hotspot/share/classfile/classFileParser.cpp
@@ -3044,6 +3044,7 @@
 static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {
   int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
   int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
+
   while (fast != -1 && fast != 0) {
     if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {
       return true;  // found a circularity
@@ -3073,14 +3074,15 @@
     for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;
          y += InstanceKlass::inner_class_next_offset) {
 
-      // To maintain compatibility, throw an exception if duplicate inner classes
-      // entries are found.
-      guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
-                          _inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
-                          _inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
-                          _inner_classes->at(idx+3) != _inner_classes->at(y+3)),
-                         "Duplicate entry in InnerClasses attribute in class file %s",
-                         CHECK_(true));
+      // 4347400: make sure there's no duplicate entry in the classes array
+      if (_major_version >= JAVA_1_5_VERSION) {
+        guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
+                            _inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
+                            _inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
+                            _inner_classes->at(idx+3) != _inner_classes->at(y+3)),
+                           "Duplicate entry in InnerClasses attribute in class file %s",
+                           CHECK_(true));
+      }
       // Return true if there are two entries with the same inner_class_info_index.
       if (_inner_classes->at(y) == _inner_classes->at(idx)) {
         return true;
@@ -3173,10 +3175,9 @@
     inner_classes->at_put(index++, inner_access_flags.as_short());
   }
 
-  // 4347400: make sure there's no duplicate entry in the classes array
-  // Also, check for circular entries.
+  // Check for circular and duplicate entries.
   bool has_circularity = false;
-  if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
+  if (_need_verify) {
     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
     if (has_circularity) {
       // If circularity check failed then ignore InnerClasses attribute.
diff --git a/src/hotspot/share/classfile/classLoader.cpp b/src/hotspot/share/classfile/classLoader.cpp
index 724ecfc..0287b73 100644
--- a/src/hotspot/share/classfile/classLoader.cpp
+++ b/src/hotspot/share/classfile/classLoader.cpp
@@ -303,13 +303,19 @@
   }
 
   // read contents into resource array
-  int size = (*filesize) + ((nul_terminate) ? 1 : 0);
+  size_t size = (uint32_t)(*filesize);
+  if (nul_terminate) {
+    if (sizeof(size) == sizeof(uint32_t) && size == UINT_MAX) {
+      return NULL; // 32-bit integer overflow will occur.
+    }
+    size++;
+  }
   buffer = NEW_RESOURCE_ARRAY(u1, size);
   if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;
 
   // return result
   if (nul_terminate) {
-    buffer[*filesize] = 0;
+    buffer[size - 1] = 0;
   }
   return buffer;
 }
diff --git a/src/hotspot/share/code/dependencies.cpp b/src/hotspot/share/code/dependencies.cpp
index 87e01ce..306280d 100644
--- a/src/hotspot/share/code/dependencies.cpp
+++ b/src/hotspot/share/code/dependencies.cpp
@@ -116,6 +116,12 @@
   }
 }
 
+void Dependencies::assert_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk) {
+  check_ctxk(ctxk);
+  check_unique_implementor(ctxk, uniqk);
+  assert_common_2(unique_implementor, ctxk, uniqk);
+}
+
 void Dependencies::assert_has_no_finalizable_subclasses(ciKlass* ctxk) {
   check_ctxk(ctxk);
   assert_common_1(no_finalizable_subclasses, ctxk);
@@ -173,6 +179,13 @@
   assert_common_2(abstract_with_unique_concrete_subtype, ctxk_dv, conck_dv);
 }
 
+void Dependencies::assert_unique_implementor(InstanceKlass* ctxk, InstanceKlass* uniqk) {
+  check_ctxk(ctxk);
+  assert(ctxk->is_interface(), "not an interface");
+  assert(ctxk->implementor() == uniqk, "not a unique implementor");
+  assert_common_2(unique_implementor, DepValue(_oop_recorder, ctxk), DepValue(_oop_recorder, uniqk));
+}
+
 void Dependencies::assert_unique_concrete_method(Klass* ctxk, Method* uniqm) {
   check_ctxk(ctxk);
   check_unique_method(ctxk, uniqm);
@@ -573,6 +586,7 @@
   "abstract_with_unique_concrete_subtype",
   "unique_concrete_method_2",
   "unique_concrete_method_4",
+  "unique_implementor",
   "no_finalizable_subclasses",
   "call_site_target_value"
 };
@@ -584,6 +598,7 @@
   2, // abstract_with_unique_concrete_subtype ctxk, k
   2, // unique_concrete_method_2 ctxk, m
   4, // unique_concrete_method_4 ctxk, m, resolved_klass, resolved_method
+  2, // unique_implementor ctxk, implementor
   1, // no_finalizable_subclasses ctxk
   2  // call_site_target_value call_site, method_handle
 };
@@ -1806,6 +1821,16 @@
   return NULL;
 }
 
+Klass* Dependencies::check_unique_implementor(InstanceKlass* ctxk, Klass* uniqk, NewKlassDepChange* changes) {
+  assert(ctxk->is_interface(), "sanity");
+  assert(ctxk->nof_implementors() > 0, "no implementors");
+  if (ctxk->nof_implementors() == 1) {
+    assert(ctxk->implementor() == uniqk, "sanity");
+    return NULL;
+  }
+  return ctxk; // no unique implementor
+}
+
 // Search for AME.
 // There are two version of checks.
 //   1) Spot checking version(Classload time). Newly added class is checked for AME.
@@ -2055,6 +2080,9 @@
   case unique_concrete_method_4:
     witness = check_unique_concrete_method(context_type(), method_argument(1), type_argument(2), method_argument(3), changes);
     break;
+  case unique_implementor:
+    witness = check_unique_implementor(context_type(), type_argument(1), changes);
+    break;
   case no_finalizable_subclasses:
     witness = check_has_no_finalizable_subclasses(context_type(), changes);
     break;
diff --git a/src/hotspot/share/code/dependencies.hpp b/src/hotspot/share/code/dependencies.hpp
index 104fc9e..0d8fa9f 100644
--- a/src/hotspot/share/code/dependencies.hpp
+++ b/src/hotspot/share/code/dependencies.hpp
@@ -143,6 +143,9 @@
     // of the analysis.
     unique_concrete_method_4, // one unique concrete method under CX
 
+    // This dependency asserts that interface CX has a unique implementor class.
+    unique_implementor, // one unique implementor under CX
+
     // This dependency asserts that no instances of class or it's
     // subclasses require finalization registration.
     no_finalizable_subclasses,
@@ -329,7 +332,10 @@
     assert(!is_concrete_klass(ctxk->as_instance_klass()), "must be abstract");
   }
   static void check_unique_method(ciKlass* ctxk, ciMethod* m) {
-    assert(!m->can_be_statically_bound(ctxk->as_instance_klass()), "redundant");
+    assert(!m->can_be_statically_bound(ctxk->as_instance_klass()) || ctxk->is_interface(), "redundant");
+  }
+  static void check_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk) {
+    assert(ctxk->implementor() == uniqk, "not a unique implementor");
   }
 
   void assert_common_1(DepType dept, ciBaseObject* x);
@@ -343,9 +349,9 @@
   void assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck);
   void assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm);
   void assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm, ciKlass* resolved_klass, ciMethod* resolved_method);
+  void assert_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk);
   void assert_has_no_finalizable_subclasses(ciKlass* ctxk);
   void assert_call_site_target_value(ciCallSite* call_site, ciMethodHandle* method_handle);
-
 #if INCLUDE_JVMCI
  private:
   static void check_ctxk(Klass* ctxk) {
@@ -366,6 +372,7 @@
   void assert_evol_method(Method* m);
   void assert_has_no_finalizable_subclasses(Klass* ctxk);
   void assert_leaf_type(Klass* ctxk);
+  void assert_unique_implementor(InstanceKlass* ctxk, InstanceKlass* uniqk);
   void assert_unique_concrete_method(Klass* ctxk, Method* uniqm);
   void assert_abstract_with_unique_concrete_subtype(Klass* ctxk, Klass* conck);
   void assert_call_site_target_value(oop callSite, oop methodHandle);
@@ -413,6 +420,7 @@
   static Klass* check_evol_method(Method* m);
   static Klass* check_leaf_type(InstanceKlass* ctxk);
   static Klass* check_abstract_with_unique_concrete_subtype(InstanceKlass* ctxk, Klass* conck, NewKlassDepChange* changes = NULL);
+  static Klass* check_unique_implementor(InstanceKlass* ctxk, Klass* uniqk, NewKlassDepChange* changes = NULL);
   static Klass* check_unique_concrete_method(InstanceKlass* ctxk, Method* uniqm, NewKlassDepChange* changes = NULL);
   static Klass* check_unique_concrete_method(InstanceKlass* ctxk, Method* uniqm, Klass* resolved_klass, Method* resolved_method, KlassDepChange* changes = NULL);
   static Klass* check_has_no_finalizable_subclasses(InstanceKlass* ctxk, NewKlassDepChange* changes = NULL);
diff --git a/src/hotspot/share/oops/instanceKlass.cpp b/src/hotspot/share/oops/instanceKlass.cpp
index 2f06313..fc6a954 100644
--- a/src/hotspot/share/oops/instanceKlass.cpp
+++ b/src/hotspot/share/oops/instanceKlass.cpp
@@ -2375,7 +2375,9 @@
   } else {
     it->push(&_default_vtable_indices);
   }
-  it->push(&_fields);
+
+  // _fields might be written into by Rewriter::scan_method() -> fd.set_has_initialized_final_update()
+  it->push(&_fields, MetaspaceClosure::_writable);
 
   if (itable_length() > 0) {
     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
diff --git a/src/hotspot/share/opto/doCall.cpp b/src/hotspot/share/opto/doCall.cpp
index c9e5a80..a0a042c 100644
--- a/src/hotspot/share/opto/doCall.cpp
+++ b/src/hotspot/share/opto/doCall.cpp
@@ -328,8 +328,10 @@
           CallGenerator* miss_cg = CallGenerator::for_uncommon_trap(callee,
               Deoptimization::Reason_class_check, Deoptimization::Action_none);
 
-          CallGenerator* cg = CallGenerator::for_guarded_call(holder, miss_cg, hit_cg);
+          ciKlass* constraint = (holder->is_subclass_of(singleton) ? holder : singleton); // avoid upcasts
+          CallGenerator* cg = CallGenerator::for_guarded_call(constraint, miss_cg, hit_cg);
           if (hit_cg != NULL && cg != NULL) {
+            dependencies()->assert_unique_implementor(declared_interface, singleton);
             dependencies()->assert_unique_concrete_method(declared_interface, cha_monomorphic_target, declared_interface, callee);
             return cg;
           }
diff --git a/src/java.base/share/classes/com/sun/crypto/provider/KeyProtector.java b/src/java.base/share/classes/com/sun/crypto/provider/KeyProtector.java
index b13a1a9..570aca6 100644
--- a/src/java.base/share/classes/com/sun/crypto/provider/KeyProtector.java
+++ b/src/java.base/share/classes/com/sun/crypto/provider/KeyProtector.java
@@ -177,6 +177,10 @@
                 byte[] encodedParams =
                     encrInfo.getAlgorithm().getEncodedParams();
 
+                if (encodedParams == null) {
+                    throw new IOException("Missing PBE parameters");
+                }
+
                 // parse the PBE parameters into the corresponding spec
                 AlgorithmParameters pbeParams =
                     AlgorithmParameters.getInstance("PBE");
diff --git a/src/java.base/share/classes/com/sun/crypto/provider/OAEPParameters.java b/src/java.base/share/classes/com/sun/crypto/provider/OAEPParameters.java
index 5726137..e4879b5 100644
--- a/src/java.base/share/classes/com/sun/crypto/provider/OAEPParameters.java
+++ b/src/java.base/share/classes/com/sun/crypto/provider/OAEPParameters.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2021, 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
@@ -110,8 +110,12 @@
                 if (!val.getOID().equals(OID_MGF1)) {
                     throw new IOException("Only MGF1 mgf is supported");
                 }
+                byte[] encodedParams = val.getEncodedParams();
+                if (encodedParams == null) {
+                    throw new IOException("Missing MGF1 parameters");
+                }
                 AlgorithmId params = AlgorithmId.parse(
-                    new DerValue(val.getEncodedParams()));
+                    new DerValue(encodedParams));
                 String mgfDigestName = params.getName();
                 if (mgfDigestName.equals("SHA-1")) {
                     mgfSpec = MGF1ParameterSpec.SHA1;
@@ -137,7 +141,12 @@
                 if (!val.getOID().equals(OID_PSpecified)) {
                     throw new IOException("Wrong OID for pSpecified");
                 }
-                DerInputStream dis = new DerInputStream(val.getEncodedParams());
+                byte[] encodedParams = val.getEncodedParams();
+                if (encodedParams == null) {
+                    throw new IOException("Missing pSpecified label");
+                }
+
+                DerInputStream dis = new DerInputStream(encodedParams);
                 p = dis.getOctetString();
                 if (dis.available() != 0) {
                     throw new IOException("Extra data for pSpecified");
diff --git a/src/java.base/share/classes/java/io/ObjectInputStream.java b/src/java.base/share/classes/java/io/ObjectInputStream.java
index edcda18..ca69dde 100644
--- a/src/java.base/share/classes/java/io/ObjectInputStream.java
+++ b/src/java.base/share/classes/java/io/ObjectInputStream.java
@@ -1297,6 +1297,8 @@
      *     <li>each object reference previously deserialized from the stream
      *     (class is {@code null}, arrayLength is -1),
      *     <li>each regular class (class is not {@code null}, arrayLength is -1),
+     *     <li>each interface class explicitly referenced in the stream
+     *         (it is not called for interfaces implemented by classes in the stream),
      *     <li>each interface of a dynamic proxy and the dynamic proxy class itself
      *     (class is not {@code null}, arrayLength is -1),
      *     <li>each array is filtered using the array type and length of the array
@@ -2058,6 +2060,30 @@
             totalObjectRefs++;
             depth++;
             desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));
+
+            if (cl != null) {
+                // Check that serial filtering has been done on the local class descriptor's superclass,
+                // in case it does not appear in the stream.
+
+                // Find the next super descriptor that has a local class descriptor.
+                // Descriptors for which there is no local class are ignored.
+                ObjectStreamClass superLocal = null;
+                for (ObjectStreamClass sDesc = desc.getSuperDesc(); sDesc != null; sDesc = sDesc.getSuperDesc()) {
+                    if ((superLocal = sDesc.getLocalDesc()) != null) {
+                        break;
+                    }
+                }
+
+                // Scan local descriptor superclasses for a match with the local descriptor of the super found above.
+                // For each super descriptor before the match, invoke the serial filter on the class.
+                // The filter is invoked for each class that has not already been filtered
+                // but would be filtered if the instance had been serialized by this Java runtime.
+                for (ObjectStreamClass lDesc = desc.getLocalDesc().getSuperDesc();
+                     lDesc != null && lDesc != superLocal;
+                     lDesc = lDesc.getSuperDesc()) {
+                    filterCheck(lDesc.forClass(), -1);
+                }
+            }
         } finally {
             depth--;
         }
@@ -2516,6 +2542,13 @@
             throw new InternalError();
         }
         clear();
+        // Check that an object follows the TC_EXCEPTION typecode
+        byte tc = bin.peekByte();
+        if (tc != TC_OBJECT &&
+            tc != TC_REFERENCE) {
+            throw new StreamCorruptedException(
+                    String.format("invalid type code: %02X", tc));
+        }
         return (IOException) readObject0(Object.class, false);
     }
 
diff --git a/src/java.base/share/classes/java/lang/StringBuffer.java b/src/java.base/share/classes/java/lang/StringBuffer.java
index a429919..f882f47f3 100644
--- a/src/java.base/share/classes/java/lang/StringBuffer.java
+++ b/src/java.base/share/classes/java/lang/StringBuffer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2021, 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
@@ -26,7 +26,12 @@
 package java.lang;
 
 import java.io.IOException;
-import java.util.Arrays;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamField;
+import java.io.Serial;
+import java.io.Serializable;
+import java.io.StreamCorruptedException;
 import jdk.internal.vm.annotation.IntrinsicCandidate;
 
 /**
@@ -106,7 +111,7 @@
  */
  public final class StringBuffer
     extends AbstractStringBuilder
-    implements java.io.Serializable, Comparable<StringBuffer>, CharSequence
+    implements Serializable, Comparable<StringBuffer>, CharSequence
 {
 
     /**
@@ -116,7 +121,7 @@
     private transient String toStringCache;
 
     /** use serialVersionUID from JDK 1.0.2 for interoperability */
-    @java.io.Serial
+    @Serial
     static final long serialVersionUID = 3388685877147921107L;
 
     /**
@@ -725,25 +730,25 @@
      *              A flag indicating whether the backing array is shared.
      *              The value is ignored upon deserialization.
      */
-    @java.io.Serial
-    private static final java.io.ObjectStreamField[] serialPersistentFields =
+    @Serial
+    private static final ObjectStreamField[] serialPersistentFields =
     {
-        new java.io.ObjectStreamField("value", char[].class),
-        new java.io.ObjectStreamField("count", Integer.TYPE),
-        new java.io.ObjectStreamField("shared", Boolean.TYPE),
+        new ObjectStreamField("value", char[].class),
+        new ObjectStreamField("count", Integer.TYPE),
+        new ObjectStreamField("shared", Boolean.TYPE),
     };
 
     /**
-     * The {@code writeObject} method is called to write the state of the {@code StringBuffer} to
-     * a stream.
+     * The {@code writeObject} method is called to write the state of the
+     * {@code StringBuffer} to a stream.
      *
      * @param  s the {@code ObjectOutputStream} to which data is written
      * @throws IOException if an I/O error occurs
      */
-    @java.io.Serial
-    private synchronized void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
-        java.io.ObjectOutputStream.PutField fields = s.putFields();
+    @Serial
+    private synchronized void writeObject(ObjectOutputStream s)
+            throws IOException {
+        ObjectOutputStream.PutField fields = s.putFields();
         char[] val = new char[capacity()];
         if (isLatin1()) {
             StringLatin1.getChars(value, 0, count, val, 0);
@@ -757,20 +762,26 @@
     }
 
     /**
-     * The {@code readObject} method is called to restore the state of the {@code StringBuffer} from
-     * a stream.
+     * The {@code readObject} method is called to restore the state of the
+     * {@code StringBuffer} from a stream.
      *
      * @param  s the {@code ObjectInputStream} from which data is read
      * @throws IOException if an I/O error occurs
      * @throws ClassNotFoundException if a serialized class cannot be loaded
      */
-    @java.io.Serial
-    private void readObject(java.io.ObjectInputStream s)
-        throws java.io.IOException, ClassNotFoundException {
-        java.io.ObjectInputStream.GetField fields = s.readFields();
+    @Serial
+    private void readObject(ObjectInputStream s)
+        throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField fields = s.readFields();
+
         char[] val = (char[])fields.get("value", null);
+        int c = fields.get("count", 0);
+        if (c < 0 || c > val.length) {
+            throw new StreamCorruptedException("count value invalid");
+        }
         initBytes(val, 0, val.length);
-        count = fields.get("count", 0);
+        count = c;
+        // ignore shared field
     }
 
     synchronized void getBytes(byte dst[], int dstBegin, byte coder) {
diff --git a/src/java.base/share/classes/java/lang/StringBuilder.java b/src/java.base/share/classes/java/lang/StringBuilder.java
index e52da83..8e759c2 100644
--- a/src/java.base/share/classes/java/lang/StringBuilder.java
+++ b/src/java.base/share/classes/java/lang/StringBuilder.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2021, 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
@@ -28,6 +28,10 @@
 import jdk.internal.vm.annotation.IntrinsicCandidate;
 
 import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serial;
+import java.io.StreamCorruptedException;
 
 /**
  * A mutable sequence of characters.  This class provides an API compatible
@@ -90,7 +94,7 @@
 {
 
     /** use serialVersionUID for interoperability */
-    @java.io.Serial
+    @Serial
     static final long serialVersionUID = 4383685877147921099L;
 
     /**
@@ -464,9 +468,8 @@
      * @param  s the {@code ObjectOutputStream} to which data is written
      * @throws IOException if an I/O error occurs
      */
-    @java.io.Serial
-    private void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
+    @Serial
+    private void writeObject(ObjectOutputStream s) throws IOException {
         s.defaultWriteObject();
         s.writeInt(count);
         char[] val = new char[capacity()];
@@ -479,20 +482,23 @@
     }
 
     /**
-     * readObject is called to restore the state of the StringBuffer from
+     * readObject is called to restore the state of the StringBuilder from
      * a stream.
      *
      * @param  s the {@code ObjectInputStream} from which data is read
      * @throws IOException if an I/O error occurs
      * @throws ClassNotFoundException if a serialized class cannot be loaded
      */
-    @java.io.Serial
-    private void readObject(java.io.ObjectInputStream s)
-        throws IOException, ClassNotFoundException {
+    @Serial
+    private void readObject(ObjectInputStream s)
+            throws IOException, ClassNotFoundException {
         s.defaultReadObject();
-        count = s.readInt();
+        int c = s.readInt();
         char[] val = (char[]) s.readObject();
+        if (c < 0 || c > val.length) {
+            throw new StreamCorruptedException("count value invalid");
+        }
         initBytes(val, 0, val.length);
+        count = c;
     }
-
 }
diff --git a/src/java.base/share/classes/java/util/Hashtable.java b/src/java.base/share/classes/java/util/Hashtable.java
index c103df5..2b6f6e7 100644
--- a/src/java.base/share/classes/java/util/Hashtable.java
+++ b/src/java.base/share/classes/java/util/Hashtable.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2021, 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
@@ -1254,7 +1254,7 @@
      * Reconstitute the Hashtable from a stream (i.e., deserialize it).
      */
     @java.io.Serial
-    private void readObject(java.io.ObjectInputStream s)
+    private void readObject(ObjectInputStream s)
             throws IOException, ClassNotFoundException {
         readHashtable(s);
     }
@@ -1263,14 +1263,16 @@
      * Perform deserialization of the Hashtable from an ObjectInputStream.
      * The Properties class overrides this method.
      */
-    void readHashtable(java.io.ObjectInputStream s)
+    void readHashtable(ObjectInputStream s)
             throws IOException, ClassNotFoundException {
-        // Read in the threshold and loadFactor
-        s.defaultReadObject();
 
-        // Validate loadFactor (ignore threshold - it will be re-computed)
-        if (loadFactor <= 0 || Float.isNaN(loadFactor))
-            throw new StreamCorruptedException("Illegal Load: " + loadFactor);
+        ObjectInputStream.GetField fields = s.readFields();
+
+        // Read and validate loadFactor (ignore threshold - it will be re-computed)
+        float lf = fields.get("loadFactor", 0.75f);
+        if (lf <= 0 || Float.isNaN(lf))
+            throw new StreamCorruptedException("Illegal load factor: " + lf);
+        lf = Math.min(Math.max(0.25f, lf), 4.0f);
 
         // Read the original length of the array and number of elements
         int origlength = s.readInt();
@@ -1282,13 +1284,13 @@
 
         // Clamp original length to be more than elements / loadFactor
         // (this is the invariant enforced with auto-growth)
-        origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);
+        origlength = Math.max(origlength, (int)(elements / lf) + 1);
 
         // Compute new length with a bit of room 5% + 3 to grow but
         // no larger than the clamped original length.  Make the length
         // odd if it's large enough, this helps distribute the entries.
         // Guard against the length ending up zero, that's not valid.
-        int length = (int)((elements + elements / 20) / loadFactor) + 3;
+        int length = (int)((elements + elements / 20) / lf) + 3;
         if (length > elements && (length & 1) == 0)
             length--;
         length = Math.min(length, origlength);
@@ -1300,8 +1302,9 @@
         // Check Map.Entry[].class since it's the nearest public type to
         // what we're actually creating.
         SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Map.Entry[].class, length);
+        Hashtable.UnsafeHolder.putLoadFactor(this, lf);
         table = new Entry<?,?>[length];
-        threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
+        threshold = (int)Math.min(length * lf, MAX_ARRAY_SIZE + 1);
         count = 0;
 
         // Read the number of elements and then all the key/value objects
@@ -1315,6 +1318,18 @@
         }
     }
 
+    // Support for resetting final field during deserializing
+    private static final class UnsafeHolder {
+        private UnsafeHolder() { throw new InternalError(); }
+        private static final jdk.internal.misc.Unsafe unsafe
+                = jdk.internal.misc.Unsafe.getUnsafe();
+        private static final long LF_OFFSET
+                = unsafe.objectFieldOffset(Hashtable.class, "loadFactor");
+        static void putLoadFactor(Hashtable<?, ?> table, float lf) {
+            unsafe.putFloat(table, LF_OFFSET, lf);
+        }
+    }
+
     /**
      * The put method used by readObject. This is provided because put
      * is overridable and should not be called in readObject since the
diff --git a/src/java.base/share/classes/java/util/IdentityHashMap.java b/src/java.base/share/classes/java/util/IdentityHashMap.java
index 34d6722..4795c30 100644
--- a/src/java.base/share/classes/java/util/IdentityHashMap.java
+++ b/src/java.base/share/classes/java/util/IdentityHashMap.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2021, 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
@@ -25,6 +25,8 @@
 
 package java.util;
 
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
 import java.lang.reflect.Array;
 import java.util.function.BiConsumer;
 import java.util.function.BiFunction;
@@ -1267,12 +1269,12 @@
      *          particular order.
      */
     @java.io.Serial
-    private void writeObject(java.io.ObjectOutputStream s)
+    private void writeObject(ObjectOutputStream s)
         throws java.io.IOException  {
-        // Write out and any hidden stuff
+        // Write out size (number of mappings) and any hidden stuff
         s.defaultWriteObject();
 
-        // Write out size (number of Mappings)
+        // Write out size again (maintained for backward compatibility)
         s.writeInt(size);
 
         // Write out keys and values (alternating)
@@ -1291,18 +1293,20 @@
      * deserializes it).
      */
     @java.io.Serial
-    private void readObject(java.io.ObjectInputStream s)
+    private void readObject(ObjectInputStream s)
         throws java.io.IOException, ClassNotFoundException  {
-        // Read in any hidden stuff
-        s.defaultReadObject();
+        // Size (number of mappings) is written to the stream twice
+        // Read first size value and ignore it
+        s.readFields();
 
-        // Read in size (number of Mappings)
+        // Read second size value, validate and assign to size field
         int size = s.readInt();
         if (size < 0)
             throw new java.io.StreamCorruptedException
                 ("Illegal mappings count: " + size);
         int cap = capacity(size);
-        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, cap);
+        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, cap*2);
+        this.size = size;
         init(cap);
 
         // Read the keys and values, and put the mappings in the table
diff --git a/src/java.base/share/classes/java/util/jar/Attributes.java b/src/java.base/share/classes/java/util/jar/Attributes.java
index a33d108..3b59f74 100644
--- a/src/java.base/share/classes/java/util/jar/Attributes.java
+++ b/src/java.base/share/classes/java/util/jar/Attributes.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2021, 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
@@ -25,6 +25,7 @@
 
 package java.util.jar;
 
+import java.io.ByteArrayOutputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
 import java.util.Collection;
@@ -366,7 +367,7 @@
 
     int read(Manifest.FastInputStream is, byte[] lbuf, String filename, int lineNumber) throws IOException {
         String name = null, value;
-        byte[] lastline = null;
+        ByteArrayOutputStream fullLine = new ByteArrayOutputStream();
 
         int len;
         while ((len = is.readLine(lbuf)) != -1) {
@@ -392,15 +393,12 @@
                                 + Manifest.getErrorPosition(filename, lineNumber) + ")");
                 }
                 lineContinued = true;
-                byte[] buf = new byte[lastline.length + len - 1];
-                System.arraycopy(lastline, 0, buf, 0, lastline.length);
-                System.arraycopy(lbuf, 1, buf, lastline.length, len - 1);
+                fullLine.write(lbuf, 1, len - 1);
                 if (is.peek() == ' ') {
-                    lastline = buf;
                     continue;
                 }
-                value = new String(buf, 0, buf.length, UTF_8.INSTANCE);
-                lastline = null;
+                value = fullLine.toString(UTF_8.INSTANCE);
+                fullLine.reset();
             } else {
                 while (lbuf[i++] != ':') {
                     if (i >= len) {
@@ -414,8 +412,8 @@
                 }
                 name = new String(lbuf, 0, i - 2, UTF_8.INSTANCE);
                 if (is.peek() == ' ') {
-                    lastline = new byte[len - i];
-                    System.arraycopy(lbuf, i, lastline, 0, len - i);
+                    fullLine.reset();
+                    fullLine.write(lbuf, i, len - i);
                     continue;
                 }
                 value = new String(lbuf, i, len - i, UTF_8.INSTANCE);
diff --git a/src/java.base/share/classes/java/util/regex/Pattern.java b/src/java.base/share/classes/java/util/regex/Pattern.java
index 5032ecf..1e03f56 100644
--- a/src/java.base/share/classes/java/util/regex/Pattern.java
+++ b/src/java.base/share/classes/java/util/regex/Pattern.java
@@ -3428,14 +3428,14 @@
     private static final int countChars(CharSequence seq, int index,
                                         int lengthInCodePoints) {
         // optimization
-        if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
-            assert (index >= 0 && index < seq.length());
+        if (lengthInCodePoints == 1 && index >= 0 && index < seq.length() &&
+            !Character.isHighSurrogate(seq.charAt(index))) {
             return 1;
         }
         int length = seq.length();
         int x = index;
         if (lengthInCodePoints >= 0) {
-            assert (index >= 0 && index < length);
+            assert ((length == 0 && index == 0) || index >= 0 && index < length);
             for (int i = 0; x < length && i < lengthInCodePoints; i++) {
                 if (Character.isHighSurrogate(seq.charAt(x++))) {
                     if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
diff --git a/src/java.base/share/classes/javax/crypto/EncryptedPrivateKeyInfo.java b/src/java.base/share/classes/javax/crypto/EncryptedPrivateKeyInfo.java
index 59b4a07..09c6974 100644
--- a/src/java.base/share/classes/javax/crypto/EncryptedPrivateKeyInfo.java
+++ b/src/java.base/share/classes/javax/crypto/EncryptedPrivateKeyInfo.java
@@ -77,15 +77,18 @@
      * @exception NullPointerException if the <code>encoded</code> is null.
      * @exception IOException if error occurs when parsing the ASN.1 encoding.
      */
-    public EncryptedPrivateKeyInfo(byte[] encoded)
-        throws IOException {
+    public EncryptedPrivateKeyInfo(byte[] encoded) throws IOException {
         if (encoded == null) {
             throw new NullPointerException("the encoded parameter " +
-                                           "must be non-null");
+                "must be non-null");
         }
-        this.encoded = encoded.clone();
-        DerValue val = new DerValue(this.encoded);
 
+        DerValue val = new DerValue(encoded);
+        if (val.tag != DerValue.tag_Sequence) {
+            throw new IOException("DER header error: no SEQ tag");
+        }
+
+        this.encoded = encoded.clone();
         DerValue[] seq = new DerValue[2];
 
         seq[0] = val.data.getDerValue();
diff --git a/src/java.base/share/classes/sun/security/pkcs/ContentInfo.java b/src/java.base/share/classes/sun/security/pkcs/ContentInfo.java
index 125da2c..fbc6a46 100644
--- a/src/java.base/share/classes/sun/security/pkcs/ContentInfo.java
+++ b/src/java.base/share/classes/sun/security/pkcs/ContentInfo.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2021, 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
@@ -127,7 +127,9 @@
 
         if (oldStyle) {
             // JDK1.1.x-style encoding
-            content = typeAndContent[1];
+            if (typeAndContent.length > 1) { // content is OPTIONAL
+                content = typeAndContent[1];
+            }
         } else {
             // This is the correct, standards-compliant encoding.
             // Parse the content (OPTIONAL field).
diff --git a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java
index 1689672..6a7b696 100644
--- a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java
+++ b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java
@@ -380,8 +380,15 @@
                 if (digestAlgName.equals("SHAKE256")
                         || digestAlgName.equals("SHAKE256-LEN")) {
                     if (digestAlgName.equals("SHAKE256-LEN")) {
-                        int v = new DerValue(digestAlgorithmId
-                                .getEncodedParams()).getInteger();
+                        // RFC8419: for EdDSA in CMS, the id-shake256-len
+                        // algorithm id must contain parameter value 512
+                        // encoded as a positive integer value
+                        byte[] params = digestAlgorithmId.getEncodedParams();
+                        if (params == null) {
+                            throw new SignatureException(
+                                    "id-shake256-len oid missing length");
+                        }
+                        int v = new DerValue(params).getInteger();
                         if (v != 512) {
                             throw new SignatureException(
                                     "Unsupported id-shake256-" + v);
@@ -523,6 +530,7 @@
                 if (spec == null) {
                     throw new NoSuchAlgorithmException("Missing PSSParameterSpec for RSASSA-PSS algorithm");
                 }
+
                 if (!AlgorithmId.get(spec.getDigestAlgorithm()).equals(digAlgId)) {
                     throw new NoSuchAlgorithmException("Incompatible digest algorithm");
                 }
diff --git a/src/java.base/share/classes/sun/security/rsa/PSSParameters.java b/src/java.base/share/classes/sun/security/rsa/PSSParameters.java
index fef496e..c2f4039 100644
--- a/src/java.base/share/classes/sun/security/rsa/PSSParameters.java
+++ b/src/java.base/share/classes/sun/security/rsa/PSSParameters.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2021, 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
@@ -102,8 +102,13 @@
                 if (!val.getOID().equals(AlgorithmId.MGF1_oid)) {
                     throw new IOException("Only MGF1 mgf is supported");
                 }
+
+                byte[] encodedParams = val.getEncodedParams();
+                if (encodedParams == null) {
+                    throw new IOException("Missing MGF1 parameters");
+                }
                 AlgorithmId params = AlgorithmId.parse(
-                        new DerValue(val.getEncodedParams()));
+                        new DerValue(encodedParams));
                 String mgfDigestName = params.getName();
                 switch (mgfDigestName) {
                 case "SHA-1":
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java
index df283e8..2e1c2db 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java
@@ -52,6 +52,7 @@
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Iterator;
+import java.util.List;
 import javax.imageio.IIOException;
 import javax.imageio.ImageIO;
 import javax.imageio.ImageReadParam;
@@ -223,6 +224,33 @@
         }
     }
 
+    private void readColorPalette(int sizeOfPalette) throws IOException {
+        final int UNIT_SIZE = 1024000;
+        if (sizeOfPalette < UNIT_SIZE) {
+            palette = new byte[sizeOfPalette];
+            iis.readFully(palette, 0, sizeOfPalette);
+        } else {
+            int bytesToRead = sizeOfPalette;
+            int bytesRead = 0;
+            List<byte[]> bufs = new ArrayList<>();
+            while (bytesToRead != 0) {
+                int sz = Math.min(bytesToRead, UNIT_SIZE);
+                byte[] unit = new byte[sz];
+                iis.readFully(unit, 0, sz);
+                bufs.add(unit);
+                bytesRead += sz;
+                bytesToRead -= sz;
+            }
+            byte[] paletteData = new byte[bytesRead];
+            int copiedBytes = 0;
+            for (byte[] ba : bufs) {
+                System.arraycopy(ba, 0, paletteData, copiedBytes, ba.length);
+                copiedBytes += ba.length;
+            }
+            palette = paletteData;
+        }
+    }
+
     /**
      * Process the image header.
      *
@@ -305,8 +333,7 @@
             // Read in the palette
             int numberOfEntries = (int)((bitmapOffset - 14 - size) / 3);
             int sizeOfPalette = numberOfEntries*3;
-            palette = new byte[sizeOfPalette];
-            iis.readFully(palette, 0, sizeOfPalette);
+            readColorPalette(sizeOfPalette);
             metadata.palette = palette;
             metadata.paletteSize = numberOfEntries;
         } else {
@@ -343,8 +370,7 @@
                     }
                     int numberOfEntries = (int)((bitmapOffset-14-size) / 4);
                     int sizeOfPalette = numberOfEntries * 4;
-                    palette = new byte[sizeOfPalette];
-                    iis.readFully(palette, 0, sizeOfPalette);
+                    readColorPalette(sizeOfPalette);
 
                     metadata.palette = palette;
                     metadata.paletteSize = numberOfEntries;
@@ -404,8 +430,7 @@
                     if (colorsUsed != 0) {
                         // there is a palette
                         sizeOfPalette = (int)colorsUsed*4;
-                        palette = new byte[sizeOfPalette];
-                        iis.readFully(palette, 0, sizeOfPalette);
+                        readColorPalette(sizeOfPalette);
 
                         metadata.palette = palette;
                         metadata.paletteSize = (int)colorsUsed;
@@ -430,8 +455,7 @@
                 // Read in the palette
                 int numberOfEntries = (int)((bitmapOffset-14-size) / 4);
                 int sizeOfPalette = numberOfEntries*4;
-                palette = new byte[sizeOfPalette];
-                iis.readFully(palette, 0, sizeOfPalette);
+                readColorPalette(sizeOfPalette);
                 metadata.palette = palette;
                 metadata.paletteSize = numberOfEntries;
 
@@ -529,8 +553,7 @@
                 // Read in the palette
                 int numberOfEntries = (int)((bitmapOffset-14-size) / 4);
                 int sizeOfPalette = numberOfEntries*4;
-                palette = new byte[sizeOfPalette];
-                iis.readFully(palette, 0, sizeOfPalette);
+                readColorPalette(sizeOfPalette);
                 metadata.palette = palette;
                 metadata.paletteSize = numberOfEntries;
 
@@ -592,7 +615,7 @@
         }
 
         if (metadata.compression == BI_RGB) {
-            long imageDataSize = (width * height * (bitsPerPixel / 8));
+            long imageDataSize = ((long)width * height * (bitsPerPixel / 8));
             if (imageDataSize > (bitmapFileSize - bitmapOffset)) {
                 throw new IIOException(I18N.getString("BMPImageReader9"));
             }
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/ReaderUtil.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/ReaderUtil.java
index 0f8d1d6..906aa3a 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/ReaderUtil.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/ReaderUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -28,6 +28,8 @@
 import java.awt.Point;
 import java.awt.Rectangle;
 import java.io.IOException;
+import java.util.List;
+import java.util.ArrayList;
 import javax.imageio.stream.ImageInputStream;
 
 /**
@@ -213,4 +215,47 @@
         }
         return result;
     }
+
+    /**
+     * An utility method to allocate and initialize a byte array
+     * step by step with pre-defined limit, instead of allocating
+     * a large array up-front based on the length derived from
+     * an image header.
+     *
+     * @param iis a {@code ImageInputStream} to decode data and store
+     * it in byte array.
+     * @param length the size of data to decode
+     *
+     * @return array of size length when decode succeeeds
+     *
+     * @throws IOException if decoding of stream fails
+     */
+    public static byte[] staggeredReadByteStream(ImageInputStream iis,
+        int length) throws IOException {
+        final int UNIT_SIZE = 1024000;
+        byte[] decodedData;
+        if (length < UNIT_SIZE) {
+            decodedData = new byte[length];
+            iis.readFully(decodedData, 0, length);
+        } else {
+            int bytesToRead = length;
+            int bytesRead = 0;
+            List<byte[]> bufs = new ArrayList<>();
+            while (bytesToRead != 0) {
+                int sz = Math.min(bytesToRead, UNIT_SIZE);
+                byte[] unit = new byte[sz];
+                iis.readFully(unit, 0, sz);
+                bufs.add(unit);
+                bytesRead += sz;
+                bytesToRead -= sz;
+            }
+            decodedData = new byte[bytesRead];
+            int copiedBytes = 0;
+            for (byte[] ba : bufs) {
+                System.arraycopy(ba, 0, decodedData, copiedBytes, ba.length);
+                copiedBytes += ba.length;
+            }
+        }
+        return decodedData;
+    }
 }
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java
index 2bedc94..9632e37 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2021, 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
@@ -1007,6 +1007,11 @@
                         }
                     }
 
+                    if (tableIndex >= prefix.length) {
+                        throw new IIOException("Code buffer limit reached,"
+                                + " no End of Image tag present, possibly data is corrupted. ");
+                    }
+
                     int ti = tableIndex;
                     int oc = oldCode;
 
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java
index 11eed2e..9d8cd29 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java
@@ -1156,6 +1156,13 @@
                 throw new IIOException("Unsupported Image Type");
             }
 
+            if ((long)width * height > Integer.MAX_VALUE - 2) {
+                // We are not able to properly decode image that has number
+                // of pixels greater than Integer.MAX_VALUE - 2
+                throw new IIOException("Can not read image of the size "
+                        + width + " by " + height);
+            }
+
             image = getDestination(param, imageTypes, width, height);
             imRas = image.getRaster();
 
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java
index 25bfef7..8576419 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java
@@ -1418,6 +1418,13 @@
         int width = metadata.IHDR_width;
         int height = metadata.IHDR_height;
 
+        if ((long)width * height > Integer.MAX_VALUE - 2) {
+            // We are not able to properly decode image that has number
+            // of pixels greater than Integer.MAX_VALUE - 2
+            throw new IIOException("Can not read image of the size "
+                    + width + " by " + height);
+        }
+
         // Init default values
         sourceXSubsampling = 1;
         sourceYSubsampling = 1;
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFDecompressor.java
index a1b0439..4516ce0 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFDecompressor.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFDecompressor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -1438,7 +1438,11 @@
      *
      * @param byteCount the number of bytes of compressed data.
      */
-    public void setByteCount(int byteCount) {
+    public void setByteCount(int byteCount) throws IOException{
+        if (byteCount < 0) {
+            throw new IIOException("Strip byte count can't be"
+                + " negative: " + byteCount);
+        }
         this.byteCount = byteCount;
     }
 
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java
index 22ebda2..4d64072 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 import javax.imageio.IIOException;
 import javax.imageio.plugins.tiff.BaselineTIFFTagSet;
 import javax.imageio.plugins.tiff.TIFFField;
+import com.sun.imageio.plugins.common.ReaderUtil;
 
 class TIFFFaxDecompressor extends TIFFDecompressor {
 
@@ -637,14 +638,14 @@
         this.bitsPerScanline = scanlineStride*8;
         this.lineBitNum = 8*dstOffset;
 
-        this.data = new byte[byteCount];
         this.bitPointer = 0;
         this.bytePointer = 0;
         this.prevChangingElems = new int[w + 1];
         this.currChangingElems = new int[w + 1];
 
         stream.seek(offset);
-        stream.readFully(data);
+        this.data = ReaderUtil.
+            staggeredReadByteStream(stream, byteCount);
 
         if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE) {
             decodeRLE();
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java
index 49f899c..5c0334a 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -319,7 +319,7 @@
                         while (bytesToRead != 0) {
                             int sz = Math.min(bytesToRead, UNIT_SIZE);
                             byte[] unit = new byte[sz];
-                            stream.readFully(unit, bytesRead, sz);
+                            stream.readFully(unit, 0, sz);
                             bufs.add(unit);
                             bytesRead += sz;
                             bytesToRead -= sz;
@@ -455,7 +455,7 @@
                     while (shortsToRead != 0) {
                         int sz = Math.min(shortsToRead, SSHORT_TILE_SIZE);
                         short[] unit = new short[sz];
-                        stream.readFully(unit, shortsRead, sz);
+                        stream.readFully(unit, 0, sz);
                         bufs.add(unit);
                         shortsRead += sz;
                         shortsToRead -= sz;
@@ -486,7 +486,7 @@
                     while (intsToRead != 0) {
                         int sz = Math.min(intsToRead, INT_TILE_SIZE);
                         int[] unit = new int[sz];
-                        stream.readFully(unit, intsToRead, sz);
+                        stream.readFully(unit, 0, sz);
                         bufs.add(unit);
                         intsRead += sz;
                         intsToRead -= sz;
@@ -518,7 +518,7 @@
                     while (srationalsToRead != 0) {
                         int sz = Math.min(srationalsToRead, SRATIONAL_TILE_SIZE);
                         int[] unit = new int[sz * 2];
-                        stream.readFully(unit, (srationalsToRead * 2), (sz * 2));
+                        stream.readFully(unit, 0, (sz * 2));
                         bufs.add(unit);
                         srationalsRead += sz;
                         srationalsToRead -= sz;
@@ -552,7 +552,7 @@
                     while (floatsToRead != 0) {
                         int sz = Math.min(floatsToRead, FLOAT_TILE_SIZE);
                         float[] unit = new float[sz];
-                        stream.readFully(unit, floatsToRead, sz);
+                        stream.readFully(unit, 0, sz);
                         bufs.add(unit);
                         floatsRead += sz;
                         floatsToRead -= sz;
@@ -583,7 +583,7 @@
                     while (doublesToRead != 0) {
                         int sz = Math.min(doublesToRead, DOUBLE_TILE_SIZE);
                         double[] unit = new double[sz];
-                        stream.readFully(unit, doublesToRead, sz);
+                        stream.readFully(unit, 0, sz);
                         bufs.add(unit);
                         doublesRead += sz;
                         doublesToRead -= sz;
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java
index 9010674..fc68258 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -27,6 +27,7 @@
 import java.io.IOException;
 import javax.imageio.IIOException;
 import javax.imageio.plugins.tiff.BaselineTIFFTagSet;
+import com.sun.imageio.plugins.common.ReaderUtil;
 
 class TIFFLZWDecompressor extends TIFFDecompressor {
 
@@ -95,9 +96,8 @@
         }
 
         stream.seek(offset);
-
-        byte[] sdata = new byte[byteCount];
-        stream.readFully(sdata);
+        byte[] sdata = ReaderUtil.
+            staggeredReadByteStream(stream, byteCount);
 
         if (flipBits) {
             for (int i = 0; i < byteCount; i++) {
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFNullDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFNullDecompressor.java
index 6ffc1f0..9b5a746 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFNullDecompressor.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFNullDecompressor.java
@@ -136,12 +136,7 @@
 
             int lastRow = activeSrcHeight - 1;
             for (int y = 0; y < activeSrcHeight; y++) {
-                int bytesRead = stream.read(b, dstOffset, activeBytesPerRow);
-                if (bytesRead < 0) {
-                    throw new EOFException();
-                } else if (bytesRead != activeBytesPerRow) {
-                    break;
-                }
+                stream.readFully(b, dstOffset, activeBytesPerRow);
                 dstOffset += scanlineStride;
 
                 // Skip unneeded bytes (row suffix + row prefix).
@@ -154,17 +149,10 @@
             stream.seek(offset);
             int bytesPerRow = (srcWidth*bitsPerPixel + 7)/8;
             if(bytesPerRow == scanlineStride) {
-                if (stream.read(b, dstOffset, bytesPerRow*srcHeight) < 0) {
-                    throw new EOFException();
-                }
+                stream.readFully(b, dstOffset, bytesPerRow*srcHeight);
             } else {
                 for (int y = 0; y < srcHeight; y++) {
-                    int bytesRead = stream.read(b, dstOffset, bytesPerRow);
-                    if (bytesRead < 0) {
-                        throw new EOFException();
-                    } else if (bytesRead != bytesPerRow) {
-                        break;
-                    }
+                    stream.readFully(b, dstOffset, bytesPerRow);
                     dstOffset += scanlineStride;
                 }
             }
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFPackBitsDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFPackBitsDecompressor.java
index 42a44a4..0a5dfe8 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFPackBitsDecompressor.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFPackBitsDecompressor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -25,6 +25,7 @@
 package com.sun.imageio.plugins.tiff;
 
 import java.io.IOException;
+import com.sun.imageio.plugins.common.ReaderUtil;
 
 public class TIFFPackBitsDecompressor extends TIFFDecompressor {
 
@@ -77,8 +78,8 @@
                           int scanlineStride) throws IOException {
         stream.seek(offset);
 
-        byte[] srcData = new byte[byteCount];
-        stream.readFully(srcData);
+        byte[] srcData = ReaderUtil.
+            staggeredReadByteStream(stream, byteCount);
 
         int bytesPerRow = (srcWidth*bitsPerPixel + 7)/8;
         byte[] buf;
diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFYCbCrDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFYCbCrDecompressor.java
index 11151d8..0f10904 100644
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFYCbCrDecompressor.java
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFYCbCrDecompressor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -180,7 +180,7 @@
         super.setOffset(offset);
     }
 
-    public void setByteCount(int byteCount) {
+    public void setByteCount(int byteCount) throws IOException {
         if(decompressor != null) {
             decompressor.setByteCount(byteCount);
         }
diff --git a/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java b/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java
index e13bae6..6f5a4bb 100644
--- a/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java
+++ b/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java
@@ -392,6 +392,10 @@
                         // meta
                         int metaType = readUnsigned();
                         int metaLength = (int) readVarInt();
+                        if (metaLength < 0) {
+                            throw new InvalidMidiDataException("length out of bounds: "
+                                    + metaLength);
+                        }
                         final byte[] metaData;
                         try {
                             metaData = new byte[metaLength];
diff --git a/src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileReader.java b/src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileReader.java
index 2c3be15..f8365f7 100644
--- a/src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileReader.java
+++ b/src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileReader.java
@@ -73,6 +73,10 @@
                 samplerate = chunk.readUnsignedInt();
                 /* framerate = */chunk.readUnsignedInt();
                 framesize = chunk.readUnsignedShort();
+                if (framesize == 0) {
+                    throw new UnsupportedAudioFileException(
+                            "Can not process audio format with 0 frame size");
+                }
                 bits = chunk.readUnsignedShort();
             }
             if (chunk.getFormat().equals("data")) {
diff --git a/src/java.desktop/share/classes/sun/font/TrueTypeFont.java b/src/java.desktop/share/classes/sun/font/TrueTypeFont.java
index b3afe08..8562976 100644
--- a/src/java.desktop/share/classes/sun/font/TrueTypeFont.java
+++ b/src/java.desktop/share/classes/sun/font/TrueTypeFont.java
@@ -503,7 +503,9 @@
                 /* checksum */ ibuffer.get();
                 table.offset = ibuffer.get() & 0x7FFFFFFF;
                 table.length = ibuffer.get() & 0x7FFFFFFF;
-                if (table.offset + table.length > fileSize) {
+                if ((table.offset + table.length < table.length) ||
+                    (table.offset + table.length > fileSize))
+                {
                     throw new FontFormatException("bad table, tag="+table.tag);
                 }
             }
@@ -798,8 +800,11 @@
                 break;
             }
         }
+
         if (entry == null || entry.length == 0 ||
-            entry.offset+entry.length > fileSize) {
+            (entry.offset + entry.length < entry.length) ||
+            (entry.offset + entry.length > fileSize))
+        {
             return null;
         }
 
@@ -888,6 +893,9 @@
             return false;
         }
         ByteBuffer eblcTable = getTableBuffer(EBLCTag);
+        if (eblcTable == null) {
+            return false;
+        }
         int numSizes = eblcTable.getInt(4);
         /* The bitmapSizeTable's start at offset of 8.
          * Each bitmapSizeTable entry is 48 bytes.
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/LoadDocument.java b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/LoadDocument.java
index bc71944..39084c8 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/LoadDocument.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/LoadDocument.java
@@ -39,7 +39,7 @@
 
 /**
  * @author Morten Jorgensen
- * @LastModified: May 2021
+ * @LastModified: Sept 2021
  */
 public final class LoadDocument {
 
@@ -190,6 +190,9 @@
         if (cache != null) {
             newdom = cache.retrieveDocument(base, originalUri, translet);
             if (newdom == null) {
+                if (translet.getAccessError() != null) {
+                    throw new Exception(translet.getAccessError());
+                }
                 final Exception e = new FileNotFoundException(originalUri);
                 throw new TransletException(e);
             }
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java
index 58b8f43..1612fd6 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java
@@ -54,7 +54,7 @@
  * @author Morten Jorgensen
  * @author G. Todd Miller
  * @author John Howard, JohnH@schemasoft.com
- * @LastModified: May 2021
+ * @LastModified: Sept 2021
  */
 public abstract class AbstractTranslet implements Translet {
 
@@ -116,6 +116,9 @@
      */
     private String _accessExternalStylesheet = JdkConstants.EXTERNAL_ACCESS_DEFAULT;
 
+    // The error message when access to exteranl resources is rejected
+    private String _accessErr = null;
+
     /************************************************************************
      * Debugging
      ************************************************************************/
@@ -786,6 +789,20 @@
         _accessExternalStylesheet = protocols;
     }
 
+    /**
+     * Returns the access error.
+     */
+    public String getAccessError() {
+        return _accessErr;
+    }
+
+    /**
+     * Sets the access error.
+     */
+    public void setAccessError(String accessErr) {
+        this._accessErr = accessErr;
+    }
+
     /************************************************************************
      * DOMImplementation caching for basis library
      ************************************************************************/
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java
index 9e266ee..b58eabc 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java
@@ -101,7 +101,7 @@
  * @author Morten Jorgensen
  * @author G. Todd Miller
  * @author Santiago Pericas-Geertsen
- * @LastModified: June 2021
+ * @LastModified: Sept 2021
  */
 public final class TransformerImpl extends Transformer
     implements DOMCache
@@ -1351,8 +1351,33 @@
             }
 
             if (resolvedSource == null)  {
-                StreamSource streamSource = new StreamSource(
-                     SystemIDResolver.getAbsoluteURI(href, baseURI));
+                /**
+                 * Uses the translet to carry over error msg.
+                 * Performs the access check without any interface changes
+                 * (e.g. Translet and DOMCache).
+                 */
+                @SuppressWarnings("unchecked") //AbstractTranslet is the sole impl.
+                AbstractTranslet t = (AbstractTranslet)translet;
+                String systemId = SystemIDResolver.getAbsoluteURI(href, baseURI);
+                String errMsg = null;
+                try {
+                    String accessError = SecuritySupport.checkAccess(systemId,
+                            t.getAllowedProtocols(),
+                            JdkConstants.ACCESS_EXTERNAL_ALL);
+                    if (accessError != null) {
+                        ErrorMsg msg = new ErrorMsg(ErrorMsg.ACCESSING_XSLT_TARGET_ERR,
+                                SecuritySupport.sanitizePath(href), accessError);
+                        errMsg = msg.toString();
+                    }
+                } catch (IOException ioe) {
+                    errMsg = ioe.getMessage();
+                }
+                if (errMsg != null) {
+                    t.setAccessError(errMsg);
+                    return null;
+                }
+
+                StreamSource streamSource = new StreamSource(systemId);
                 return getDOM(streamSource) ;
             }
 
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java
index 1ec084e..67f6478 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11DocumentScannerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -54,7 +54,7 @@
  * @author Andy Clark, IBM
  * @author Arnaud  Le Hors, IBM
  * @author Eric Ye, IBM
- *
+ * @LastModified: Aug 2021
  */
 public class XML11DocumentScannerImpl
     extends XMLDocumentScannerImpl {
@@ -278,16 +278,6 @@
                                            + fStringBuffer.toString() + "\"");
                     }
                 }
-                // note that none of these characters should ever get through
-                // XML11EntityScanner.  Not sure why
-                // this check was originally necessary.  - NG
-                else if (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) {
-                    fEntityScanner.scanChar(null);
-                    fStringBuffer.append(' ');
-                    if (entityDepth == fEntityDepth) {
-                        fStringBuffer2.append('\n');
-                    }
-                }
                 else if (c != -1 && XMLChar.isHighSurrogate(c)) {
                     fStringBuffer3.clear();
                     if (scanSurrogates(fStringBuffer3)) {
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
index 4be8d68..332aeb5 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
@@ -21,6 +21,7 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+import static com.sun.org.apache.xerces.internal.impl.Constants.XML_VERSION_1_1;
 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;
@@ -40,7 +41,7 @@
  * @author Michael Glavassevich, IBM
  * @author Neil Graham, IBM
  *
- * @LastModified: Apr 2021
+ * @LastModified: Aug 2021
  */
 
 public class XML11EntityScanner
@@ -116,7 +117,7 @@
                 load(1, false, false);
                 offset = 0;
             }
-            if (c == '\r' && external) {
+            if (c == '\r' && external && fCurrentEntity.position < fCurrentEntity.count) {
                 int cc = fCurrentEntity.ch[fCurrentEntity.position++];
                 if (cc != '\n' && cc != 0x85) {
                     fCurrentEntity.position--;
@@ -761,71 +762,12 @@
         }
 
         // normalize newlines
-        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 {
-                c = fCurrentEntity.ch[fCurrentEntity.position++];
-                if ((c == '\r' ) && external) {
-                    newlines++;
-                    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;
-                        }
-                    }
-                    int cc = fCurrentEntity.ch[fCurrentEntity.position];
-                    if (cc == '\n' || cc == 0x85) {
-                        fCurrentEntity.position++;
-                        offset++;
-                    }
-                    /*** NEWLINE NORMALIZATION ***/
-                    else {
-                        newlines++;
-                    }
-                }
-                else if (c == '\n' || ((c == 0x85 || c == 0x2028) && external)) {
-                    newlines++;
-                    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;
-                        }
-                    }
-                }
-                else {
-                    fCurrentEntity.position--;
-                    break;
-                }
-            } while (fCurrentEntity.position < fCurrentEntity.count - 1);
-            for (int i = offset; i < fCurrentEntity.position; i++) {
-                fCurrentEntity.ch[i] = '\n';
-            }
-            int length = fCurrentEntity.position - offset;
-            if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-                checkEntityLimit(null, fCurrentEntity, offset, length);
-                content.setValues(fCurrentEntity.ch, offset, length);
-                return -1;
-            }
+        if (normalizeNewlines(XML_VERSION_1_1, content, false, false, null)) {
+            return -1;
         }
 
+        int c;
+        boolean external = fCurrentEntity.isExternal();
         // inner loop, scanning for content
         if (external) {
             while (fCurrentEntity.position < fCurrentEntity.count) {
@@ -913,65 +855,12 @@
         }
 
         // normalize newlines
-        int offset = fCurrentEntity.position;
-        int c = fCurrentEntity.ch[offset];
-        int newlines = 0;
-        boolean external = fCurrentEntity.isExternal();
-        if (c == '\n' || ((c == '\r' || c == 0x85 || c == 0x2028) && external)) {
-            do {
-                c = fCurrentEntity.ch[fCurrentEntity.position++];
-                if ((c == '\r' ) && external) {
-                    newlines++;
-                    fCurrentEntity.lineNumber++;
-                    fCurrentEntity.columnNumber = 1;
-                    if (fCurrentEntity.position == fCurrentEntity.count) {
-                        offset = 0;
-                        fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
-                        fCurrentEntity.position = newlines;
-                        fCurrentEntity.startPosition = newlines;
-                        if (load(newlines, false, true)) {
-                            break;
-                        }
-                    }
-                    int cc = fCurrentEntity.ch[fCurrentEntity.position];
-                    if (cc == '\n' || cc == 0x85) {
-                        fCurrentEntity.position++;
-                        offset++;
-                    }
-                    /*** NEWLINE NORMALIZATION ***/
-                    else {
-                        newlines++;
-                    }
-                }
-                else if (c == '\n' || ((c == 0x85 || c == 0x2028) && external)) {
-                    newlines++;
-                    fCurrentEntity.lineNumber++;
-                    fCurrentEntity.columnNumber = 1;
-                    if (fCurrentEntity.position == fCurrentEntity.count) {
-                        offset = 0;
-                        fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
-                        fCurrentEntity.position = newlines;
-                        fCurrentEntity.startPosition = newlines;
-                        if (load(newlines, false, true)) {
-                            break;
-                        }
-                    }
-                }
-                else {
-                    fCurrentEntity.position--;
-                    break;
-                }
-            } while (fCurrentEntity.position < fCurrentEntity.count - 1);
-            for (int i = offset; i < fCurrentEntity.position; i++) {
-                fCurrentEntity.ch[i] = '\n';
-            }
-            int length = fCurrentEntity.position - offset;
-            if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-                content.setValues(fCurrentEntity.ch, offset, length);
-                return -1;
-            }
+        if (normalizeNewlines(XML_VERSION_1_1, content, false, true, null)) {
+            return -1;
         }
 
+        int c;
+        boolean external = fCurrentEntity.isExternal();
         // scan literal value
         if (external) {
             while (fCurrentEntity.position < fCurrentEntity.count) {
@@ -1093,66 +982,11 @@
             }
 
             // normalize newlines
-            int offset = fCurrentEntity.position;
-            int c = fCurrentEntity.ch[offset];
-            int newlines = 0;
-            if (c == '\n' || ((c == '\r' || c == 0x85 || c == 0x2028) && external)) {
-                do {
-                    c = fCurrentEntity.ch[fCurrentEntity.position++];
-                    if ((c == '\r' ) && external) {
-                        newlines++;
-                        fCurrentEntity.lineNumber++;
-                        fCurrentEntity.columnNumber = 1;
-                        if (fCurrentEntity.position == fCurrentEntity.count) {
-                            offset = 0;
-                            fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
-                            fCurrentEntity.position = newlines;
-                            fCurrentEntity.startPosition = newlines;
-                            if (load(newlines, false, true)) {
-                                break;
-                            }
-                        }
-                        int cc = fCurrentEntity.ch[fCurrentEntity.position];
-                        if (cc == '\n' || cc == 0x85) {
-                            fCurrentEntity.position++;
-                            offset++;
-                        }
-                        /*** NEWLINE NORMALIZATION ***/
-                        else {
-                            newlines++;
-                        }
-                    }
-                    else if (c == '\n' || ((c == 0x85 || c == 0x2028) && external)) {
-                        newlines++;
-                        fCurrentEntity.lineNumber++;
-                        fCurrentEntity.columnNumber = 1;
-                        if (fCurrentEntity.position == fCurrentEntity.count) {
-                            offset = 0;
-                            fCurrentEntity.baseCharOffset += (fCurrentEntity.position - fCurrentEntity.startPosition);
-                            fCurrentEntity.position = newlines;
-                            fCurrentEntity.startPosition = newlines;
-                            fCurrentEntity.count = newlines;
-                            if (load(newlines, false, true)) {
-                                break;
-                            }
-                        }
-                    }
-                    else {
-                        fCurrentEntity.position--;
-                        break;
-                    }
-                } while (fCurrentEntity.position < fCurrentEntity.count - 1);
-                for (int i = offset; i < fCurrentEntity.position; i++) {
-                    fCurrentEntity.ch[i] = '\n';
-                }
-                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;
-                }
+            if (normalizeNewlines(XML_VERSION_1_1, buffer, true, false, NameType.COMMENT)) {
+                return true;
             }
 
+            int c;
             // iterate over buffer looking for delimiter
             OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
                 c = fCurrentEntity.ch[fCurrentEntity.position++];
@@ -1256,22 +1090,6 @@
             checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
         }
-        else if (c == '\n' && (cc == '\r' ) && fCurrentEntity.isExternal()) {
-            // handle newlines
-            if (fCurrentEntity.position == fCurrentEntity.count) {
-                invokeListeners(1);
-                fCurrentEntity.ch[0] = (char)cc;
-                load(1, false, false);
-            }
-            int ccc = fCurrentEntity.ch[++fCurrentEntity.position];
-            if (ccc == '\n' || ccc == 0x85) {
-                fCurrentEntity.position++;
-            }
-            fCurrentEntity.lineNumber++;
-            fCurrentEntity.columnNumber = 1;
-            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
-            return true;
-        }
 
         // character was not skipped
         return false;
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
index 7dbdf60..8a01f74 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
@@ -91,7 +91,7 @@
  * @author K.Venugopal SUN Microsystems
  * @author Neeraj Bajaj SUN Microsystems
  * @author Sunitha Reddy SUN Microsystems
- * @LastModified: May 2021
+ * @LastModified: Aug 2021
  */
 public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
 
@@ -1235,7 +1235,7 @@
             externalEntity = (Entity.ExternalEntity)entity;
             extLitSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getLiteralSystemId() : null);
             extBaseSysId = (externalEntity.entityLocation != null ? externalEntity.entityLocation.getBaseSystemId() : null);
-            expandedSystemId = expandSystemId(extLitSysId, extBaseSysId);
+            expandedSystemId = expandSystemId(extLitSysId, extBaseSysId, fStrictURI);
             boolean unparsed = entity.isUnparsed();
             boolean parameter = entityName.startsWith("%");
             boolean general = !parameter;
@@ -1312,15 +1312,13 @@
              */
             xmlInputSource = staxInputSource.getXMLInputSource() ;
             if (!fISCreatedByResolver) {
-                //let the not-LoadExternalDTD or not-SupportDTD process to handle the situation
-                if (fLoadExternalDTD) {
-                    String accessError = SecuritySupport.checkAccess(expandedSystemId, fAccessExternalDTD, JdkConstants.ACCESS_EXTERNAL_ALL);
-                    if (accessError != null) {
-                        fErrorReporter.reportError(this.getEntityScanner(),XMLMessageFormatter.XML_DOMAIN,
-                                "AccessExternalEntity",
-                                new Object[] { SecuritySupport.sanitizePath(expandedSystemId), accessError },
-                                XMLErrorReporter.SEVERITY_FATAL_ERROR);
-                    }
+                String accessError = SecuritySupport.checkAccess(expandedSystemId,
+                        fAccessExternalDTD, JdkConstants.ACCESS_EXTERNAL_ALL);
+                if (accessError != null) {
+                    fErrorReporter.reportError(this.getEntityScanner(),XMLMessageFormatter.XML_DOMAIN,
+                            "AccessExternalEntity",
+                            new Object[] { SecuritySupport.sanitizePath(expandedSystemId), accessError },
+                            XMLErrorReporter.SEVERITY_FATAL_ERROR);
                 }
             }
         }
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
index c48ed8f..33ffe98 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
@@ -21,6 +21,8 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+import static com.sun.org.apache.xerces.internal.impl.Constants.XML_VERSION_1_0;
+import static com.sun.org.apache.xerces.internal.impl.Constants.XML_VERSION_1_1;
 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;
@@ -55,7 +57,7 @@
  * @author Arnaud  Le Hors, IBM
  * @author K.Venugopal Sun Microsystems
  *
- * @LastModified: Apr 2021
+ * @LastModified: Sep 2021
  */
 public class XMLEntityScanner implements XMLLocator  {
 
@@ -149,6 +151,15 @@
     // indicates that the operation is for detecting XML version
     boolean detectingVersion = false;
 
+    // offset of the current cursor position
+    int offset = 0;
+
+    // number of newlines in the current process
+    int newlines = 0;
+
+    // indicating whether the content has been counted towards limit
+    boolean counted = false;
+
     //
     // Constructors
     //
@@ -553,7 +564,7 @@
         }
 
         // scan character
-        int offset = fCurrentEntity.position;
+        offset = fCurrentEntity.position;
         int c = fCurrentEntity.ch[fCurrentEntity.position++];
         if (c == '\n' || (c == '\r' && isExternal)) {
             fCurrentEntity.lineNumber++;
@@ -561,10 +572,10 @@
             if (fCurrentEntity.position == fCurrentEntity.count) {
                 invokeListeners(1);
                 fCurrentEntity.ch[0] = (char)c;
-                load(1, false, false);
+                load(1, true, false);
                 offset = 0;
             }
-            if (c == '\r' && isExternal) {
+            if (c == '\r' && isExternal && fCurrentEntity.position < fCurrentEntity.count) {
                 if (fCurrentEntity.ch[fCurrentEntity.position++] != '\n') {
                     fCurrentEntity.position--;
                 }
@@ -614,7 +625,7 @@
         }
 
         // scan nmtoken
-        int offset = fCurrentEntity.position;
+        offset = fCurrentEntity.position;
         boolean vc = false;
         char c;
         while (true){
@@ -695,7 +706,7 @@
         }
 
         // scan name
-        int offset = fCurrentEntity.position;
+        offset = fCurrentEntity.position;
         int length;
         if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) {
             if (++fCurrentEntity.position == fCurrentEntity.count) {
@@ -788,7 +799,7 @@
         }
 
         // scan qualified name
-        int offset = fCurrentEntity.position;
+        offset = fCurrentEntity.position;
 
         //making a check if if the specified character is a valid name start character
         //as defined by production [5] in the XML 1.0 specification.
@@ -1043,81 +1054,11 @@
         }
 
         // normalize newlines
-        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+": ");
-                print();
-                System.out.println();
-            }
-            do {
-                c = fCurrentEntity.ch[fCurrentEntity.position++];
-                if (c == '\r' && isExternal) {
-                    newlines++;
-                    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;
-                        }
-                    }
-                    if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
-                        fCurrentEntity.position++;
-                        offset++;
-                    }
-                    /*** NEWLINE NORMALIZATION ***/
-                    else {
-                        newlines++;
-                    }
-                } else if (c == '\n') {
-                    newlines++;
-                    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;
-                        }
-                    }
-                } else {
-                    fCurrentEntity.position--;
-                    break;
-                }
-            } while (fCurrentEntity.position < fCurrentEntity.count - 1);
-            for (int i = offset; i < fCurrentEntity.position; i++) {
-                fCurrentEntity.ch[i] = '\n';
-            }
-            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);
-                //content.append(fCurrentEntity.ch, offset, length);
-                if (DEBUG_BUFFER) {
-                    System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
-                    print();
-                    System.out.println();
-                }
-                return -1;
-            }
-            if (DEBUG_BUFFER) {
-                System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
-                print();
-                System.out.println();
-            }
+        if (normalizeNewlines(XML_VERSION_1_0, content, false, false, null)) {
+            return -1;
         }
 
+        int c;
         while (fCurrentEntity.position < fCurrentEntity.count) {
             c = fCurrentEntity.ch[fCurrentEntity.position++];
             if (!XMLChar.isContent(c)) {
@@ -1202,85 +1143,14 @@
         }
 
         // normalize newlines
-        int offset = fCurrentEntity.position;
-        int c = fCurrentEntity.ch[offset];
-        int newlines = 0;
         if(whiteSpaceInfoNeeded)
             whiteSpaceLen=0;
-        if (c == '\n' || (c == '\r' && isExternal)) {
-            if (DEBUG_BUFFER) {
-                System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
-                print();
-                System.out.println();
-            }
-            do {
-                c = fCurrentEntity.ch[fCurrentEntity.position++];
-                if (c == '\r' && isExternal) {
-                    newlines++;
-                    fCurrentEntity.lineNumber++;
-                    fCurrentEntity.columnNumber = 1;
-                    if (fCurrentEntity.position == fCurrentEntity.count) {
-                        offset = 0;
-                        fCurrentEntity.position = newlines;
-                        if (load(newlines, false, true)) {
-                            break;
-                        }
-                    }
-                    if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
-                        fCurrentEntity.position++;
-                        offset++;
-                    }
-                    /*** NEWLINE NORMALIZATION ***/
-                    else {
-                        newlines++;
-                    }
-                    /***/
-                } else if (c == '\n') {
-                    newlines++;
-                    fCurrentEntity.lineNumber++;
-                    fCurrentEntity.columnNumber = 1;
-                    if (fCurrentEntity.position == fCurrentEntity.count) {
-                        offset = 0;
-                        fCurrentEntity.position = newlines;
-                        if (load(newlines, false, true)) {
-                            break;
-                        }
-                    }
-                    /*** NEWLINE NORMALIZATION ***
-                     * if (fCurrentEntity.ch[fCurrentEntity.position] == '\r'
-                     * && external) {
-                     * fCurrentEntity.position++;
-                     * offset++;
-                     * }
-                     * /***/
-                } else {
-                    fCurrentEntity.position--;
-                    break;
-                }
-            } while (fCurrentEntity.position < fCurrentEntity.count - 1);
-            int i=0;
-            for ( i = offset; i < fCurrentEntity.position; i++) {
-                fCurrentEntity.ch[i] = '\n';
-                storeWhiteSpace(i);
-            }
 
-            int length = fCurrentEntity.position - offset;
-            if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-                content.setValues(fCurrentEntity.ch, offset, length);
-                if (DEBUG_BUFFER) {
-                    System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
-                    print();
-                    System.out.println();
-                }
-                return -1;
-            }
-            if (DEBUG_BUFFER) {
-                System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
-                print();
-                System.out.println();
-            }
+        if (normalizeNewlines(XML_VERSION_1_0, content, false, true, null)) {
+            return -1;
         }
 
+        int c;
         // scan literal value
         for (; fCurrentEntity.position<fCurrentEntity.count; fCurrentEntity.position++) {
             c = fCurrentEntity.ch[fCurrentEntity.position];
@@ -1331,7 +1201,7 @@
      *
      * @param whiteSpacePos position of a whitespace in the scanner entity buffer
      */
-    private void storeWhiteSpace(int whiteSpacePos) {
+    void storeWhiteSpace(int whiteSpacePos) {
         if (whiteSpaceLen >= whiteSpaceLookup.length) {
             int [] tmp = new int[whiteSpaceLookup.length + 100];
             System.arraycopy(whiteSpaceLookup, 0, tmp, 0, whiteSpaceLookup.length);
@@ -1415,75 +1285,11 @@
                 return false;
             }
 
-            // normalize newlines
-            int offset = fCurrentEntity.position;
-            int c = fCurrentEntity.ch[offset];
-            int newlines = 0;
-            if (c == '\n' || (c == '\r' && isExternal)) {
-                if (DEBUG_BUFFER) {
-                    System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
-                    print();
-                    System.out.println();
-                }
-                do {
-                    c = fCurrentEntity.ch[fCurrentEntity.position++];
-                    if (c == '\r' && isExternal) {
-                        newlines++;
-                        fCurrentEntity.lineNumber++;
-                        fCurrentEntity.columnNumber = 1;
-                        if (fCurrentEntity.position == fCurrentEntity.count) {
-                            offset = 0;
-                            fCurrentEntity.position = newlines;
-                            if (load(newlines, false, true)) {
-                                break;
-                            }
-                        }
-                        if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
-                            fCurrentEntity.position++;
-                            offset++;
-                        }
-                        /*** NEWLINE NORMALIZATION ***/
-                        else {
-                            newlines++;
-                        }
-                    } else if (c == '\n') {
-                        newlines++;
-                        fCurrentEntity.lineNumber++;
-                        fCurrentEntity.columnNumber = 1;
-                        if (fCurrentEntity.position == fCurrentEntity.count) {
-                            offset = 0;
-                            fCurrentEntity.position = newlines;
-                            fCurrentEntity.count = newlines;
-                            if (load(newlines, false, true)) {
-                                break;
-                            }
-                        }
-                    } else {
-                        fCurrentEntity.position--;
-                        break;
-                    }
-                } while (fCurrentEntity.position < fCurrentEntity.count - 1);
-                for (int i = offset; i < fCurrentEntity.position; i++) {
-                    fCurrentEntity.ch[i] = '\n';
-                }
-                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+": ");
-                        print();
-                        System.out.println();
-                    }
-                    return true;
-                }
-                if (DEBUG_BUFFER) {
-                    System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
-                    print();
-                    System.out.println();
-                }
+            if (normalizeNewlines(XML_VERSION_1_0, buffer, true, false, NameType.COMMENT)) {
+                return true;
             }
 
+            int c;
             // iterate over buffer looking for delimiter
             OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
                 c = fCurrentEntity.ch[fCurrentEntity.position++];
@@ -1570,7 +1376,7 @@
         }
 
         // skip character
-        int offset = fCurrentEntity.position;
+        offset = fCurrentEntity.position;
         int cc = fCurrentEntity.ch[fCurrentEntity.position];
         if (cc == c) {
             fCurrentEntity.position++;
@@ -1587,26 +1393,6 @@
             }
             checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
             return true;
-        } else if (c == '\n' && cc == '\r' && isExternal) {
-            // handle newlines
-            if (fCurrentEntity.position == fCurrentEntity.count) {
-                invokeListeners(1);
-                fCurrentEntity.ch[0] = (char)cc;
-                load(1, false, false);
-            }
-            fCurrentEntity.position++;
-            if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
-                fCurrentEntity.position++;
-            }
-            fCurrentEntity.lineNumber++;
-            fCurrentEntity.columnNumber = 1;
-            if (DEBUG_BUFFER) {
-                System.out.print(")skipChar, '"+(char)c+"': ");
-                print();
-                System.out.println(" -> true");
-            }
-            checkEntityLimit(nt, fCurrentEntity, offset, fCurrentEntity.position - offset);
-            return true;
         }
 
         // character was not skipped
@@ -1659,7 +1445,7 @@
 
         // skip spaces
         int c = fCurrentEntity.ch[fCurrentEntity.position];
-        int offset = fCurrentEntity.position - 1;
+        offset = fCurrentEntity.position - 1;
         if (XMLChar.isSpace(c)) {
             do {
                 boolean entityChanged = false;
@@ -2332,5 +2118,86 @@
 
     } // skipDeclSpaces():boolean
 
+    /**
+     * Normalizes newlines. As specified in XML specification, this method
+     * converts newlines, '\n', '\r' and '\r\n' to '\n' as 2.11 End-of-Line Handling.
+     * Further, it may put them in a cache for later process as needed, for example
+     * as specified in 3.3.3 Attribute-Value Normalization.
+     *
+     * @ImplNote this method does not limit to processing external parsed entities
+     * as 2.11 required. It handles all cases where newlines need to be processed.
+     *
+     * @param buffer the current content buffer
+     * @param append a flag indicating whether to append to the buffer
+     * @param storeWS a flag indicating whether the whitespaces need to be stored
+     * for later processing
+     * @param nt the type of the entity
+     * @return true if the cursor is at the end of the current entity, false otherwise.
+     * @throws IOException
+     */
+    protected boolean normalizeNewlines(short version, XMLString buffer, boolean append,
+            boolean storeWS, NameType nt)
+            throws IOException {
+        // normalize newlines
+        offset = fCurrentEntity.position;
+        int c = fCurrentEntity.ch[offset];
+        newlines = 0;
+        // how this information is used is determined by the caller of this method
+        counted = false;
+        if ((c == '\n' || c == '\r') ||
+                (version == XML_VERSION_1_1 && (c == 0x85 || c == 0x2028) && isExternal)) {
+            do {
+                c = fCurrentEntity.ch[fCurrentEntity.position++];
+                if ((c == '\n' || c == '\r') ||
+                    (version == XML_VERSION_1_1 && (c == 0x85 || c == 0x2028))) {
+                    newlines++;
+                    fCurrentEntity.lineNumber++;
+                    fCurrentEntity.columnNumber = 1;
+                    if (fCurrentEntity.position == fCurrentEntity.count) {
+                        checkEntityLimit(nt, fCurrentEntity, offset, newlines);
+                        offset = 0;
+                        fCurrentEntity.position = newlines;
+                        if (load(newlines, false, true)) {
+                            counted = true;
+                            break;
+                        }
+                    }
+                    if (c == '\r') {
+                        int cc = fCurrentEntity.ch[fCurrentEntity.position];
+                        if (cc == '\n' || (version == XML_VERSION_1_1 && cc == 0x85)) {
+                            fCurrentEntity.position++;
+                            offset++;
+                        }
+                        /*** NEWLINE NORMALIZATION ***/
+                        else {
+                            newlines++;
+                        }
+                    }
+                } else {
+                    fCurrentEntity.position--;
+                    break;
+                }
+            } while (fCurrentEntity.position < fCurrentEntity.count - 1);
 
+            for (int i = offset; i < fCurrentEntity.position; i++) {
+                fCurrentEntity.ch[i] = '\n';
+                if (storeWS) {
+                    storeWhiteSpace(i);
+                }
+            }
+
+            int length = fCurrentEntity.position - offset;
+            if (fCurrentEntity.position == fCurrentEntity.count - 1) {
+                checkEntityLimit(nt, fCurrentEntity, offset, length);
+                if (append) {
+                    buffer.append(fCurrentEntity.ch, offset, length);
+                } else {
+                    buffer.setValues(fCurrentEntity.ch, offset, length);
+                }
+
+                return true;
+            }
+        }
+        return false;
+    }
 } // class XMLEntityScanner
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
index 6a63621..2102b85 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -67,7 +67,7 @@
  * @author Eric Ye, IBM
  * @author K.Venugopal SUN Microsystems
  * @author Sunitha Reddy, SUN Microsystems
- * @LastModified: Feb 2020
+ * @LastModified: Aug 2021
  */
 public abstract class XMLScanner
         implements XMLComponent {
@@ -956,12 +956,6 @@
                         System.out.println("** valueF: \""
                                 + stringBuffer.toString() + "\"");
                     }
-                } else if (c == '\n' || c == '\r') {
-                    fEntityScanner.scanChar(null);
-                    stringBuffer.append(' ');
-                    if (entityDepth == fEntityDepth && fNeedNonNormalizedValue) {
-                        fStringBuffer2.append('\n');
-                    }
                 } else if (c != -1 && XMLChar.isHighSurrogate(c)) {
                     fStringBuffer3.clear();
                     if (scanSurrogates(fStringBuffer3)) {
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLStringBuffer.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLStringBuffer.java
index 9e91573..118aeb7 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLStringBuffer.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/XMLStringBuffer.java
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -41,20 +40,12 @@
  *
  * @author Andy Clark, IBM
  * @author Eric Ye, IBM
- *
+ * @LastModified: Aug 2021
  */
 public class XMLStringBuffer
 extends XMLString {
 
     //
-    // Constants
-    //
-
-
-    /** Default buffer size (32). */
-    public static final int DEFAULT_SIZE = 32;
-
-    //
     // Data
     //
 
@@ -112,79 +103,4 @@
         length = 0;
     }
 
-    /**
-     * append
-     *
-     * @param c
-     */
-    public void append(char c) {
-        if(this.length + 1 > this.ch.length){
-            int newLength = this.ch.length * 2 ;
-            if(newLength < this.ch.length + DEFAULT_SIZE){
-                newLength = this.ch.length + DEFAULT_SIZE;
-            }
-            char [] tmp = new char[newLength];
-            System.arraycopy(this.ch, 0, tmp, 0, this.length);
-            this.ch = tmp;
-        }
-        this.ch[this.length] = c ;
-        this.length++;
-    } // append(char)
-
-    /**
-     * append
-     *
-     * @param s
-     */
-    public void append(String s) {
-        int length = s.length();
-        if (this.length + length > this.ch.length) {
-            int newLength = this.ch.length * 2 ;
-            if(newLength < this.ch.length + length + DEFAULT_SIZE){
-                newLength = this.ch.length + length+ DEFAULT_SIZE;
-            }
-
-            char[] newch = new char[newLength];
-            System.arraycopy(this.ch, 0, newch, 0, this.length);
-            this.ch = newch;
-        }
-        s.getChars(0, length, this.ch, this.length);
-        this.length += length;
-    } // append(String)
-
-    /**
-     * append
-     *
-     * @param ch
-     * @param offset
-     * @param length
-     */
-    public void append(char[] ch, int offset, int length) {
-        if (this.length + length > this.ch.length) {
-            int newLength = this.ch.length * 2 ;
-            if(newLength < this.ch.length + length + DEFAULT_SIZE){
-                newLength = this.ch.length + length + DEFAULT_SIZE;
-            }
-            char[] newch = new char[newLength];
-            System.arraycopy(this.ch, 0, newch, 0, this.length);
-            this.ch = newch;
-        }
-        //making the code more robust as it would handle null or 0 length data,
-        //add the data only when it contains some thing
-        if(ch != null && length > 0){
-            System.arraycopy(ch, offset, this.ch, this.length, length);
-            this.length += length;
-        }
-    } // append(char[],int,int)
-
-    /**
-     * append
-     *
-     * @param s
-     */
-    public void append(XMLString s) {
-        append(s.ch, s.offset, s.length);
-    } // append(XMLString)
-
-
 } // class XMLStringBuffer
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xni/XMLString.java b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xni/XMLString.java
index f63e1d2..9d26c25 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xni/XMLString.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/xni/XMLString.java
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -42,9 +41,11 @@
  *
  * @author Eric Ye, IBM
  * @author Andy Clark, IBM
- *
+ * @LastModified: Aug 2021
  */
 public class XMLString {
+    /** Default buffer size (32). */
+    public static final int DEFAULT_SIZE = 32;
 
     //
     // Data
@@ -189,4 +190,78 @@
         return length > 0 ? new String(ch, offset, length) : "";
     } // toString():String
 
+    /**
+     * Appends a char to the buffer.
+     *
+     * @param c the char
+     */
+    public void append(char c) {
+        if(this.length + 1 > this.ch.length){
+            int newLength = this.ch.length * 2 ;
+            if(newLength < this.ch.length + DEFAULT_SIZE){
+                newLength = this.ch.length + DEFAULT_SIZE;
+            }
+            char [] tmp = new char[newLength];
+            System.arraycopy(this.ch, 0, tmp, 0, this.length);
+            this.ch = tmp;
+        }
+        this.ch[this.length] = c ;
+        this.length++;
+    } // append(char)
+
+    /**
+     * Appends a string to the buffer.
+     *
+     * @param s the string
+     */
+    public void append(String s) {
+        int length = s.length();
+        if (this.length + length > this.ch.length) {
+            int newLength = this.ch.length * 2 ;
+            if(newLength < this.ch.length + length + DEFAULT_SIZE){
+                newLength = this.ch.length + length+ DEFAULT_SIZE;
+            }
+
+            char[] newch = new char[newLength];
+            System.arraycopy(this.ch, 0, newch, 0, this.length);
+            this.ch = newch;
+        }
+        s.getChars(0, length, this.ch, this.length);
+        this.length += length;
+    } // append(String)
+
+    /**
+     * Appends a number of characters to the buffer.
+     *
+     * @param ch the char array
+     * @param offset the offset
+     * @param length the length
+     */
+    public void append(char[] ch, int offset, int length) {
+        if (this.length + length > this.ch.length) {
+            int newLength = this.ch.length * 2 ;
+            if(newLength < this.ch.length + length + DEFAULT_SIZE){
+                newLength = this.ch.length + length + DEFAULT_SIZE;
+            }
+            char[] newch = new char[newLength];
+            System.arraycopy(this.ch, 0, newch, 0, this.length);
+            this.ch = newch;
+        }
+        //making the code more robust as it would handle null or 0 length data,
+        //add the data only when it contains some thing
+        if(ch != null && length > 0){
+            System.arraycopy(ch, offset, this.ch, this.length, length);
+            this.length += length;
+        }
+    } // append(char[],int,int)
+
+    /**
+     * Appends another buffer to this buffer
+     *
+     * @param s another buffer
+     */
+    public void append(XMLString s) {
+        append(s.ch, s.offset, s.length);
+    } // append(XMLString)
+
 } // class XMLString
diff --git a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/SystemIDResolver.java b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/SystemIDResolver.java
index de383ca..caf2a4b 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/SystemIDResolver.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/SystemIDResolver.java
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -35,6 +34,8 @@
  * fact that it's declared to throw TransformerException.  Please
  * see code comments for details on how resolution is performed.</p>
  * @xsl.usage internal
+ *
+ * @LastModified: Sept 2021
  */
 public class SystemIDResolver
 {
@@ -275,7 +276,7 @@
   public static String getAbsoluteURI(String urlString, String base)
           throws TransformerException
   {
-    if (base == null)
+    if (base == null || base.length() == 0)
       return getAbsoluteURI(urlString);
 
     String absoluteBase = getAbsoluteURI(base);
diff --git a/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c b/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c
index a21ce9f..f08a7c0 100644
--- a/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c
+++ b/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -399,6 +399,7 @@
     /*
      * Setup data to copy to target process
      */
+    memset(&data, 0, sizeof(data));
     data._GetModuleHandle = _GetModuleHandle;
     data._GetProcAddress = _GetProcAddress;
 
diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthInputStream.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthInputStream.java
index c875a1a..ac6fb7b 100644
--- a/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthInputStream.java
+++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthInputStream.java
@@ -41,6 +41,9 @@
 
     FixedLengthInputStream (ExchangeImpl t, InputStream src, long len) {
         super (t, src);
+        if (len < 0) {
+            throw new IllegalArgumentException("Content-Length: " + len);
+        }
         this.remaining = len;
     }
 
diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthOutputStream.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthOutputStream.java
index 8b43164..4935214 100644
--- a/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthOutputStream.java
+++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/FixedLengthOutputStream.java
@@ -47,6 +47,9 @@
 
     FixedLengthOutputStream (ExchangeImpl t, OutputStream src, long len) {
         super (src);
+        if (len < 0) {
+            throw new IllegalArgumentException("Content-Length: " + len);
+        }
         this.t = t;
         this.remaining = len;
     }
diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/Request.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/Request.java
index e8d719f..03e2a9ee 100644
--- a/src/jdk.httpserver/share/classes/sun/net/httpserver/Request.java
+++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/Request.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2021, 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
@@ -206,7 +206,9 @@
                         "sun.net.httpserver.maxReqHeaders) exceeded, " +
                         ServerConfig.getMaxReqHeaders() + ".");
             }
-
+            if (k == null) {  // Headers disallows null keys, use empty string
+                k = "";       // instead to represent invalid key
+            }
             hdrs.add (k,v);
             len = 0;
         }
diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java
index 9e5bcbf..748dcfd 100644
--- a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java
+++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java
@@ -615,6 +615,11 @@
                     headerValue = headers.getFirst("Content-Length");
                     if (headerValue != null) {
                         clen = Long.parseLong(headerValue);
+                        if (clen < 0) {
+                            reject(Code.HTTP_BAD_REQUEST, requestLine,
+                                    "Illegal Content-Length value");
+                            return;
+                        }
                     }
                     if (clen == 0) {
                         requestCompleted(connection);
@@ -937,7 +942,7 @@
      * Validates a RFC 7230 header-key.
      */
     static boolean isValidHeaderKey(String token) {
-        if (token == null) return false;
+        if (token == null || token.isEmpty()) return false;
 
         boolean isValidChar;
         char[] chars = token.toCharArray();
@@ -950,6 +955,6 @@
                 return false;
             }
         }
-        return !token.isEmpty();
+        return true;
     }
 }
diff --git a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/IsMatureTest.java b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/IsMatureTest.java
index 534ab86..87f4d3d 100644
--- a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/IsMatureTest.java
+++ b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/IsMatureTest.java
@@ -78,10 +78,13 @@
                 && compLevel != CompilerWhiteBoxTest.COMP_LEVEL_SIMPLE) {
             Asserts.assertNE(methodData, 0L,
                     "Multiple times invoked method should have method data");
-            /* a method is not mature in Xcomp mode with tiered compilation disabled,
-               see NonTieredCompPolicy::is_mature */
-            Asserts.assertEQ(isMature, !(Platform.isComp() && !TIERED),
-                    "Unexpected isMature state for multiple times invoked method");
+            // The method may or may not be mature if it's compiled with limited profile.
+            if (compLevel != CompilerWhiteBoxTest.COMP_LEVEL_LIMITED_PROFILE) {
+               /* a method is not mature in Xcomp mode with tiered compilation disabled,
+                 see NonTieredCompPolicy::is_mature */
+               Asserts.assertEQ(isMature, !(Platform.isComp() && !TIERED),
+                       "Unexpected isMature state for multiple times invoked method");
+            }
         }
     }
 }
diff --git a/test/hotspot/jtreg/gc/shenandoah/jni/TestStringCriticalWithDedup.java b/test/hotspot/jtreg/gc/shenandoah/jni/TestStringCriticalWithDedup.java
index 8bd3d88..4eaf93f 100644
--- a/test/hotspot/jtreg/gc/shenandoah/jni/TestStringCriticalWithDedup.java
+++ b/test/hotspot/jtreg/gc/shenandoah/jni/TestStringCriticalWithDedup.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2021, Red Hat, Inc. 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
diff --git a/test/hotspot/jtreg/gc/shenandoah/jni/libTestStringCriticalWithDedup.c b/test/hotspot/jtreg/gc/shenandoah/jni/libTestStringCriticalWithDedup.c
index 665ae58..6b09818 100644
--- a/test/hotspot/jtreg/gc/shenandoah/jni/libTestStringCriticalWithDedup.c
+++ b/test/hotspot/jtreg/gc/shenandoah/jni/libTestStringCriticalWithDedup.c
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2021, Red Hat, Inc. 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
diff --git a/test/jdk/java/util/Hashtable/DeserializedLength.java b/test/jdk/java/util/Hashtable/DeserializedLength.java
index 376c1f0..d515878 100644
--- a/test/jdk/java/util/Hashtable/DeserializedLength.java
+++ b/test/jdk/java/util/Hashtable/DeserializedLength.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2021, 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
@@ -100,7 +100,7 @@
         );
 
         for (int elements : new int[]{10, 50, 500, 5000}) {
-            for (float loadFactor : new float[]{0.15f, 0.5f, 0.75f, 1.0f, 2.5f}) {
+            for (float loadFactor : new float[]{0.25f, 0.5f, 0.75f, 1.0f, 2.5f}) {
                 ok &= testDeserializedLength(elements, loadFactor);
             }
         }
diff --git a/test/jdk/javax/imageio/plugins/tiff/LargeTIFFTagTest.java b/test/jdk/javax/imageio/plugins/tiff/LargeTIFFTagTest.java
new file mode 100644
index 0000000..dad0dd4
--- /dev/null
+++ b/test/jdk/javax/imageio/plugins/tiff/LargeTIFFTagTest.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8270893
+ * @summary Ensure that we don't throw IndexOutOfBoundsException when
+ *          we read TIFF tag with content more than 1024000 bytes
+ * @run main LargeTIFFTagTest
+ */
+
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.Iterator;
+
+public class LargeTIFFTagTest {
+    public static void main(String[] args) throws IOException {
+        // TIFF stream length to hold 22 bytes of TIFF header
+        // plus 1024002 bytes of data in one TIFFTag
+        int length = 1024024;
+        byte[] ba = new byte[length];
+        // Little endian TIFF stream with header and only one
+        // IFD entry at offset 22 having count value 1024002.
+        byte[] header = new byte[] { (byte)0x49, (byte) 0x49,
+                (byte)0x2a, (byte)0x00, (byte)0x08, (byte)0x00,
+                (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00,
+                (byte)0x73, (byte)0x87, (byte)0x07, (byte)0x00,
+                (byte)0x02, (byte)0xA0, (byte)0x0F, (byte)0x00,
+                (byte)0x16, (byte)0x00, (byte)0x00, (byte)0x00};
+        // copy first 22 bytes of TIFF header to byte array
+        for (int i = 0; i < 22; i++) {
+            ba[i] = header[i];
+        }
+        ByteArrayInputStream bais = new ByteArrayInputStream(ba);
+        ImageInputStream stream = ImageIO.createImageInputStream(bais);
+        Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
+
+        if(readers.hasNext()) {
+            ImageReader reader = readers.next();
+            reader.setInput(stream);
+            try {
+                reader.readAll(0, null);
+            } catch (IllegalArgumentException e) {
+                // do nothing we expect IllegalArgumentException but we
+                // should not throw IndexOutOfBoundsException.
+                System.out.println(e.toString());
+                System.out.println("Caught IllegalArgumentException ignore it");
+            }
+        } else {
+            throw new RuntimeException("No readers available for TIFF format");
+        }
+    }
+}