Merge jdk7u66-b17 into jdk7u71-b01
diff --git a/.hgtags b/.hgtags
index 98e74b1..2ad6ad3 100644
--- a/.hgtags
+++ b/.hgtags
@@ -29,6 +29,8 @@
 88cca6736257395bc0140d762046a2b580b6af25 jdk7u66-b14
 22cb4e441c704438b9f310d6c6dc10b341dc6a02 jdk7u66-b15
 fc7222cfbd514c4ecde8e069f4d3166f81b4f97e jdk7u66-b16
+3e5c0d9d8d0113a28dfde78aec5dacdee6f9c407 jdk7u66-b17
+e87bdfd308e64ba0580bda481d58ec0eb03ad8ec jdk7u60-b33
 76e2529a4b21064e43d6492251d43ed03d64924d jdk7u65-b08
 fa5ec4087fbbb3f99aa7458cfc93cae6d53e5bc0 jdk7u71-b00
 ccff8ee195d332d5ce30a1c9be6d1df55095da79 jdk7u55-b14
@@ -452,4 +454,3 @@
 6ee841686c0d3951c2e9c50e148e5982aadad185 jdk7u65-b14
 c913f41402b46e3476ea6985a2c34380045cc6b1 jdk7u65-b15
 4a09127a9af1a366a616da42c8c508abc90725b6 jdk7u65-b16
-3e5c0d9d8d0113a28dfde78aec5dacdee6f9c407 jdk7u66-b17
diff --git a/.hgtags-top-repo b/.hgtags-top-repo
index 3b350fe..f915c1c 100644
--- a/.hgtags-top-repo
+++ b/.hgtags-top-repo
@@ -448,6 +448,7 @@
 ac5183999ba532c6b89f24fe01f6f0eb96799719 jdk7u60-b30
 7e9c1a4c2d50e10ccc6d81b8dc0786e82128a676 jdk7u60-b31
 f792c1446b57932f5cd661afa72bcf41cfe6d1a6 jdk7u60-b32
+870408bbbfa50a6f44997a844c6c31c0cb0cbc40 jdk7u60-b33
 3a683f1730a148bcc1ca6eb9137116db427093f6 jdk7u65-b02
 c154a8de7d34128ab75f46a2b6a909796f63b6e3 jdk7u65-b03
 62e22dbc36410d76716bfa5e9fd679fcb4b1d845 jdk7u65-b04
@@ -463,6 +464,7 @@
 0cfadcb9f8006ac5601bb0ce8b74211d6b223c11 jdk7u65-b14
 3cce3737be368dc3d304508cd0d6e354f8a19f55 jdk7u65-b15
 2c8b05ed9802cf4e5f61439a6d6286e7f7cd444e jdk7u65-b16
+927d8d3db13c5221237b51efe45206054ee6e3f3 jdk7u65-b17
 48eb3345e05fe904d2e92067da0abd04a9b375e4 jdk7u66-b00
 4fb9423d086d86d212257afd6fc79957f737af5b jdk7u66-b01
 964663d4303723fbcb16cf05e857576c08c237ae jdk7u66-b09
@@ -473,3 +475,5 @@
 d06bbfe19d6cefe62e359c2fd8bf9243a148a337 jdk7u66-b14
 df30693e9a66897ba0dced205bbaefc57dca7704 jdk7u66-b15
 6dc5eb9b70071b43cb0e287f30afd0348ae20ae1 jdk7u66-b16
+4f4905b6d3e837c50654bc432956a4a100246d4e jdk7u66-b17
+c779fbb7b87ec014a3371b0dd1e9317ba1280469 jdk7u71-b00
diff --git a/corba/.hgtags b/corba/.hgtags
index 8352cea..910f978 100644
--- a/corba/.hgtags
+++ b/corba/.hgtags
@@ -450,6 +450,7 @@
 39734d26e279098fae06cee5a127e126090ddec9 jdk7u60-b30
 8939f268abb8c153de653f2659fff6716e5f83f8 jdk7u60-b31
 9665790000e22370daefddbf56dd81e89e07b7c4 jdk7u60-b32
+437b4b2aed4811af16efcafca7995684493d205b jdk7u60-b33
 6a89d959cbade46fcd281f421ac40a804d098f0b jdk7u65-b02
 afed3d62e8051fe65f431abe87dad50cbeba3800 jdk7u65-b03
 38fabf72970ae509350f57ffad99f6ac8fc6fdad jdk7u65-b04
@@ -465,6 +466,7 @@
 6efadedfe3295dbf2af4a350d813524af029b116 jdk7u65-b14
 78966cf34d868ef18b8a3fa7edec368e1cc4739d jdk7u65-b15
 d765ed30bd5ed2bdd71fda56c056333e1b4b0d7d jdk7u65-b16
+cd642d59aca29ff2b56e7ed016be758828f199cd jdk7u65-b17
 5b8210c41bc41135687028bcb000ca116e2090f6 jdk7u66-b00
 9f0f0bdd4cfb01a5d64f9528b7ffda3974171120 jdk7u66-b01
 596d979a5d4deb9d10b068479276cd4b2a12432e jdk7u66-b09
@@ -475,3 +477,5 @@
 1e46e65dd58db00180f1ccaaae93ae7946b22d29 jdk7u66-b14
 f2c867d52b393e661216057f0b559ef3fd122530 jdk7u66-b15
 3039f266eef2ba54ec2869d87adac6e395c82fe9 jdk7u66-b16
+0b46b93a61966e8d2332f1d3899d7c858a653d91 jdk7u66-b17
+fd1c9030a08d513b5a477f82a46855bb6a9cacac jdk7u71-b00
diff --git a/hotspot/.hgtags b/hotspot/.hgtags
index 45ddda9..1ac9ddf 100644
--- a/hotspot/.hgtags
+++ b/hotspot/.hgtags
@@ -668,6 +668,7 @@
 13f561930b3e80a94e2baddc51dfc6c43c5ca601 jdk7u60-b30
 35b2dbe7f7c69ea0f2feb1e66fe8651511a5fb6d jdk7u60-b31
 f166d2e391993f1b12b4ad1685baf999c78e6372 jdk7u60-b32
+cc1fea28c886ef100632247a708eac0c83640914 jdk7u60-b33
 eb797fab50d3b440b17b3e7c5d83f42bfa73655e jdk7u65-b02
 bb00df28ecdbd0da89ab4ed81f6f2b732fa512da jdk7u65-b03
 848481af9003067546c7f34c166bb8d745b95d5f jdk7u65-b04
@@ -683,6 +684,7 @@
 7ec585caae47f7202fb5357607f9ad058b03870e jdk7u65-b14
 7058f0d30de6826b6866ce2d146c63e943be33af jdk7u65-b15
 f1b2970a2564c3360db420431cfbba215da6ae43 jdk7u65-b16
+4c6df9a369cb9d54fe2d898452883a22b8ec6640 jdk7u65-b17
 6b37a189944aaa09e81d97d394496464d16bee42 jdk7u66-b00
 121dc94194d9234e2b13c867d875e23e1bdd6abd jdk7u66-b01
 f28ea516eb0b9e99f1e342954ab4642456af4da1 jdk7u66-b09
@@ -693,3 +695,5 @@
 b44baba406f2de6eeccc57dbfae653cf124b527b jdk7u66-b14
 d20b495c96d3f8899a64657aba0fc72799773cb3 jdk7u66-b15
 3bbfed065c601187449d319fd70bba6ae1ebb707 jdk7u66-b16
+4abb71ff14b2e6cf932e5c61900f480d5e1afedb jdk7u66-b17
+4ceb9c03fe8ee6b93d22854780ef8c737edd14b2 jdk7u71-b00
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-debug b/hotspot/make/bsd/makefiles/mapfile-vers-debug
index fd1b9ba..dac7736 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-debug
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -82,6 +82,7 @@
                 _JVM_EnableCompiler
                 _JVM_Exit
                 _JVM_FillInStackTrace
+                _JVM_FindClassFromCaller
                 _JVM_FindClassFromClass
                 _JVM_FindClassFromClassLoader
                 _JVM_FindClassFromBootLoader
diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-product b/hotspot/make/bsd/makefiles/mapfile-vers-product
index d21645b..692eb18 100644
--- a/hotspot/make/bsd/makefiles/mapfile-vers-product
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-product
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -82,6 +82,7 @@
                 _JVM_EnableCompiler
                 _JVM_Exit
                 _JVM_FillInStackTrace
+                _JVM_FindClassFromCaller
                 _JVM_FindClassFromClass
                 _JVM_FindClassFromClassLoader
                 _JVM_FindClassFromBootLoader
diff --git a/hotspot/make/hotspot_version b/hotspot/make/hotspot_version
index ee1fc01..9db9945 100644
--- a/hotspot/make/hotspot_version
+++ b/hotspot/make/hotspot_version
@@ -34,8 +34,8 @@
 HOTSPOT_VM_COPYRIGHT=Copyright 2014
 
 HS_MAJOR_VER=24
-HS_MINOR_VER=66
-HS_BUILD_NUMBER=02
+HS_MINOR_VER=71
+HS_BUILD_NUMBER=01
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=7
diff --git a/hotspot/make/linux/makefiles/mapfile-vers-debug b/hotspot/make/linux/makefiles/mapfile-vers-debug
index 1a0bc01..d79ad57 100644
--- a/hotspot/make/linux/makefiles/mapfile-vers-debug
+++ b/hotspot/make/linux/makefiles/mapfile-vers-debug
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/linux/makefiles/mapfile-vers-product b/hotspot/make/linux/makefiles/mapfile-vers-product
index e53bc5c..a0af89d 100644
--- a/hotspot/make/linux/makefiles/mapfile-vers-product
+++ b/hotspot/make/linux/makefiles/mapfile-vers-product
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
diff --git a/hotspot/make/solaris/makefiles/mapfile-vers b/hotspot/make/solaris/makefiles/mapfile-vers
index eb55548..1a5fe74 100644
--- a/hotspot/make/solaris/makefiles/mapfile-vers
+++ b/hotspot/make/solaris/makefiles/mapfile-vers
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -84,6 +84,7 @@
 		JVM_EnableCompiler;
 		JVM_Exit;
 		JVM_FillInStackTrace;
+		JVM_FindClassFromCaller;
 		JVM_FindClassFromClass;
 		JVM_FindClassFromClassLoader;
 		JVM_FindClassFromBootLoader;
diff --git a/hotspot/src/share/vm/adlc/formssel.cpp b/hotspot/src/share/vm/adlc/formssel.cpp
index 7dd3561..2227cb8 100644
--- a/hotspot/src/share/vm/adlc/formssel.cpp
+++ b/hotspot/src/share/vm/adlc/formssel.cpp
@@ -536,12 +536,6 @@
   if( data_type != Form::none )
     rematerialize = true;
 
-  // Ugly: until a better fix is implemented, disable rematerialization for
-  // negD nodes because they are proved to be problematic.
-  if (is_ideal_negD()) {
-    return false;
-  }
-
   // Constants
   if( _components.count() == 1 && _components[0]->is(Component::USE_DEF) )
     rematerialize = true;
diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp
index c1566d3..8c5e970 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp
@@ -2721,6 +2721,11 @@
       "bootstrap_method_index %u has bad constant type in class file %s",
       bootstrap_method_index,
       CHECK);
+
+    guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
+      "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
+      CHECK);
+
     operands->short_at_put(operand_fill_index++, bootstrap_method_index);
     operands->short_at_put(operand_fill_index++, argument_count);
 
@@ -2738,7 +2743,6 @@
   }
 
   assert(operand_fill_index == operands()->length(), "exact fill");
-  assert(constantPoolOopDesc::operand_array_length(operands()) == attribute_array_length, "correct decode");
 
   u1* current_end = cfs->current();
   guarantee_property(current_end == current_start + attribute_byte_length,
diff --git a/hotspot/src/share/vm/interpreter/linkResolver.cpp b/hotspot/src/share/vm/interpreter/linkResolver.cpp
index b17f405..1676add 100644
--- a/hotspot/src/share/vm/interpreter/linkResolver.cpp
+++ b/hotspot/src/share/vm/interpreter/linkResolver.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -187,6 +187,14 @@
 
 void LinkResolver::lookup_method_in_klasses(methodHandle& result, KlassHandle klass, Symbol* name, Symbol* signature, TRAPS) {
   methodOop result_oop = klass->uncached_lookup_method(name, signature);
+
+  //JDK 7 does not support default methods, but this code ported from JDK8 to keep code consistent for all JDK.
+  if (klass->oop_is_array()) {
+    // Only consider klass and super klass for arrays
+    result = methodHandle(THREAD, result_oop);
+    return;
+  }
+
   if (EnableInvokeDynamic && result_oop != NULL) {
     vmIntrinsics::ID iid = result_oop->intrinsic_id();
     if (MethodHandles::is_signature_polymorphic(iid)) {
@@ -421,7 +429,7 @@
   // 2. lookup method in resolved klass and its super klasses
   lookup_method_in_klasses(resolved_method, resolved_klass, method_name, method_signature, CHECK);
 
-  if (resolved_method.is_null()) { // not found in the class hierarchy
+  if (resolved_method.is_null() && !resolved_klass->oop_is_array()) { // not found in the class hierarchy
     // 3. lookup method in all the interfaces implemented by the resolved klass
     lookup_method_in_interfaces(resolved_method, resolved_klass, method_name, method_signature, CHECK);
 
@@ -434,16 +442,16 @@
         CLEAR_PENDING_EXCEPTION;
       }
     }
+  }
 
-    if (resolved_method.is_null()) {
-      // 4. method lookup failed
-      ResourceMark rm(THREAD);
-      THROW_MSG_CAUSE(vmSymbols::java_lang_NoSuchMethodError(),
-                      methodOopDesc::name_and_sig_as_C_string(Klass::cast(resolved_klass()),
-                                                              method_name,
-                                                              method_signature),
-                      nested_exception);
-    }
+  if (resolved_method.is_null()) {
+    // 4. method lookup failed
+    ResourceMark rm(THREAD);
+    THROW_MSG_CAUSE(vmSymbols::java_lang_NoSuchMethodError(),
+                    methodOopDesc::name_and_sig_as_C_string(Klass::cast(resolved_klass()),
+                                                            method_name,
+                                                            method_signature),
+                    nested_exception);
   }
 
   // 5. check if method is concrete
@@ -514,17 +522,18 @@
   // lookup method in this interface or its super, java.lang.Object
   lookup_instance_method_in_klasses(resolved_method, resolved_klass, method_name, method_signature, CHECK);
 
-  if (resolved_method.is_null()) {
+  if (resolved_method.is_null() && !resolved_klass->oop_is_array()) {
     // lookup method in all the super-interfaces
     lookup_method_in_interfaces(resolved_method, resolved_klass, method_name, method_signature, CHECK);
-    if (resolved_method.is_null()) {
-      // no method found
-      ResourceMark rm(THREAD);
-      THROW_MSG(vmSymbols::java_lang_NoSuchMethodError(),
-                methodOopDesc::name_and_sig_as_C_string(Klass::cast(resolved_klass()),
-                                                        method_name,
-                                                        method_signature));
-    }
+  }
+
+  if (resolved_method.is_null()) {
+    // no method found
+    ResourceMark rm(THREAD);
+    THROW_MSG(vmSymbols::java_lang_NoSuchMethodError(),
+              methodOopDesc::name_and_sig_as_C_string(Klass::cast(resolved_klass()),
+                                                      method_name,
+                                                      method_signature));
   }
 
   if (check_access) {
@@ -614,7 +623,7 @@
 
   // Resolve instance field
   fieldDescriptor fd; // find_field initializes fd if found
-  KlassHandle sel_klass(THREAD, instanceKlass::cast(resolved_klass())->find_field(field, sig, &fd));
+  KlassHandle sel_klass(THREAD, resolved_klass->find_field(field, sig, &fd));
   // check if field exists; i.e., if a klass containing the field def has been selected
   if (sel_klass.is_null()){
     ResourceMark rm(THREAD);
diff --git a/hotspot/src/share/vm/oops/arrayKlass.cpp b/hotspot/src/share/vm/oops/arrayKlass.cpp
index 4aa1155..16142b8 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.cpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,6 +64,13 @@
   return NULL;
 }
 
+// find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
+klassOop arrayKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
+  // There are no fields in an array klass but look to the super class (Object)
+  assert(super(), "super klass must be present");
+  return Klass::cast(super())->find_field(name, sig, fd);
+}
+
 methodOop arrayKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
   // There are no methods in an array klass but the super class (Object) has some
   assert(super(), "super klass must be present");
diff --git a/hotspot/src/share/vm/oops/arrayKlass.hpp b/hotspot/src/share/vm/oops/arrayKlass.hpp
index 13dbaec..7df8434 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.hpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,8 @@
 #include "oops/klassOop.hpp"
 #include "oops/klassVtable.hpp"
 
+class fieldDescriptor;
+
 // arrayKlass is the abstract baseclass for all array classes
 
 class arrayKlass: public Klass {
@@ -83,6 +85,9 @@
   virtual oop multi_allocate(int rank, jint* sizes, TRAPS);
   objArrayOop allocate_arrayArray(int n, int length, TRAPS);
 
+  // find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
+  klassOop find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
+
   // Lookup operations
   methodOop uncached_lookup_method(Symbol* name, Symbol* signature) const;
 
diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp
index 596d5ad..ff33181 100644
--- a/hotspot/src/share/vm/oops/klass.cpp
+++ b/hotspot/src/share/vm/oops/klass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -119,6 +119,15 @@
   return is_subclass_of(k);
 }
 
+klassOop Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
+#ifdef ASSERT
+  tty->print_cr("Error: find_field called on a klass oop."
+                " Likely error: reflection method does not correctly"
+                " wrap return value in a mirror object.");
+#endif
+  ShouldNotReachHere();
+  return NULL;
+}
 
 methodOop Klass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
 #ifdef ASSERT
diff --git a/hotspot/src/share/vm/oops/klass.hpp b/hotspot/src/share/vm/oops/klass.hpp
index bcbd4e7..a449e87 100644
--- a/hotspot/src/share/vm/oops/klass.hpp
+++ b/hotspot/src/share/vm/oops/klass.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,6 +88,7 @@
 class klassVtable;
 class KlassHandle;
 class OrderAccess;
+class fieldDescriptor;
 
 // Holder (or cage) for the C++ vtable of each kind of Klass.
 // We want to tightly constrain the location of the C++ vtable in the overall layout.
@@ -514,6 +515,7 @@
   virtual void initialize(TRAPS);
   // lookup operation for MethodLookupCache
   friend class MethodLookupCache;
+  virtual klassOop find_field(Symbol* name, Symbol* signature, fieldDescriptor* fd) const;
   virtual methodOop uncached_lookup_method(Symbol* name, Symbol* signature) const;
  public:
   methodOop lookup_method(Symbol* name, Symbol* signature) const {
diff --git a/hotspot/src/share/vm/opto/reg_split.cpp b/hotspot/src/share/vm/opto/reg_split.cpp
index b83ffc6..b396c64 100644
--- a/hotspot/src/share/vm/opto/reg_split.cpp
+++ b/hotspot/src/share/vm/opto/reg_split.cpp
@@ -51,15 +51,6 @@
 
 static const char out_of_nodes[] = "out of nodes during split";
 
-static bool contains_no_live_range_input(const Node* def) {
-  for (uint i = 1; i < def->req(); ++i) {
-    if (def->in(i) != NULL && def->in_RegMask(i).is_NotEmpty()) {
-      return false;
-    }
-  }
-  return true;
-}
-
 //------------------------------get_spillcopy_wide-----------------------------
 // Get a SpillCopy node with wide-enough masks.  Use the 'wide-mask', the
 // wide ideal-register spill-mask if possible.  If the 'wide-mask' does
@@ -326,10 +317,13 @@
   if( def->req() > 1 ) {
     for( uint i = 1; i < def->req(); i++ ) {
       Node *in = def->in(i);
-      // Check for single-def (LRG cannot redefined)
       uint lidx = n2lidx(in);
-      if( lidx >= _maxlrg ) continue; // Value is a recent spill-copy
-      if (lrgs(lidx).is_singledef()) continue;
+      // We do not need this for live ranges that are only defined once.
+      // However, this is not true for spill copies that are added in this
+      // Split() pass, since they might get coalesced later on in this pass.
+      if (lidx < _maxlrg && lrgs(lidx).is_singledef()) {
+         continue;
+       }
 
       Block *b_def = _cfg._bbs[def->_idx];
       int idx_def = b_def->find_node(def);
@@ -1303,7 +1297,7 @@
       Node *def = Reaches[pidx][slidx];
       assert( def, "must have reaching def" );
       // If input up/down sense and reg-pressure DISagree
-      if (def->rematerialize() && contains_no_live_range_input(def)) {
+      if (def->rematerialize()) {
         // Place the rematerialized node above any MSCs created during
         // phi node splitting.  end_idx points at the insertion point
         // so look at the node before it.
diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp
index 7dcd968..839c11f 100644
--- a/hotspot/src/share/vm/prims/jvm.cpp
+++ b/hotspot/src/share/vm/prims/jvm.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -746,6 +746,7 @@
   return (jclass) JNIHandles::make_local(env, Klass::cast(k)->java_mirror());
 JVM_END
 
+// Not used; JVM_FindClassFromCaller replaces this.
 JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
                                                jboolean init, jobject loader,
                                                jboolean throwError))
@@ -772,6 +773,42 @@
   return result;
 JVM_END
 
+// Find a class with this name in this loader, using the caller's protection domain.
+JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
+                                          jboolean init, jobject loader,
+                                          jclass caller))
+  JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
+  // Java libraries should ensure that name is never null...
+  if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
+    // It's impossible to create this class;  the name cannot fit
+    // into the constant pool.
+    THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
+  }
+
+  TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
+
+  oop loader_oop = JNIHandles::resolve(loader);
+  oop from_class = JNIHandles::resolve(caller);
+  oop protection_domain = NULL;
+  // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
+  // NPE. Put it in another way, the bootstrap class loader has all permission and
+  // thus no checkPackageAccess equivalence in the VM class loader.
+  // The caller is also passed as NULL by the java code if there is no security
+  // manager to avoid the performance cost of getting the calling class.
+  if (from_class != NULL && loader_oop != NULL) {
+    protection_domain = instanceKlass::cast(java_lang_Class::as_klassOop(from_class))->protection_domain();
+  }
+
+  Handle h_loader(THREAD, loader_oop);
+  Handle h_prot(THREAD, protection_domain);
+  jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
+                                               h_prot, false, THREAD);
+
+  if (TraceClassResolution && result != NULL) {
+    trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
+  }
+  return result;
+JVM_END
 
 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
                                          jboolean init, jclass from))
@@ -4098,10 +4135,15 @@
 
 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
 
-jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) {
+jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
+                                    Handle loader, Handle protection_domain,
+                                    jboolean throwError, TRAPS) {
   // Security Note:
   //   The Java level wrapper will perform the necessary security check allowing
-  //   us to pass the NULL as the initiating class loader.
+  //   us to pass the NULL as the initiating class loader.  The VM is responsible for
+  //   the checkPackageAccess relative to the initiating class loader via the
+  //   protection_domain. The protection_domain is passed as NULL by the java code
+  //   if there is no security manager in 3-arg Class.forName().
   klassOop klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
 
   KlassHandle klass_handle(THREAD, klass);
diff --git a/hotspot/src/share/vm/prims/jvm.h b/hotspot/src/share/vm/prims/jvm.h
index 7ca4418..2cd2f5d 100644
--- a/hotspot/src/share/vm/prims/jvm.h
+++ b/hotspot/src/share/vm/prims/jvm.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -415,6 +415,19 @@
 JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
 
 /*
+ * Find a class from a given class loader.  Throws ClassNotFoundException.
+ *  name:   name of class
+ *  init:   whether initialization is done
+ *  loader: class loader to look up the class. This may not be the same as the caller's
+ *          class loader.
+ *  caller: initiating class. The initiating class may be null when a security
+ *          manager is not installed.
+ */
+JNIEXPORT jclass JNICALL
+JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
+                        jobject loader, jclass caller);
+
+/*
  * Find a class from a given class.
  */
 JNIEXPORT jclass JNICALL
diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp
index 02971ac..ec79354 100644
--- a/hotspot/src/share/vm/runtime/arguments.cpp
+++ b/hotspot/src/share/vm/runtime/arguments.cpp
@@ -2057,6 +2057,10 @@
     PrintNMTStatistics = false;
   }
 
+#ifdef COMPILER1
+  status &= verify_interval(SafepointPollOffset, 0, os::vm_page_size() - BytesPerWord, "SafepointPollOffset");
+#endif
+
   return status;
 }
 
diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp
index bf8b9d0..b0179c2 100644
--- a/hotspot/src/share/vm/runtime/globals.hpp
+++ b/hotspot/src/share/vm/runtime/globals.hpp
@@ -1094,9 +1094,11 @@
           "Prevent spurious or premature wakeups from object.wait "         \
           "(Solaris only)")                                                 \
                                                                             \
-  product(intx, NativeMonitorTimeout, -1, "(Unstable)" )                    \
-  product(intx, NativeMonitorFlags, 0, "(Unstable)" )                       \
-  product(intx, NativeMonitorSpinLimit, 20, "(Unstable)" )                  \
+  experimental(intx, NativeMonitorTimeout, -1, "(Unstable)")                \
+                                                                            \
+  experimental(intx, NativeMonitorFlags, 0, "(Unstable)")                   \
+                                                                            \
+  experimental(intx, NativeMonitorSpinLimit, 20, "(Unstable)")              \
                                                                             \
   develop(bool, UsePthreads, false,                                         \
           "Use pthread-based instead of libthread-based synchronization "   \
diff --git a/jaxp/.hgtags b/jaxp/.hgtags
index 8402159..5174b36 100644
--- a/jaxp/.hgtags
+++ b/jaxp/.hgtags
@@ -451,6 +451,7 @@
 cef2dec8b5d76555c5b7b2e1a62275206f76a07a jdk7u60-b30
 bfa8403a1e28bdc1e94ba61d89e170e4ccc7d58b jdk7u60-b31
 33a8a292a02aa76139d0d04970a0d87cc674f2e3 jdk7u60-b32
+583c5eeb9f31275121aecca60307b8885a1a80d0 jdk7u60-b33
 27909f138bdb9ffdd2ab4bded231c7ccc2264046 jdk7u65-b02
 b3307181bd0f1a2c6e1e2c403b87a76e34452110 jdk7u65-b03
 efa9425faaf402b7ea9c6226eb08236d8fa1ff2b jdk7u65-b04
@@ -466,6 +467,7 @@
 ddb29a56b839563502b9f80deca5d6064641f1d7 jdk7u65-b14
 708c636721447ebf679c2c754cb36a503c6177b8 jdk7u65-b15
 a34a9f6740955e1cd844c5b701d76dbe7290913a jdk7u65-b16
+178512d1bd9caf56d61811ad0d4b4269475407aa jdk7u65-b17
 86e93799766d67102a37559b3831abcc825d7e24 jdk7u66-b00
 d34839cb2f15dee01cdfb1fd93378849de34d662 jdk7u66-b01
 19e4e978c8212921104ba16d0db6bf18c6f8d0ab jdk7u66-b09
@@ -476,3 +478,5 @@
 15206a7046a97d0a0fd824bec8b0e4174a56d8eb jdk7u66-b14
 af60b8e3b9deb32d50552916e0afd38a30feaef0 jdk7u66-b15
 36bba6c72f866df5c65ba8678544bf0442a952b3 jdk7u66-b16
+9a777cc0d6b3b25d13feca1e610584d042565367 jdk7u66-b17
+174a2f822f4f600f798e9963f0c1496206dce471 jdk7u71-b00
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
index 6d35622..c819090 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
@@ -612,9 +612,9 @@
         //fElementStack2.clear();
         //fReplaceEntityReferences = true;
         //fSupportExternalEntities = true;
-        Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_REPLACING_ENTITY_REFERENCES);
+        Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES);
         fReplaceEntityReferences = bo.booleanValue();
-        bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_SUPPORTING_EXTERNAL_ENTITIES);
+        bo = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES);
         fSupportExternalEntities = bo.booleanValue();
         Boolean cdata = (Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.STAX_REPORT_CDATA_EVENT) ;
         if(cdata != null)
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
index 0eb09ed..fdb74e7 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java
@@ -50,6 +50,7 @@
 import java.util.Map;
 import java.util.Stack;
 import javax.xml.XMLConstants;
+import javax.xml.stream.XMLInputFactory;
 
 
 /**
@@ -302,6 +303,11 @@
     /** Property Manager. This is used from Stax */
     protected PropertyManager fPropertyManager ;
 
+    /** StAX properties */
+    boolean fSupportDTD = true;
+    boolean fReplaceEntityReferences = true;
+    boolean fSupportExternalEntities = true;
+
     /** used to restrict external access */
     protected String fAccessExternalDTD = EXTERNAL_ACCESS_DEFAULT;
 
@@ -1133,7 +1139,8 @@
             boolean parameter = entityName.startsWith("%");
             boolean general = !parameter;
             if (unparsed || (general && !fExternalGeneralEntities) ||
-                    (parameter && !fExternalParameterEntities)) {
+                    (parameter && !fExternalParameterEntities) ||
+                    !fSupportDTD || !fSupportExternalEntities) {
 
                 if (fEntityHandler != null) {
                     fResourceIdentifier.clear();
@@ -1428,6 +1435,10 @@
             fStaxEntityResolver = null;
         }
 
+        fSupportDTD = ((Boolean)propertyManager.getProperty(XMLInputFactory.SUPPORT_DTD)).booleanValue();
+        fReplaceEntityReferences = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)).booleanValue();
+        fSupportExternalEntities = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)).booleanValue();
+
         // Zephyr feature ignore-external-dtd is the opposite of Xerces' load-external-dtd
         fLoadExternalDTD = !((Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.IGNORE_EXTERNAL_DTD)).booleanValue();
 
@@ -1499,6 +1510,11 @@
         fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER, null);
         entityExpansionIndex = fSecurityManager.getIndex(Constants.JDK_ENTITY_EXPANSION_LIMIT);
 
+        //StAX Property
+        fSupportDTD = true;
+        fReplaceEntityReferences = true;
+        fSupportExternalEntities = true;
+
         // JAXP 1.5 feature
         XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER, null);
         if (spm == null) {
diff --git a/jaxws/.hgtags b/jaxws/.hgtags
index 26b9b0c..94ea727 100644
--- a/jaxws/.hgtags
+++ b/jaxws/.hgtags
@@ -450,6 +450,7 @@
 39e67887a3b112bf74f84df2aac0f46c65bfb005 jdk7u60-b30
 dfc2c4b9b16bd2d68435ddc9bb12036982021844 jdk7u60-b31
 0e17943c39fadb810b4dd2e9ac732503b86043f4 jdk7u60-b32
+910559d7f754d8fd6ab80a627869877443358316 jdk7u60-b33
 8ac19021e6af5d92b46111a6c41430f36ccdb901 jdk7u65-b02
 a70d681bc273a110d10cf3c4f9b35b25ca6a600f jdk7u65-b03
 7cd17f96988509e99fbb71003aeb76d92b638fef jdk7u65-b04
@@ -465,6 +466,7 @@
 11deffa2096f08dab69de13d4fcf361c6d252636 jdk7u65-b14
 39ad61a579fd824fbec1bec4e071376449ba8195 jdk7u65-b15
 198bf1acd262f2c16715d3be5e33d7b8de1e7776 jdk7u65-b16
+df4dc644fe344e973fc1692c28683eec8ba82600 jdk7u65-b17
 d63ca1c5bdb9fb2e36ec4afda431c0d1dfdfc07c jdk7u66-b00
 1dce52b208a9528266c26352e03e67ec0ddb4dd7 jdk7u66-b01
 04481967eff566b8a379a0315d2a3a255928d6ce jdk7u66-b09
@@ -475,3 +477,5 @@
 ae584331109f291e03af72cc9fcbbe5f8f789ab1 jdk7u66-b14
 36461c772d3101a8cb1eca16a9c81ed53218a4c9 jdk7u66-b15
 19ed8a653a3e8c6536fd1090c14f93e690eda7a3 jdk7u66-b16
+ea1e6f01f95c9a0984378643754d0f493bfa4484 jdk7u66-b17
+6092d0059338df25e82fbc69cc749b95e2565547 jdk7u71-b00
diff --git a/jdk/.hgtags b/jdk/.hgtags
index 2320154..cb14c6b 100644
--- a/jdk/.hgtags
+++ b/jdk/.hgtags
@@ -434,6 +434,7 @@
 8dc56d0f3e860658619eaa57d10fb1a4182d71cd jdk7u60-b30
 feac9624a1e1ffebe09a19ae351d88e3ef98c441 jdk7u60-b31
 fb40615ef352e03ee94c0682a6ca0a0e6a33a70b jdk7u60-b32
+9cfcdeeecfac66004cb5bbb2c5bba5c57e170539 jdk7u60-b33
 a42a3bb22f6991d8f6a30e4f1782ad620c40eb65 jdk7u65-b02
 756071871d61e1ca410c63a3f1c4dabcc51a90df jdk7u65-b03
 bac16c82c14a35d1e9d3c4d0bd317dbbb296f34e jdk7u65-b04
@@ -449,6 +450,7 @@
 2e6105ddad44866c4cdc1ba06620b48685e34111 jdk7u65-b14
 8cff6ce00a91820b4cb7ef24ed42063c2305127d jdk7u65-b15
 190017413768f02addea8b2c5106157e3c4076c7 jdk7u65-b16
+23e78e36bc39f4f761ac2b0e055c562c3ff204f5 jdk7u65-b17
 9ccfe70cee626ac7831cfa7b7a7eb7a88fe1cd42 jdk7u66-b00
 fc87b55d62fc1e81aaf61ff21175129b8ccc302e jdk7u66-b01
 c67e394e49429565540f04c5c2a5544f750658bb jdk7u66-b09
@@ -459,3 +461,5 @@
 74d01c3385b915490255cd7467a3740aa3dce310 jdk7u66-b14
 07fc91c550da6ba689e3abc9e688edcb73f9c95c jdk7u66-b15
 d4814cafa25f5b076be9e99be2a8c0d98929476d jdk7u66-b16
+69adfb3ccee5373438a6c394646c2c5ab93c89ee jdk7u66-b17
+ee0cedc50d3250edf24e96aecc785580dd61944f jdk7u71-b00
diff --git a/jdk/make/java/net/FILES_c.gmk b/jdk/make/java/net/FILES_c.gmk
index 02bd96d..bf5a60e 100644
--- a/jdk/make/java/net/FILES_c.gmk
+++ b/jdk/make/java/net/FILES_c.gmk
@@ -24,6 +24,7 @@
 #
 
 FILES_c = \
+        AbstractPlainDatagramSocketImpl.c \
         DatagramPacket.c \
         InetAddress.c \
         Inet4Address.c \
diff --git a/jdk/make/java/net/mapfile-vers b/jdk/make/java/net/mapfile-vers
index 771dc87..0897f03 100644
--- a/jdk/make/java/net/mapfile-vers
+++ b/jdk/make/java/net/mapfile-vers
@@ -28,6 +28,8 @@
 SUNWprivate_1.1 {
         global:
                 JNI_OnLoad;
+                Java_java_net_AbstractPlainDatagramSocketImpl_init;
+                Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable;
                 Java_java_net_PlainSocketImpl_socketListen;
                 Java_java_net_PlainDatagramSocketImpl_getTTL;
                 Java_java_net_PlainDatagramSocketImpl_init;
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/RSACipher.java b/jdk/src/share/classes/com/sun/crypto/provider/RSACipher.java
index 644813d..08aa93c 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/RSACipher.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/RSACipher.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,8 @@
 
 import sun.security.rsa.*;
 import sun.security.jca.Providers;
+import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
+import sun.security.util.KeyUtil;
 
 /**
  * RSA cipher implementation. Supports RSA en/decryption and signing/verifying
@@ -91,8 +93,8 @@
     // padding object
     private RSAPadding padding;
 
-    // cipher parameter for OAEP padding
-    private OAEPParameterSpec spec = null;
+    // cipher parameter for OAEP padding and TLS RSA premaster secret
+    private AlgorithmParameterSpec spec = null;
 
     // buffer for the data
     private byte[] buffer;
@@ -110,6 +112,9 @@
     // hash algorithm for OAEP
     private String oaepHashAlgorithm = "SHA-1";
 
+    // the source of randomness
+    private SecureRandom random;
+
     public RSACipher() {
         paddingType = PAD_PKCS1;
     }
@@ -175,7 +180,7 @@
 
     // see JCE spec
     protected AlgorithmParameters engineGetParameters() {
-        if (spec != null) {
+        if (spec != null && spec instanceof OAEPParameterSpec) {
             try {
                 AlgorithmParameters params =
                     AlgorithmParameters.getInstance("OAEP", "SunJCE");
@@ -278,8 +283,13 @@
             buffer = new byte[n];
         } else if (paddingType == PAD_PKCS1) {
             if (params != null) {
-                throw new InvalidAlgorithmParameterException
-                ("Parameters not supported");
+                if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
+                    throw new InvalidAlgorithmParameterException(
+                            "Parameters not supported");
+                }
+
+                spec = params;
+                this.random = random;   // for TLS RSA premaster secret
             }
             int blockType = (mode <= MODE_DECRYPT) ? RSAPadding.PAD_BLOCKTYPE_2
                                                    : RSAPadding.PAD_BLOCKTYPE_1;
@@ -295,19 +305,18 @@
                 throw new InvalidKeyException
                         ("OAEP cannot be used to sign or verify signatures");
             }
-            OAEPParameterSpec myParams;
             if (params != null) {
                 if (!(params instanceof OAEPParameterSpec)) {
                     throw new InvalidAlgorithmParameterException
                         ("Wrong Parameters for OAEP Padding");
                 }
-                myParams = (OAEPParameterSpec) params;
+                spec = params;
             } else {
-                myParams = new OAEPParameterSpec(oaepHashAlgorithm, "MGF1",
+                spec = new OAEPParameterSpec(oaepHashAlgorithm, "MGF1",
                     MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
             }
             padding = RSAPadding.getInstance(RSAPadding.PAD_OAEP_MGF1, n,
-                random, myParams);
+                random, (OAEPParameterSpec)spec);
             if (encrypt) {
                 int k = padding.getMaxDataSize();
                 buffer = new byte[k];
@@ -422,17 +431,40 @@
         if (wrappedKey.length > buffer.length) {
             throw new InvalidKeyException("Key is too long for unwrapping");
         }
+
+        boolean isTlsRsaPremasterSecret =
+                algorithm.equals("TlsRsaPremasterSecret");
+        Exception failover = null;
+        byte[] encoded = null;
+
         update(wrappedKey, 0, wrappedKey.length);
         try {
-            byte[] encoded = doFinal();
-            return ConstructKeys.constructKey(encoded, algorithm, type);
+            encoded = doFinal();
         } catch (BadPaddingException e) {
-            // should not occur
-            throw new InvalidKeyException("Unwrapping failed", e);
+            if (isTlsRsaPremasterSecret) {
+                failover = e;
+            } else {
+                throw new InvalidKeyException("Unwrapping failed", e);
+            }
         } catch (IllegalBlockSizeException e) {
             // should not occur, handled with length check above
             throw new InvalidKeyException("Unwrapping failed", e);
         }
+
+        if (isTlsRsaPremasterSecret) {
+            if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
+                throw new IllegalStateException(
+                        "No TlsRsaPremasterSecretParameterSpec specified");
+            }
+
+            // polish the TLS premaster secret
+            encoded = KeyUtil.checkTlsPreMasterSecretKey(
+                ((TlsRsaPremasterSecretParameterSpec)spec).getClientVersion(),
+                ((TlsRsaPremasterSecretParameterSpec)spec).getServerVersion(),
+                random, encoded, (failover != null));
+        }
+
+        return ConstructKeys.constructKey(encoded, algorithm, type);
     }
 
     // see JCE spec
@@ -440,5 +472,4 @@
         RSAKey rsaKey = RSAKeyFactory.toRSAKey(key);
         return rsaKey.getModulus().bitLength();
     }
-
 }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/TlsRsaPremasterSecretGenerator.java b/jdk/src/share/classes/com/sun/crypto/provider/TlsRsaPremasterSecretGenerator.java
index ef9098f..2a25cb6 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/TlsRsaPremasterSecretGenerator.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/TlsRsaPremasterSecretGenerator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -56,7 +56,7 @@
 
     protected void engineInit(AlgorithmParameterSpec params,
             SecureRandom random) throws InvalidAlgorithmParameterException {
-        if (params instanceof TlsRsaPremasterSecretParameterSpec == false) {
+        if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
             throw new InvalidAlgorithmParameterException(MSG);
         }
         this.spec = (TlsRsaPremasterSecretParameterSpec)params;
@@ -67,21 +67,20 @@
         throw new InvalidParameterException(MSG);
     }
 
+    // Only can be used in client side to generate TLS RSA premaster secret.
     protected SecretKey engineGenerateKey() {
         if (spec == null) {
             throw new IllegalStateException(
                 "TlsRsaPremasterSecretGenerator must be initialized");
         }
-        byte[] b = spec.getEncodedSecret();
-        if (b == null) {
-            if (random == null) {
-                random = new SecureRandom();
-            }
-            b = new byte[48];
-            random.nextBytes(b);
-            b[0] = (byte)spec.getMajorVersion();
-            b[1] = (byte)spec.getMinorVersion();
+
+        if (random == null) {
+            random = new SecureRandom();
         }
+        byte[] b = new byte[48];
+        random.nextBytes(b);
+        b[0] = (byte)spec.getMajorVersion();
+        b[1] = (byte)spec.getMinorVersion();
 
         return new SecretKeySpec(b, "TlsRsaPremasterSecret");
     }
diff --git a/jdk/src/share/classes/java/lang/Class.java b/jdk/src/share/classes/java/lang/Class.java
index 9d06b45..5bfdb88 100644
--- a/jdk/src/share/classes/java/lang/Class.java
+++ b/jdk/src/share/classes/java/lang/Class.java
@@ -187,8 +187,8 @@
     @CallerSensitive
     public static Class<?> forName(String className)
                 throws ClassNotFoundException {
-        return forName0(className, true,
-                        ClassLoader.getClassLoader(Reflection.getCallerClass()));
+        Class<?> caller = Reflection.getCallerClass();
+        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
     }
 
 
@@ -257,22 +257,27 @@
                                    ClassLoader loader)
         throws ClassNotFoundException
     {
-        if (loader == null) {
-            SecurityManager sm = System.getSecurityManager();
-            if (sm != null) {
-                ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
+        Class<?> caller = null;
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            // Reflective call to get caller class is only needed if a security manager
+            // is present.  Avoid the overhead of making this call otherwise.
+            caller = Reflection.getCallerClass();
+            if (loader == null) {
+                ClassLoader ccl = ClassLoader.getClassLoader(caller);
                 if (ccl != null) {
                     sm.checkPermission(
                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
                 }
             }
         }
-        return forName0(name, initialize, loader);
+        return forName0(name, initialize, loader, caller);
     }
 
-    /** Called after security checks have been made. */
+    /** Called after security check for system loader access checks have been made. */
     private static native Class<?> forName0(String name, boolean initialize,
-                                            ClassLoader loader)
+                                            ClassLoader loader,
+                                            Class<?> caller)
         throws ClassNotFoundException;
 
     /**
diff --git a/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java b/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java
index 55bf6ae..a4cb1da 100644
--- a/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java
+++ b/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java
@@ -661,6 +661,12 @@
             refKind = REF_invokeVirtual;
         }
 
+        if (member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual) {
+            // Methods from Object declared in an interface can be resolved by JVM to invokevirtual kind.
+            // Need to convert it back to invokeinterface to pass verification and make the invocation works as expected.
+            refKind = REF_invokeInterface;
+        }
+
         // push arguments
         for (int i = 0; i < name.arguments.length; i++) {
             emitPushArgument(name, i);
diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandle.java b/jdk/src/share/classes/java/lang/invoke/MethodHandle.java
index ced6799..0670492 100644
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandle.java
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandle.java
@@ -1260,8 +1260,6 @@
     /*non-public*/
     MethodHandle viewAsType(MethodType newType) {
         // No actual conversions, just a new view of the same method.
-        if (!type.isViewableAs(newType))
-            throw new InternalError();
         return MethodHandleImpl.makePairwiseConvert(this, newType, 0);
     }
 
diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
index 3dbe40b..e5b66df 100644
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
@@ -1268,9 +1268,30 @@
             int allowedModes = this.allowedModes;
             if (allowedModes == TRUSTED)  return;
             int mods = m.getModifiers();
-            if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
-                // cannot "new" a protected ctor in a different package
-                mods ^= Modifier.PROTECTED;
+            if (Modifier.isProtected(mods)) {
+                if (refKind == REF_invokeVirtual &&
+                        m.getDeclaringClass() == Object.class &&
+                        m.getName().equals("clone") &&
+                        refc.isArray()) {
+                    // The JVM does this hack also.
+                    // (See ClassVerifier::verify_invoke_instructions
+                    // and LinkResolver::check_method_accessability.)
+                    // Because the JVM does not allow separate methods on array types,
+                    // there is no separate method for int[].clone.
+                    // All arrays simply inherit Object.clone.
+                    // But for access checking logic, we make Object.clone
+                    // (normally protected) appear to be public.
+                    // Later on, when the DirectMethodHandle is created,
+                    // its leading argument will be restricted to the
+                    // requested array type.
+                    // N.B. The return type is not adjusted, because
+                    // that is *not* the bytecode behavior.
+                    mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
+                }
+                if (refKind == REF_newInvokeSpecial) {
+                    // cannot "new" a protected ctor in a different package
+                    mods ^= Modifier.PROTECTED;
+                }
             }
             if (Modifier.isFinal(mods) &&
                     MethodHandleNatives.refKindIsSetter(refKind))
diff --git a/jdk/src/share/classes/java/lang/invoke/MethodType.java b/jdk/src/share/classes/java/lang/invoke/MethodType.java
index c690dad..dbe2979 100644
--- a/jdk/src/share/classes/java/lang/invoke/MethodType.java
+++ b/jdk/src/share/classes/java/lang/invoke/MethodType.java
@@ -628,7 +628,7 @@
      * @return the parameter types (as an immutable list)
      */
     public List<Class<?>> parameterList() {
-        return Collections.unmodifiableList(Arrays.asList(ptypes));
+        return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
     }
 
     /*non-public*/ Class<?> lastParameterType() {
diff --git a/jdk/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java b/jdk/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java
index b7f0f2f..7f9315d 100644
--- a/jdk/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java
+++ b/jdk/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java
@@ -70,6 +70,7 @@
     static {
         java.security.AccessController.doPrivileged(
                   new sun.security.action.LoadLibraryAction("net"));
+        init();
     }
 
     /**
@@ -362,4 +363,7 @@
     protected boolean nativeConnectDisabled() {
         return connectDisabled;
     }
+
+    native int dataAvailable();
+    private static native void init();
 }
diff --git a/jdk/src/share/classes/java/net/DatagramSocket.java b/jdk/src/share/classes/java/net/DatagramSocket.java
index 62493a8..8b2ea8d 100644
--- a/jdk/src/share/classes/java/net/DatagramSocket.java
+++ b/jdk/src/share/classes/java/net/DatagramSocket.java
@@ -85,6 +85,17 @@
      */
     boolean oldImpl = false;
 
+    /**
+     * Set when a socket is ST_CONNECTED until we are certain
+     * that any packets which might have been received prior
+     * to calling connect() but not read by the application
+     * have been read. During this time we check the source
+     * address of all packets received to be sure they are from
+     * the connected destination. Other packets are read but
+     * silently dropped.
+     */
+    private boolean explicitFilter = false;
+    private int bytesLeftToFilter;
     /*
      * Connection state:
      * ST_NOT_CONNECTED = socket not connected
@@ -144,6 +155,15 @@
 
                 // socket is now connected by the impl
                 connectState = ST_CONNECTED;
+                // Do we need to filter some packets?
+                int avail = getImpl().dataAvailable();
+                if (avail == -1) {
+                    throw new SocketException();
+                }
+                explicitFilter = avail > 0;
+                if (explicitFilter) {
+                    bytesLeftToFilter = getReceiveBufferSize();
+                }
             } catch (SocketException se) {
 
                 // connection will be emulated by DatagramSocket
@@ -494,6 +514,7 @@
             connectedAddress = null;
             connectedPort = -1;
             connectState = ST_NOT_CONNECTED;
+            explicitFilter = false;
         }
     }
 
@@ -752,10 +773,12 @@
                     } // end of while
                 }
             }
-            if (connectState == ST_CONNECTED_NO_IMPL) {
+            if ((connectState == ST_CONNECTED_NO_IMPL) || explicitFilter) {
                 // We have to do the filtering the old fashioned way since
                 // the native impl doesn't support connect or the connect
-                // via the impl failed.
+                // via the impl failed, or .. "explicitFilter" may be set when
+                // a socket is connected via the impl, for a period of time
+                // when packets from other sources might be queued on socket.
                 boolean stop = false;
                 while (!stop) {
                     InetAddress peekAddress = null;
@@ -774,8 +797,18 @@
                     if ((!connectedAddress.equals(peekAddress)) ||
                         (connectedPort != peekPort)) {
                         // throw the packet away and silently continue
-                        DatagramPacket tmp = new DatagramPacket(new byte[1], 1);
+                        DatagramPacket tmp = new DatagramPacket(
+                                                new byte[1024], 1024);
                         getImpl().receive(tmp);
+                        if (explicitFilter) {
+                            bytesLeftToFilter -= tmp.getLength();
+                            if (bytesLeftToFilter <= 0 ||
+                                getImpl().dataAvailable() <= 0)
+                            {
+                                explicitFilter = false;
+                                stop = true;
+                            }
+                        }
                     } else {
                         stop = true;
                     }
diff --git a/jdk/src/share/classes/java/net/DatagramSocketImpl.java b/jdk/src/share/classes/java/net/DatagramSocketImpl.java
index 3ed11e4b..70e509f 100644
--- a/jdk/src/share/classes/java/net/DatagramSocketImpl.java
+++ b/jdk/src/share/classes/java/net/DatagramSocketImpl.java
@@ -47,6 +47,12 @@
      */
     protected FileDescriptor fd;
 
+    int dataAvailable() {
+        // default impl returns zero, which disables the calling
+        // functionality
+        return 0;
+    }
+
     /**
      * Creates a datagram socket.
      * @exception SocketException if there is an error in the
diff --git a/jdk/src/share/classes/java/security/Signature.java b/jdk/src/share/classes/java/security/Signature.java
index 59cc0d4..f512d4d 100644
--- a/jdk/src/share/classes/java/security/Signature.java
+++ b/jdk/src/share/classes/java/security/Signature.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -589,6 +589,9 @@
         if (outbuf == null) {
             throw new IllegalArgumentException("No output buffer given");
         }
+        if (offset < 0 || len < 0) {
+            throw new IllegalArgumentException("offset or len is less than 0");
+        }
         if (outbuf.length - offset < len) {
             throw new IllegalArgumentException
                 ("Output buffer too small for specified offset and length");
@@ -657,9 +660,16 @@
     public final boolean verify(byte[] signature, int offset, int length)
         throws SignatureException {
         if (state == VERIFY) {
-            if ((signature == null) || (offset < 0) || (length < 0) ||
-                (length > signature.length - offset)) {
-                throw new IllegalArgumentException("Bad arguments");
+            if (signature == null) {
+                throw new IllegalArgumentException("signature is null");
+            }
+            if (offset < 0 || length < 0) {
+                throw new IllegalArgumentException
+                    ("offset or length is less than 0");
+            }
+            if (signature.length - offset < length) {
+                throw new IllegalArgumentException
+                    ("signature too small for specified offset and length");
             }
 
             return engineVerify(signature, offset, length);
@@ -712,6 +722,16 @@
     public final void update(byte[] data, int off, int len)
             throws SignatureException {
         if (state == SIGN || state == VERIFY) {
+            if (data == null) {
+                throw new IllegalArgumentException("data is null");
+            }
+            if (off < 0 || len < 0) {
+                throw new IllegalArgumentException("off or len is less than 0");
+            }
+            if (data.length - off < len) {
+                throw new IllegalArgumentException
+                    ("data too small for specified offset and length");
+            }
             engineUpdate(data, off, len);
         } else {
             throw new SignatureException("object not initialized for "
diff --git a/jdk/src/share/classes/java/security/cert/CertificateRevokedException.java b/jdk/src/share/classes/java/security/cert/CertificateRevokedException.java
index a76299c..0939b68 100644
--- a/jdk/src/share/classes/java/security/cert/CertificateRevokedException.java
+++ b/jdk/src/share/classes/java/security/cert/CertificateRevokedException.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -95,7 +95,10 @@
         this.revocationDate = new Date(revocationDate.getTime());
         this.reason = reason;
         this.authority = authority;
-        this.extensions = new HashMap(extensions);
+        // make sure Map only contains correct types
+        this.extensions = Collections.checkedMap(new HashMap<String, Extension>(),
+                                                 String.class, Extension.class);
+        this.extensions.putAll(extensions);
     }
 
     /**
@@ -174,7 +177,8 @@
     public String getMessage() {
         return "Certificate has been revoked, reason: "
                + reason + ", revocation date: " + revocationDate
-               + ", authority: " + authority + ", extensions: " + extensions;
+               + ", authority: " + authority + ", extension OIDs: "
+               + extensions.keySet();
     }
 
     /**
diff --git a/jdk/src/share/classes/java/util/logging/LogRecord.java b/jdk/src/share/classes/java/util/logging/LogRecord.java
index 93540d9..4952e3d 100644
--- a/jdk/src/share/classes/java/util/logging/LogRecord.java
+++ b/jdk/src/share/classes/java/util/logging/LogRecord.java
@@ -510,7 +510,13 @@
         // If necessary, try to regenerate the resource bundle.
         if (resourceBundleName != null) {
             try {
-                resourceBundle = ResourceBundle.getBundle(resourceBundleName);
+                // use system class loader to ensure the ResourceBundle
+                // instance is a different instance than null loader uses
+                final ResourceBundle bundle =
+                        ResourceBundle.getBundle(resourceBundleName,
+                                Locale.getDefault(),
+                                ClassLoader.getSystemClassLoader());
+                resourceBundle = bundle;
             } catch (MissingResourceException ex) {
                 // This is not a good place to throw an exception,
                 // so we simply leave the resourceBundle null.
diff --git a/jdk/src/share/classes/java/util/logging/Logger.java b/jdk/src/share/classes/java/util/logging/Logger.java
index d52d1d5..bacea91 100644
--- a/jdk/src/share/classes/java/util/logging/Logger.java
+++ b/jdk/src/share/classes/java/util/logging/Logger.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1526,6 +1526,9 @@
         }
 
         setCallersClassLoaderRef(callersClass);
+        if (isSystemLogger && getCallersClassLoader() != null) {
+            checkPermission();
+        }
         if (findResourceBundle(name, true) == null) {
             // We've failed to find an expected ResourceBundle.
             // unset the caller's ClassLoader since we were unable to find the
@@ -1689,7 +1692,9 @@
         Logger target = this;
         while (target != null) {
             final String rbn = isSystemLogger
-                ? target.resourceBundleName
+                // ancestor of a system logger is expected to be a system logger.
+                // ignore resource bundle name if it's not.
+                ? (target.isSystemLogger ? target.resourceBundleName : null)
                 : target.getResourceBundleName();
             if (rbn != null) {
                 return rbn;
diff --git a/jdk/src/share/classes/javax/crypto/CipherInputStream.java b/jdk/src/share/classes/javax/crypto/CipherInputStream.java
index b9f3cf8..9301faf 100644
--- a/jdk/src/share/classes/javax/crypto/CipherInputStream.java
+++ b/jdk/src/share/classes/javax/crypto/CipherInputStream.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -86,6 +86,8 @@
     private int ostart = 0;
     // the offset pointing to the last "new" byte
     private int ofinish = 0;
+    // The stream has been read from.  False if the stream has never been read.
+    private boolean read = false;
 
     /**
      * private convenience function.
@@ -101,13 +103,15 @@
     private int getMoreData() throws IOException {
         if (done) return -1;
         int readin = input.read(ibuffer);
+        read = true;
         if (readin == -1) {
             done = true;
             try {
                 obuffer = cipher.doFinal();
+            } catch (IllegalBlockSizeException | BadPaddingException e) {
+                obuffer = null;
+                throw new IOException(e);
             }
-            catch (IllegalBlockSizeException e) {obuffer = null;}
-            catch (BadPaddingException e) {obuffer = null;}
             if (obuffer == null)
                 return -1;
             else {
@@ -118,7 +122,10 @@
         }
         try {
             obuffer = cipher.update(ibuffer, 0, readin);
-        } catch (IllegalStateException e) {obuffer = null;};
+        } catch (IllegalStateException e) {
+            obuffer = null;
+            throw e;
+        }
         ostart = 0;
         if (obuffer == null)
             ofinish = 0;
@@ -298,9 +305,12 @@
             // throw away the unprocessed data
             cipher.doFinal();
         }
-        catch (BadPaddingException ex) {
-        }
-        catch (IllegalBlockSizeException ex) {
+        catch (BadPaddingException | IllegalBlockSizeException ex) {
+            /* If no data has been read from the stream to be en/decrypted,
+               we supress any exceptions, and close quietly. */
+            if (read) {
+                throw new IOException(ex);
+            }
         }
         ostart = 0;
         ofinish = 0;
diff --git a/jdk/src/share/classes/javax/crypto/JceSecurity.java b/jdk/src/share/classes/javax/crypto/JceSecurity.java
index cac9cc7..b0ad3d2 100644
--- a/jdk/src/share/classes/javax/crypto/JceSecurity.java
+++ b/jdk/src/share/classes/javax/crypto/JceSecurity.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -216,26 +216,28 @@
     private static final Map codeBaseCacheRef = new WeakHashMap();
 
     /*
-     * Retuns the CodeBase for the given class.
+     * Returns the CodeBase for the given class.
      */
     static URL getCodeBase(final Class clazz) {
-        URL url = (URL)codeBaseCacheRef.get(clazz);
-        if (url == null) {
-            url = (URL)AccessController.doPrivileged(new PrivilegedAction() {
-                public Object run() {
-                    ProtectionDomain pd = clazz.getProtectionDomain();
-                    if (pd != null) {
-                        CodeSource cs = pd.getCodeSource();
-                        if (cs != null) {
-                            return cs.getLocation();
+        synchronized (codeBaseCacheRef) {
+            URL url = (URL)codeBaseCacheRef.get(clazz);
+            if (url == null) {
+                url = (URL)AccessController.doPrivileged(new PrivilegedAction() {
+                    public Object run() {
+                        ProtectionDomain pd = clazz.getProtectionDomain();
+                        if (pd != null) {
+                            CodeSource cs = pd.getCodeSource();
+                            if (cs != null) {
+                                return cs.getLocation();
+                            }
                         }
+                        return NULL_URL;
                     }
-                    return NULL_URL;
-                }
-            });
-            codeBaseCacheRef.put(clazz, url);
+                });
+                codeBaseCacheRef.put(clazz, url);
+            }
+            return (url == NULL_URL) ? null : url;
         }
-        return (url == NULL_URL) ? null : url;
     }
 
     private static void setupJurisdictionPolicies() throws Exception {
diff --git a/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java b/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java
index e327716..5b224af 100644
--- a/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java
+++ b/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java
@@ -755,10 +755,22 @@
                     + scanlineStride);
         }
 
-        for (int i = 0; i < data.length; i++) {
-            if (scanlineStride > data[i].length) {
-                throw new RasterFormatException("Incorrect scanline stride: "
-                    + scanlineStride);
+        if ((long)minX - sampleModelTranslateX < 0 ||
+            (long)minY - sampleModelTranslateY < 0) {
+
+            throw new RasterFormatException("Incorrect origin/translate: (" +
+                    minX + ", " + minY + ") / (" +
+                    sampleModelTranslateX + ", " + sampleModelTranslateY + ")");
+        }
+
+
+        if (height > 1 || minY - sampleModelTranslateY > 0) {
+            // buffer should contain at least one scanline
+            for (int i = 0; i < data.length; i++) {
+                if (scanlineStride > data[i].length) {
+                    throw new RasterFormatException("Incorrect scanline stride: "
+                        + scanlineStride);
+                }
             }
         }
 
diff --git a/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java b/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java
index 13954f3..5f0f0fb 100644
--- a/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java
+++ b/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java
@@ -885,15 +885,31 @@
             }
         }
 
+        if ((long)minX - sampleModelTranslateX < 0 ||
+            (long)minY - sampleModelTranslateY < 0) {
+
+            throw new RasterFormatException("Incorrect origin/translate: (" +
+                    minX + ", " + minY + ") / (" +
+                    sampleModelTranslateX + ", " + sampleModelTranslateY + ")");
+        }
+
         // we can be sure that width and height are greater than 0
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height) ||
-            scanlineStride > data.length)
+            scanlineStride > (Integer.MAX_VALUE / height))
         {
             // integer overflow
             throw new RasterFormatException("Incorrect scanline stride: "
                     + scanlineStride);
         }
+
+        if (height > 1 || minY - sampleModelTranslateY > 0) {
+            // buffer should contain at least one scanline
+            if (scanlineStride > data.length) {
+                throw new RasterFormatException("Incorrect scanline stride: "
+                        + scanlineStride);
+            }
+        }
+
         int lastScanOffset = (height - 1) * scanlineStride;
 
         if (pixelStride < 0 ||
diff --git a/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java b/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java
index c819c9d..55cf996 100644
--- a/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java
+++ b/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java
@@ -1386,17 +1386,32 @@
             throw new RasterFormatException("Invalid raster dimension");
         }
 
+        if ((long)minX - sampleModelTranslateX < 0 ||
+            (long)minY - sampleModelTranslateY < 0) {
+
+            throw new RasterFormatException("Incorrect origin/translate: (" +
+                    minX + ", " + minY + ") / (" +
+                    sampleModelTranslateX + ", " + sampleModelTranslateY + ")");
+        }
+
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height) ||
-            scanlineStride > data.length)
+            scanlineStride > (Integer.MAX_VALUE / height))
         {
             throw new RasterFormatException("Invalid scanline stride");
         }
 
-        int lastbit = (dataBitOffset
-                       + (height-1) * scanlineStride * 8
-                       + (width-1) * pixelBitStride
-                       + pixelBitStride - 1);
+        if (height > 1 || minY - sampleModelTranslateY > 0) {
+            // buffer should contain at least one scanline
+            if (scanlineStride > data.length) {
+                throw new RasterFormatException("Incorrect scanline stride: "
+                        + scanlineStride);
+            }
+        }
+
+        long lastbit = (long) dataBitOffset
+                       + (long) (height - 1) * (long) scanlineStride * 8
+                       + (long) (width - 1) * (long) pixelBitStride
+                       + (long) pixelBitStride - 1;
         if (lastbit < 0 || lastbit / 8 >= data.length) {
             throw new RasterFormatException("raster dimensions overflow " +
                                             "array bounds");
diff --git a/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java b/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java
index 2f49597..9efe71d 100644
--- a/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java
+++ b/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java
@@ -654,15 +654,31 @@
                                             ") must be >= 0");
         }
 
+        if ((long)minX - sampleModelTranslateX < 0 ||
+            (long)minY - sampleModelTranslateY < 0) {
+
+            throw new RasterFormatException("Incorrect origin/translate: (" +
+                    minX + ", " + minY + ") / (" +
+                    sampleModelTranslateX + ", " + sampleModelTranslateY + ")");
+        }
+
         // we can be sure that width and height are greater than 0
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height) ||
-            scanlineStride > data.length)
+            scanlineStride > (Integer.MAX_VALUE / height))
         {
             // integer overflow
             throw new RasterFormatException("Incorrect scanline stride: "
                     + scanlineStride);
         }
+
+        if (height > 1 || minY - sampleModelTranslateY > 0) {
+            // buffer should contain at least one scanline
+            if (scanlineStride > data.length) {
+                throw new RasterFormatException("Incorrect scanline stride: "
+                        + scanlineStride);
+            }
+        }
+
         int lastScanOffset = (height - 1) * scanlineStride;
 
         if (pixelStride < 0 ||
diff --git a/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java b/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java
index 058a257..249a2c4 100644
--- a/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java
+++ b/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java
@@ -754,10 +754,21 @@
                     + scanlineStride);
         }
 
-        for (int i = 0; i < data.length; i++) {
-            if (scanlineStride > data[i].length) {
-                throw new RasterFormatException("Incorrect scanline stride: "
-                    + scanlineStride);
+        if ((long)minX - sampleModelTranslateX < 0 ||
+            (long)minY - sampleModelTranslateY < 0) {
+
+            throw new RasterFormatException("Incorrect origin/translate: (" +
+                    minX + ", " + minY + ") / (" +
+                    sampleModelTranslateX + ", " + sampleModelTranslateY + ")");
+        }
+
+        if (height > 1 || minY - sampleModelTranslateY > 0) {
+            // buffer should contain at least one scanline
+            for (int i = 0; i < data.length; i++) {
+                if (scanlineStride > data[i].length) {
+                    throw new RasterFormatException("Incorrect scanline stride: "
+                        + scanlineStride);
+                }
             }
         }
 
diff --git a/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java b/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java
index a84da63..bf4465d 100644
--- a/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java
+++ b/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java
@@ -819,15 +819,31 @@
             }
         }
 
+        if ((long)minX - sampleModelTranslateX < 0 ||
+            (long)minY - sampleModelTranslateY < 0) {
+
+            throw new RasterFormatException("Incorrect origin/translate: (" +
+                    minX + ", " + minY + ") / (" +
+                    sampleModelTranslateX + ", " + sampleModelTranslateY + ")");
+        }
+
         // we can be sure that width and height are greater than 0
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height) ||
-            scanlineStride > data.length)
+            scanlineStride > (Integer.MAX_VALUE / height))
         {
             // integer overflow
             throw new RasterFormatException("Incorrect scanline stride: "
                     + scanlineStride);
         }
+
+        if (height > 1 || minY - sampleModelTranslateY > 0) {
+            // buffer should contain at least one scanline
+            if (scanlineStride > data.length) {
+                throw new RasterFormatException("Incorrect scanline stride: "
+                        + scanlineStride);
+            }
+        }
+
         int lastScanOffset = (height - 1) * scanlineStride;
 
         if (pixelStride < 0 ||
diff --git a/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java b/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java
index 7453413..bb2a24c 100644
--- a/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java
+++ b/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java
@@ -751,6 +751,26 @@
 
                     // set or refresh local address
                     localAddress = Net.localAddress(fd);
+
+                    // flush any packets already received.
+                    boolean blocking = false;
+                    synchronized (blockingLock()) {
+                        try {
+                            blocking = isBlocking();
+                            // remainder of each packet thrown away
+                            ByteBuffer tmpBuf = ByteBuffer.allocate(1);
+                            if (blocking) {
+                                configureBlocking(false);
+                            }
+                            do {
+                                tmpBuf.clear();
+                            } while (read(tmpBuf) > 0);
+                        } finally {
+                            if (blocking) {
+                                configureBlocking(true);
+                            }
+                        }
+                    }
                 }
             }
         }
diff --git a/jdk/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java b/jdk/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java
index 6e73de7..7fa40a4 100644
--- a/jdk/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java
+++ b/jdk/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,7 +29,6 @@
 import java.lang.reflect.*;
 import java.io.Serializable;
 import java.util.*;
-import java.lang.annotation.*;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
@@ -45,6 +44,11 @@
     private final Map<String, Object> memberValues;
 
     AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) {
+        Class<?>[] superInterfaces = type.getInterfaces();
+        if (!type.isAnnotation() ||
+            superInterfaces.length != 1 ||
+            superInterfaces[0] != java.lang.annotation.Annotation.class)
+            throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type.");
         this.type = type;
         this.memberValues = memberValues;
     }
@@ -57,13 +61,17 @@
         if (member.equals("equals") && paramTypes.length == 1 &&
             paramTypes[0] == Object.class)
             return equalsImpl(args[0]);
-        assert paramTypes.length == 0;
-        if (member.equals("toString"))
+        if (paramTypes.length != 0)
+            throw new AssertionError("Too many parameters for an annotation method");
+
+        switch(member) {
+        case "toString":
             return toStringImpl();
-        if (member.equals("hashCode"))
+        case "hashCode":
             return hashCodeImpl();
-        if (member.equals("annotationType"))
+        case "annotationType":
             return type;
+        }
 
         // Handle annotation member accessors
         Object result = memberValues.get(member);
@@ -129,7 +137,7 @@
      * Implementation of dynamicProxy.toString()
      */
     private String toStringImpl() {
-        StringBuffer result = new StringBuffer(128);
+        StringBuilder result = new StringBuilder(128);
         result.append('@');
         result.append(type.getName());
         result.append('(');
@@ -277,6 +285,7 @@
                 new PrivilegedAction<Method[]>() {
                     public Method[] run() {
                         final Method[] mm = type.getDeclaredMethods();
+                        validateAnnotationMethods(mm);
                         AccessibleObject.setAccessible(mm, true);
                         return mm;
                     }
@@ -287,6 +296,93 @@
     private transient volatile Method[] memberMethods = null;
 
     /**
+     * Validates that a method is structurally appropriate for an
+     * annotation type. As of Java SE 7, annotation types cannot
+     * contain static methods and the declared methods of an
+     * annotation type must take zero arguments and there are
+     * restrictions on the return type.
+     */
+    private void validateAnnotationMethods(Method[] memberMethods) {
+        /*
+         * Specification citations below are from JLS
+         * 9.6.1. Annotation Type Elements
+         */
+        boolean valid = true;
+        for(Method method : memberMethods) {
+            /*
+             * "By virtue of the AnnotationTypeElementDeclaration
+             * production, a method declaration in an annotation type
+             * declaration cannot have formal parameters, type
+             * parameters, or a throws clause.
+             *
+             * "By virtue of the AnnotationTypeElementModifier
+             * production, a method declaration in an annotation type
+             * declaration cannot be default or static."
+             */
+            if (method.getModifiers() != (Modifier.PUBLIC | Modifier.ABSTRACT) ||
+                method.getParameterTypes().length != 0 ||
+                method.getExceptionTypes().length != 0) {
+                valid = false;
+                break;
+            }
+
+            /*
+             * "It is a compile-time error if the return type of a
+             * method declared in an annotation type is not one of the
+             * following: a primitive type, String, Class, any
+             * parameterized invocation of Class, an enum type
+             * (section 8.9), an annotation type, or an array type
+             * (chapter 10) whose element type is one of the preceding
+             * types."
+             */
+            Class<?> returnType = method.getReturnType();
+            if (returnType.isArray()) {
+                returnType = returnType.getComponentType();
+                if (returnType.isArray()) { // Only single dimensional arrays
+                    valid = false;
+                    break;
+                }
+            }
+
+            if (!((returnType.isPrimitive() && returnType != void.class) ||
+                  returnType == java.lang.String.class ||
+                  returnType == java.lang.Class.class ||
+                  returnType.isEnum() ||
+                  returnType.isAnnotation())) {
+                valid = false;
+                break;
+            }
+
+            /*
+             * "It is a compile-time error if any method declared in an
+             * annotation type has a signature that is
+             * override-equivalent to that of any public or protected
+             * method declared in class Object or in the interface
+             * java.lang.annotation.Annotation."
+             *
+             * The methods in Object or Annotation meeting the other
+             * criteria (no arguments, contrained return type, etc.)
+             * above are:
+             *
+             * String toString()
+             * int hashCode()
+             * Class<? extends Annotation> annotationType()
+             */
+            String methodName = method.getName();
+            if ((methodName.equals("toString") && returnType == java.lang.String.class) ||
+                (methodName.equals("hashCode") && returnType == int.class) ||
+                (methodName.equals("annotationType") && returnType == java.lang.Class.class)) {
+                valid = false;
+                break;
+            }
+        }
+        if (valid)
+            return;
+        else
+            throw new AnnotationFormatError("Malformed method on an annotation type");
+    }
+
+    /**
      * Implementation of dynamicProxy.hashCode()
      */
     private int hashCodeImpl() {
@@ -330,7 +426,6 @@
         throws java.io.IOException, ClassNotFoundException {
         s.defaultReadObject();
 
-
         // Check to make sure that types have not evolved incompatibly
 
         AnnotationType annotationType = null;
@@ -343,7 +438,6 @@
 
         Map<String, Class<?>> memberTypes = annotationType.memberTypes();
 
-
         // If there are annotation members without values, that
         // situation is handled by the invoke method.
         for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {
diff --git a/jdk/src/share/classes/sun/security/internal/spec/TlsRsaPremasterSecretParameterSpec.java b/jdk/src/share/classes/sun/security/internal/spec/TlsRsaPremasterSecretParameterSpec.java
index a38a7fa..0741499 100644
--- a/jdk/src/share/classes/sun/security/internal/spec/TlsRsaPremasterSecretParameterSpec.java
+++ b/jdk/src/share/classes/sun/security/internal/spec/TlsRsaPremasterSecretParameterSpec.java
@@ -26,11 +26,11 @@
 package sun.security.internal.spec;
 
 import java.security.spec.AlgorithmParameterSpec;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 
 /**
- * Parameters for SSL/TLS RSA Premaster secret generation.
- * This class is used by SSL/TLS client to initialize KeyGenerators of the
- * type "TlsRsaPremasterSecret".
+ * Parameters for SSL/TLS RSA premaster secret.
  *
  * <p>Instances of this class are immutable.
  *
@@ -43,90 +43,108 @@
 public class TlsRsaPremasterSecretParameterSpec
         implements AlgorithmParameterSpec {
 
-    private final int majorVersion;
-    private final int minorVersion;
-    private final byte[] encodedSecret;
+    /*
+     * The TLS spec says that the version in the RSA premaster secret must
+     * be the maximum version supported by the client (i.e. the version it
+     * requested in its client hello version). However, we (and other
+     * implementations) used to send the active negotiated version. The
+     * system property below allows to toggle the behavior.
+     */
+    private final static String PROP_NAME =
+                                "com.sun.net.ssl.rsaPreMasterSecretFix";
+
+    /*
+     * Default is "false" (old behavior) for compatibility reasons in
+     * SSLv3/TLSv1.  Later protocols (TLSv1.1+) do not use this property.
+     */
+    private final static boolean rsaPreMasterSecretFix =
+            AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
+                public Boolean run() {
+                    String value = System.getProperty(PROP_NAME);
+                    if (value != null && value.equalsIgnoreCase("true")) {
+                        return Boolean.TRUE;
+                    }
+
+                    return Boolean.FALSE;
+                }
+            });
+
+    private final int clientVersion;
+    private final int serverVersion;
 
     /**
      * Constructs a new TlsRsaPremasterSecretParameterSpec.
-     * <P>
-     * The version numbers will be placed inside the premaster secret to
-     * detect version rollbacks attacks as described in the TLS specification.
-     * Note that they do not indicate the protocol version negotiated for
-     * the handshake.
      *
-     * @param majorVersion the major number of the protocol version
-     * @param minorVersion the minor number of the protocol version
+     * @param clientVersion the version of the TLS protocol by which the
+     *        client wishes to communicate during this session
+     * @param serverVersion the negotiated version of the TLS protocol which
+     *        contains the lower of that suggested by the client in the client
+     *        hello and the highest supported by the server.
      *
-     * @throws IllegalArgumentException if minorVersion or majorVersion are
-     *   negative or larger than 255
+     * @throws IllegalArgumentException if clientVersion or serverVersion are
+     *   negative or larger than (2^16 - 1)
      */
-    public TlsRsaPremasterSecretParameterSpec(int majorVersion,
-            int minorVersion) {
-        this.majorVersion =
-            TlsMasterSecretParameterSpec.checkVersion(majorVersion);
-        this.minorVersion =
-            TlsMasterSecretParameterSpec.checkVersion(minorVersion);
-        this.encodedSecret = null;
+    public TlsRsaPremasterSecretParameterSpec(
+            int clientVersion, int serverVersion) {
+
+        this.clientVersion = checkVersion(clientVersion);
+        this.serverVersion = checkVersion(serverVersion);
     }
 
     /**
-     * Constructs a new TlsRsaPremasterSecretParameterSpec.
-     * <P>
-     * The version numbers will be placed inside the premaster secret to
-     * detect version rollbacks attacks as described in the TLS specification.
-     * Note that they do not indicate the protocol version negotiated for
-     * the handshake.
-     * <P>
-     * Usually, the encoded secret key is a random number that acts as
-     * dummy pre_master_secret to avoid vulnerabilities described by
-     * section 7.4.7.1, RFC 5246.
+     * Returns the version of the TLS protocol by which the client wishes to
+     * communicate during this session.
      *
-     * @param majorVersion the major number of the protocol version
-     * @param minorVersion the minor number of the protocol version
-     * @param encodedSecret the encoded secret key
-     *
-     * @throws IllegalArgumentException if minorVersion or majorVersion are
-     *   negative or larger than 255, or encodedSecret is not exactly 48 bytes.
+     * @return the version of the TLS protocol in ClientHello message
      */
-    public TlsRsaPremasterSecretParameterSpec(int majorVersion,
-            int minorVersion, byte[] encodedSecret) {
-        this.majorVersion =
-            TlsMasterSecretParameterSpec.checkVersion(majorVersion);
-        this.minorVersion =
-            TlsMasterSecretParameterSpec.checkVersion(minorVersion);
-
-        if (encodedSecret == null || encodedSecret.length != 48) {
-            throw new IllegalArgumentException(
-                        "Encoded secret is not exactly 48 bytes");
-        }
-        this.encodedSecret = encodedSecret.clone();
+    public int getClientVersion() {
+        return clientVersion;
     }
 
     /**
-     * Returns the major version.
+     * Returns the negotiated version of the TLS protocol which contains the
+     * lower of that suggested by the client in the client hello and the
+     * highest supported by the server.
      *
-     * @return the major version.
+     * @return the negotiated version of the TLS protocol in ServerHello message
+     */
+    public int getServerVersion() {
+        return serverVersion;
+    }
+
+    /**
+     * Returns the major version used in RSA premaster secret.
+     *
+     * @return the major version used in RSA premaster secret.
      */
     public int getMajorVersion() {
-        return majorVersion;
+        if (rsaPreMasterSecretFix || clientVersion >= 0x0302) {
+                                                        // 0x0302: TLSv1.1
+            return (clientVersion >>> 8) & 0xFF;
+        }
+
+        return (serverVersion >>> 8) & 0xFF;
     }
 
     /**
-     * Returns the minor version.
+     * Returns the minor version used in RSA premaster secret.
      *
-     * @return the minor version.
+     * @return the minor version used in RSA premaster secret.
      */
     public int getMinorVersion() {
-        return minorVersion;
+        if (rsaPreMasterSecretFix || clientVersion >= 0x0302) {
+                                                        // 0x0302: TLSv1.1
+            return clientVersion & 0xFF;
+        }
+
+        return serverVersion & 0xFF;
     }
 
-    /**
-     * Returns the encoded secret.
-     *
-     * @return the encoded secret, may be null if no encoded secret.
-     */
-    public byte[] getEncodedSecret() {
-        return encodedSecret == null ? null : encodedSecret.clone();
+    private int checkVersion(int version) {
+        if ((version < 0) || (version > 0xFFFF)) {
+            throw new IllegalArgumentException(
+                        "Version must be between 0 and 65,535");
+        }
+        return version;
     }
 }
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
index e2ff0fc..253b891 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
@@ -37,6 +37,8 @@
 import static sun.security.pkcs11.TemplateManager.*;
 import sun.security.pkcs11.wrapper.*;
 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
+import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
+import sun.security.util.KeyUtil;
 
 /**
  * RSA Cipher implementation class. We currently only support
@@ -102,6 +104,12 @@
     // maximum output size. this is the length of the key
     private int outputSize;
 
+    // cipher parameter for TLS RSA premaster secret
+    private AlgorithmParameterSpec spec = null;
+
+    // the source of randomness
+    private SecureRandom random;
+
     P11RSACipher(Token token, String algorithm, long mechanism)
             throws PKCS11Exception {
         super();
@@ -165,8 +173,12 @@
             AlgorithmParameterSpec params, SecureRandom random)
             throws InvalidKeyException, InvalidAlgorithmParameterException {
         if (params != null) {
-            throw new InvalidAlgorithmParameterException
-                ("Parameters not supported");
+            if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
+                throw new InvalidAlgorithmParameterException(
+                        "Parameters not supported");
+            }
+            spec = params;
+            this.random = random;   // for TLS RSA premaster secret
         }
         implInit(opmode, key);
     }
@@ -176,8 +188,8 @@
             SecureRandom random)
             throws InvalidKeyException, InvalidAlgorithmParameterException {
         if (params != null) {
-            throw new InvalidAlgorithmParameterException
-                ("Parameters not supported");
+            throw new InvalidAlgorithmParameterException(
+                        "Parameters not supported");
         }
         implInit(opmode, key);
     }
@@ -452,21 +464,101 @@
     protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
             int type) throws InvalidKeyException, NoSuchAlgorithmException {
 
-        // XXX implement unwrap using C_Unwrap() for all keys
-        implInit(Cipher.DECRYPT_MODE, p11Key);
-        if (wrappedKey.length > maxInputSize) {
-            throw new InvalidKeyException("Key is too long for unwrapping");
+        boolean isTlsRsaPremasterSecret =
+                algorithm.equals("TlsRsaPremasterSecret");
+        Exception failover = null;
+
+        SecureRandom secureRandom = random;
+        if (secureRandom == null && isTlsRsaPremasterSecret) {
+            secureRandom = new SecureRandom();
         }
-        implUpdate(wrappedKey, 0, wrappedKey.length);
-        try {
-            byte[] encoded = doFinal();
+
+        // Should C_Unwrap be preferred for non-TLS RSA premaster secret?
+        if (token.supportsRawSecretKeyImport()) {
+            // XXX implement unwrap using C_Unwrap() for all keys
+            implInit(Cipher.DECRYPT_MODE, p11Key);
+            if (wrappedKey.length > maxInputSize) {
+                throw new InvalidKeyException("Key is too long for unwrapping");
+            }
+
+            byte[] encoded = null;
+            implUpdate(wrappedKey, 0, wrappedKey.length);
+            try {
+                encoded = doFinal();
+            } catch (BadPaddingException e) {
+                if (isTlsRsaPremasterSecret) {
+                    failover = e;
+                } else {
+                    throw new InvalidKeyException("Unwrapping failed", e);
+                }
+            } catch (IllegalBlockSizeException e) {
+                // should not occur, handled with length check above
+                throw new InvalidKeyException("Unwrapping failed", e);
+            }
+
+            if (isTlsRsaPremasterSecret) {
+                if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
+                    throw new IllegalStateException(
+                            "No TlsRsaPremasterSecretParameterSpec specified");
+                }
+
+                // polish the TLS premaster secret
+                TlsRsaPremasterSecretParameterSpec psps =
+                        (TlsRsaPremasterSecretParameterSpec)spec;
+                encoded = KeyUtil.checkTlsPreMasterSecretKey(
+                        psps.getClientVersion(), psps.getServerVersion(),
+                        secureRandom, encoded, (failover != null));
+            }
+
             return ConstructKeys.constructKey(encoded, algorithm, type);
-        } catch (BadPaddingException e) {
-            // should not occur
-            throw new InvalidKeyException("Unwrapping failed", e);
-        } catch (IllegalBlockSizeException e) {
-            // should not occur, handled with length check above
-            throw new InvalidKeyException("Unwrapping failed", e);
+        } else {
+            Session s = null;
+            SecretKey secretKey = null;
+            try {
+                try {
+                    s = token.getObjSession();
+                    long keyType = CKK_GENERIC_SECRET;
+                    CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] {
+                            new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
+                            new CK_ATTRIBUTE(CKA_KEY_TYPE, keyType),
+                        };
+                    attributes = token.getAttributes(
+                            O_IMPORT, CKO_SECRET_KEY, keyType, attributes);
+                    long keyID = token.p11.C_UnwrapKey(s.id(),
+                            new CK_MECHANISM(mechanism), p11Key.keyID,
+                            wrappedKey, attributes);
+                    secretKey = P11Key.secretKey(s, keyID,
+                            algorithm, 48 << 3, attributes);
+                } catch (PKCS11Exception e) {
+                    if (isTlsRsaPremasterSecret) {
+                        failover = e;
+                    } else {
+                        throw new InvalidKeyException("unwrap() failed", e);
+                    }
+                }
+
+                if (isTlsRsaPremasterSecret) {
+                    byte[] replacer = new byte[48];
+                    if (failover == null) {
+                        // Does smart compiler dispose this operation?
+                        secureRandom.nextBytes(replacer);
+                    }
+
+                    TlsRsaPremasterSecretParameterSpec psps =
+                            (TlsRsaPremasterSecretParameterSpec)spec;
+
+                    // Please use the tricky failover and replacer byte array
+                    // as the parameters so that smart compiler won't dispose
+                    // the unused variable .
+                    secretKey = polishPreMasterSecretKey(token, s,
+                            failover, replacer, secretKey,
+                            psps.getClientVersion(), psps.getServerVersion());
+                }
+
+                return secretKey;
+            } finally {
+                token.releaseSession(s);
+            }
         }
     }
 
@@ -475,6 +567,34 @@
         int n = P11KeyFactory.convertKey(token, key, algorithm).length();
         return n;
     }
+
+    private static SecretKey polishPreMasterSecretKey(
+            Token token, Session session,
+            Exception failover, byte[] replacer, SecretKey secretKey,
+            int clientVersion, int serverVersion) {
+
+        if (failover != null) {
+            CK_VERSION version = new CK_VERSION(
+                    (clientVersion >>> 8) & 0xFF, clientVersion & 0xFF);
+            try {
+                CK_ATTRIBUTE[] attributes = token.getAttributes(
+                        O_GENERATE, CKO_SECRET_KEY,
+                        CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
+                long keyID = token.p11.C_GenerateKey(session.id(),
+                    // new CK_MECHANISM(CKM_TLS_PRE_MASTER_KEY_GEN, version),
+                        new CK_MECHANISM(CKM_SSL3_PRE_MASTER_KEY_GEN, version),
+                        attributes);
+                return P11Key.secretKey(session,
+                        keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
+            } catch (PKCS11Exception e) {
+                throw new ProviderException(
+                        "Could not generate premaster secret", e);
+            }
+        }
+
+        return secretKey;
+    }
+
 }
 
 final class ConstructKeys {
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java b/jdk/src/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java
index ff9b183..21c8537 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java
@@ -73,7 +73,7 @@
 
     protected void engineInit(AlgorithmParameterSpec params,
             SecureRandom random) throws InvalidAlgorithmParameterException {
-        if (params instanceof TlsRsaPremasterSecretParameterSpec == false) {
+        if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
             throw new InvalidAlgorithmParameterException(MSG);
         }
         this.spec = (TlsRsaPremasterSecretParameterSpec)params;
@@ -83,38 +83,32 @@
         throw new InvalidParameterException(MSG);
     }
 
+    // Only can be used in client side to generate TLS RSA premaster secret.
     protected SecretKey engineGenerateKey() {
         if (spec == null) {
             throw new IllegalStateException
                         ("TlsRsaPremasterSecretGenerator must be initialized");
         }
 
-        byte[] b = spec.getEncodedSecret();
-        if (b == null) {
-            CK_VERSION version = new CK_VERSION(
+        CK_VERSION version = new CK_VERSION(
                         spec.getMajorVersion(), spec.getMinorVersion());
-            Session session = null;
-            try {
-                session = token.getObjSession();
-                CK_ATTRIBUTE[] attributes = token.getAttributes(
-                        O_GENERATE, CKO_SECRET_KEY,
-                        CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
-                long keyID = token.p11.C_GenerateKey(session.id(),
-                        new CK_MECHANISM(mechanism, version), attributes);
-                SecretKey key = P11Key.secretKey(session,
-                        keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
-                return key;
-            } catch (PKCS11Exception e) {
-                throw new ProviderException(
-                        "Could not generate premaster secret", e);
-            } finally {
-                token.releaseSession(session);
-            }
+        Session session = null;
+        try {
+            session = token.getObjSession();
+            CK_ATTRIBUTE[] attributes = token.getAttributes(
+                    O_GENERATE, CKO_SECRET_KEY,
+                    CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
+            long keyID = token.p11.C_GenerateKey(session.id(),
+                    new CK_MECHANISM(mechanism, version), attributes);
+            SecretKey key = P11Key.secretKey(session,
+                    keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
+            return key;
+        } catch (PKCS11Exception e) {
+            throw new ProviderException(
+                    "Could not generate premaster secret", e);
+        } finally {
+            token.releaseSession(session);
         }
-
-        // Won't worry, the TlsRsaPremasterSecret will be soon converted to
-        // TlsMasterSecret.
-        return new SecretKeySpec(b, "TlsRsaPremasterSecret");
     }
 
 }
diff --git a/jdk/src/share/classes/sun/security/pkcs11/Token.java b/jdk/src/share/classes/sun/security/pkcs11/Token.java
index f19f8b7..1d427c3 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/Token.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/Token.java
@@ -35,6 +35,7 @@
 import sun.security.jca.JCAUtil;
 
 import sun.security.pkcs11.wrapper.*;
+import static sun.security.pkcs11.TemplateManager.*;
 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
 
 /**
@@ -121,6 +122,9 @@
     private final static CK_MECHANISM_INFO INVALID_MECH =
         new CK_MECHANISM_INFO(0, 0, 0);
 
+    // flag indicating whether the token supports raw secret key material import
+    private Boolean supportsRawSecretKeyImport;
+
     Token(SunPKCS11 provider) throws PKCS11Exception {
         this.provider = provider;
         this.removable = provider.removable;
@@ -159,6 +163,36 @@
         return writeProtected;
     }
 
+    // return whether the token supports raw secret key material import
+    boolean supportsRawSecretKeyImport() {
+        if (supportsRawSecretKeyImport == null) {
+            SecureRandom random = JCAUtil.getSecureRandom();
+            byte[] encoded = new byte[48];
+            random.nextBytes(encoded);
+
+            CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[3];
+            attributes[0] = new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);
+            attributes[1] = new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_GENERIC_SECRET);
+            attributes[2] = new CK_ATTRIBUTE(CKA_VALUE, encoded);
+
+            Session session = null;
+            try {
+                attributes = getAttributes(O_IMPORT,
+                        CKO_SECRET_KEY, CKK_GENERIC_SECRET, attributes);
+                session = getObjSession();
+                long keyID = p11.C_CreateObject(session.id(), attributes);
+
+                supportsRawSecretKeyImport = Boolean.TRUE;
+            } catch (PKCS11Exception e) {
+                supportsRawSecretKeyImport = Boolean.FALSE;
+            } finally {
+                releaseSession(session);
+            }
+        }
+
+        return supportsRawSecretKeyImport;
+    }
+
     // return whether we are logged in
     // uses cached result if current. session is optional and may be null
     boolean isLoggedIn(Session session) throws PKCS11Exception {
diff --git a/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java b/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java
index 0c1022b..fb12f2f 100644
--- a/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java
+++ b/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,6 +36,8 @@
 
 import java.security.cert.X509Certificate;
 import java.security.cert.CertificateException;
+import java.security.cert.CertificateParsingException;
+import javax.security.auth.x500.X500Principal;
 
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
@@ -93,6 +95,60 @@
             Debug.getBooleanProperty("jsse.enableSNIExtension", true);
 
     /*
+     * Allow unsafe server certificate change?
+     *
+     * Server certificate change during SSL/TLS renegotiation may be considered
+     * unsafe, as described in the Triple Handshake attacks:
+     *
+     *    https://secure-resumption.com/tlsauth.pdf
+     *
+     * Endpoint identification (See
+     * SSLParameters.getEndpointIdentificationAlgorithm()) is a pretty nice
+     * guarantee that the server certificate change in the renegotiation is legal.
+     * However, endpoint identification is only enabled for HTTPS and LDAP
+     * over SSL/TLS by default. It is not enough to protect SSL/TLS
+     * connections other than HTTPS and LDAP.
+     *
+     * The renegotiation indication extension (See RFC 5764) is a pretty
+     * strong guarantee that the endpoints on both client and server sides
+     * are identical on the same connection. However, the Triple Handshake
+     * attacks can bypass this guarantee if there is a session-resumption
+     * handshake between the initial full handshake and the renegotiation
+     * full handshake.
+     *
+     * Server certificate change may be unsafe and should be restricted if
+     * endpoint identification is not enabled and the previous handshake is
+     * a session-resumption abbreviated initial handshake, unless the
+     * identities reproesented by both certificates can be regraded as the
+     * same (See isIdentityEquivalent()).
+     *
+     * Considering the compatibility impact and the actual requirements to
+     * support server certificate change in practice, the system property,
+     * jdk.tls.allowUnsafeServerCertChange, is used to define whether unsafe
+     * server certificate change in renegotiation is allowed or not. The
+     * default value of the system property is "false". To mitigate the
+     * compatibility impact, applications may want to set the system
+     * property to "true" at their own risk.
+     *
+     * If the value of the system property is "false", server certificate
+     * change in renegotiation after a session-resumption abbreviated initial
+     * handshake is restricted (See isIdentityEuivalent()).
+     *
+     * If the system property is set to "truie" explicitly, the restriction on
+     * server certificate change in renegotiation is disabled.
+     */
+    private final static boolean allowUnsafeServerCertChange =
+        Debug.getBooleanProperty("jdk.tls.allowUnsafeServerCertChange", false);
+
+    /*
+     * the reserved server certificate chain in previous handshaking
+     *
+     * The server certificate chain is only reserved if the previous
+     * handshake is a session-resumption abbreviated initial handshake.
+     */
+    private X509Certificate[] reservedServerCerts = null;
+
+    /*
      * Constructors
      */
     ClientHandshaker(SSLSocketImpl socket, SSLContextImpl context,
@@ -551,8 +607,7 @@
                 // we wanted to resume, but the server refused
                 session = null;
                 if (!enableNewSession) {
-                    throw new SSLException
-                        ("New session creation is disabled");
+                    throw new SSLException("New session creation is disabled");
                 }
             }
         }
@@ -563,6 +618,11 @@
             }
 
             setHandshakeSessionSE(session);
+            // Reserve the handshake state if this is a session-resumption
+            // abbreviated initial handshake.
+            if (isInitialHandshake) {
+                session.setAsSessionResumption(true);
+            }
             return;
         }
 
@@ -1035,6 +1095,13 @@
         }
 
         /*
+         * Reset the handshake state if this is not an initial handshake.
+         */
+        if (!isInitialHandshake) {
+            session.setAsSessionResumption(false);
+        }
+
+        /*
          * OK, it verified.  If we're doing the fast handshake, add that
          * "Finished" message to the hash of handshake messages, then send
          * our own change_cipher_spec and Finished message for the server
@@ -1131,8 +1198,22 @@
                 System.out.println("%% No cached client session");
             }
         }
-        if ((session != null) && (session.isRejoinable() == false)) {
-            session = null;
+        if (session != null) {
+            // If unsafe server certificate change is not allowed, reserve
+            // current server certificates if the preious handshake is a
+            // session-resumption abbreviated initial handshake.
+            if (!allowUnsafeServerCertChange && session.isSessionResumption()) {
+                try {
+                    // If existing, peer certificate chain cannot be null.
+                    reservedServerCerts =
+                        (X509Certificate[])session.getPeerCertificates();
+                } catch (SSLPeerUnverifiedException puve) {
+                    // Maybe not certificate-based, ignore the exception.
+                }
+            }
+            if (!session.isRejoinable()) {
+                session = null;
+            }
         }
 
         if (session != null) {
@@ -1303,8 +1384,25 @@
         }
         X509Certificate[] peerCerts = mesg.getCertificateChain();
         if (peerCerts.length == 0) {
-            fatalSE(Alerts.alert_bad_certificate,
-                "empty certificate chain");
+            fatalSE(Alerts.alert_bad_certificate, "empty certificate chain");
+        }
+
+        // Allow server certificate change in client side during renegotiation
+        // after session-resumption abbreviated initial handshake ?
+        //
+        // DO NOT need to check allowUnsafeServerCertChange here. We only
+        // reserve server certificates when allowUnsafeServerCertChange is
+        // false.
+        if (reservedServerCerts != null) {
+            // It is not necessary to check the certificate update if endpoint
+            // identification is enabled.
+            String identityAlg = getEndpointIdentificationAlgorithmSE();
+            if ((identityAlg == null || identityAlg.length() == 0) &&
+                !isIdentityEquivalent(peerCerts[0], reservedServerCerts[0])) {
+                fatalSE(Alerts.alert_bad_certificate,
+                        "server certificate change is restricted" +
+                        "during renegotiation");
+            }
         }
         // ask the trust manager to verify the chain
         X509TrustManager tm = sslContext.getX509TrustManager();
@@ -1342,4 +1440,82 @@
         }
         session.setPeerCertificates(peerCerts);
     }
+
+    /*
+     * Whether the certificates can represent the same identity?
+     *
+     * The certificates can be used to represent the same identity:
+     *     1. If the subject alternative names of IP address are present in
+     *        both certificates, they should be identical; otherwise,
+     *     2. if the subject alternative names of DNS name are present in
+     *        both certificates, they should be identical; otherwise,
+     *     3. if the subject fields are present in both certificates, the
+     *        certificate subjects and issuers should be identical.
+     */
+
+    private static boolean isIdentityEquivalent(X509Certificate thisCert,
+            X509Certificate prevCert) {
+        if (thisCert.equals(prevCert)) {
+            return true;
+        }
+
+        // check the iPAddress field in subjectAltName extension
+        Object thisIPAddress = getSubjectAltName(thisCert, 7);  // 7: iPAddress
+        Object prevIPAddress = getSubjectAltName(prevCert, 7);
+        if (thisIPAddress != null && prevIPAddress!= null) {
+            // only allow the exactly match
+            return Objects.equals(thisIPAddress, prevIPAddress);
+        }
+
+        // check the dNSName field in subjectAltName extension
+        Object thisDNSName = getSubjectAltName(thisCert, 2);    // 2: dNSName
+        Object prevDNSName = getSubjectAltName(prevCert, 2);
+        if (thisDNSName != null && prevDNSName!= null) {
+            // only allow the exactly match
+            return Objects.equals(thisDNSName, prevDNSName);
+        }
+
+        // check the certificate subject and issuer
+        X500Principal thisSubject = thisCert.getSubjectX500Principal();
+        X500Principal prevSubject = prevCert.getSubjectX500Principal();
+        X500Principal thisIssuer = thisCert.getIssuerX500Principal();
+        X500Principal prevIssuer = prevCert.getIssuerX500Principal();
+        if (!thisSubject.getName().isEmpty() &&
+                !prevSubject.getName().isEmpty() &&
+                thisSubject.equals(prevSubject) &&
+                thisIssuer.equals(prevIssuer)) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /*
+     * Returns the subject alternative name of the specified type in the
+     * subjectAltNames extension of a certificate.
+     */
+    private static Object getSubjectAltName(X509Certificate cert, int type) {
+        Collection<List<?>> subjectAltNames;
+
+        try {
+            subjectAltNames = cert.getSubjectAlternativeNames();
+        } catch (CertificateParsingException cpe) {
+            if (debug != null && Debug.isOn("handshake")) {
+                System.out.println(
+                        "Attempt to obtain subjectAltNames extension failed!");
+            }
+            return null;
+        }
+
+        if (subjectAltNames != null) {
+            for (List<?> subjectAltName : subjectAltNames) {
+                int subjectAltNameType = (Integer)subjectAltName.get(0);
+                if (subjectAltNameType == type) {
+                    return subjectAltName.get(1);
+                }
+            }
+        }
+
+        return null;
+    }
 }
diff --git a/jdk/src/share/classes/sun/security/ssl/Handshaker.java b/jdk/src/share/classes/sun/security/ssl/Handshaker.java
index e2e1775..c0343f6 100644
--- a/jdk/src/share/classes/sun/security/ssl/Handshaker.java
+++ b/jdk/src/share/classes/sun/security/ssl/Handshaker.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -348,6 +348,16 @@
         }
     }
 
+    String getEndpointIdentificationAlgorithmSE() {
+        SSLParameters paras;
+        if (conn != null) {
+            paras = conn.getSSLParameters();
+        } else {
+            paras = engine.getSSLParameters();
+        }
+        return paras.getEndpointIdentificationAlgorithm();
+    }
+
     private void setVersionSE(ProtocolVersion protocolVersion) {
         if (conn != null) {
             conn.setVersion(protocolVersion);
diff --git a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
index 250146f..ffe1be4 100644
--- a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
+++ b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
@@ -50,23 +50,6 @@
  */
 final class RSAClientKeyExchange extends HandshakeMessage {
 
-    /**
-     * The TLS spec says that the version in the RSA premaster secret must
-     * be the maximum version supported by the client (i.e. the version it
-     * requested in its client hello version). However, we (and other
-     * implementations) used to send the active negotiated version. The
-     * system property below allows to toggle the behavior.
-     */
-    private final static String PROP_NAME =
-                                "com.sun.net.ssl.rsaPreMasterSecretFix";
-
-    /*
-     * Default is "false" (old behavior) for compatibility reasons in
-     * SSLv3/TLSv1.  Later protocols (TLSv1.1+) do not use this property.
-     */
-    private final static boolean rsaPreMasterSecretFix =
-                                Debug.getBooleanProperty(PROP_NAME, false);
-
     /*
      * The following field values were encrypted with the server's public
      * key (or temp key from server key exchange msg) and are presented
@@ -90,22 +73,12 @@
         }
         this.protocolVersion = protocolVersion;
 
-        int major, minor;
-
-        if (rsaPreMasterSecretFix || maxVersion.v >= ProtocolVersion.TLS11.v) {
-            major = maxVersion.major;
-            minor = maxVersion.minor;
-        } else {
-            major = protocolVersion.major;
-            minor = protocolVersion.minor;
-        }
-
         try {
             String s = ((protocolVersion.v >= ProtocolVersion.TLS12.v) ?
                 "SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
             KeyGenerator kg = JsseJce.getKeyGenerator(s);
-            kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor),
-                    generator);
+            kg.init(new TlsRsaPremasterSecretParameterSpec(
+                    maxVersion.v, protocolVersion.v), generator);
             preMaster = kg.generateKey();
 
             Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
@@ -140,18 +113,17 @@
             }
         }
 
-        Exception failover = null;
-        byte[] encoded = null;
         try {
             Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
             // Cannot generate key here, please don't use Cipher.UNWRAP_MODE!
-            cipher.init(Cipher.DECRYPT_MODE, privateKey);
-            encoded = cipher.doFinal(encrypted);
-        } catch (BadPaddingException bpe) {
-            failover = bpe;
-            encoded = null;
-        } catch (IllegalBlockSizeException ibse) {
-            // the message it too big to process with RSA
+            cipher.init(Cipher.UNWRAP_MODE, privateKey,
+                    new TlsRsaPremasterSecretParameterSpec(
+                            maxVersion.v, currentVersion.v),
+                    generator);
+            preMaster = (SecretKey)cipher.unwrap(encrypted,
+                                "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
+        } catch (InvalidKeyException ibk) {
+            // the message is too big to process with RSA
             throw new SSLProtocolException(
                 "Unable to process PreMasterSecret, may be too big");
         } catch (Exception e) {
@@ -162,124 +134,6 @@
             }
             throw new RuntimeException("Could not generate dummy secret", e);
         }
-
-        // polish the premaster secret
-        preMaster = polishPreMasterSecretKey(
-                    currentVersion, maxVersion, generator, encoded, failover);
-    }
-
-    /**
-     * To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
-     * treating incorrectly formatted message blocks and/or mismatched
-     * version numbers in a manner indistinguishable from correctly
-     * formatted RSA blocks.
-     *
-     * RFC 5246 describes the approach as :
-     *
-     *  1. Generate a string R of 48 random bytes
-     *
-     *  2. Decrypt the message to recover the plaintext M
-     *
-     *  3. If the PKCS#1 padding is not correct, or the length of message
-     *     M is not exactly 48 bytes:
-     *        pre_master_secret = R
-     *     else If ClientHello.client_version <= TLS 1.0, and version
-     *     number check is explicitly disabled:
-     *        premaster secret = M
-     *     else If M[0..1] != ClientHello.client_version:
-     *        premaster secret = R
-     *     else:
-     *        premaster secret = M
-     *
-     * Note that #2 has completed before the call of this method.
-     */
-    private SecretKey polishPreMasterSecretKey(ProtocolVersion currentVersion,
-            ProtocolVersion clientHelloVersion, SecureRandom generator,
-            byte[] encoded, Exception failoverException) {
-
-        this.protocolVersion = clientHelloVersion;
-        if (generator == null) {
-            generator = new SecureRandom();
-        }
-        byte[] random = new byte[48];
-        generator.nextBytes(random);
-
-        if (failoverException == null && encoded != null) {
-            // check the length
-            if (encoded.length != 48) {
-                if (debug != null && Debug.isOn("handshake")) {
-                    System.out.println(
-                        "incorrect length of premaster secret: " +
-                        encoded.length);
-                }
-
-                return generatePreMasterSecret(
-                        clientHelloVersion, random, generator);
-            }
-
-            if (clientHelloVersion.major != encoded[0] ||
-                        clientHelloVersion.minor != encoded[1]) {
-
-                if (clientHelloVersion.v <= ProtocolVersion.TLS10.v &&
-                       currentVersion.major == encoded[0] &&
-                       currentVersion.minor == encoded[1]) {
-                    /*
-                     * For compatibility, we maintain the behavior that the
-                     * version in pre_master_secret can be the negotiated
-                     * version for TLS v1.0 and SSL v3.0.
-                     */
-                    this.protocolVersion = currentVersion;
-                } else {
-                    if (debug != null && Debug.isOn("handshake")) {
-                        System.out.println("Mismatching Protocol Versions, " +
-                            "ClientHello.client_version is " +
-                            clientHelloVersion +
-                            ", while PreMasterSecret.client_version is " +
-                            ProtocolVersion.valueOf(encoded[0], encoded[1]));
-                    }
-
-                    encoded = random;
-                }
-            }
-
-            return generatePreMasterSecret(
-                    clientHelloVersion, encoded, generator);
-        }
-
-        if (debug != null && Debug.isOn("handshake") &&
-                    failoverException != null) {
-            System.out.println("Error decrypting premaster secret:");
-            failoverException.printStackTrace(System.out);
-        }
-
-        return generatePreMasterSecret(clientHelloVersion, random, generator);
-    }
-
-    // generate a premaster secret with the specified version number
-    private static SecretKey generatePreMasterSecret(
-            ProtocolVersion version, byte[] encodedSecret,
-            SecureRandom generator) {
-
-        if (debug != null && Debug.isOn("handshake")) {
-            System.out.println("Generating a random fake premaster secret");
-        }
-
-        try {
-            String s = ((version.v >= ProtocolVersion.TLS12.v) ?
-                "SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
-            KeyGenerator kg = JsseJce.getKeyGenerator(s);
-            kg.init(new TlsRsaPremasterSecretParameterSpec(
-                    version.major, version.minor, encodedSecret), generator);
-            return kg.generateKey();
-        } catch (InvalidAlgorithmParameterException |
-                NoSuchAlgorithmException iae) {
-            // unlikely to happen, otherwise, must be a provider exception
-            if (debug != null && Debug.isOn("handshake")) {
-                System.out.println("RSA premaster secret generation error:");
-                iae.printStackTrace(System.out);
-            }
-            throw new RuntimeException("Could not generate dummy secret", iae);
-        }
     }
 
     @Override
diff --git a/jdk/src/share/classes/sun/security/ssl/SSLSessionImpl.java b/jdk/src/share/classes/sun/security/ssl/SSLSessionImpl.java
index 110fc9c..8ed2c28 100644
--- a/jdk/src/share/classes/sun/security/ssl/SSLSessionImpl.java
+++ b/jdk/src/share/classes/sun/security/ssl/SSLSessionImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -117,6 +117,14 @@
     private Principal localPrincipal;
 
     /*
+     * Is the session currently re-established with a session-resumption
+     * abbreviated initial handshake?
+     *
+     * Note that currently we only set this variable in client side.
+     */
+    private boolean isSessionResumption = false;
+
+    /*
      * We count session creations, eventually for statistical data but
      * also since counters make shorter debugging IDs than the big ones
      * we use in the protocol for uniqueness-over-time.
@@ -320,6 +328,22 @@
     }
 
     /**
+     * Return true if the session is currently re-established with a
+     * session-resumption abreviated initial handshake.
+     */
+    boolean isSessionResumption() {
+        return isSessionResumption;
+    }
+
+    /**
+     * Resets whether the session is re-established with a session-resumption
+     * abbreviated initial handshake.
+     */
+    void setAsSessionResumption(boolean flag) {
+        isSessionResumption = flag;
+    }
+
+    /**
      * Returns the name of the cipher suite in use on this session
      */
     public String getCipherSuite() {
diff --git a/jdk/src/share/classes/sun/security/util/KeyUtil.java b/jdk/src/share/classes/sun/security/util/KeyUtil.java
index df7055a..661e3b9 100644
--- a/jdk/src/share/classes/sun/security/util/KeyUtil.java
+++ b/jdk/src/share/classes/sun/security/util/KeyUtil.java
@@ -32,6 +32,7 @@
 import java.security.interfaces.ECKey;
 import java.security.interfaces.RSAKey;
 import java.security.interfaces.DSAKey;
+import java.security.SecureRandom;
 import java.security.spec.KeySpec;
 import javax.crypto.SecretKey;
 import javax.crypto.interfaces.DHKey;
@@ -157,6 +158,79 @@
     }
 
     /**
+     * Check the format of TLS PreMasterSecret.
+     * <P>
+     * To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
+     * treating incorrectly formatted message blocks and/or mismatched
+     * version numbers in a manner indistinguishable from correctly
+     * formatted RSA blocks.
+     *
+     * RFC 5246 describes the approach as :
+     *
+     *  1. Generate a string R of 48 random bytes
+     *
+     *  2. Decrypt the message to recover the plaintext M
+     *
+     *  3. If the PKCS#1 padding is not correct, or the length of message
+     *     M is not exactly 48 bytes:
+     *        pre_master_secret = R
+     *     else If ClientHello.client_version <= TLS 1.0, and version
+     *     number check is explicitly disabled:
+     *        premaster secret = M
+     *     else If M[0..1] != ClientHello.client_version:
+     *        premaster secret = R
+     *     else:
+     *        premaster secret = M
+     *
+     * Note that #2 should have completed before the call to this method.
+     *
+     * @param  clientVersion the version of the TLS protocol by which the
+     *         client wishes to communicate during this session
+     * @param  serverVersion the negotiated version of the TLS protocol which
+     *         contains the lower of that suggested by the client in the client
+     *         hello and the highest supported by the server.
+     * @param  encoded the encoded key in its "RAW" encoding format
+     * @param  isFailover whether or not the previous decryption of the
+     *         encrypted PreMasterSecret message run into problem
+     * @return the polished PreMasterSecret key in its "RAW" encoding format
+     */
+    public static byte[] checkTlsPreMasterSecretKey(
+            int clientVersion, int serverVersion, SecureRandom random,
+            byte[] encoded, boolean isFailOver) {
+
+        if (random == null) {
+            random = new SecureRandom();
+        }
+        byte[] replacer = new byte[48];
+        random.nextBytes(replacer);
+
+        if (!isFailOver && (encoded != null)) {
+            // check the length
+            if (encoded.length != 48) {
+                // private, don't need to clone the byte array.
+                return replacer;
+            }
+
+            int encodedVersion =
+                    ((encoded[0] & 0xFF) << 8) | (encoded[1] & 0xFF);
+            if (clientVersion != encodedVersion) {
+                if (clientVersion > 0x0301 ||               // 0x0301: TLSv1
+                       serverVersion != encodedVersion) {
+                    encoded = replacer;
+                }   // Otherwise, For compatibility, we maintain the behavior
+                    // that the version in pre_master_secret can be the
+                    // negotiated version for TLS v1.0 and SSL v3.0.
+            }
+
+            // private, don't need to clone the byte array.
+            return encoded;
+        }
+
+        // private, don't need to clone the byte array.
+        return replacer;
+    }
+
+    /**
      * Returns whether the Diffie-Hellman public key is valid or not.
      *
      * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
diff --git a/jdk/src/share/classes/sun/util/locale/BaseLocale.java b/jdk/src/share/classes/sun/util/locale/BaseLocale.java
index 6eee582..e0e9ed0 100644
--- a/jdk/src/share/classes/sun/util/locale/BaseLocale.java
+++ b/jdk/src/share/classes/sun/util/locale/BaseLocale.java
@@ -31,6 +31,7 @@
  */
 
 package sun.util.locale;
+import java.lang.ref.SoftReference;
 
 
 public final class BaseLocale {
@@ -163,11 +164,11 @@
         return h;
     }
 
-    private static final class Key implements Comparable<Key> {
-        private final String lang;
-        private final String scrt;
-        private final String regn;
-        private final String vart;
+    private static final class Key {
+        private final SoftReference<String> lang;
+        private final SoftReference<String> scrt;
+        private final SoftReference<String> regn;
+        private final SoftReference<String> vart;
         private final boolean normalized;
         private final int hash;
 
@@ -179,10 +180,10 @@
             assert language.intern() == language
                    && region.intern() == region;
 
-            lang = language;
-            scrt = "";
-            regn = region;
-            vart = "";
+            lang = new SoftReference(language);
+            scrt = new SoftReference("");
+            regn = new SoftReference(region);
+            vart = new SoftReference("");
             this.normalized = true;
 
             int h = language.hashCode();
@@ -203,40 +204,40 @@
                     String variant, boolean normalized) {
             int h = 0;
             if (language != null) {
-                lang = language;
+                lang = new SoftReference(language);
                 int len = language.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + LocaleUtils.toLower(language.charAt(i));
                 }
             } else {
-                lang = "";
+                lang = new SoftReference("");
             }
             if (script != null) {
-                scrt = script;
+                scrt = new SoftReference(script);
                 int len = script.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + LocaleUtils.toLower(script.charAt(i));
                 }
             } else {
-                scrt = "";
+                scrt = new SoftReference("");
             }
             if (region != null) {
-                regn = region;
+                regn = new SoftReference(region);
                 int len = region.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + LocaleUtils.toLower(region.charAt(i));
                 }
             } else {
-                regn = "";
+                regn = new SoftReference("");
             }
             if (variant != null) {
-                vart = variant;
+                vart = new SoftReference(variant);
                 int len = variant.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + variant.charAt(i);
                 }
             } else {
-                vart = "";
+                vart = new SoftReference("");
             }
             hash = h;
             this.normalized = normalized;
@@ -244,28 +245,31 @@
 
         @Override
         public boolean equals(Object obj) {
-            return (this == obj) ||
-                    (obj instanceof Key)
-                    && this.hash == ((Key)obj).hash
-                    && LocaleUtils.caseIgnoreMatch(((Key)obj).lang, this.lang)
-                    && LocaleUtils.caseIgnoreMatch(((Key)obj).scrt, this.scrt)
-                    && LocaleUtils.caseIgnoreMatch(((Key)obj).regn, this.regn)
-                    && ((Key)obj).vart.equals(vart); // variant is case sensitive in JDK!
+            if (this == obj) {
+                return true;
         }
 
-        @Override
-        public int compareTo(Key other) {
-            int res = LocaleUtils.caseIgnoreCompare(this.lang, other.lang);
-            if (res == 0) {
-                res = LocaleUtils.caseIgnoreCompare(this.scrt, other.scrt);
-                if (res == 0) {
-                    res = LocaleUtils.caseIgnoreCompare(this.regn, other.regn);
-                    if (res == 0) {
-                        res = this.vart.compareTo(other.vart);
+            if (obj instanceof Key && this.hash == ((Key)obj).hash) {
+                String tl = this.lang.get();
+                String ol = ((Key)obj).lang.get();
+                if (tl != null && ol != null &&
+                    LocaleUtils.caseIgnoreMatch(ol, tl)) {
+                    String ts = this.scrt.get();
+                    String os = ((Key)obj).scrt.get();
+                    if (ts != null && os != null &&
+                        LocaleUtils.caseIgnoreMatch(os, ts)) {
+                        String tr = this.regn.get();
+                        String or = ((Key)obj).regn.get();
+                        if (tr != null && or != null &&
+                            LocaleUtils.caseIgnoreMatch(or, tr)) {
+                            String tv = this.vart.get();
+                            String ov = ((Key)obj).vart.get();
+                            return (ov != null && ov.equals(tv));
                     }
                 }
             }
-            return res;
+            }
+            return false;
         }
 
         @Override
@@ -278,10 +282,10 @@
                 return key;
             }
 
-            String lang = LocaleUtils.toLowerString(key.lang).intern();
-            String scrt = LocaleUtils.toTitleString(key.scrt).intern();
-            String regn = LocaleUtils.toUpperString(key.regn).intern();
-            String vart = key.vart.intern(); // preserve upper/lower cases
+            String lang = LocaleUtils.toLowerString(key.lang.get()).intern();
+            String scrt = LocaleUtils.toTitleString(key.scrt.get()).intern();
+            String regn = LocaleUtils.toUpperString(key.regn.get()).intern();
+            String vart = key.vart.get().intern(); // preserve upper/lower cases
 
             return new Key(lang, scrt, regn, vart, true);
         }
@@ -294,12 +298,18 @@
 
         @Override
         protected Key normalizeKey(Key key) {
+            assert key.lang.get() != null &&
+                   key.scrt.get() != null &&
+                   key.regn.get() != null &&
+                   key.vart.get() != null;
+
             return Key.normalize(key);
         }
 
         @Override
         protected BaseLocale createObject(Key key) {
-            return new BaseLocale(key.lang, key.scrt, key.regn, key.vart);
+            return new BaseLocale(key.lang.get(), key.scrt.get(),
+                                  key.regn.get(), key.vart.get());
         }
     }
 }
diff --git a/jdk/src/share/classes/sun/util/locale/LocaleObjectCache.java b/jdk/src/share/classes/sun/util/locale/LocaleObjectCache.java
index 88920aa..eae1480 100644
--- a/jdk/src/share/classes/sun/util/locale/LocaleObjectCache.java
+++ b/jdk/src/share/classes/sun/util/locale/LocaleObjectCache.java
@@ -57,8 +57,10 @@
             value = entry.get();
         }
         if (value == null) {
-            key = normalizeKey(key);
             V newVal = createObject(key);
+            // make sure key is normalized *after* the object creation
+            // so that newVal is assured to be created from a valid key.
+            key = normalizeKey(key);
             if (key == null || newVal == null) {
                 // subclass must return non-null key/value object
                 return null;
diff --git a/jdk/src/share/javavm/export/jvm.h b/jdk/src/share/javavm/export/jvm.h
index f298cca..82c823c 100644
--- a/jdk/src/share/javavm/export/jvm.h
+++ b/jdk/src/share/javavm/export/jvm.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -384,6 +384,19 @@
 JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
 
 /*
+ * Find a class from a given class loader.  Throws ClassNotFoundException.
+ *  name:   name of class
+ *  init:   whether initialization is done
+ *  loader: class loader to look up the class. This may not be the same as the caller's
+ *          class loader.
+ *  caller: initiating class. The initiating class may be null when a security
+ *          manager is not installed.
+ */
+JNIEXPORT jclass JNICALL
+JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
+                        jobject loader, jclass caller);
+
+/*
  * Find a class from a given class loader. Throw ClassNotFoundException
  * or NoClassDefFoundError depending on the value of the last
  * argument.
diff --git a/jdk/src/share/native/java/lang/Class.c b/jdk/src/share/native/java/lang/Class.c
index db5246d..21b4645 100644
--- a/jdk/src/share/native/java/lang/Class.c
+++ b/jdk/src/share/native/java/lang/Class.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -97,7 +97,7 @@
 
 JNIEXPORT jclass JNICALL
 Java_java_lang_Class_forName0(JNIEnv *env, jclass this, jstring classname,
-                              jboolean initialize, jobject loader)
+                              jboolean initialize, jobject loader, jclass caller)
 {
     char *clname;
     jclass cls = 0;
@@ -135,8 +135,7 @@
         goto done;
     }
 
-    cls = JVM_FindClassFromClassLoader(env, clname, initialize,
-                                       loader, JNI_FALSE);
+    cls = JVM_FindClassFromCaller(env, clname, initialize, loader, caller);
 
  done:
     if (clname != buf) {
diff --git a/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp b/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp
index 144006e..469ba51 100644
--- a/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp
+++ b/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp
@@ -243,12 +243,22 @@
         le_uint16 srSetCount = SWAPW(subRuleSetCount);
 
         if (coverageIndex < srSetCount) {
+            LEReferenceToArrayOf<Offset> subRuleSetTableOffsetArrayRef(base, success,
+                    &subRuleSetTableOffsetArray[coverageIndex], 1);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             Offset subRuleSetTableOffset = SWAPW(subRuleSetTableOffsetArray[coverageIndex]);
             LEReferenceTo<SubRuleSetTable>
                  subRuleSetTable(base, success, (const SubRuleSetTable *) ((char *) this + subRuleSetTableOffset));
             le_uint16 subRuleCount = SWAPW(subRuleSetTable->subRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
 
+            LEReferenceToArrayOf<Offset> subRuleTableOffsetArrayRef(base, success,
+                    subRuleSetTable->subRuleTableOffsetArray, subRuleCount);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             for (le_uint16 subRule = 0; subRule < subRuleCount; subRule += 1) {
                 Offset subRuleTableOffset =
                     SWAPW(subRuleSetTable->subRuleTableOffsetArray[subRule]);
@@ -301,13 +311,22 @@
                                                                 glyphIterator->getCurrGlyphID(),
                                                                 success);
 
-        if (setClass < scSetCount && subClassSetTableOffsetArray[setClass] != 0) {
+        if (setClass < scSetCount) {
+            LEReferenceToArrayOf<Offset>
+                 subClassSetTableOffsetArrayRef(base, success, subClassSetTableOffsetArray, setClass);
+            if (LE_FAILURE(success)) { return 0; }
+            if (subClassSetTableOffsetArray[setClass] != 0) {
+
             Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
             LEReferenceTo<SubClassSetTable>
                  subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
             le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
-
+                LEReferenceToArrayOf<Offset>
+                    subClassRuleTableOffsetArrayRef(base, success, subClassSetTable->subClassRuleTableOffsetArray, subClassRuleCount);
+                if (LE_FAILURE(success)) {
+                    return 0;
+                }
             for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
                 Offset subClassRuleTableOffset =
                     SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
@@ -331,6 +350,7 @@
                 glyphIterator->setCurrStreamPosition(position);
             }
         }
+        }
 
         // XXX If we get here, the table is mal-formed...
     }
@@ -442,13 +462,22 @@
         le_uint16 srSetCount = SWAPW(chainSubRuleSetCount);
 
         if (coverageIndex < srSetCount) {
+            LEReferenceToArrayOf<Offset>
+                chainSubRuleSetTableOffsetArrayRef(base, success, chainSubRuleSetTableOffsetArray, coverageIndex);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             Offset chainSubRuleSetTableOffset = SWAPW(chainSubRuleSetTableOffsetArray[coverageIndex]);
             LEReferenceTo<ChainSubRuleSetTable>
                  chainSubRuleSetTable(base, success, (const ChainSubRuleSetTable *) ((char *) this + chainSubRuleSetTableOffset));
             le_uint16 chainSubRuleCount = SWAPW(chainSubRuleSetTable->chainSubRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
             GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
-
+            LEReferenceToArrayOf<Offset>
+                chainSubRuleTableOffsetArrayRef(base, success, chainSubRuleSetTable->chainSubRuleTableOffsetArray, chainSubRuleCount);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             for (le_uint16 subRule = 0; subRule < chainSubRuleCount; subRule += 1) {
                 Offset chainSubRuleTableOffset =
                     SWAPW(chainSubRuleSetTable->chainSubRuleTableOffsetArray[subRule]);
@@ -530,6 +559,11 @@
         le_int32 setClass = inputClassDefinitionTable->getGlyphClass(inputClassDefinitionTable,
                                                                      glyphIterator->getCurrGlyphID(),
                                                                      success);
+        LEReferenceToArrayOf<Offset>
+            chainSubClassSetTableOffsetArrayRef(base, success, chainSubClassSetTableOffsetArray, setClass);
+        if (LE_FAILURE(success)) {
+            return 0;
+        }
 
         if (setClass < scSetCount && chainSubClassSetTableOffsetArray[setClass] != 0) {
             Offset chainSubClassSetTableOffset = SWAPW(chainSubClassSetTableOffsetArray[setClass]);
@@ -538,7 +572,11 @@
             le_uint16 chainSubClassRuleCount = SWAPW(chainSubClassSetTable->chainSubClassRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
             GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
-
+            LEReferenceToArrayOf<Offset>
+                chainSubClassRuleTableOffsetArrayRef(base, success, chainSubClassSetTable->chainSubClassRuleTableOffsetArray, chainSubClassRuleCount);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             for (le_uint16 scRule = 0; scRule < chainSubClassRuleCount; scRule += 1) {
                 Offset chainSubClassRuleTableOffset =
                     SWAPW(chainSubClassSetTable->chainSubClassRuleTableOffsetArray[scRule]);
@@ -603,12 +641,14 @@
     }
 
     le_uint16 backtrkGlyphCount = SWAPW(backtrackGlyphCount);
+    LEReferenceToArrayOf<Offset> backtrackGlyphArrayRef(base, success, backtrackCoverageTableOffsetArray, backtrkGlyphCount);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
     le_uint16 inputGlyphCount = (le_uint16) SWAPW(backtrackCoverageTableOffsetArray[backtrkGlyphCount]);
     LEReferenceToArrayOf<Offset>   inputCoverageTableOffsetArray(base, success, &backtrackCoverageTableOffsetArray[backtrkGlyphCount + 1], inputGlyphCount+2); // offset
     if (LE_FAILURE(success)) { return 0; }
     const le_uint16 lookaheadGlyphCount = (le_uint16) SWAPW(inputCoverageTableOffsetArray[inputGlyphCount]);
-
-    if( LE_FAILURE(success) ) { return 0; }
     LEReferenceToArrayOf<Offset>   lookaheadCoverageTableOffsetArray(base, success, inputCoverageTableOffsetArray.getAlias(inputGlyphCount + 1, success), lookaheadGlyphCount+2);
 
     if( LE_FAILURE(success) ) { return 0; }
diff --git a/jdk/src/share/native/sun/font/layout/LEScripts.h b/jdk/src/share/native/sun/font/layout/LEScripts.h
index 5524ef3..bb1b07e 100644
--- a/jdk/src/share/native/sun/font/layout/LEScripts.h
+++ b/jdk/src/share/native/sun/font/layout/LEScripts.h
@@ -263,12 +263,6 @@
     tirhScriptCode = 158,
 
 /**
- * @stable ICU 52
- */
-    aghbScriptCode = 159,
-    mahjScriptCode = 160,
-
-/**
  * @stable ICU 2.2
  */
     scriptCodeCount
diff --git a/jdk/src/solaris/native/java/net/AbstractPlainDatagramSocketImpl.c b/jdk/src/solaris/native/java/net/AbstractPlainDatagramSocketImpl.c
new file mode 100644
index 0000000..075fffc
--- /dev/null
+++ b/jdk/src/solaris/native/java/net/AbstractPlainDatagramSocketImpl.c
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#ifdef __solaris__
+#include <unistd.h>
+#include <stropts.h>
+
+#ifndef BSD_COMP
+#define BSD_COMP
+#endif
+
+#endif
+
+#include <sys/ioctl.h>
+
+#include "jvm.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#include "java_net_AbstractPlainDatagramSocketImpl.h"
+
+static jfieldID IO_fd_fdID;
+
+static jfieldID apdsi_fdID;
+
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
+
+    apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
+                                   "Ljava/io/FileDescriptor;");
+    CHECK_NULL(apdsi_fdID);
+
+    IO_fd_fdID = NET_GetFileDescriptorID(env);
+}
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    dataAvailable
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
+(JNIEnv *env, jobject this) {
+    int fd, retval;
+
+    jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
+
+    if (IS_NULL(fdObj)) {
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+                        "Socket closed");
+        return -1;
+    }
+    fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
+
+    if (ioctl(fd, FIONREAD, &retval) < 0) {
+        return -1;
+    }
+    return retval;
+}
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSACipher.java b/jdk/src/windows/classes/sun/security/mscapi/RSACipher.java
index 7ab2962..023725b 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSACipher.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSACipher.java
@@ -35,6 +35,8 @@
 import javax.crypto.spec.*;
 
 import sun.security.rsa.RSAKeyFactory;
+import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
+import sun.security.util.KeyUtil;
 
 /**
  * RSA cipher implementation using the Microsoft Crypto API.
@@ -92,9 +94,16 @@
 
     // the public key, if we were initialized using a public key
     private sun.security.mscapi.Key publicKey;
+
     // the private key, if we were initialized using a private key
     private sun.security.mscapi.Key privateKey;
 
+    // cipher parameter for TLS RSA premaster secret
+    private AlgorithmParameterSpec spec = null;
+
+    // the source of randomness
+    private SecureRandom random;
+
     public RSACipher() {
         paddingType = PAD_PKCS1;
     }
@@ -155,8 +164,12 @@
             throws InvalidKeyException, InvalidAlgorithmParameterException {
 
         if (params != null) {
-            throw new InvalidAlgorithmParameterException
-                ("Parameters not supported");
+            if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
+                throw new InvalidAlgorithmParameterException(
+                        "Parameters not supported");
+            }
+            spec = params;
+            this.random = random;   // for TLS RSA premaster secret
         }
         init(opmode, key);
     }
@@ -356,39 +369,47 @@
     }
 
     // see JCE spec
-    protected java.security.Key engineUnwrap(byte[] wrappedKey, String algorithm,
+    protected java.security.Key engineUnwrap(byte[] wrappedKey,
+            String algorithm,
             int type) throws InvalidKeyException, NoSuchAlgorithmException {
 
         if (wrappedKey.length > buffer.length) {
             throw new InvalidKeyException("Key is too long for unwrapping");
         }
+
+        boolean isTlsRsaPremasterSecret =
+                algorithm.equals("TlsRsaPremasterSecret");
+        Exception failover = null;
+        byte[] encoded = null;
+
         update(wrappedKey, 0, wrappedKey.length);
-
         try {
-            byte[] encoding = doFinal();
-
-            switch (type) {
-            case Cipher.PUBLIC_KEY:
-                return constructPublicKey(encoding, algorithm);
-
-            case Cipher.PRIVATE_KEY:
-                return constructPrivateKey(encoding, algorithm);
-
-            case Cipher.SECRET_KEY:
-                return constructSecretKey(encoding, algorithm);
-
-            default:
-                throw new InvalidKeyException("Unknown key type " + type);
-            }
-
+            encoded = doFinal();
         } catch (BadPaddingException e) {
-            // should not occur
-            throw new InvalidKeyException("Unwrapping failed", e);
-
+            if (isTlsRsaPremasterSecret) {
+                failover = e;
+            } else {
+                throw new InvalidKeyException("Unwrapping failed", e);
+            }
         } catch (IllegalBlockSizeException e) {
             // should not occur, handled with length check above
             throw new InvalidKeyException("Unwrapping failed", e);
         }
+
+        if (isTlsRsaPremasterSecret) {
+            if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
+                throw new IllegalStateException(
+                        "No TlsRsaPremasterSecretParameterSpec specified");
+            }
+
+            // polish the TLS premaster secret
+            encoded = KeyUtil.checkTlsPreMasterSecretKey(
+                ((TlsRsaPremasterSecretParameterSpec)spec).getClientVersion(),
+                ((TlsRsaPremasterSecretParameterSpec)spec).getServerVersion(),
+                random, encoded, (failover != null));
+        }
+
+        return constructKey(encoded, algorithm, type);
     }
 
     // see JCE spec
@@ -452,6 +473,22 @@
         return new SecretKeySpec(encodedKey, encodedKeyAlgorithm);
     }
 
+    private static Key constructKey(byte[] encodedKey,
+            String encodedKeyAlgorithm,
+            int keyType) throws InvalidKeyException, NoSuchAlgorithmException {
+
+        switch (keyType) {
+            case Cipher.PUBLIC_KEY:
+                return constructPublicKey(encodedKey, encodedKeyAlgorithm);
+            case Cipher.PRIVATE_KEY:
+                return constructPrivateKey(encodedKey, encodedKeyAlgorithm);
+            case Cipher.SECRET_KEY:
+                return constructSecretKey(encodedKey, encodedKeyAlgorithm);
+            default:
+                throw new InvalidKeyException("Unknown key type " + keyType);
+        }
+    }
+
     /*
      * Encrypt/decrypt a data buffer using Microsoft Crypto API with HCRYPTKEY.
      * It expects and returns ciphertext data in big-endian form.
diff --git a/jdk/src/windows/native/java/net/AbstractPlainDatagramSocketImpl.c b/jdk/src/windows/native/java/net/AbstractPlainDatagramSocketImpl.c
new file mode 100644
index 0000000..f66c3b5
--- /dev/null
+++ b/jdk/src/windows/native/java/net/AbstractPlainDatagramSocketImpl.c
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <windows.h>
+#include <winsock2.h>
+
+#include "jvm.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#include "java_net_AbstractPlainDatagramSocketImpl.h"
+
+static jfieldID IO_fd_fdID;
+
+static jfieldID apdsi_fdID;
+
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
+
+    apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
+                                   "Ljava/io/FileDescriptor;");
+    CHECK_NULL(apdsi_fdID);
+
+    IO_fd_fdID = NET_GetFileDescriptorID(env);
+    CHECK_NULL(IO_fd_fdID);
+}
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    dataAvailable
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
+(JNIEnv *env, jobject this) {
+    SOCKET fd;
+    int  retval;
+
+    jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
+
+    if (IS_NULL(fdObj)) {
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+                        "Socket closed");
+        return -1;
+    }
+    fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID);
+
+    if (ioctlsocket(fd, FIONREAD, &retval) < 0) {
+        return -1;
+    }
+    return retval;
+}
+
diff --git a/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c b/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c
index 7ed415d..8e02c18 100644
--- a/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c
+++ b/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -213,6 +213,14 @@
 void
 SplashRedrawWindow(Splash * splash)
 {
+    if (!SplashIsStillLooping(splash)) {
+        KillTimer(splash->hWnd, 0);
+    }
+
+    if (splash->currentFrame < 0) {
+        return;
+    }
+
     SplashUpdateScreenData(splash);
     if (splash->isLayered) {
         BLENDFUNCTION bf;
@@ -303,9 +311,6 @@
             time = 0;
         SetTimer(splash->hWnd, 0, time, NULL);
     }
-    else {
-        KillTimer(splash->hWnd, 0);
-    }
 }
 
 void SplashReconfigureNow(Splash * splash) {
diff --git a/jdk/test/com/sun/crypto/provider/TLS/TestPremaster.java b/jdk/test/com/sun/crypto/provider/TLS/TestPremaster.java
index bbbfbb6..f19e754 100644
--- a/jdk/test/com/sun/crypto/provider/TLS/TestPremaster.java
+++ b/jdk/test/com/sun/crypto/provider/TLS/TestPremaster.java
@@ -33,6 +33,7 @@
 
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
+import java.util.Formatter;
 
 import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
 
@@ -52,27 +53,51 @@
             System.out.println("OK: " + e);
         }
 
-        test(kg, 3, 0);
-        test(kg, 3, 1);
-        test(kg, 3, 2);
-        test(kg, 4, 0);
+        int[] protocolVersions = {0x0300, 0x0301, 0x0302, 0x0400};
+        for (int clientVersion : protocolVersions) {
+            for (int serverVersion : protocolVersions) {
+                test(kg, clientVersion, serverVersion);
+                if (serverVersion >= clientVersion) {
+                    break;
+                }
+            }
+        }
 
         System.out.println("Done.");
     }
 
-    private static void test(KeyGenerator kg, int major, int minor)
-            throws Exception {
+    private static void test(KeyGenerator kg,
+            int clientVersion, int serverVersion) throws Exception {
 
-        kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor));
+        System.out.printf(
+                "Testing RSA pre-master secret key generation between " +
+                "client (0x%04X) and server(0x%04X)%n",
+                clientVersion, serverVersion);
+        kg.init(new TlsRsaPremasterSecretParameterSpec(
+                                    clientVersion, serverVersion));
+
         SecretKey key = kg.generateKey();
         byte[] encoded = key.getEncoded();
-        if (encoded.length != 48) {
-            throw new Exception("length: " + encoded.length);
-        }
-        if ((encoded[0] != major) || (encoded[1] != minor)) {
-            throw new Exception("version mismatch: "  + encoded[0] +
-                "." + encoded[1]);
-        }
-        System.out.println("OK: " + major + "." + minor);
+        if (encoded != null) {  // raw key material may be not extractable
+            if (encoded.length != 48) {
+                throw new Exception("length: " + encoded.length);
+            }
+            int v = versionOf(encoded[0], encoded[1]);
+            if (clientVersion != v) {
+                if (serverVersion != v || clientVersion >= 0x0302) {
+                    throw new Exception(String.format(
+                        "version mismatch: (0x%04X) rather than (0x%04X) " +
+                        "is used in pre-master secret", v, clientVersion));
+                }
+                System.out.printf("Use compatible version (0x%04X)%n", v);
+            }
+            System.out.println("Passed, version matches!");
+       } else {
+            System.out.println("Raw key material is not extractable");
+       }
+    }
+
+    private static int versionOf(int major, int minor) {
+        return ((major & 0xFF) << 8) | (minor & 0xFF);
     }
 }
diff --git a/jdk/test/java/lang/invoke/MethodHandlesTest.java b/jdk/test/java/lang/invoke/MethodHandlesTest.java
index 90c3d99..102365d 100644
--- a/jdk/test/java/lang/invoke/MethodHandlesTest.java
+++ b/jdk/test/java/lang/invoke/MethodHandlesTest.java
@@ -140,7 +140,7 @@
         Object actual   = calledLog.get(calledLog.size() - 1);
         if (expected.equals(actual) && verbosity < 9)  return;
         System.out.println("assertCalled "+name+":");
-        System.out.println("expected:   "+expected);
+        System.out.println("expected:   "+deepToString(expected));
         System.out.println("actual:     "+actual);
         System.out.println("ex. types:  "+getClasses(expected));
         System.out.println("act. types: "+getClasses(actual));
@@ -148,7 +148,25 @@
     }
     static void printCalled(MethodHandle target, String name, Object... args) {
         if (verbosity >= 3)
-            System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
+            System.out.println("calling MH="+target+" to "+name+deepToString(args));
+    }
+    static String deepToString(Object x) {
+        if (x == null)  return "null";
+        if (x instanceof Collection)
+            x = ((Collection)x).toArray();
+        if (x instanceof Object[]) {
+            Object[] ax = (Object[]) x;
+            ax = Arrays.copyOf(ax, ax.length, Object[].class);
+            for (int i = 0; i < ax.length; i++)
+                ax[i] = deepToString(ax[i]);
+            x = Arrays.deepToString(ax);
+        }
+        if (x.getClass().isArray())
+            try {
+                x = Arrays.class.getMethod("toString", x.getClass()).invoke(null, x);
+            } catch (ReflectiveOperationException ex) { throw new Error(ex); }
+        assert(!(x instanceof Object[]));
+        return x.toString();
     }
 
     static Object castToWrapper(Object value, Class<?> dst) {
@@ -230,6 +248,12 @@
                     { param = c; break; }
             }
         }
+        if (param.isArray()) {
+            Class<?> ctype = param.getComponentType();
+            Object arg = Array.newInstance(ctype, 2);
+            Array.set(arg, 0, randomArg(ctype));
+            return arg;
+        }
         if (param.isInterface() && param.isAssignableFrom(List.class))
             return Arrays.asList("#"+nextArg());
         if (param.isInterface() || param.isAssignableFrom(String.class))
@@ -584,6 +608,16 @@
         testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
     }
 
+    @Test
+    public void testFindVirtualClone() throws Throwable {
+        // test some ad hoc system methods
+        testFindVirtual(false, PUBLIC, Object.class, Object.class, "clone");
+        testFindVirtual(true, PUBLIC, Object[].class, Object.class, "clone");
+        testFindVirtual(true, PUBLIC, int[].class, Object.class, "clone");
+        for (Class<?> cls : new Class<?>[]{ boolean[].class, long[].class, float[].class, char[].class })
+            testFindVirtual(true, PUBLIC, cls, Object.class, "clone");
+    }
+
     void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
         Class<?> rcvc = defc;
         testFindVirtual(rcvc, defc, ret, name, params);
@@ -596,6 +630,9 @@
     void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
         testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
     }
+    void testFindVirtual(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
+        testFindVirtual(positive, lookup, defc, defc, ret, name, params);
+    }
     void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
         countTest(positive);
         String methodName = name.substring(1 + name.indexOf('/'));  // foo/bar => foo
@@ -635,8 +672,21 @@
         Object[] argsWithSelf = randomArgs(paramsWithSelf);
         if (selfc.isAssignableFrom(rcvc) && rcvc != selfc)  argsWithSelf[0] = randomArg(rcvc);
         printCalled(target, name, argsWithSelf);
-        target.invokeWithArguments(argsWithSelf);
-        assertCalled(name, argsWithSelf);
+        Object res = target.invokeWithArguments(argsWithSelf);
+        if (Example.class.isAssignableFrom(defc) || IntExample.class.isAssignableFrom(defc)) {
+            assertCalled(name, argsWithSelf);
+        } else if (name.equals("clone")) {
+            // Ad hoc method call outside Example.  For Object[].clone.
+            printCalled(target, name, argsWithSelf);
+            assertEquals(MethodType.methodType(Object.class, rcvc), target.type());
+            Object orig = argsWithSelf[0];
+            assertEquals(orig.getClass(), res.getClass());
+            if (res instanceof Object[])
+                assertArrayEquals((Object[])res, (Object[])argsWithSelf[0]);
+            assert(Arrays.deepEquals(new Object[]{res}, new Object[]{argsWithSelf[0]}));
+        } else {
+            assert(false) : Arrays.asList(positive, lookup, rcvc, defc, ret, name, deepToString(params));
+        }
         if (verbosity >= 1)
             System.out.print(':');
     }
diff --git a/jdk/test/java/lang/invoke/ObjectMethodInInterfaceTest.java b/jdk/test/java/lang/invoke/ObjectMethodInInterfaceTest.java
new file mode 100644
index 0000000..2ba7116
--- /dev/null
+++ b/jdk/test/java/lang/invoke/ObjectMethodInInterfaceTest.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8031502
+ * @summary JSR292: IncompatibleClassChangeError in LambdaForm for CharSequence.toString() method handle type converter
+ * @compile ObjectMethodInInterfaceTest.java
+ * @run main/othervm -Djava.lang.invoke.MethodHandle.COMPILE_THRESHOLD=0 test.java.lang.invoke.ObjectMethodInInterfaceTest
+ */
+package test.java.lang.invoke;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+
+public class ObjectMethodInInterfaceTest {
+    public static void main(String[] args) throws Throwable {
+        MethodHandle mh = MethodHandles.lookup().findVirtual(CharSequence.class, "toString", MethodType.methodType(String.class));
+        MethodType mt = MethodType.methodType(Object.class, CharSequence.class);
+        mh = mh.asType(mt);
+
+        Object res = mh.invokeExact((CharSequence)"123");
+
+        System.out.println("TEST PASSED");
+    }
+}
diff --git a/jdk/test/sun/awt/image/bug8038000.java b/jdk/test/sun/awt/image/bug8038000.java
new file mode 100644
index 0000000..2bfdc27
--- /dev/null
+++ b/jdk/test/sun/awt/image/bug8038000.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug     8038000
+ *
+ * @summary Verifies that we could create different type of Rasters with height 1
+ * and strideline which exceeds raster width.
+ * Also checks that a set of RasterOp work correctly with such kind of Rasters.
+ *
+ * @run     main bug8038000
+ */
+
+import java.awt.*;
+import java.awt.color.ColorSpace;
+import java.awt.geom.AffineTransform;
+import java.awt.image.*;
+import java.util.Arrays;
+
+public class bug8038000 {
+
+    public static void main(String[] args) throws Exception {
+        new bug8038000().checkOps();
+
+        // No exceptions - Passed
+    }
+
+    private void checkOps() throws Exception {
+
+        RasterOp[] ops = new RasterOp[] {
+                new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                        ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB), null),
+                new AffineTransformOp(AffineTransform.getScaleInstance(1, 1.1), null)
+        };
+
+
+        for (RasterOp op: ops) {
+            // Banded rasters
+            checkOp(Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 10, 1, 10,
+                            new int[] {0, 1, 2}, new int[]{2,1,0}, null),
+                    Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 10, 1, 1001,
+                            new int[] {0, 1, 2}, new int[]{2,1,0}, null), op);
+            checkOp(Raster.createBandedRaster(DataBuffer.TYPE_USHORT, 10, 1, 10,
+                    new int[] {0, 1, 2}, new int[]{2,1,0}, null),
+                    Raster.createBandedRaster(DataBuffer.TYPE_USHORT, 10, 1, 1001,
+                            new int[] {0, 1, 2}, new int[]{2,1,0}, null), op);
+            checkOp(Raster.createBandedRaster(DataBuffer.TYPE_INT, 10, 1, 10,
+                    new int[] {0, 1, 2}, new int[]{2,1,0}, null),
+                    Raster.createBandedRaster(DataBuffer.TYPE_INT, 10, 1, 1001,
+                            new int[] {0, 1, 2}, new int[]{2,1,0}, null), op);
+
+            // Interleaved rasters
+            checkOp(Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
+                            10, 1, 30, 3, new int[]{0, 1, 2}, null),
+                    Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
+                            10, 1, 1001, 3, new int[]{0, 1, 2}, null),
+                    op);
+
+            checkOp(Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT,
+                            10, 1, 30, 3, new int[]{0, 1, 2}, null),
+                    Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT,
+                            10, 1, 1001, 3, new int[]{0, 1, 2}, null),
+                    op);
+
+            // Packed rasters
+            checkOp(Raster.createPackedRaster(new DataBufferByte(10), 10, 1, 10,
+                            new int[] {0x01, 0x02, 0x04}, null),
+                    Raster.createPackedRaster(new DataBufferByte(10), 10, 1, 2000,
+                            new int[] {0x01, 0x02, 0x04}, null),
+                    op);
+            checkOp(Raster.createPackedRaster(new DataBufferInt(10), 10, 1, 10,
+                        new int[] {0xff0000, 0x00ff00, 0x0000ff}, null),
+                    Raster.createPackedRaster(new DataBufferInt(10), 10, 1, 20,
+                            new int[] {0xff0000, 0x00ff00, 0x0000ff}, null),
+                    op);
+
+        }
+    }
+
+    /**
+     *  Takes two identical rasters (identical with the exception of scanline stride)
+     *  fills their pixels with identical data, applies the RasterOp to both rasters
+     *  and checks that the result is the same
+     */
+    private void checkOp(WritableRaster wr1, WritableRaster wr2, RasterOp op) {
+        System.out.println("Checking " + op + " with rasters: \n    " + wr1 +
+                "\n    " + wr2);
+        try {
+            WritableRaster r1 = op.filter(fillRaster(wr1), null);
+            WritableRaster r2 = op.filter(fillRaster(wr2), null);
+            compareRasters(r1, r2);
+        } catch (ImagingOpException e) {
+            System.out.println("    Skip: Op is not supported: " + e);
+        }
+    }
+
+    private WritableRaster fillRaster(WritableRaster wr) {
+        int c = 0;
+        for(int x = wr.getMinX(); x < wr.getMinX() + wr.getWidth(); x++) {
+            for(int y = wr.getMinY(); y < wr.getMinY() + wr.getHeight(); y++) {
+                for (int b = 0; b < wr.getNumBands(); b++) {
+                    wr.setSample(x, y, b, c++);
+                }
+            }
+        }
+        return wr;
+    }
+
+    private void compareRasters(Raster r1, Raster r2) {
+        Rectangle bounds = r1.getBounds();
+        if (!bounds.equals(r2.getBounds())) {
+            throw new RuntimeException("Bounds differ.");
+        }
+
+        if (r1.getNumBands() != r2.getNumBands()) {
+            throw new RuntimeException("Bands differ.");
+        }
+
+        int[] b1 = new int[r1.getNumBands()];
+        int[] b2 = new int[r1.getNumBands()];
+
+        for (int x = (int) bounds.getX(); x < bounds.getMaxX(); x++) {
+            for (int y = (int) bounds.getY(); y < bounds.getMaxY(); y++) {
+                r1.getPixel(x,y, b1);
+                r2.getPixel(x,y, b2);
+                if (!Arrays.equals(b1, b2)) {
+                    throw new RuntimeException("Pixels differ.");
+                }
+            }
+        }
+    }
+}
diff --git a/jdk/test/sun/security/pkcs11/fips/CipherTest.java b/jdk/test/sun/security/pkcs11/fips/CipherTest.java
index 0d9f8b3..d7b381a 100644
--- a/jdk/test/sun/security/pkcs11/fips/CipherTest.java
+++ b/jdk/test/sun/security/pkcs11/fips/CipherTest.java
@@ -458,8 +458,21 @@
                 return false;
             }
 
+            // No ECDH-capable certificate in key store. May restructure
+            // this in the future.
+            if (cipherSuite.contains("ECDHE_ECDSA") ||
+                    cipherSuite.contains("ECDH_ECDSA") ||
+                    cipherSuite.contains("ECDH_RSA")) {
+                System.out.println("Skipping unsupported test for " +
+                                    cipherSuite + " of " + protocol);
+                return false;
+            }
+
             // skip SSLv2Hello protocol
-            if (protocol.equals("SSLv2Hello")) {
+            //
+            // skip TLSv1.2 protocol, we have not implement "SunTls12Prf" and
+            // SunTls12RsaPremasterSecret in SunPKCS11 provider
+            if (protocol.equals("SSLv2Hello") || protocol.equals("TLSv1.2")) {
                 System.out.println("Skipping unsupported test for " +
                                     cipherSuite + " of " + protocol);
                 return false;
diff --git a/jdk/test/sun/security/pkcs11/fips/ClientJSSEServerJSSE.java b/jdk/test/sun/security/pkcs11/fips/ClientJSSEServerJSSE.java
index d9119e2..59b763e2 100644
--- a/jdk/test/sun/security/pkcs11/fips/ClientJSSEServerJSSE.java
+++ b/jdk/test/sun/security/pkcs11/fips/ClientJSSEServerJSSE.java
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 6313675 6323647
+ * @bug 6313675 6323647 8028192
  * @summary Verify that all ciphersuites work in FIPS mode
  * @library ..
  * @ignore JSSE supported cipher suites are changed with CR 6916074,
@@ -44,9 +44,13 @@
             return;
         }
 
-        if ("sparc".equals(System.getProperty("os.arch")) == false) {
-            // we have not updated other platforms with the proper NSS libraries yet
-            System.out.println("Test currently works only on solaris-sparc, skipping");
+        String arch = System.getProperty("os.arch");
+        if (!("sparc".equals(arch) || "sparcv9".equals(arch))) {
+            // we have not updated other platforms with the proper NSS
+            // libraries yet
+            System.out.println(
+                    "Test currently works only on solaris-sparc " +
+                    "and solaris-sparcv9. Skipping on " + arch);
             return;
         }
 
diff --git a/jdk/test/sun/security/pkcs11/tls/TestPremaster.java b/jdk/test/sun/security/pkcs11/tls/TestPremaster.java
index f7a51041..05e8efb 100644
--- a/jdk/test/sun/security/pkcs11/tls/TestPremaster.java
+++ b/jdk/test/sun/security/pkcs11/tls/TestPremaster.java
@@ -34,6 +34,7 @@
 
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
+import java.util.Formatter;
 
 import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
 
@@ -59,27 +60,51 @@
             System.out.println("OK: " + e);
         }
 
-        test(kg, 3, 0);
-        test(kg, 3, 1);
-        test(kg, 3, 2);
-        test(kg, 4, 0);
+        int[] protocolVersions = {0x0300, 0x0301, 0x0302, 0x0400};
+        for (int clientVersion : protocolVersions) {
+            for (int serverVersion : protocolVersions) {
+                test(kg, clientVersion, serverVersion);
+                if (serverVersion >= clientVersion) {
+                    break;
+                }
+            }
+        }
 
         System.out.println("Done.");
     }
 
-    private static void test(KeyGenerator kg, int major, int minor)
-            throws Exception {
+    private static void test(KeyGenerator kg,
+            int clientVersion, int serverVersion) throws Exception {
 
-        kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor));
+        System.out.printf(
+                "Testing RSA pre-master secret key generation between " +
+                "client (0x%04X) and server(0x%04X)%n",
+                clientVersion, serverVersion);
+        kg.init(new TlsRsaPremasterSecretParameterSpec(
+                                    clientVersion, serverVersion));
         SecretKey key = kg.generateKey();
         byte[] encoded = key.getEncoded();
-        if (encoded.length != 48) {
-            throw new Exception("length: " + encoded.length);
-        }
-        if ((encoded[0] != major) || (encoded[1] != minor)) {
-            throw new Exception("version mismatch: "  + encoded[0] +
-                "." + encoded[1]);
-        }
-        System.out.println("OK: " + major + "." + minor);
+        if (encoded != null) {  // raw key material may be not extractable
+            if (encoded.length != 48) {
+                throw new Exception("length: " + encoded.length);
+            }
+            int v = versionOf(encoded[0], encoded[1]);
+            if (clientVersion != v) {
+                if (serverVersion != v || clientVersion >= 0x0302) {
+                    throw new Exception(String.format(
+                        "version mismatch: (0x%04X) rather than (0x%04X) " +
+                        "is used in pre-master secret", v, clientVersion));
+                }
+                System.out.printf("Use compatible version (0x%04X)%n", v);
+            }
+            System.out.println("Passed, version matches!");
+       } else {
+            System.out.println("Raw key material is not extractable");
+       }
     }
+
+    private static int versionOf(int major, int minor) {
+        return ((major & 0xFF) << 8) | (minor & 0xFF);
+    }
+
 }
diff --git a/langtools/.hgtags b/langtools/.hgtags
index 3cfdfcb..8d56a94 100644
--- a/langtools/.hgtags
+++ b/langtools/.hgtags
@@ -450,6 +450,7 @@
 b578e801c5f0e41be96d58e213b32f5c0c9278e8 jdk7u60-b30
 c1c8f9d50b3e0d7d8af08be4270649a7572b68d4 jdk7u60-b31
 ab67af57536bf46e54b5b28462d34274aaa67025 jdk7u60-b32
+e7a68fd132f7a2f39ed72d804b4574a4cc3defb2 jdk7u60-b33
 75b8c65f4c148baa4084022035b22de47df9426b jdk7u65-b02
 16bb02dae837566f3c350c6313b09f6110dcba68 jdk7u65-b03
 91677116552f743f3589f3d2ba255fa1079c0c48 jdk7u65-b04
@@ -465,6 +466,7 @@
 52769f410515f6a7fa66a93b24a1327fa6b6174a jdk7u65-b14
 7f2891e4c6fcd9c0e31f50189a50c8de189d774f jdk7u65-b15
 dea7e67840b68ae6752b37e69e242dae2765b878 jdk7u65-b16
+15a051dfadb6a7d014f0d2739ccf0a63ade56313 jdk7u65-b17
 684f0285b699d304d1efff487b550ff2e1679e98 jdk7u66-b00
 a927daae851fa81d0470d2b67f52e8156e4d423c jdk7u66-b01
 6f229fda19bdabf7a3d1caad9d809dd713cce65d jdk7u66-b09
@@ -475,3 +477,5 @@
 3ceea3a91e4cbc29a435519747c22dfb02e68f67 jdk7u66-b14
 2918f02cde3e0fd134e2051e67296c3f935825e6 jdk7u66-b15
 9442596a63f000f4290265aa0574ee5fa8865808 jdk7u66-b16
+bd740cf100e1f7f866bd902fb668e77dcd866251 jdk7u66-b17
+df0aa7e382459053c7fa92f133080cdf679c6100 jdk7u71-b00