Merge jdk7u40-b38 into jdk7u45-b06
diff --git a/.hgtags b/.hgtags
index 2f512d1..49a5ee5 100644
--- a/.hgtags
+++ b/.hgtags
@@ -1,3 +1,35 @@
+349a1ee17aaf01b86ba52e2d35cf82649518039d jdk7u40-b38
+9a85d57b3679e2e8097517981e39c504fc66defc jdk7u40-b36
+97dc18024e6857c3794befe4adfe66811e994c31 jdk7u40-b34
+d35f5a6f518b06074471eb04e71def8bb284e24e jdk7u40-b33
+ae3ad0dd59d698a4c2bb52cc5e94aeea8001f15d jdk7u40-b32
+383f8de2a5d6c728c6750338ab96dcd5ba621189 jdk7u40-b31
+4ee9159f6a4ce5a6da7391fe4f66c3e448b3ec56 jdk7u21-b02
+12080e889e97a80be70eaab42bf392802df80de3 jdk7u21-b03
+f0cb28b0ddeb5387fc79d9bddd913a1dd5f34b61 jdk7u21-b04
+574d16cddfad3c118c5385fc4a519acb01f37133 jdk7u25-b01
+fc5da5088c32286bf2efaaf10fa87dc7c9eb1729 jdk7u25-b02
+e2db7d3429be72e207eea5b067fe9a811a6aba8e jdk7u25-b03
+c49a0e1bd91b406bddcade68714ceb7fe650f9cc jdk7u25-b04
+9c64248ac466ce0c014dd9b13a3db01c0cca5a4b jdk7u25-b05
+157a8643099a815e005c08893ed4e54df5c45a11 jdk7u25-b06
+32e05d0e45247ddf9ac7730615391ebca5156582 jdk7u25-b07
+afc46639f09fc49968349e10371aaa5497457f9d jdk7u25-b08
+be11510c3e762cd25ec719f7b45a6b3480980df0 jdk7u25-b09
+6a4b68b746b61b257c7965b6622d4b34f6256bb6 jdk7u25-b10
+e390da5c8e7416ff2aa3dea09acc70fc29d42009 jdk7u25-b11
+aeae68c217d1f06e650c543066cf2ab3fb5b08c3 jdk7u25-b12
+7408c9d0f2782594810e17a72837653f2fdfef6a jdk7u25-b13
+80453640fa743a7626c5665b611f81510436501d jdk7u25-b14
+edade8a1fe65cb51bfff727b4f7294bae07330d5 jdk7u25-b15
+766aa39db7ece8f3cdf14f9b41dc94f97741e54c jdk7u25-b30
+28317f5a37fa14762d66522962173b5ee356147d jdk7u25-b16
+641059852432f54578c4a92bbb20d9fc346388f4 jdk7u25-b32
+d28f526fa74a58537596f30304ac4b664c584cee jdk7u45-b01
+3e1cdb6cb29e808ab5311c96c4f9ae253bdafc1c jdk7u45-b02
+024c60b315431cca9f44ca0e031c48888171fa2e jdk7u45-b03
+8b8eb9f700734346931fdcee95747d4a215b87b4 jdk7u45-b04
+4b03620a3e443d3e00bd3e1af1ecc271e74f22db jdk7u45-b05
 13f4106350d36726309fa99c124a73d32236f99d jdk7u21-b31
 0ab9e8cfd10f5454e21d13e74fc19474f068d705 jdk7u9-b32
 2aa64e9463a2c0fc01f2d32f95a02894152ddf97 jdk7u10-b31
@@ -304,4 +336,3 @@
 a39882a84ef3eea19591c82dc09b7318d40f8307 jdk7u60-b00
 151b8fdbb246ccd1356da759b44083fa03eaebbd jdk7u40-b35
 9a838f63a38d2a584e48bdaed10c53ca9992bb35 jdk7u40-b37
-349a1ee17aaf01b86ba52e2d35cf82649518039d jdk7u40-b38
diff --git a/.hgtags-top-repo b/.hgtags-top-repo
index e3d9c8a..94e1d45 100644
--- a/.hgtags-top-repo
+++ b/.hgtags-top-repo
@@ -300,6 +300,22 @@
 84285f4e0aa2f81b80bc6fbe713d768c0d9a7156 jdk7u25-b09
 aae1e27d347b71f65f548c12b918ede98d869b7c jdk7u25-b10
 039f12124903cd0b7633a17a26f6ca281f7aaeae jdk7u25-b11
+210f464368dba0fc4f8d239654fa7432ad2ed31f jdk7u14-b16
+f07712232642fc30dcf7c433ff890e7247b5fd0b jdk7u14-b17
+9e2a9a2c5b240daa4e27ff75d030a77827174753 jdk7u14-b18
+d9d4dc020cb37142230f6a20d2a75a677c5cd26f jdk7u14-b19
+d9d4dc020cb37142230f6a20d2a75a677c5cd26f jdk7u14-b19
+b4b7795ef8047e3d2b2ba48a70c08d9184073100 jdk7u14-b19
+f413e7a22c198559af5aca28309356e6d4edd78f jdk7u14-b20
+41686e19d8189a546434a52dd9679e9b6a0a68be jdk7u14-b21
+3e3177719b43f732239d6d51e96d26ee18440960 jdk7u14-b22
+8c6e2197930c79f6beafd83181714cc817b83229 jdk7u40-b23
+5169c92728b54a4b5e9a41071f8bf8701d0fe1fa jdk7u40-b24
+f89fd7e2800c1c35b6c339f54780d5579bb30991 jdk7u40-b25
+4ef57f592525d36487ea6eeb2be84d0e9170b26b jdk7u40-b26
+75167199239375d05b68668023c885c2776fd548 jdk7u40-b27
+ac751f3867ecffca814b25daf5e19d82d83fc755 jdk7u40-b28
+dbe42a627813892d1bb59a4240c24f60ef22930a jdk7u40-b29
 2d02518960053d2b1dcb9aabacd709788e92c549 jdk7u25-b12
 37c4268341d79b16165bdaf7e1fad489d692bc83 jdk7u25-b13
 9de1fc3635def64c19c51f272f09b51d8cf0ca98 jdk7u25-b14
@@ -327,10 +343,15 @@
 ac751f3867ecffca814b25daf5e19d82d83fc755 jdk7u40-b28
 dbe42a627813892d1bb59a4240c24f60ef22930a jdk7u40-b29
 1c141e6fde911c4974c87e340eb698754607f422 jdk7u40-b30
-58a2a470aa3bccd3eb3624e68bca9397c8cc26a2 jdk7u40-b31
+e51f24701c608e57ba7ae69ba28bbc2daab02c4c jdk7u45-b01
 da376fd5e4d68f8a45003a6e175267dc840711cc jdk7u40-b32
 3fdfe7f1b06354e11e8af51b7c653c8a0adb3987 jdk7u40-b33
 a1ae13479e8767329fa20774b5cea5976aaeb37b jdk7u40-b34
 af755d12719e898e3af917e8a56b64ebf83019bc jdk7u40-b35
 59598f7b6a7be5e0470447694c1f5b7d951f6ff1 jdk7u40-b36
 5bfb3aa1655e5364a8c1c17343ff84dad7e13f25 jdk7u40-b37
+7d3e6ccad487d84e764932802cd42d2afebccd7a jdk7u40-b38
+07e41ff8674c9438cb1124cf78eed8636ed5d4fa jdk7u45-b02
+23c983c352a170d7a5fb7d703081daf1816d257a jdk7u45-b03
+1018a8ab686da6c1be22bec3ab9d01b2dc206333 jdk7u45-b04
+22e0ca1fa645d0518b514159afafe34335699c11 jdk7u45-b05
diff --git a/Makefile b/Makefile
index ffc25d4..73b1f77 100644
--- a/Makefile
+++ b/Makefile
@@ -264,7 +264,7 @@
 	        DEBUG_NAME=$(DEBUG_NAME) \
 		GENERATE_DOCS=false \
 		$(if $(findstring true,$(BUILD_INSTALL)),BUILD_INSTALL_BUNDLES=true,) \
-		CREATE_DEBUGINFO_BUNDLES=false \
+		CREATE_DEBUGINFO_BUNDLES=true \
 	        $(BOOT_CYCLE_DEBUG_SETTINGS) \
 		generic_build_repo_series
 
diff --git a/corba/.hgtags b/corba/.hgtags
index 55dbe9b..4affd6a 100644
--- a/corba/.hgtags
+++ b/corba/.hgtags
@@ -302,6 +302,22 @@
 161ec4dd450d59e1b8ad136db231925c97ff6205 jdk7u25-b09
 c9da98e82bb006dccd94a50871d6cdb66fa2d7e7 jdk7u25-b10
 109386df5b8e259d0af802217769a3c448404e49 jdk7u25-b11
+38282b734daefcbb8155b7d7ef9664130330ed14 jdk7u14-b16
+8b1d77697ca4d2a9c29d67fd2ff03aded9b06012 jdk7u14-b17
+862b43d26e03bbceb3465f93354860e0d17eb324 jdk7u14-b18
+bfbaab73969d4d978d0280d6ad51bac8c47dbaf8 jdk7u14-b19
+bfbaab73969d4d978d0280d6ad51bac8c47dbaf8 jdk7u14-b19
+a921b45a1f9086a7d598a76f920639050386f996 jdk7u14-b19
+54320e5d9da60df24f0e2c57c011809911dc06e1 jdk7u14-b20
+fb590ca4de9aaf1f6bca945be040dffc55b5e8d2 jdk7u14-b21
+e5d89aa2c1a11dba841a646858dda9ea18dc8f57 jdk7u14-b22
+d85df1552f877a1cc51f43bc07a42a0c48f18e0b jdk7u40-b23
+d3ab3b19caa02ee85359cfe07b6e0b74eb7b3d74 jdk7u40-b24
+abfc54516d0b7f9aed34ef175f6bbb93fda4cbb3 jdk7u40-b25
+be9099c54a35c00d0dfe6beeed8ea5d4ab3cd3fe jdk7u40-b26
+f745eeabb0eaabe8c0835c175b31f1e1c0f00bd4 jdk7u40-b27
+c8b9201f88f4ce417df7a40efcb7fef656d94512 jdk7u40-b28
+1ad0a5a3f7b1e9d95670d733d7e70714050ba6bf jdk7u40-b29
 ef8e6f8305d524f3b448a85f901aadf1adc81fc0 jdk7u25-b12
 eca480919c71072a31f62a61cb3aad30677007e3 jdk7u25-b13
 577c4dd1a6e9bc1bb2c2e5d5ecbab8eacb4121af jdk7u25-b14
@@ -336,3 +352,9 @@
 fab3339a833da9631ead479621edcf6df2df457d jdk7u40-b35
 cd3871b1516988ea4a3099d6e1886abe2e74e771 jdk7u40-b36
 dc9a63376b39223bfb612d9e8efd275023de6399 jdk7u40-b37
+8391dff270bbf75dc434e53ed68993ab833475e8 jdk7u40-b38
+4f54264ca4df2fc50fbb9bb2654dad97776d10ac jdk7u45-b01
+1a1a1dedf437c50797a49c21a12161a79c761757 jdk7u45-b02
+3a2cca8c2f209b533af6c1201cc8aee43628e578 jdk7u45-b03
+4f4f7869bd6585042ad9596426dd1aa0829b8e98 jdk7u45-b04
+faee62d13040eae3d081f0383843a391ceef1edd jdk7u45-b05
diff --git a/corba/src/share/classes/com/sun/corba/se/impl/presentation/rmi/InvocationHandlerFactoryImpl.java b/corba/src/share/classes/com/sun/corba/se/impl/presentation/rmi/InvocationHandlerFactoryImpl.java
index 37a5968..076ed19 100644
--- a/corba/src/share/classes/com/sun/corba/se/impl/presentation/rmi/InvocationHandlerFactoryImpl.java
+++ b/corba/src/share/classes/com/sun/corba/se/impl/presentation/rmi/InvocationHandlerFactoryImpl.java
@@ -43,6 +43,8 @@
 import com.sun.corba.se.spi.orbutil.proxy.DelegateInvocationHandlerImpl ;
 import com.sun.corba.se.spi.orbutil.proxy.CompositeInvocationHandler ;
 import com.sun.corba.se.spi.orbutil.proxy.CompositeInvocationHandlerImpl ;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 
 public class InvocationHandlerFactoryImpl implements InvocationHandlerFactory
 {
@@ -114,24 +116,32 @@
         // which extends org.omg.CORBA.Object.  This handler delegates all
         // calls directly to a DynamicStubImpl, which extends
         // org.omg.CORBA.portable.ObjectImpl.
-        InvocationHandler dynamicStubHandler =
+        final InvocationHandler dynamicStubHandler =
             DelegateInvocationHandlerImpl.create( stub ) ;
 
         // Create an invocation handler that handles any remote interface
         // methods.
-        InvocationHandler stubMethodHandler = new StubInvocationHandlerImpl(
+        final InvocationHandler stubMethodHandler = new StubInvocationHandlerImpl(
             pm, classData, stub ) ;
 
         // Create a composite handler that handles the DynamicStub interface
         // as well as the remote interfaces.
         final CompositeInvocationHandler handler =
             new CustomCompositeInvocationHandlerImpl( stub ) ;
+
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+            @Override
+            public Void run() {
         handler.addInvocationHandler( DynamicStub.class,
             dynamicStubHandler ) ;
         handler.addInvocationHandler( org.omg.CORBA.Object.class,
             dynamicStubHandler ) ;
         handler.addInvocationHandler( Object.class,
             dynamicStubHandler ) ;
+                return null;
+            }
+        });
+
 
         // If the method passed to invoke is not from DynamicStub or its superclasses,
         // it must be from an implemented interface, so we just handle
diff --git a/corba/src/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java b/corba/src/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java
index 7bd9880..054071b 100644
--- a/corba/src/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java
+++ b/corba/src/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,7 +55,7 @@
 /**
  * @author Harold Carr
  */
-public class SelectorImpl
+class SelectorImpl
     extends
         Thread
     implements
diff --git a/corba/src/share/classes/com/sun/corba/se/spi/orbutil/proxy/CompositeInvocationHandlerImpl.java b/corba/src/share/classes/com/sun/corba/se/spi/orbutil/proxy/CompositeInvocationHandlerImpl.java
index fb81cee..91aacd5 100644
--- a/corba/src/share/classes/com/sun/corba/se/spi/orbutil/proxy/CompositeInvocationHandlerImpl.java
+++ b/corba/src/share/classes/com/sun/corba/se/spi/orbutil/proxy/CompositeInvocationHandlerImpl.java
@@ -36,6 +36,7 @@
 
 import com.sun.corba.se.spi.logging.CORBALogDomains ;
 import com.sun.corba.se.impl.logging.ORBUtilSystemException ;
+import com.sun.corba.se.impl.presentation.rmi.DynamicAccessPermission;
 
 public class CompositeInvocationHandlerImpl implements
     CompositeInvocationHandler
@@ -46,11 +47,13 @@
     public void addInvocationHandler( Class interf,
         InvocationHandler handler )
     {
+        checkAccess();
         classToInvocationHandler.put( interf, handler ) ;
     }
 
     public void setDefaultHandler( InvocationHandler handler )
     {
+        checkAccess();
         defaultHandler = handler ;
     }
 
@@ -78,4 +81,12 @@
 
         return handler.invoke( proxy, method, args ) ;
     }
+
+    private static final DynamicAccessPermission perm = new DynamicAccessPermission("access");
+    private void checkAccess() {
+        final SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            sm.checkPermission(perm);
+}
+    }
 }
diff --git a/corba/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java b/corba/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java
index 143beef..d2278a8 100644
--- a/corba/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java
+++ b/corba/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,9 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.io.SerializablePermission;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.Vector;
 import java.util.Hashtable;
 import java.util.Enumeration;
@@ -49,6 +52,7 @@
 import com.sun.corba.se.impl.util.PackagePrefixChecker;
 import sun.rmi.rmic.Main;
 
+
 /**
  * An IIOP stub/tie generator for rmic.
  *
@@ -78,6 +82,7 @@
     protected boolean castArray = false;
     protected Hashtable transactionalObjects = new Hashtable() ;
     protected boolean POATie = false ;
+    protected boolean emitPermissionCheck = false;
 
     /**
      * Default constructor for Main to use.
@@ -193,6 +198,9 @@
                     } else if (argv[i].equals("-standardPackage")) {
                         standardPackage = true;
                         argv[i] = null;
+                    } else if (argv[i].equals("-emitPermissionCheck")) {
+                        emitPermissionCheck = true;
+                        argv[i] = null;
                     } else if (arg.equals("-xstubbase")) {
                         argv[i] = null;
                         if (++i < argv.length && argv[i] != null && !argv[i].startsWith("-")) {
@@ -390,9 +398,22 @@
 
         writePackageAndImports(p);
 
+//        generate
+//        import java.security.AccessController;
+//        import java.security.PrivilegedAction;
+//        import java.io.SerializablePermission;
+        if (emitPermissionCheck) {
+            p.pln("import java.security.AccessController;");
+            p.pln("import java.security.PrivilegedAction;");
+            p.pln("import java.io.SerializablePermission;");
+            p.pln();
+            p.pln();
+        }
+
         // Declare the stub class; implement all remote interfaces.
 
         p.p("public class " + currentClass);
+
         p.p(" extends " + getName(stubBaseClass));
         p.p(" implements ");
         if (remoteInterfaces.length > 0) {
@@ -422,6 +443,56 @@
         writeIds( p, theType, false );
         p.pln();
 
+        if (emitPermissionCheck) {
+
+            // produce the following generated code
+            // private static Void checkPermission() {
+            // SecurityManager sm = System.getSecurityManager();
+            // if (sm != null) {
+            //     sm.checkPermission(new SerializablePermission(
+            // "enableSubclassImplementation")); // testing
+            // }
+            // return null;
+            // }
+            //
+            // private _XXXXXX_Stub(Void ignore) {
+            // }
+            //
+            // public _XXXXXX_Stub() {
+            // this(checkPermission());
+            // }
+            // where XXXXXX is the name of the remote interface
+
+                p.pln();
+                p.plnI("private static Void checkPermission() {");
+                p.plnI("SecurityManager sm = System.getSecurityManager();");
+                p.pln("if (sm != null) {");
+                p.pI();
+                p.plnI("sm.checkPermission(new SerializablePermission(");
+                p.plnI("\"enableSubclassImplementation\"));");
+                p.pO();
+                p.pO();
+                p.pOln("}");
+                p.pln("return null;");
+                p.pO();
+                p.pOln("}");
+                p.pln();
+                p.pO();
+
+                p.pI();
+                p.pln("private " + currentClass + "(Void ignore) {  }");
+                p.pln();
+
+                p.plnI("public " + currentClass + "() { ");
+                p.pln("this(checkPermission());");
+                p.pOln("}");
+                p.pln();
+        }
+
+       if (!emitPermissionCheck) {
+            p.pI();
+       }
+
         // Write the _ids() method...
 
         p.plnI("public String[] _ids() { ");
@@ -815,7 +886,6 @@
                             CompoundType theType) throws IOException {
 
         // Wtite the method declaration and opening brace...
-
         String methodName = method.getName();
         String methodIDLName = method.getIDLName();
 
@@ -1631,7 +1701,7 @@
 
         // Write data members...
         p.pln();
-        p.pln("private " + getName(theType) + " target = null;");
+        p.pln("volatile private " + getName(theType) + " target = null;");
         p.pln();
 
         // Write the ids...
@@ -1695,6 +1765,10 @@
 
         if (remoteMethods.length > 0) {
             p.plnI("try {");
+            p.pln(getName(theType) + " target = this.target;");
+            p.plnI("if (target == null) {");
+            p.pln("throw new java.io.IOException();");
+            p.pOln("}");
             p.plnI(idExtInputStream + " "+in+" = ");
             p.pln("(" + idExtInputStream + ") "+_in+";");
             p.pO();
diff --git a/hotspot/.hgtags b/hotspot/.hgtags
index 3e53ae3..8281fba 100644
--- a/hotspot/.hgtags
+++ b/hotspot/.hgtags
@@ -476,6 +476,24 @@
 8386245b59c3e82b7c728b7d3832ea342c62615d jdk7u21-b50
 c5e4585a045fe165d067ec0e98af42eace20c5f8 jdk7u21-b12
 00dbf9fa12ec6b1ba15d9a9a12495f50e10837bf jdk7u21-b31
+bf2d84c5103d98db1697b50071a649ea23c4e33d jdk7u25-b01
+07119340f80f77dfcb03fa568641e80b43d4be74 jdk7u25-b02
+655bea6843fb7beabd8d9eeda59572c0c7055b85 jdk7u25-b03
+96a4e612195c0d753be24cf38fea0ee8ce30edcf jdk7u25-b04
+7151c26b838828a20cb28595ef1f70403d1868cf jdk7u25-b05
+fbb5f6083dd00ca7417e4a45311f33918bb2a5f0 jdk7u25-b06
+83abf4b2fc8a5bb7226177c5e4334bd0bfd7a8df jdk7u25-b07
+525252cd9fca4869c3fd81bc61299a85e73ff9c7 jdk7u25-b08
+706a255a8404b7e41579cea278df6bb87c314567 jdk7u25-b09
+402184622f60a2ba35479bdf124a8d4694835406 jdk7u25-b10
+cca49a35bf83664456af112482ffb3a7465d21fa jdk7u25-b11
+7ca68c0674df72fdd784de337c049404d2b5b0c3 jdk7u25-b12
+3e145a686fedd9eefdcb6b714241200ed236b41d jdk7u25-b13
+4fafaf293aa5666e8c9f5ca1d96c3f752305f586 jdk7u25-b14
+40acb370626fbc439e4cfed8854960a83a376fba jdk7u25-b15
+97a3ebd62052410e0709035f40032d3f2113ed86 jdk7u25-b30
+b80a290e6e3011097273525c4f352c70b9857464 jdk7u25-b16
+273e8afccd6ef9e10e9fe121f7b323755191f3cc jdk7u25-b32
 e3d2c238e29c421c3b5c001e400acbfb30790cfc jdk7u14-b14
 860ae068f4dff62a77c8315f0335b7e935087e86 hs24-b34
 12619005c5e29be6e65f0dc9891ca19d9ffb1aaa jdk7u14-b15
@@ -542,3 +560,9 @@
 675a89fd4548389e3d54a29c6fe271d913e7eee6 hs24-b55
 13edc330a937d4323f38b6a59cc255b6d61c51dc jdk7u40-b36
 295528bfcdd10051f72572a26bfad2317b7de464 jdk7u40-b37
+1f3b0ff9649c4be3b08cc829d37eee98d9c6e605 jdk7u40-b38
+5fb434aa203c32b4551167b922a70e79831ffdf4 jdk7u45-b01
+f2039061ba49de742ae88cc3123fd1237965d665 jdk7u45-b02
+d6fd3f84a30ce82a37fc39b6e5e9d73bd8054ab2 jdk7u45-b03
+7f16aa9067386aeb3668336aa6cd63ef3dc4f44a jdk7u45-b04
+b4fe146b820b47d8b59bbb9dc9d43221436ed0ae jdk7u45-b05
diff --git a/hotspot/make/hotspot_version b/hotspot/make/hotspot_version
index 5dee8fa1..849825a 100644
--- a/hotspot/make/hotspot_version
+++ b/hotspot/make/hotspot_version
@@ -34,8 +34,8 @@
 HOTSPOT_VM_COPYRIGHT=Copyright 2013
 
 HS_MAJOR_VER=24
-HS_MINOR_VER=0
-HS_BUILD_NUMBER=55
+HS_MINOR_VER=45
+HS_BUILD_NUMBER=05
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=7
diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp
index 8d57bb1..6ffa4bf 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp
@@ -4051,9 +4051,8 @@
   for (int index = 0; index < num_methods; index++) {
     methodOop m = (methodOop)methods->obj_at(index);
 
-    // skip private, static and <init> methods
-    if ((!m->is_private()) &&
-        (!m->is_static()) &&
+    // skip static and <init> methods
+    if ((!m->is_static()) &&
         (m->name() != vmSymbols::object_initializer_name())) {
 
       Symbol* name = m->name();
diff --git a/jaxp/.hgtags b/jaxp/.hgtags
index 99edce1..eb10fc8 100644
--- a/jaxp/.hgtags
+++ b/jaxp/.hgtags
@@ -302,6 +302,22 @@
 5952538d55e624132f97400332a50b71880c874c jdk7u25-b09
 aa00dd983dd0f5b07269d0648a0325e9b3e0d957 jdk7u25-b10
 0fb6d76bcd2e8d54d0a69e1c3d2a85d84b3e17a4 jdk7u25-b11
+7b47e1a26f7cbb8d8d22ea165f2d7fbbbd354c77 jdk7u14-b16
+77ac1ef42b2fd47cc87b9800f63efdd4cf2fa05d jdk7u14-b17
+d47975f80a24b55410fa2e2c5f50f3405d83fe73 jdk7u14-b18
+331e489ecb7b19fa98c60324f7ce5d168284a8c8 jdk7u14-b19
+331e489ecb7b19fa98c60324f7ce5d168284a8c8 jdk7u14-b19
+c3c9f04cf10c2fe576b208f6a8ca3777b1d31145 jdk7u14-b19
+5e1fee011646b4a3ff29b7b9cdc208e0a0577cb4 jdk7u14-b20
+d1c8bb1cbc9183fc994b5fedf26886ceda0d59f9 jdk7u14-b21
+d1c6afebdfe28eb07eb2d03a6911a0f33b619165 jdk7u14-b22
+0e4c549d3635122145ac88bad7b98716976ca49e jdk7u40-b23
+d17acb2ee133811baa8eae3436a8c191fc433da1 jdk7u40-b24
+52bcce690998b4ad91abddae118847f4358c6110 jdk7u40-b25
+cd764ada36b50e2096ba35b4c27ca8f83b3db964 jdk7u40-b26
+7626b3fbc822fd4efd5ba3b5fc18f2fef5749597 jdk7u40-b27
+9186b6efd2b2eafa7fee5be1b043f59f25db12a6 jdk7u40-b28
+740942c76fb668a04bf89feccf069f6958651d54 jdk7u40-b29
 5e87aee78c91efa65bd5aeb37bcc1c1c637a7f0c jdk7u25-b12
 83b80c094befd08cbac4247d9b8f12c6a039f23f jdk7u25-b13
 68cc0d2a49f09b5c611b2775f2e66de1022bdedc jdk7u25-b14
@@ -336,3 +352,9 @@
 4056df34b559b904edc9f94a323769f19cf8f426 jdk7u40-b35
 07024f18376ce9597ec8679ebcb9f2efdc5afab0 jdk7u40-b36
 f40f45bd95d4140f691c03132f2ab2c8a0233a8f jdk7u40-b37
+680bf140cdd58e7878318ecafc41c9db47ebfacd jdk7u40-b38
+1a7e2024963d3a8d6cde209de0967ac43418b82a jdk7u45-b01
+72b314bf2ee171bec2157f737ba3bf77fbdf1118 jdk7u45-b02
+399c58bf22ad35a3527a286123497615100746b2 jdk7u45-b03
+e66ea9257ba8a77fc64f6f2924584b183767d82b jdk7u45-b04
+3a6dce39c05c254aba9f3ae57c035bf3facfe8b9 jdk7u45-b05
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/XalanConstants.java b/jaxp/src/com/sun/org/apache/xalan/internal/XalanConstants.java
index ce50626..9dc521f 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/XalanConstants.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/XalanConstants.java
@@ -39,33 +39,138 @@
     //
     // Constants
     //
-    // Oracle Feature:
+    //Xerces security manager
+    public static final String SECURITY_MANAGER =
+            "http://apache.org/xml/properties/security-manager";
+
+    //
+    // Implementation limits: API properties
+    //
+    /** Oracle JAXP property prefix ("http://www.oracle.com/xml/jaxp/properties/"). */
+    public static final String ORACLE_JAXP_PROPERTY_PREFIX =
+        "http://www.oracle.com/xml/jaxp/properties/";
     /**
-     * <p>Use Service Mechanism</p>
-     *
-     * <ul>
-     *   <li>
+     * JDK entity expansion limit; Note that the existing system property
+     * "entityExpansionLimit" with no prefix is still observed
+     */
+    public static final String JDK_ENTITY_EXPANSION_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "entityExpansionLimit";
+
+    /**
+     * JDK element attribute limit; Note that the existing system property
+     * "elementAttributeLimit" with no prefix is still observed
+     */
+    public static final String JDK_ELEMENT_ATTRIBUTE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "elementAttributeLimit";
+
+    /**
+     * JDK maxOccur limit; Note that the existing system property
+     * "maxOccurLimit" with no prefix is still observed
+     */
+    public static final String JDK_MAX_OCCUR_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxOccurLimit";
+
+    /**
+     * JDK total entity size limit
+     */
+    public static final String JDK_TOTAL_ENTITY_SIZE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "totalEntitySizeLimit";
+
+    /**
+     * JDK maximum general entity size limit
+     */
+    public static final String JDK_GENEAL_ENTITY_SIZE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxGeneralEntitySizeLimit";
+    /**
+     * JDK maximum parameter entity size limit
+     */
+    public static final String JDK_PARAMETER_ENTITY_SIZE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxParameterEntitySizeLimit";
+    /**
+     * JDK maximum XML name limit
+     */
+    public static final String JDK_XML_NAME_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxXMLNameLimit";
+    /**
+     * JDK property indicating whether the parser shall print out entity
+     * count information
+     * Value: a string "yes" means print, "no" or any other string means not.
+     */
+    public static final String JDK_ENTITY_COUNT_INFO =
+            ORACLE_JAXP_PROPERTY_PREFIX + "getEntityCountInfo";
+
+    //
+    // Implementation limits: corresponding System Properties of the above
+    // API properties
+    //
+    /**
+     * JDK entity expansion limit; Note that the existing system property
+     * "entityExpansionLimit" with no prefix is still observed
+     */
+    public static final String SP_ENTITY_EXPANSION_LIMIT = "jdk.xml.entityExpansionLimit";
+
+    /**
+     * JDK element attribute limit; Note that the existing system property
+     * "elementAttributeLimit" with no prefix is still observed
+     */
+    public static final String SP_ELEMENT_ATTRIBUTE_LIMIT =  "jdk.xml.elementAttributeLimit";
+
+    /**
+     * JDK maxOccur limit; Note that the existing system property
+     * "maxOccurLimit" with no prefix is still observed
+     */
+    public static final String SP_MAX_OCCUR_LIMIT = "jdk.xml.maxOccurLimit";
+
+    /**
+     * JDK total entity size limit
+     */
+    public static final String SP_TOTAL_ENTITY_SIZE_LIMIT = "jdk.xml.totalEntitySizeLimit";
+
+    /**
+     * JDK maximum general entity size limit
+     */
+    public static final String SP_GENEAL_ENTITY_SIZE_LIMIT = "jdk.xml.maxGeneralEntitySizeLimit";
+    /**
+     * JDK maximum parameter entity size limit
+     */
+    public static final String SP_PARAMETER_ENTITY_SIZE_LIMIT = "jdk.xml.maxParameterEntitySizeLimit";
+    /**
+     * JDK maximum XML name limit
+     */
+    public static final String SP_XML_NAME_LIMIT = "jdk.xml.maxXMLNameLimit";
+
+    //legacy System Properties
+    public final static String ENTITY_EXPANSION_LIMIT = "entityExpansionLimit";
+    public static final String ELEMENT_ATTRIBUTE_LIMIT = "elementAttributeLimit" ;
+    public final static String MAX_OCCUR_LIMIT = "maxOccurLimit";
+
+    /**
+     * A string "yes" that can be used for properties such as getEntityCountInfo
+     */
+    public static final String JDK_YES = "yes";
+
+    // Oracle Feature:
+        /**
+         * <p>Use Service Mechanism</p>
+         *
+         * <ul>
+         *   <li>
          * {@code true} instruct an object to use service mechanism to
          * find a service implementation. This is the default behavior.
          *   </li>
          *   <li>
          * {@code false} instruct an object to skip service mechanism and
          * use the default implementation for that service.
-     *   </li>
-     * </ul>
-    */
-
+         *   </li>
+         * </ul>
+         */
     public static final String ORACLE_FEATURE_SERVICE_MECHANISM = "http://www.oracle.com/feature/use-service-mechanism";
 
-    /** Oracle JAXP property prefix ("http://www.oracle.com/xml/jaxp/properties/"). */
-    public static final String ORACLE_JAXP_PROPERTY_PREFIX =
-        "http://www.oracle.com/xml/jaxp/properties/";
 
     //System Properties corresponding to ACCESS_EXTERNAL_* properties
     public static final String SP_ACCESS_EXTERNAL_STYLESHEET = "javax.xml.accessExternalStylesheet";
     public static final String SP_ACCESS_EXTERNAL_DTD = "javax.xml.accessExternalDTD";
 
-
     //all access keyword
     public static final String ACCESS_EXTERNAL_ALL = "all";
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java b/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java
new file mode 100644
index 0000000..99a8e2d
--- /dev/null
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityManager.java
@@ -0,0 +1,449 @@
+/*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
+ *
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * The contents of this file are subject to the terms of either the GNU
+ * General Public License Version 2 only ("GPL") or the Common Development
+ * and Distribution License("CDDL") (collectively, the "License").  You
+ * may not use this file except in compliance with the License.  You can
+ * obtain a copy of the License at
+ * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
+ * or packager/legal/LICENSE.txt.  See the License for the specific
+ * language governing permissions and limitations under the License.
+ *
+ * When distributing the software, include this License Header Notice in each
+ * file and include the License file at packager/legal/LICENSE.txt.
+ *
+ * GPL Classpath Exception:
+ * Oracle designates this particular file as subject to the "Classpath"
+ * exception as provided by Oracle in the GPL Version 2 section of the License
+ * file that accompanied this code.
+ *
+ * Modifications:
+ * If applicable, add the following below the License Header, with the fields
+ * enclosed by brackets [] replaced by your own identifying information:
+ * "Portions Copyright [year] [name of copyright owner]"
+ *
+ * Contributor(s):
+ * If you wish your version of this file to be governed by only the CDDL or
+ * only the GPL Version 2, indicate your decision by adding "[Contributor]
+ * elects to include this software in this distribution under the [CDDL or GPL
+ * Version 2] license."  If you don't indicate a single choice of license, a
+ * recipient has the option to distribute your version of this file under
+ * either the CDDL, the GPL Version 2 or to extend the choice of license to
+ * its licensees as provided above.  However, if you add GPL Version 2 code
+ * and therefore, elected the GPL Version 2 license, then the option applies
+ * only if the new code is made subject to such option by the copyright
+ * holder.
+ */
+package com.sun.org.apache.xalan.internal.utils;
+
+import com.sun.org.apache.xalan.internal.XalanConstants;
+
+
+/**
+ * This class is not the same as that in Xerces. It is used to manage the
+ * state of corresponding Xerces properties and pass the values over to
+ * the Xerces Security Manager.
+ *
+ * @author Joe Wang Oracle Corp.
+ *
+ */
+public final class XMLSecurityManager {
+
+    /**
+     * States of the settings of a property, in the order: default value, value
+     * set by FEATURE_SECURE_PROCESSING, jaxp.properties file, jaxp system
+     * properties, and jaxp api properties
+     */
+    public static enum State {
+        //this order reflects the overriding order
+
+        DEFAULT("default"), FSP("FEATURE_SECURE_PROCESSING"),
+        JAXPDOTPROPERTIES("jaxp.properties"), SYSTEMPROPERTY("system property"),
+        APIPROPERTY("property");
+
+        final String literal;
+        State(String literal) {
+            this.literal = literal;
+        }
+
+        String literal() {
+            return literal;
+        }
+    }
+
+    /**
+     * Limits managed by the security manager
+     */
+    public static enum Limit {
+
+        ENTITY_EXPANSION_LIMIT(XalanConstants.JDK_ENTITY_EXPANSION_LIMIT,
+                XalanConstants.SP_ENTITY_EXPANSION_LIMIT, 0, 64000),
+        MAX_OCCUR_NODE_LIMIT(XalanConstants.JDK_MAX_OCCUR_LIMIT,
+                XalanConstants.SP_MAX_OCCUR_LIMIT, 0, 5000),
+        ELEMENT_ATTRIBUTE_LIMIT(XalanConstants.JDK_ELEMENT_ATTRIBUTE_LIMIT,
+                XalanConstants.SP_ELEMENT_ATTRIBUTE_LIMIT, 0, 10000),
+        TOTAL_ENTITY_SIZE_LIMIT(XalanConstants.JDK_TOTAL_ENTITY_SIZE_LIMIT,
+                XalanConstants.SP_TOTAL_ENTITY_SIZE_LIMIT, 0, 50000000),
+        GENEAL_ENTITY_SIZE_LIMIT(XalanConstants.JDK_GENEAL_ENTITY_SIZE_LIMIT,
+                XalanConstants.SP_GENEAL_ENTITY_SIZE_LIMIT, 0, 0),
+        PARAMETER_ENTITY_SIZE_LIMIT(XalanConstants.JDK_PARAMETER_ENTITY_SIZE_LIMIT,
+                XalanConstants.SP_PARAMETER_ENTITY_SIZE_LIMIT, 0, 1000000);
+
+        final String apiProperty;
+        final String systemProperty;
+        final int defaultValue;
+        final int secureValue;
+
+        Limit(String apiProperty, String systemProperty, int value, int secureValue) {
+            this.apiProperty = apiProperty;
+            this.systemProperty = systemProperty;
+            this.defaultValue = value;
+            this.secureValue = secureValue;
+        }
+
+        public boolean equalsAPIPropertyName(String propertyName) {
+            return (propertyName == null) ? false : apiProperty.equals(propertyName);
+        }
+
+        public boolean equalsSystemPropertyName(String propertyName) {
+            return (propertyName == null) ? false : systemProperty.equals(propertyName);
+        }
+
+        public String apiProperty() {
+            return apiProperty;
+        }
+
+        String systemProperty() {
+            return systemProperty;
+        }
+
+        int defaultValue() {
+            return defaultValue;
+        }
+
+        int secureValue() {
+            return secureValue;
+        }
+    }
+
+    /**
+     * Map old property names with the new ones
+     */
+    public static enum NameMap {
+
+        ENTITY_EXPANSION_LIMIT(XalanConstants.SP_ENTITY_EXPANSION_LIMIT,
+                XalanConstants.ENTITY_EXPANSION_LIMIT),
+        MAX_OCCUR_NODE_LIMIT(XalanConstants.SP_MAX_OCCUR_LIMIT,
+                XalanConstants.MAX_OCCUR_LIMIT),
+        ELEMENT_ATTRIBUTE_LIMIT(XalanConstants.SP_ELEMENT_ATTRIBUTE_LIMIT,
+                XalanConstants.ELEMENT_ATTRIBUTE_LIMIT);
+        final String newName;
+        final String oldName;
+
+        NameMap(String newName, String oldName) {
+            this.newName = newName;
+            this.oldName = oldName;
+        }
+
+        String getOldName(String newName) {
+            if (newName.equals(this.newName)) {
+                return oldName;
+            }
+            return null;
+        }
+    }
+    /**
+     * Values of the properties
+     */
+    private final int[] values;
+    /**
+     * States of the settings for each property
+     */
+    private State[] states;
+    /**
+     * States that determine if properties are set explicitly
+     */
+    private boolean[] isSet;
+
+
+    /**
+     * Index of the special entityCountInfo property
+     */
+    private int indexEntityCountInfo = 10000;
+    private String printEntityCountInfo = "";
+
+    /**
+     * Default constructor. Establishes default values for known security
+     * vulnerabilities.
+     */
+    public XMLSecurityManager() {
+        this(false);
+    }
+
+    /**
+     * Instantiate Security Manager in accordance with the status of
+     * secure processing
+     * @param secureProcessing
+     */
+    public XMLSecurityManager(boolean secureProcessing) {
+        values = new int[Limit.values().length];
+        states = new State[Limit.values().length];
+        isSet = new boolean[Limit.values().length];
+        for (Limit limit : Limit.values()) {
+            if (secureProcessing) {
+                values[limit.ordinal()] = limit.secureValue();
+                states[limit.ordinal()] = State.FSP;
+            } else {
+                values[limit.ordinal()] = limit.defaultValue();
+                states[limit.ordinal()] = State.DEFAULT;
+            }
+        }
+        //read system properties or jaxp.properties
+        readSystemProperties();
+    }
+
+    /**
+     * Setting FEATURE_SECURE_PROCESSING explicitly
+     */
+    public void setSecureProcessing(boolean secure) {
+        for (Limit limit : Limit.values()) {
+            if (secure) {
+                setLimit(limit.ordinal(), State.FSP, limit.secureValue());
+            } else {
+                setLimit(limit.ordinal(), State.FSP, limit.defaultValue());
+            }
+        }
+    }
+
+    /**
+     * Set limit by property name and state
+     * @param propertyName property name
+     * @param state the state of the property
+     * @param value the value of the property
+     * @return true if the property is managed by the security manager; false
+     *              if otherwise.
+     */
+    public boolean setLimit(String propertyName, State state, Object value) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            setLimit(index, state, value);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Set the value for a specific limit.
+     *
+     * @param limit the limit
+     * @param state the state of the property
+     * @param value the value of the property
+     */
+    public void setLimit(Limit limit, State state, int value) {
+        setLimit(limit.ordinal(), state, value);
+    }
+
+    /**
+     * Set the value of a property by its index
+     *
+     * @param index the index of the property
+     * @param state the state of the property
+     * @param value the value of the property
+     */
+    public void setLimit(int index, State state, Object value) {
+        if (index == indexEntityCountInfo) {
+            //if it's explicitly set, it's treated as yes no matter the value
+            printEntityCountInfo = (String)value;
+        } else {
+            int temp = 0;
+            try {
+                temp = Integer.parseInt((String) value);
+                if (temp < 0) {
+                    temp = 0;
+                }
+            } catch (NumberFormatException e) {}
+            setLimit(index, state, temp);        }
+    }
+
+    /**
+     * Set the value of a property by its index
+     *
+     * @param index the index of the property
+     * @param state the state of the property
+     * @param value the value of the property
+     */
+    public void setLimit(int index, State state, int value) {
+        if (index == indexEntityCountInfo) {
+            //if it's explicitly set, it's treated as yes no matter the value
+            printEntityCountInfo = XalanConstants.JDK_YES;
+        } else {
+            //only update if it shall override
+            if (state.compareTo(states[index]) >= 0) {
+                values[index] = value;
+                states[index] = state;
+                isSet[index] = true;
+            }
+        }
+    }
+
+
+    /**
+     * Return the value of the specified property.
+     *
+     * @param propertyName the property name
+     * @return the value of the property as a string. If a property is managed
+     * by this manager, its value shall not be null.
+     */
+    public String getLimitAsString(String propertyName) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            return getLimitValueByIndex(index);
+        }
+
+        return null;
+    }
+
+    /**
+     * Return the value of a property by its ordinal
+     *
+     * @param limit the property
+     * @return value of a property
+     */
+    public String getLimitValueAsString(Limit limit) {
+        return Integer.toString(values[limit.ordinal()]);
+    }
+
+    /**
+     * Return the value of the specified property
+     *
+     * @param limit the property
+     * @return the value of the property
+     */
+    public int getLimit(Limit limit) {
+        return values[limit.ordinal()];
+    }
+
+    /**
+     * Return the value of a property by its ordinal
+     *
+     * @param index the index of a property
+     * @return value of a property
+     */
+    public int getLimitByIndex(int index) {
+        return values[index];
+    }
+    /**
+     * Return the value of a property by its index
+     *
+     * @param index the index of a property
+     * @return limit of a property as a string
+     */
+    public String getLimitValueByIndex(int index) {
+        if (index == indexEntityCountInfo) {
+            return printEntityCountInfo;
+        }
+
+        return Integer.toString(values[index]);
+    }
+    /**
+     * Return the state of the limit property
+     *
+     * @param limit the limit
+     * @return the state of the limit property
+     */
+    public State getState(Limit limit) {
+        return states[limit.ordinal()];
+    }
+
+    /**
+     * Return the state of the limit property
+     *
+     * @param limit the limit
+     * @return the state of the limit property
+     */
+    public String getStateLiteral(Limit limit) {
+        return states[limit.ordinal()].literal();
+    }
+
+    /**
+     * Get the index by property name
+     *
+     * @param propertyName property name
+     * @return the index of the property if found; return -1 if not
+     */
+    public int getIndex(String propertyName) {
+        for (Limit limit : Limit.values()) {
+            if (limit.equalsAPIPropertyName(propertyName)) {
+                //internally, ordinal is used as index
+                return limit.ordinal();
+            }
+        }
+        //special property to return entity count info
+        if (propertyName.equals(XalanConstants.JDK_ENTITY_COUNT_INFO)) {
+            return indexEntityCountInfo;
+        }
+        return -1;
+    }
+
+    /**
+     * Indicate if a property is set explicitly
+     * @param index
+     * @return
+     */
+    public boolean isSet(int index) {
+        return isSet[index];
+    }
+
+    public boolean printEntityCountInfo() {
+        return printEntityCountInfo.equals(XalanConstants.JDK_YES);
+    }
+    /**
+     * Read from system properties, or those in jaxp.properties
+     */
+    private void readSystemProperties() {
+
+        for (Limit limit : Limit.values()) {
+            if (!getSystemProperty(limit, limit.systemProperty())) {
+                //if system property is not found, try the older form if any
+                for (NameMap nameMap : NameMap.values()) {
+                    String oldName = nameMap.getOldName(limit.systemProperty());
+                    if (oldName != null) {
+                        getSystemProperty(limit, oldName);
+                    }
+                }
+            }
+        }
+
+    }
+
+    /**
+     * Read from system properties, or those in jaxp.properties
+     *
+     * @param property the type of the property
+     * @param sysPropertyName the name of system property
+     */
+    private boolean getSystemProperty(Limit limit, String sysPropertyName) {
+        try {
+            String value = SecuritySupport.getSystemProperty(sysPropertyName);
+            if (value != null && !value.equals("")) {
+                values[limit.ordinal()] = Integer.parseInt(value);
+                states[limit.ordinal()] = State.SYSTEMPROPERTY;
+                return true;
+            }
+
+            value = SecuritySupport.readJAXPProperty(sysPropertyName);
+            if (value != null && !value.equals("")) {
+                values[limit.ordinal()] = Integer.parseInt(value);
+                states[limit.ordinal()] = State.JAXPDOTPROPERTIES;
+                return true;
+            }
+        } catch (NumberFormatException e) {
+            //invalid setting
+            throw new NumberFormatException("Invalid setting for system property: " + limit.systemProperty());
+        }
+        return false;
+    }
+}
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityPropertyManager.java b/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityPropertyManager.java
index 5f5501a..35dc9a5 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityPropertyManager.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/utils/XMLSecurityPropertyManager.java
@@ -94,6 +94,23 @@
     }
 
     /**
+     * Set limit by property name and state
+     * @param propertyName property name
+     * @param state the state of the property
+     * @param value the value of the property
+     * @return true if the property is managed by the security property manager;
+     *         false if otherwise.
+     */
+    public boolean setValue(String propertyName, State state, Object value) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            setValue(index, state, (String)value);
+            return true;
+        }
+        return false;
+    }
+
+    /**
      * Set the value for a specific property.
      *
      * @param property the property
@@ -121,6 +138,22 @@
             states[index] = state;
         }
     }
+
+    /**
+     * Return the value of the specified property
+     *
+     * @param propertyName the property name
+     * @return the value of the property as a string
+     */
+    public String getValue(String propertyName) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            return getValueByIndex(index);
+        }
+
+        return null;
+    }
+
     /**
      * Return the value of the specified property
      *
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Import.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Import.java
index fdfbe17..e1971d3 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Import.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Import.java
@@ -86,7 +86,7 @@
             if (input == null) {
                 docToLoad = SystemIDResolver.getAbsoluteURI(docToLoad, currLoadedDoc);
                 String accessError = SecuritySupport.checkAccess(docToLoad,
-                        xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET),
+                        (String)xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET),
                         XalanConstants.ACCESS_EXTERNAL_ALL);
 
                 if (accessError != null) {
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Include.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Include.java
index 71c129f..5bf12f8 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Include.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Include.java
@@ -87,7 +87,7 @@
             if (input == null) {
                 docToLoad = SystemIDResolver.getAbsoluteURI(docToLoad, currLoadedDoc);
                 String accessError = SecuritySupport.checkAccess(docToLoad,
-                        xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET),
+                        (String)xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET),
                         XalanConstants.ACCESS_EXTERNAL_ALL);
 
                 if (accessError != null) {
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
index 3c186a1..0903d9a 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
@@ -28,6 +28,7 @@
 import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
 import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
+import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodType;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
@@ -487,6 +488,20 @@
             }
 
             final XMLReader reader = parser.getXMLReader();
+            try {
+                XMLSecurityManager securityManager =
+                        (XMLSecurityManager)_xsltc.getProperty(XalanConstants.SECURITY_MANAGER);
+                for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
+                    reader.setProperty(limit.apiProperty(), securityManager.getLimitValueAsString(limit));
+                }
+                if (securityManager.printEntityCountInfo()) {
+                    parser.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
+                }
+            } catch (SAXException se) {
+                System.err.println("Warning:  " + reader.getClass().getName() + ": "
+                            + se.getMessage());
+            }
+
             return(parse(reader, input));
         }
         catch (ParserConfigurationException e) {
@@ -565,7 +580,7 @@
                 }
                 path = SystemIDResolver.getAbsoluteURI(path);
                 String accessError = SecuritySupport.checkAccess(path,
-                        _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET),
+                        (String)_xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET),
                         XalanConstants.ACCESS_EXTERNAL_ALL);
                 if (accessError != null) {
                     ErrorMsg msg = new ErrorMsg(ErrorMsg.ACCESSING_XSLT_TARGET_ERR,
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
index 97fff3b..10823f1 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
@@ -44,11 +44,11 @@
 import com.sun.org.apache.bcel.internal.classfile.JavaClass;
 import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
+import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util;
 import com.sun.org.apache.xml.internal.dtm.DTM;
 
-import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
 import org.xml.sax.InputSource;
 import org.xml.sax.XMLReader;
 
@@ -146,6 +146,7 @@
      */
     private String _accessExternalDTD = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
 
+    private XMLSecurityManager _xmlSecurityManager;
 
     /**
      * XSLTC compiler constructor
@@ -184,12 +185,14 @@
     /**
      * Return allowed protocols for accessing external stylesheet.
      */
-    public String getProperty(String name) {
+    public Object getProperty(String name) {
         if (name.equals(XMLConstants.ACCESS_EXTERNAL_STYLESHEET)) {
             return _accessExternalStylesheet;
         }
         else if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
             return _accessExternalDTD;
+        } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
+            return _xmlSecurityManager;
         }
         return null;
     }
@@ -197,12 +200,14 @@
     /**
      * Set allowed protocols for accessing external stylesheet.
      */
-    public void setProperty(String name, String value) {
+    public void setProperty(String name, Object value) {
         if (name.equals(XMLConstants.ACCESS_EXTERNAL_STYLESHEET)) {
             _accessExternalStylesheet = (String)value;
         }
         else if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
             _accessExternalDTD = (String)value;
+        } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
+            _xmlSecurityManager = (XMLSecurityManager)value;
         }
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
index 879c1cb..ff43ca9 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
@@ -29,7 +29,7 @@
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.URIResolver;
 import javax.xml.transform.sax.TemplatesHandler;
-
+import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.CompilerException;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.SourceLoader;
@@ -103,6 +103,8 @@
                 (String)tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET));
         xsltc.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD,
                 (String)tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD));
+        xsltc.setProperty(XalanConstants.SECURITY_MANAGER,
+                tfactory.getAttribute(XalanConstants.SECURITY_MANAGER));
 
 
         if ("true".equals(tfactory.getAttribute(TransformerFactoryImpl.ENABLE_INLINING)))
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
index 9dd19f6..c267970 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
@@ -77,6 +77,7 @@
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityPropertyManager.Property;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityPropertyManager.State;
+import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 
 import org.xml.sax.InputSource;
 import org.xml.sax.XMLFilter;
@@ -227,17 +228,17 @@
      */
     private boolean _useServicesMechanism;
 
-    /**
+     /**
      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
      */
     private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
-
      /**
      * protocols allowed for external DTD references in source file and/or stylesheet.
      */
     private String _accessExternalDTD = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
 
     private XMLSecurityPropertyManager _xmlSecurityPropertyMgr;
+    private XMLSecurityManager _xmlSecurityManager;
 
     /**
      * javax.xml.transform.sax.TransformerFactory implementation.
@@ -264,6 +265,9 @@
                 Property.ACCESS_EXTERNAL_DTD);
         _accessExternalStylesheet = _xmlSecurityPropertyMgr.getValue(
                 Property.ACCESS_EXTERNAL_STYLESHEET);
+
+        //Parser's security manager
+        _xmlSecurityManager = new XMLSecurityManager(true);
     }
 
     /**
@@ -322,11 +326,21 @@
               return Boolean.TRUE;
             else
               return Boolean.FALSE;
+        } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
+            return _xmlSecurityManager;
         }
 
-        int index = _xmlSecurityPropertyMgr.getIndex(name);
-        if (index > -1) {
-            return _xmlSecurityPropertyMgr.getValueByIndex(index);
+        /** Check to see if the property is managed by the security manager **/
+        String propertyValue = (_xmlSecurityManager != null) ?
+                _xmlSecurityManager.getLimitAsString(name) : null;
+        if (propertyValue != null) {
+            return propertyValue;
+        } else {
+            propertyValue = (_xmlSecurityPropertyMgr != null) ?
+                _xmlSecurityPropertyMgr.getValue(name) : null;
+            if (propertyValue != null) {
+                return propertyValue;
+            }
         }
 
         // Throw an exception for all other attributes
@@ -429,10 +443,13 @@
             }
         }
 
-        int index = _xmlSecurityPropertyMgr.getIndex(name);
-        if (index > -1) {
-            _xmlSecurityPropertyMgr.setValue(index,
-                    State.APIPROPERTY, (String)value);
+        if (_xmlSecurityManager != null &&
+                _xmlSecurityManager.setLimit(name, XMLSecurityManager.State.APIPROPERTY, value)) {
+            return;
+        }
+
+        if (_xmlSecurityPropertyMgr != null &&
+            _xmlSecurityPropertyMgr.setValue(name, XMLSecurityPropertyManager.State.APIPROPERTY, value)) {
             _accessExternalDTD = _xmlSecurityPropertyMgr.getValue(
                     Property.ACCESS_EXTERNAL_DTD);
             _accessExternalStylesheet = _xmlSecurityPropertyMgr.getValue(
@@ -482,6 +499,7 @@
                 throw new TransformerConfigurationException(err.toString());
             }
             _isNotSecureProcessing = !value;
+            _xmlSecurityManager.setSecureProcessing(value);
 
             // set external access restriction when FSP is explicitly set
             if (value && XalanConstants.IS_JDK8_OR_ABOVE) {
@@ -851,6 +869,7 @@
         if (!_isNotSecureProcessing) xsltc.setSecureProcessing(true);
         xsltc.setProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, _accessExternalStylesheet);
         xsltc.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD);
+        xsltc.setProperty(XalanConstants.SECURITY_MANAGER, _xmlSecurityManager);
         xsltc.init();
 
         // Set a document loader (for xsl:include/import) if defined
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java
index a32ab82..919fb57 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java
@@ -25,6 +25,7 @@
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
+import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -218,6 +219,7 @@
      */
     private String _accessExternalDTD = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
 
+    private XMLSecurityManager _securityManager;
     /**
      * A hashtable to store parameters for the identity transform. These
      * are not needed during the transformation, but we must keep track of
@@ -272,8 +274,11 @@
         _useServicesMechanism = _tfactory.useServicesMechnism();
         _accessExternalStylesheet = (String)_tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
         _accessExternalDTD = (String)_tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
+        _securityManager = (XMLSecurityManager)_tfactory.getAttribute(XalanConstants.SECURITY_MANAGER);
         _readerManager = XMLReaderManager.getInstance(_useServicesMechanism);
         _readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD);
+        _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing);
+        _readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager);
         //_isIncremental = tfactory._incremental;
     }
 
@@ -289,6 +294,7 @@
      */
     public void setSecureProcessing(boolean flag) {
         _isSecureProcessing = flag;
+        _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing);
     }
     /**
      * Return the state of the services mechanism feature.
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java
index 25c45c0..4c6e029 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java
@@ -23,6 +23,7 @@
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
+import com.sun.org.apache.xalan.internal.XalanConstants;
 import java.io.InputStream;
 import java.io.Reader;
 
@@ -43,6 +44,7 @@
 import javax.xml.transform.stream.StreamSource;
 
 import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
+import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
 
@@ -105,6 +107,13 @@
                     if (reader == null) {
                        try {
                            reader= XMLReaderFactory.createXMLReader();
+                           try {
+                                reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                                            xsltc.isSecureProcessing());
+                           } catch (SAXNotRecognizedException e) {
+                                System.err.println("Warning:  " + reader.getClass().getName() + ": "
+                                        + e.getMessage());
+                           }
                        } catch (Exception e ) {
                            try {
 
@@ -144,6 +153,22 @@
                                 + e.getMessage());
                     }
 
+                    try {
+                        XMLSecurityManager securityManager =
+                                (XMLSecurityManager)xsltc.getProperty(XalanConstants.SECURITY_MANAGER);
+                        if (securityManager != null) {
+                            for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
+                                reader.setProperty(limit.apiProperty(),
+                                        securityManager.getLimitValueAsString(limit));
+                            }
+                            if (securityManager.printEntityCountInfo()) {
+                                reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
+                            }
+                        }
+                    } catch (SAXException se) {
+                        System.err.println("Warning:  " + reader.getClass().getName() + ": "
+                                    + se.getMessage());
+                    }
                     xsltc.setXMLReader(reader);
                 }catch (SAXNotRecognizedException snre ) {
                   throw new TransformerConfigurationException
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java
index 832724a..1e8dcd9 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java
@@ -33,6 +33,7 @@
 import com.sun.org.apache.xerces.internal.util.PropertyState;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
 import com.sun.org.apache.xerces.internal.utils.ObjectFactory;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.XMLDTDContentModelHandler;
 import com.sun.org.apache.xerces.internal.xni.XMLDTDHandler;
@@ -59,6 +60,7 @@
 import org.w3c.dom.ls.LSResourceResolver;
 
 
+
 /**
  * Xerces implementation of DOMConfiguration that maintains a table of recognized parameters.
  *
@@ -156,6 +158,9 @@
     protected static final String SCHEMA_DV_FACTORY =
         Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY;
 
+    /** Property identifier: Security manager. */
+    private static final String SECURITY_MANAGER = Constants.SECURITY_MANAGER;
+
     /** Property identifier: Security property manager. */
     private static final String XML_SECURITY_PROPERTY_MANAGER =
             Constants.XML_SECURITY_PROPERTY_MANAGER;
@@ -279,6 +284,7 @@
             JAXP_SCHEMA_LANGUAGE,
             DTD_VALIDATOR_FACTORY_PROPERTY,
             SCHEMA_DV_FACTORY,
+            SECURITY_MANAGER,
             XML_SECURITY_PROPERTY_MANAGER
         };
         addRecognizedProperties(recognizedProperties);
@@ -313,6 +319,8 @@
         fValidationManager = createValidationManager();
         setProperty(VALIDATION_MANAGER, fValidationManager);
 
+        setProperty(SECURITY_MANAGER, new XMLSecurityManager(true));
+
         setProperty(Constants.XML_SECURITY_PROPERTY_MANAGER,
                 new XMLSecurityPropertyManager());
 
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/Constants.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/Constants.java
index bcc2a79..579622a 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/Constants.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/Constants.java
@@ -174,8 +174,6 @@
     /** JAXP schemaSource language: when used internally may include DTD namespace (DOM) */
     public static final String SCHEMA_LANGUAGE = "schemaLanguage";
 
-    public static final String SYSTEM_PROPERTY_ELEMENT_ATTRIBUTE_LIMIT = "elementAttributeLimit" ;
-
     /** JAXP Standard property prefix ("http://javax.xml.XMLConstants/property/"). */
     public static final String JAXPAPI_PROPERTY_PREFIX =
         "http://javax.xml.XMLConstants/property/";
@@ -209,6 +207,107 @@
     public static final boolean IS_JDK8_OR_ABOVE = isJavaVersionAtLeast(8);
 
     //
+    // Implementation limits: corresponding System Properties of the above
+    // API properties
+    //
+    /**
+     * JDK entity expansion limit; Note that the existing system property
+     * "entityExpansionLimit" with no prefix is still observed
+     */
+    public static final String JDK_ENTITY_EXPANSION_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "entityExpansionLimit";
+
+    /**
+     * JDK element attribute limit; Note that the existing system property
+     * "elementAttributeLimit" with no prefix is still observed
+     */
+    public static final String JDK_ELEMENT_ATTRIBUTE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "elementAttributeLimit";
+
+    /**
+     * JDK maxOccur limit; Note that the existing system property
+     * "maxOccurLimit" with no prefix is still observed
+     */
+    public static final String JDK_MAX_OCCUR_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxOccurLimit";
+
+    /**
+     * JDK total entity size limit
+     */
+    public static final String JDK_TOTAL_ENTITY_SIZE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "totalEntitySizeLimit";
+
+    /**
+     * JDK maximum general entity size limit
+     */
+    public static final String JDK_GENEAL_ENTITY_SIZE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxGeneralEntitySizeLimit";
+    /**
+     * JDK maximum parameter entity size limit
+     */
+    public static final String JDK_PARAMETER_ENTITY_SIZE_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxParameterEntitySizeLimit";
+    /**
+     * JDK maximum XML name limit
+     */
+    public static final String JDK_XML_NAME_LIMIT =
+            ORACLE_JAXP_PROPERTY_PREFIX + "maxXMLNameLimit";
+    /**
+     * JDK property to allow printing out information from the limit analyzer
+     */
+    public static final String JDK_ENTITY_COUNT_INFO =
+            ORACLE_JAXP_PROPERTY_PREFIX + "getEntityCountInfo";
+
+    //
+    // Implementation limits: API properties
+    //
+    /**
+     * JDK entity expansion limit; Note that the existing system property
+     * "entityExpansionLimit" with no prefix is still observed
+     */
+    public static final String SP_ENTITY_EXPANSION_LIMIT = "jdk.xml.entityExpansionLimit";
+
+    /**
+     * JDK element attribute limit; Note that the existing system property
+     * "elementAttributeLimit" with no prefix is still observed
+     */
+    public static final String SP_ELEMENT_ATTRIBUTE_LIMIT =  "jdk.xml.elementAttributeLimit";
+
+    /**
+     * JDK maxOccur limit; Note that the existing system property
+     * "maxOccurLimit" with no prefix is still observed
+     */
+    public static final String SP_MAX_OCCUR_LIMIT = "jdk.xml.maxOccurLimit";
+
+    /**
+     * JDK total entity size limit
+     */
+    public static final String SP_TOTAL_ENTITY_SIZE_LIMIT = "jdk.xml.totalEntitySizeLimit";
+
+    /**
+     * JDK maximum general entity size limit
+     */
+    public static final String SP_GENEAL_ENTITY_SIZE_LIMIT = "jdk.xml.maxGeneralEntitySizeLimit";
+    /**
+     * JDK maximum parameter entity size limit
+     */
+    public static final String SP_PARAMETER_ENTITY_SIZE_LIMIT = "jdk.xml.maxParameterEntitySizeLimit";
+    /**
+     * JDK maximum XML name limit
+     */
+    public static final String SP_XML_NAME_LIMIT = "jdk.xml.maxXMLNameLimit";
+
+    //legacy System Properties
+    public final static String ENTITY_EXPANSION_LIMIT = "entityExpansionLimit";
+    public static final String ELEMENT_ATTRIBUTE_LIMIT = "elementAttributeLimit" ;
+    public final static String MAX_OCCUR_LIMIT = "maxOccurLimit";
+
+    /**
+     * A string "yes" that can be used for properties such as getEntityCountInfo
+     */
+    public static final String JDK_YES = "yes";
+
+    //
     // DOM features
     //
 
@@ -443,7 +542,7 @@
     public static final String LOCALE_PROPERTY = "locale";
 
     /** property identifier: security manager. */
-    protected static final String SECURITY_MANAGER =
+    public static final String SECURITY_MANAGER =
         Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
 
 
@@ -511,9 +610,6 @@
      */
     public final static String ATTRIBUTE_DECLARED = "ATTRIBUTE_DECLARED";
 
-        public final static String ENTITY_EXPANSION_LIMIT = "entityExpansionLimit";
-
-        public final static String MAX_OCCUR_LIMIT = "maxOccurLimit";
 
     /**
      * {@link org.w3c.dom.TypeInfo} associated with current element/attribute
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/PropertyManager.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/PropertyManager.java
index 0f5119d..8fbf916 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/PropertyManager.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/PropertyManager.java
@@ -25,6 +25,7 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.xml.internal.stream.StaxEntityResolverWrapper;
 import java.util.HashMap;
@@ -50,12 +51,16 @@
 
     private static final String STRING_INTERNING = "http://xml.org/sax/features/string-interning";
 
+    /** Property identifier: Security manager. */
+    private static final String SECURITY_MANAGER = Constants.SECURITY_MANAGER;
+
     /** Property identifier: Security property manager. */
     private static final String XML_SECURITY_PROPERTY_MANAGER =
             Constants.XML_SECURITY_PROPERTY_MANAGER;
 
     HashMap supportedProps = new HashMap();
 
+    private XMLSecurityManager fSecurityManager;
     private XMLSecurityPropertyManager fSecurityPropertyMgr;
 
     public static final int CONTEXT_READER = 1;
@@ -82,6 +87,7 @@
 
         HashMap properties = propertyManager.getProperties();
         supportedProps.putAll(properties);
+        fSecurityManager = (XMLSecurityManager)getProperty(SECURITY_MANAGER);
         fSecurityPropertyMgr = (XMLSecurityPropertyManager)getProperty(XML_SECURITY_PROPERTY_MANAGER);
     }
 
@@ -124,6 +130,8 @@
         supportedProps.put(Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE, new Boolean(false));
         supportedProps.put(Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_UNDECLARED_ELEMDEF_FEATURE, new Boolean(false));
 
+        fSecurityManager = new XMLSecurityManager(true);
+        supportedProps.put(SECURITY_MANAGER, fSecurityManager);
         fSecurityPropertyMgr = new XMLSecurityPropertyManager();
         supportedProps.put(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
     }
@@ -142,6 +150,7 @@
      */
     public boolean containsProperty(String property){
         return supportedProps.containsKey(property) ||
+                (fSecurityManager != null && fSecurityManager.getIndex(property) > -1) ||
                 (fSecurityPropertyMgr!=null && fSecurityPropertyMgr.getIndex(property) > -1) ;
     }
 
@@ -169,12 +178,15 @@
             supportedProps.put( Constants.XERCES_PROPERTY_PREFIX + Constants.STAX_ENTITY_RESOLVER_PROPERTY , new StaxEntityResolverWrapper((XMLResolver)value)) ;
         }
 
-        int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(property) : -1;
-        if (index > -1) {
-            fSecurityPropertyMgr.setValue(index,
-                    XMLSecurityPropertyManager.State.APIPROPERTY, (String)value);
-        } else {
-            supportedProps.put(property, value);
+        //check if the property is managed by security manager
+        if (fSecurityManager == null ||
+                !fSecurityManager.setLimit(property, XMLSecurityManager.State.APIPROPERTY, value)) {
+            //check if the property is managed by security property manager
+            if (fSecurityPropertyMgr == null ||
+                    !fSecurityPropertyMgr.setValue(property, XMLSecurityPropertyManager.State.APIPROPERTY, value)) {
+                //fall back to the existing property manager
+                supportedProps.put(property, value);
+            }
         }
 
         if(equivalentProperty != null){
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
index dbfd46a..7a826df 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
@@ -108,6 +108,7 @@
  * @author Elena Litani, IBM
  * @author Michael Glavassevich, IBM
  * @author Sunitha Reddy, Sun Microsystems
+ * @version $Id: XML11NSDocumentScannerImpl.java,v 1.6 2010-11-01 04:39:40 joehw Exp $
  */
 public class XML11NSDocumentScannerImpl extends XML11DocumentScannerImpl {
 
@@ -236,7 +237,8 @@
 
             // attributes
             scanAttribute(fAttributes);
-            if (fSecurityManager != null && fAttributes.getLength() > fElementAttributeLimit){
+            if (fSecurityManager != null && (!fSecurityManager.isNoLimit(fElementAttributeLimit)) &&
+                    fAttributes.getLength() > fElementAttributeLimit){
                 fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
                                              "ElementAttributeLimit",
                                              new Object[]{rawname, new Integer(fElementAttributeLimit) },
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
index 6c5553c..18a9902 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
@@ -44,6 +44,8 @@
 import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
 import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
 import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
+import com.sun.xml.internal.stream.Entity;
 
 /**
  * This class is responsible for scanning the declarations found
@@ -66,7 +68,7 @@
  * @author Glenn Marcy, IBM
  * @author Eric Ye, IBM
  *
- * @version $Id: XMLDTDScannerImpl.java,v 1.7 2007/09/26 12:52:40 ndw Exp $
+ * @version $Id: XMLDTDScannerImpl.java,v 1.8 2010-11-01 04:39:41 joehw Exp $
  */
 public class XMLDTDScannerImpl
 extends XMLScanner
@@ -1545,7 +1547,7 @@
 
         // internal entity
         if (systemId == null) {
-            scanEntityValue(fLiteral, fLiteral2);
+            scanEntityValue(name, isPEDecl, fLiteral, fLiteral2);
             // since we need it's value anyway, let's snag it so it doesn't get corrupted
             // if a new load takes place before we store the entity values
             fStringBuffer.clear();
@@ -1610,7 +1612,7 @@
      * the use of scanCharReferenceValue), and fStringBuffer2, anything in them
      * at the time of calling is lost.
      */
-    protected final void scanEntityValue(XMLString value,
+    protected final void scanEntityValue(String entityName, boolean isPEDecl, XMLString value,
     XMLString nonNormalizedValue)
     throws IOException, XNIException {
         int quote = fEntityScanner.scanChar();
@@ -1622,10 +1624,20 @@
 
         XMLString literal = fString;
         XMLString literal2 = fString;
+        int countChar = 0;
+        if (fLimitAnalyzer == null && fSecurityManager != null) {
+            fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
+            fLimitAnalyzer.startEntity(entityName);
+        }
+
         if (fEntityScanner.scanLiteral(quote, fString) != quote) {
             fStringBuffer.clear();
             fStringBuffer2.clear();
             do {
+                if (isPEDecl && fLimitAnalyzer != null) {
+                    checkLimit("%" + entityName, fString.length + countChar);
+                }
+                countChar = 0;
                 fStringBuffer.append(fString);
                 fStringBuffer2.append(fString);
                 if (fEntityScanner.skipChar('&')) {
@@ -1685,6 +1697,7 @@
                     }
                 }
                 else {
+                    countChar++;
                     int c = fEntityScanner.peekChar();
                     if (XMLChar.isHighSurrogate(c)) {
                         scanSurrogates(fStringBuffer2);
@@ -1708,9 +1721,17 @@
             fStringBuffer2.append(fString);
             literal = fStringBuffer;
             literal2 = fStringBuffer2;
+        } else {
+            if (isPEDecl) {
+                checkLimit("%" + entityName, literal);
+        }
         }
         value.setValues(literal);
         nonNormalizedValue.setValues(literal2);
+        if (fLimitAnalyzer != null) {
+            fLimitAnalyzer.endEntity(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, entityName);
+        }
+
         if (!fEntityScanner.skipChar(quote)) {
             reportFatalError("CloseQuoteMissingInDecl", null);
         }
@@ -2126,6 +2147,43 @@
         //new SymbolTable());
     }
 
+    /**
+     * Add the count of the content buffer and check if the accumulated
+     * value exceeds the limit
+     * @param entityName entity name
+     * @param buffer content buffer
+     */
+    private void checkLimit(String entityName, XMLString buffer) {
+        checkLimit(entityName, buffer.length);
+    }
+
+    /**
+     * Add the count and check limit
+     * @param entityName entity name
+     * @param len length of the buffer
+     */
+    private void checkLimit(String entityName, int len) {
+        if (fLimitAnalyzer == null) {
+            fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
+        }
+        fLimitAnalyzer.addValue(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT, entityName, len);
+        if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT)) {
+                    fSecurityManager.debugPrint();
+            reportFatalError("MaxEntitySizeLimit", new Object[]{entityName,
+                fLimitAnalyzer.getValue(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getLimit(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.PARAMETER_ENTITY_SIZE_LIMIT)});
+        }
+        if (fSecurityManager.isOverLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT)) {
+            fSecurityManager.debugPrint();
+            reportFatalError("TotalEntitySizeLimit",
+                new Object[]{fLimitAnalyzer.getTotalValue(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getLimit(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                fSecurityManager.getStateLiteral(XMLSecurityManager.Limit.TOTAL_ENTITY_SIZE_LIMIT)});
+        }
+
+    }
+
     public DTDGrammar getGrammar(){
         return nvGrammarInfo;
     }
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
index 050b852..1472f45 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
@@ -50,12 +50,14 @@
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.NamespaceSupport;
 import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
+import com.sun.org.apache.xerces.internal.utils.XMLLimitAnalyzer;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager.Limit;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager.State;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
-import com.sun.xml.internal.stream.Entity;
 import javax.xml.XMLConstants;
 import javax.xml.stream.XMLStreamConstants;
 import javax.xml.stream.events.XMLEvent;
@@ -165,7 +167,7 @@
 
     /** Feature identifier: standard uri conformant */
     protected static final String STANDARD_URI_CONFORMANT =
-            Constants.XERCES_FEATURE_PREFIX +Constants.STANDARD_URI_CONFORMANT_FEATURE;
+            Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE;
 
     /** Property identifier: Security property manager. */
     private static final String XML_SECURITY_PROPERTY_MANAGER =
@@ -213,11 +215,8 @@
     };
 
     private static final char [] cdata = {'[','C','D','A','T','A','['};
-    private static final char [] endTag = {'<','/'};
-
-    //this variable is also used by XMLDocumentScannerImpl in the same package
     static final char [] xmlDecl = {'<','?','x','m','l'};
-
+    private static final char [] endTag = {'<','/'};
     // debugging
 
     /** Debug scanner state. */
@@ -316,6 +315,7 @@
     protected String fDeclaredEncoding =  null;
     /** Xerces Feature: Disallow doctype declaration. */
     protected boolean fDisallowDoctype = false;
+
     /**
      * comma-delimited list of protocols that are allowed for the purpose
      * of accessing external dtd or entity references
@@ -384,7 +384,6 @@
 
     protected boolean foundBuiltInRefs = false;
 
-    protected SecurityManager fSecurityManager = null;
 
     //skip element algorithm
     static final short MAX_DEPTH_LIMIT = 5 ;
@@ -571,8 +570,11 @@
         // xerces features
         fReportCdataEvent = componentManager.getFeature(Constants.STAX_REPORT_CDATA_EVENT, true);
 
-        fSecurityManager = (SecurityManager)componentManager.getProperty(Constants.SECURITY_MANAGER, null);
-        fElementAttributeLimit = (fSecurityManager != null)?fSecurityManager.getElementAttrLimit():0;
+        fSecurityManager = (XMLSecurityManager)componentManager.getProperty(Constants.SECURITY_MANAGER, null);
+        fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
+
+        fElementAttributeLimit = (fSecurityManager != null)?
+                fSecurityManager.getLimit(XMLSecurityManager.Limit.ELEMENT_ATTRIBUTE_LIMIT):0;
 
         fNotifyBuiltInRefs = componentManager.getFeature(NOTIFY_BUILTIN_REFS, false);
 
@@ -598,9 +600,6 @@
         //xxx: external entities are supported in Xerces
         // it would be good to define feature for this case
         fSupportExternalEntities = true;
-        fSupportExternalEntities = true;
-        fSupportExternalEntities = true;
-        fSupportExternalEntities = true;
         fReplaceEntityReferences = true;
         fIsCoalesce = false;
 
@@ -667,10 +666,13 @@
 
         dtdGrammarUtil = null;
 
-         // JAXP 1.5 features and properties
+        // JAXP 1.5 features and properties
         XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)
                 propertyManager.getProperty(XML_SECURITY_PROPERTY_MANAGER);
         fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
+
+        fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(Constants.SECURITY_MANAGER);
+        fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
     } // reset(XMLComponentManager)
 
     /**
@@ -769,10 +771,10 @@
 
         //JAXP 1.5 properties
         if (propertyId.equals(XML_SECURITY_PROPERTY_MANAGER))
-        {
+            {
             XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)value;
             fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
-        }
+            }
 
     } // setProperty(String,Object)
 
@@ -1322,7 +1324,8 @@
             fAddDefaultAttr = true;
             do {
                 scanAttribute(fAttributes);
-                if (fSecurityManager != null && fAttributes.getLength() > fElementAttributeLimit){
+                if (fSecurityManager != null && !fSecurityManager.isNoLimit(fElementAttributeLimit) &&
+                        fAttributes.getLength() > fElementAttributeLimit){
                     fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
                                                  "ElementAttributeLimit",
                                                  new Object[]{rawname, new Integer(fAttributes.getLength()) },
@@ -2036,6 +2039,13 @@
 
     } // getDriverName():String
 
+    /**
+     * Check the protocol used in the systemId against allowed protocols
+     *
+     * @param systemId the Id of the URI
+     * @param allowedProtocols a list of allowed protocols separated by comma
+     * @return the name of the protocol if rejected, null otherwise
+     */
     String checkAccess(String systemId, String allowedProtocols) throws IOException {
         String baseSystemId = fEntityScanner.getBaseSystemId();
         String expandedSystemId = fEntityManager.expandSystemId(systemId, baseSystemId,fStrictURI);
@@ -2833,6 +2843,8 @@
                             if(DEBUG){
                                 System.out.println("NOT USING THE BUFFER, STRING = " + fTempString.toString());
                             }
+                            //check limit before returning event
+                            checkLimit(fContentBuffer);
                             if(dtdGrammarUtil!= null && dtdGrammarUtil.isIgnorableWhiteSpace(fContentBuffer)){
                                 if(DEBUG)System.out.println("Return SPACE EVENT");
                                 return XMLEvent.SPACE;
@@ -2931,6 +2943,8 @@
                             fLastSectionWasCharacterData = true ;
                             continue;
                         }else{
+                            //check limit before returning event
+                            checkLimit(fContentBuffer);
                             if(dtdGrammarUtil!= null && dtdGrammarUtil.isIgnorableWhiteSpace(fContentBuffer)){
                                 if(DEBUG)System.out.println("Return SPACE EVENT");
                                 return XMLEvent.SPACE;
@@ -3141,6 +3155,30 @@
             } //while loop
         }//next
 
+        /**
+         * Add the count of the content buffer and check if the accumulated
+         * value exceeds the limit
+         * @param buffer content buffer
+         */
+        protected void checkLimit(XMLStringBuffer buffer) {
+            if (fLimitAnalyzer.isTracking(fCurrentEntityName)) {
+                fLimitAnalyzer.addValue(Limit.GENEAL_ENTITY_SIZE_LIMIT, fCurrentEntityName, buffer.length);
+                if (fSecurityManager.isOverLimit(Limit.GENEAL_ENTITY_SIZE_LIMIT)) {
+                    fSecurityManager.debugPrint();
+                    reportFatalError("MaxEntitySizeLimit", new Object[]{fCurrentEntityName,
+                        fLimitAnalyzer.getValue(Limit.GENEAL_ENTITY_SIZE_LIMIT),
+                        fSecurityManager.getLimit(Limit.GENEAL_ENTITY_SIZE_LIMIT),
+                        fSecurityManager.getStateLiteral(Limit.GENEAL_ENTITY_SIZE_LIMIT)});
+                }
+                if (fSecurityManager.isOverLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT)) {
+                    fSecurityManager.debugPrint();
+                    reportFatalError("TotalEntitySizeLimit",
+                        new Object[]{fLimitAnalyzer.getTotalValue(Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                        fSecurityManager.getLimit(Limit.TOTAL_ENTITY_SIZE_LIMIT),
+                        fSecurityManager.getStateLiteral(Limit.TOTAL_ENTITY_SIZE_LIMIT)});
+                }
+            }
+        }
 
         //
         // Protected methods
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 b3ae5c3..d6407c7 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
@@ -18,19 +18,17 @@
  * limitations under the License.
  */
 
-package com.sun.org.apache.xerces.internal.impl ;
+package com.sun.org.apache.xerces.internal.impl;
 
-import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.io.ASCIIReader;
 import com.sun.org.apache.xerces.internal.impl.io.UCSReader;
 import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
-import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
 import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
 import com.sun.org.apache.xerces.internal.util.*;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
-import com.sun.org.apache.xerces.internal.util.URI;
 import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
+import com.sun.org.apache.xerces.internal.utils.XMLLimitAnalyzer;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
@@ -174,7 +172,6 @@
     /** access external dtd: file protocol */
     static final String EXTERNAL_ACCESS_DEFAULT = Constants.EXTERNAL_ACCESS_DEFAULT;
 
-
     // recognized features and properties
 
     /** Recognized features. */
@@ -307,6 +304,7 @@
 
     /** used to restrict external access */
     protected String fAccessExternalDTD = EXTERNAL_ACCESS_DEFAULT;
+
     // settings
 
     /**
@@ -324,9 +322,12 @@
      */
     protected int fBufferSize = DEFAULT_BUFFER_SIZE;
 
-    // stores defaults for entity expansion limit if it has
-    // been set on the configuration.
-    protected SecurityManager fSecurityManager = null;
+    /** Security Manager */
+    protected XMLSecurityManager fSecurityManager = null;
+
+    protected XMLLimitAnalyzer fLimitAnalyzer = null;
+
+    protected int entityExpansionIndex;
 
     /**
      * True if the document entity is standalone. This should really
@@ -352,10 +353,6 @@
     /** XML 1.1 entity scanner. */
     protected XMLEntityScanner fXML11EntityScanner;
 
-    /** entity expansion limit (contains useful data if and only if
-    fSecurityManager is non-null) */
-    protected int fEntityExpansionLimit = 0;
-
     /** count of entities expanded: */
     protected int fEntityExpansionCount = 0;
 
@@ -833,6 +830,9 @@
         fCurrentEntity.setEncodingExternallySpecified(encodingExternallySpecified);
         fEntityScanner.setCurrentEntity(fCurrentEntity);
         fResourceIdentifier.setValues(publicId, literalSystemId, baseSystemId, expandedSystemId);
+        if (fLimitAnalyzer != null) {
+            fLimitAnalyzer.startEntity(name);
+        }
         return encoding;
     } //setupCurrentEntity(String, XMLInputSource, boolean, boolean):  String
 
@@ -1294,10 +1294,13 @@
         //expansions exceeds the entity expansion limit, parser will throw fatal error.
         // Note that this represents the nesting level of open entities.
         fEntityExpansionCount++;
-        if( fSecurityManager != null && fEntityExpansionCount > fEntityExpansionLimit ){
-            fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
-                                             "EntityExpansionLimitExceeded",
-                                             new Object[]{new Integer(fEntityExpansionLimit) },
+        if(fLimitAnalyzer != null) {
+           fLimitAnalyzer.addValue(entityExpansionIndex, name, 1);
+        }
+        if( fSecurityManager != null && fSecurityManager.isOverLimit(entityExpansionIndex)){
+            fSecurityManager.debugPrint();
+            fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,"EntityExpansionLimitExceeded",
+                    new Object[]{fSecurityManager.getLimitValueByIndex(entityExpansionIndex)},
                                              XMLErrorReporter.SEVERITY_FATAL_ERROR );
             // is there anything better to do than reset the counter?
             // at least one can envision debugging applications where this might
@@ -1361,6 +1364,12 @@
         if(fCurrentEntity != null){
             //close the reader
             try{
+                if (fLimitAnalyzer != null) {
+                    fLimitAnalyzer.endEntity(XMLSecurityManager.Limit.GENEAL_ENTITY_SIZE_LIMIT, fCurrentEntity.name);
+                    if (fCurrentEntity.name.equals("[xml]")) {
+                        fSecurityManager.debugPrint();
+                    }
+                }
                 fCurrentEntity.close();
             }catch(IOException ex){
                 throw new XNIException(ex);
@@ -1426,6 +1435,9 @@
         XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) propertyManager.getProperty(XML_SECURITY_PROPERTY_MANAGER);
         fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
 
+        fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(SECURITY_MANAGER);
+        fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
+
         // initialize state
         //fStandalone = false;
         fEntities.clear();
@@ -1485,7 +1497,9 @@
         fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_RESOLVER, null);
         fStaxEntityResolver = (StaxEntityResolverWrapper)componentManager.getProperty(STAX_ENTITY_RESOLVER, null);
         fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER, null);
-        fSecurityManager = (SecurityManager)componentManager.getProperty(SECURITY_MANAGER, null);
+        fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER, null);
+        fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
+        entityExpansionIndex = fSecurityManager.getIndex(Constants.JDK_ENTITY_EXPANSION_LIMIT);
 
         // JAXP 1.5 feature
         XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER, null);
@@ -1506,7 +1520,6 @@
     // a class acting as a component manager but not
     // implementing that interface for whatever reason.
     public void reset() {
-        fEntityExpansionLimit = (fSecurityManager != null)?fSecurityManager.getEntityExpansionLimit():0;
 
         // initialize state
         fStandalone = false;
@@ -1642,19 +1655,18 @@
             }
             if (suffixLength == Constants.SECURITY_MANAGER_PROPERTY.length() &&
                 propertyId.endsWith(Constants.SECURITY_MANAGER_PROPERTY)) {
-                fSecurityManager = (SecurityManager)value;
-                fEntityExpansionLimit = (fSecurityManager != null)?fSecurityManager.getEntityExpansionLimit():0;
+                fSecurityManager = (XMLSecurityManager)value;
+                fLimitAnalyzer = fSecurityManager.getLimitAnalyzer();
             }
         }
 
         //JAXP 1.5 properties
         if (propertyId.equals(XML_SECURITY_PROPERTY_MANAGER))
-        {
+            {
             XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)value;
             fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
+            }
         }
-    }
-
     /**
      * Returns a list of property identifiers that are recognized by
      * this component. This method may return null if no properties
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java
index b0461eb..464511c 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLNSDocumentScannerImpl.java
@@ -58,6 +58,7 @@
  * @author Neeraj Bajaj, Sun Microsystems
  * @author Venugopal Rao K, Sun Microsystems
  * @author Elena Litani, IBM
+ * @version $Id: XMLNSDocumentScannerImpl.java,v 1.11 2010-11-01 04:39:41 joehw Exp $
  */
 public class XMLNSDocumentScannerImpl
         extends XMLDocumentScannerImpl {
@@ -251,7 +252,8 @@
 
             do {
                 scanAttribute(fAttributes);
-                if (fSecurityManager != null && fAttributes.getLength() > fElementAttributeLimit){
+                if (fSecurityManager != null && (!fSecurityManager.isNoLimit(fElementAttributeLimit)) &&
+                        fAttributes.getLength() > fElementAttributeLimit){
                     fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
                                                  "ElementAttributeLimit",
                                                  new Object[]{rawname, new Integer(fAttributes.getLength()) },
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
index 0c66aa2..70de786 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
@@ -32,6 +32,8 @@
 import com.sun.org.apache.xerces.internal.util.XMLChar;
 import com.sun.org.apache.xerces.internal.util.XMLResourceIdentifierImpl;
 import com.sun.org.apache.xerces.internal.util.XMLStringBuffer;
+import com.sun.org.apache.xerces.internal.utils.XMLLimitAnalyzer;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.xni.XMLAttributes;
 import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
@@ -106,6 +108,9 @@
     protected static final String ENTITY_MANAGER =
             Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
 
+    /** Property identifier: Security manager. */
+    private static final String SECURITY_MANAGER = Constants.SECURITY_MANAGER;
+
     // debugging
 
     /** Debug attribute normalization. */
@@ -159,6 +164,12 @@
     /** xxx this should be available from EntityManager Entity storage */
     protected XMLEntityStorage fEntityStore = null ;
 
+    /** Security manager. */
+    protected XMLSecurityManager fSecurityManager = null;
+
+    /** Limit analyzer. */
+    protected XMLLimitAnalyzer fLimitAnalyzer = null;
+
     // protected data
 
     /** event type */
@@ -256,6 +267,7 @@
         fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
         fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
         fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER);
+        fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER);
 
         //this step is extra because we have separated the storage of entity
         fEntityStore = fEntityManager.getEntityStore() ;
@@ -293,6 +305,10 @@
                 fEntityManager = (XMLEntityManager)value;
             }
         }
+
+        if (propertyId.equals(SECURITY_MANAGER)) {
+            fSecurityManager = (XMLSecurityManager)value;
+        }
                 /*else if(propertyId.equals(Constants.STAX_PROPERTIES)){
             fStaxProperties = (HashMap)value;
             //TODO::discuss with neeraj what are his thoughts on passing properties.
@@ -352,6 +368,8 @@
         fEntityManager = (XMLEntityManager)propertyManager.getProperty(ENTITY_MANAGER);
         fEntityStore = fEntityManager.getEntityStore() ;
         fEntityScanner = (XMLEntityScanner)fEntityManager.getEntityScanner() ;
+        fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(SECURITY_MANAGER);
+
         //fEntityManager.reset();
         // DTD preparsing defaults:
         fValidation = false;
@@ -499,7 +517,7 @@
                             reportFatalError("SDDeclInvalid",  new Object[] {standalone});
                         }
                     } else {
-                        reportFatalError("EncodingDeclRequired", null);
+                        reportFatalError("SDDeclNameInvalid", null);
                     }
                     break;
                 }
@@ -510,8 +528,9 @@
             sawSpace = fEntityScanner.skipSpaces();
         }
         // restore original literal value
-        if(currLiteral)
+        if(currLiteral) {
             currEnt.literal = true;
+        }
         // REVISIT: should we remove this error reporting?
         if (scanningTextDecl && state != STATE_DONE) {
             reportFatalError("MorePseudoAttributes", null);
@@ -564,7 +583,7 @@
             XMLString value)
             throws IOException, XNIException {
 
-        String name = fEntityScanner.scanName();
+        String name = scanPseudoAttributeName();
         // XMLEntityManager.print(fEntityManager.getCurrentEntity());
 
         if (name == null) {
@@ -617,6 +636,35 @@
     } // scanPseudoAttribute(XMLString):String
 
     /**
+     * Scans the name of a pseudo attribute. The only legal names
+     * in XML 1.0/1.1 documents are 'version', 'encoding' and 'standalone'.
+     *
+     * @return the name of the pseudo attribute or <code>null</code>
+     * if a legal pseudo attribute name could not be scanned.
+     */
+    private String scanPseudoAttributeName() throws IOException, XNIException {
+        final int ch = fEntityScanner.peekChar();
+        switch (ch) {
+            case 'v':
+                if (fEntityScanner.skipString(fVersionSymbol)) {
+                    return fVersionSymbol;
+                }
+                break;
+            case 'e':
+                if (fEntityScanner.skipString(fEncodingSymbol)) {
+                    return fEncodingSymbol;
+                }
+                break;
+            case 's':
+                if (fEntityScanner.skipString(fStandaloneSymbol)) {
+                    return fStandaloneSymbol;
+                }
+                break;
+        }
+        return null;
+    } // scanPseudoAttributeName()
+
+    /**
      * Scans a processing instruction.
      * <p>
      * <pre>
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
index 1a5d62a..200b904 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
@@ -44,6 +44,7 @@
         
 # 2.9 Standalone Document Declaration
         SDDeclInvalid = The standalone document declaration value must be \"yes\" or \"no\", not \"{0}\".
+        SDDeclNameInvalid = The standalone name in XML declaration may be misspelled.
 # 2.12 Language Identification
         XMLLangInvalid = The xml:lang attribute value \"{0}\" is an invalid language identifier.
 # 3. Logical Structures
@@ -292,8 +293,10 @@
         InvalidCharInLiteral=InvalidCharInLiteral
 
 
-#Application can set the limit of number of entities that should be expanded by the parser.
-EntityExpansionLimitExceeded=The parser has encountered more than \"{0}\" entity expansions in this document; this is the limit imposed by the application.
+# Implementation limits
+        EntityExpansionLimitExceeded=JAXP00010001: The parser has encountered more than \"{0}\" entity expansions in this document; this is the limit imposed by the JDK.
+        ElementAttributeLimit=JAXP00010002:  Element \"{0}\" has more than \"{1}\" attributes, \"{1}\" is the limit imposed by the JDK.
+        MaxEntitySizeLimit=JAXP00010003: The length of entity \"{0}\" is \"{1}\" that exceeds the \"{2}\" limit set by \"{3}\".
+        TotalEntitySizeLimit=JAXP00010004: The accumulated size \"{0}\" of entities exceeded the \"{1}\" limit set by \"{2}\".
+        MaxXMLNameLimit=JAXP00010005: The name \"{0}\" exceeded the \"{1}\" limit set by \"{2}\".
 
-# Application can set the limit of number of attributes of entity that should be expanded by the parser.
-ElementAttributeLimit= Element \"{0}\" has more than \"{1}\" attributes, \"{1}\" is the limit imposed by the application.
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java
index d183166..6aa06b8 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java
@@ -21,13 +21,13 @@
 
 package com.sun.org.apache.xerces.internal.impl.xs.models;
 
-import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
-import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
-import com.sun.org.apache.xerces.internal.util.SecurityManager ;
-import com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode;
-import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
-import com.sun.org.apache.xerces.internal.impl.xs.XSMessageFormatter;
 import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
+import com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode;
+import com.sun.org.apache.xerces.internal.impl.xs.XSMessageFormatter;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
+import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
+import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 
 /**
  *
@@ -68,7 +68,7 @@
 
     // stores defaults for different security holes (maxOccurLimit in current context) if it has
     // been set on the configuration.
-    private SecurityManager fSecurityManager = null;
+    private XMLSecurityManager fSecurityManager = null;
 
     /** default constructor */
     public CMNodeFactory() {
@@ -77,10 +77,10 @@
     public void reset(XMLComponentManager componentManager){
         fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
         try {
-            fSecurityManager = (SecurityManager)componentManager.getProperty(SECURITY_MANAGER);
+            fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER);
             //we are setting the limit of number of nodes to 3times the maxOccur value..
             if(fSecurityManager != null){
-                maxNodeLimit = fSecurityManager.getMaxOccurNodeLimit() * MULTIPLICITY ;
+                maxNodeLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT) * MULTIPLICITY ;
             }
         }
         catch (XMLConfigurationException e) {
@@ -109,7 +109,8 @@
     }
 
     public void nodeCountCheck(){
-        if( fSecurityManager != null && nodeCount++ > maxNodeLimit){
+        if( fSecurityManager != null && !fSecurityManager.isNoLimit(maxNodeLimit) &&
+                nodeCount++ > maxNodeLimit){
             if(DEBUG){
                 System.out.println("nodeCount = " + nodeCount ) ;
                 System.out.println("nodeLimit = " + maxNodeLimit ) ;
@@ -150,8 +151,9 @@
 
             if (suffixLength == Constants.SECURITY_MANAGER_PROPERTY.length() &&
                 propertyId.endsWith(Constants.SECURITY_MANAGER_PROPERTY)) {
-                fSecurityManager = (SecurityManager)value;
-                maxNodeLimit = (fSecurityManager != null) ? fSecurityManager.getMaxOccurNodeLimit() * MULTIPLICITY : 0 ;
+                fSecurityManager = (XMLSecurityManager)value;
+                maxNodeLimit = (fSecurityManager != null) ?
+                        fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT) * MULTIPLICITY : 0 ;
                 return;
             }
             if (suffixLength == Constants.ERROR_REPORTER_PROPERTY.length() &&
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java
index 3744692..f9eea6a 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSAttributeChecker.java
@@ -40,6 +40,7 @@
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
 import com.sun.org.apache.xerces.internal.util.XMLChar;
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.xs.XSConstants;
 import java.util.HashMap;
@@ -1194,8 +1195,8 @@
                     if (!optimize) {
                     //Revisit :: IMO this is not right place to check
                     // maxOccurNodeLimit.
-                    int maxOccurNodeLimit = fSchemaHandler.fSecureProcessing.getMaxOccurNodeLimit();
-                    if (max > maxOccurNodeLimit) {
+                    int maxOccurNodeLimit = fSchemaHandler.fSecureProcessing.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT);
+                    if (max > maxOccurNodeLimit && !fSchemaHandler.fSecureProcessing.isNoLimit(maxOccurNodeLimit)) {
                         reportSchemaFatalError("maxOccurLimit", new Object[] {new Integer(maxOccurNodeLimit)}, element);
 
                         // reset max values in case processing continues on error
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java
index d947cf8..8d302e8 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java
@@ -70,7 +70,6 @@
 import com.sun.org.apache.xerces.internal.util.DefaultErrorHandler;
 import com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper;
 import com.sun.org.apache.xerces.internal.util.SAXInputSource;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.StAXInputSource;
 import com.sun.org.apache.xerces.internal.util.StAXLocationWrapper;
 import com.sun.org.apache.xerces.internal.util.SymbolHash;
@@ -78,6 +77,7 @@
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
 import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException;
 import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.xni.XNIException;
@@ -257,7 +257,7 @@
      *
      * <p>Protected to allow access by any traverser.</p>
      */
-    protected SecurityManager fSecureProcessing = null;
+    protected XMLSecurityManager fSecureProcessing = null;
 
     private String fAccessExternalSchema;
     private String fAccessExternalDTD;
@@ -2251,12 +2251,12 @@
                     }
                     catch (SAXException se) {}
 
-                    try {
-                        parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, fAccessExternalDTD);
-                    } catch (SAXNotRecognizedException exc) {
-                        System.err.println("Warning: " + parser.getClass().getName() + ": " +
-                                exc.getMessage());
-                    }
+                     try {
+                             parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, fAccessExternalDTD);
+                     } catch (SAXNotRecognizedException exc) {
+                         System.err.println("Warning: " + parser.getClass().getName() + ": " +
+                                 exc.getMessage());
+                     }
                 }
                 // If XML names and Namespace URIs are already internalized we
                 // can avoid running them through the SymbolTable.
@@ -3509,7 +3509,7 @@
 
         fSecureProcessing = null;
         if( componentManager!=null ) {
-            fSecureProcessing = (SecurityManager) componentManager.getProperty(SECURE_PROCESSING, null);
+            fSecureProcessing = (XMLSecurityManager) componentManager.getProperty(SECURE_PROCESSING, null);
         }
 
         //set entity resolver
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/DocumentBuilderImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/DocumentBuilderImpl.java
index 0c90afe..1072a0d 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/DocumentBuilderImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/DocumentBuilderImpl.java
@@ -36,7 +36,7 @@
 import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator;
 import com.sun.org.apache.xerces.internal.jaxp.validation.XSGrammarPoolContainer;
 import com.sun.org.apache.xerces.internal.parsers.DOMParser;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager.Property;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager.State;
@@ -46,7 +46,6 @@
 import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentSource;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration;
-import javax.xml.XMLConstants;
 import org.w3c.dom.DOMImplementation;
 import org.w3c.dom.Document;
 import org.xml.sax.EntityResolver;
@@ -110,7 +109,6 @@
     /** Property identifier: access to external schema */
     public static final String ACCESS_EXTERNAL_SCHEMA = XMLConstants.ACCESS_EXTERNAL_SCHEMA;
 
-
     private final DOMParser domParser;
     private final Schema grammar;
 
@@ -125,6 +123,7 @@
     /** Initial EntityResolver */
     private final EntityResolver fInitEntityResolver;
 
+    private XMLSecurityManager fSecurityManager;
     private XMLSecurityPropertyManager fSecurityPropertyMgr;
 
     DocumentBuilderImpl(DocumentBuilderFactoryImpl dbf, Hashtable dbfAttrs, Hashtable features)
@@ -173,10 +172,10 @@
         fSecurityPropertyMgr = new XMLSecurityPropertyManager();
         domParser.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
 
-        // If the secure processing feature is on set a security manager.
-        if (secureProcessing) {
-            domParser.setProperty(SECURITY_MANAGER, new SecurityManager());
+        fSecurityManager = new XMLSecurityManager(secureProcessing);
+        domParser.setProperty(SECURITY_MANAGER, fSecurityManager);
 
+        if (secureProcessing) {
             /**
              * If secure processing is explicitly set on the factory, the
              * access properties will be set unless the corresponding
@@ -250,9 +249,9 @@
                 String feature = (String) entry.getKey();
                 boolean value = ((Boolean) entry.getValue()).booleanValue();
                 domParser.setFeature(feature, value);
-            }
         }
     }
+    }
 
     /**
      * Set any DocumentBuilderFactory attributes of our underlying DOMParser
@@ -289,30 +288,33 @@
                             // spec when schema validation is enabled
                             domParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                         }
-                     }
-                 } else if(JAXP_SCHEMA_SOURCE.equals(name)){
-                    if( isValidating() ) {
-                        String value=(String)dbfAttrs.get(JAXP_SCHEMA_LANGUAGE);
-                        if(value !=null && W3C_XML_SCHEMA.equals(value)){
-                            domParser.setProperty(name, val);
-                        }else{
+                    }
+                        } else if(JAXP_SCHEMA_SOURCE.equals(name)){
+                        if( isValidating() ) {
+                                                String value=(String)dbfAttrs.get(JAXP_SCHEMA_LANGUAGE);
+                                                if(value !=null && W3C_XML_SCHEMA.equals(value)){
+                                        domParser.setProperty(name, val);
+                                                }else{
                             throw new IllegalArgumentException(
                                 DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN,
                                 "jaxp-order-not-supported",
                                 new Object[] {JAXP_SCHEMA_LANGUAGE, JAXP_SCHEMA_SOURCE}));
+                                                }
+                                        }
+                } else {
+                    //check if the property is managed by security manager
+                    if (fSecurityManager == null ||
+                            !fSecurityManager.setLimit(name, XMLSecurityManager.State.APIPROPERTY, val)) {
+                        //check if the property is managed by security property manager
+                        if (fSecurityPropertyMgr == null ||
+                                !fSecurityPropertyMgr.setValue(name, XMLSecurityPropertyManager.State.APIPROPERTY, val)) {
+                            //fall back to the existing property manager
+                            domParser.setProperty(name, val);
                         }
-                     }
-                  } else {
-                    int index = fSecurityPropertyMgr.getIndex(name);
-                    if (index > -1) {
-                        fSecurityPropertyMgr.setValue(index,
-                                XMLSecurityPropertyManager.State.APIPROPERTY, (String)val);
-                    } else {
-                        // Let Xerces code handle the property
-                        domParser.setProperty(name, val);
                     }
-                  }
-             }
+
+                }
+            }
         }
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java
index 2a9300b..8c21efc 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java
@@ -34,8 +34,8 @@
 import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator;
 import com.sun.org.apache.xerces.internal.jaxp.validation.XSGrammarPoolContainer;
 import com.sun.org.apache.xerces.internal.util.SAXMessageFormatter;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.Status;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.XMLDocumentHandler;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLComponent;
@@ -112,6 +112,7 @@
     /** Initial EntityResolver */
     private final EntityResolver fInitEntityResolver;
 
+    private final XMLSecurityManager fSecurityManager;
     private final XMLSecurityPropertyManager fSecurityPropertyMgr;
 
     /**
@@ -130,10 +131,10 @@
     SAXParserImpl(SAXParserFactoryImpl spf, Hashtable features, boolean secureProcessing)
         throws SAXException
     {
+        fSecurityManager = new XMLSecurityManager(secureProcessing);
         fSecurityPropertyMgr = new XMLSecurityPropertyManager();
-
         // Instantiate a SAXParser directly and not through SAX so that we use the right ClassLoader
-        xmlReader = new JAXPSAXParser(this, fSecurityPropertyMgr);
+        xmlReader = new JAXPSAXParser(this, fSecurityPropertyMgr, fSecurityManager);
 
         // JAXP "namespaceAware" == SAX Namespaces feature
         // Note: there is a compatibility problem here with default values:
@@ -154,9 +155,9 @@
 
         xmlReader.setProperty0(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
 
-        // If the secure processing feature is on set a security manager.
+        xmlReader.setProperty0(SECURITY_MANAGER, fSecurityManager);
+
         if (secureProcessing) {
-            xmlReader.setProperty0(SECURITY_MANAGER, new SecurityManager());
             /**
              * By default, secure processing is set, no external access is allowed.
              * However, we need to check if it is actively set on the factory since we
@@ -164,6 +165,7 @@
              * the default value
              */
             if (features != null) {
+
                 Object temp = features.get(XMLConstants.FEATURE_SECURE_PROCESSING);
                 if (temp != null) {
                     boolean value = ((Boolean) temp).booleanValue();
@@ -172,7 +174,6 @@
                                 XMLSecurityPropertyManager.State.FSP, Constants.EXTERNAL_ACCESS_DEFAULT_FSP);
                         fSecurityPropertyMgr.setValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA,
                                 XMLSecurityPropertyManager.State.FSP, Constants.EXTERNAL_ACCESS_DEFAULT_FSP);
-
                     }
                 }
             }
@@ -398,22 +399,34 @@
         private final HashMap fInitFeatures = new HashMap();
         private final HashMap fInitProperties = new HashMap();
         private final SAXParserImpl fSAXParser;
+        private XMLSecurityManager fSecurityManager;
         private XMLSecurityPropertyManager fSecurityPropertyMgr;
 
 
         public JAXPSAXParser() {
-            this(null, null);
+            this(null, null, null);
         }
 
-        JAXPSAXParser(SAXParserImpl saxParser, XMLSecurityPropertyManager spm) {
+        JAXPSAXParser(SAXParserImpl saxParser, XMLSecurityPropertyManager securityPropertyMgr,
+                XMLSecurityManager securityManager) {
             super();
             fSAXParser = saxParser;
-            fSecurityPropertyMgr = spm;
-
+            fSecurityManager = securityManager;
+            fSecurityPropertyMgr = securityPropertyMgr;
             /**
              * This class may be used directly. So initialize the security manager if
              * it is null.
              */
+            if (fSecurityManager == null) {
+                fSecurityManager = new XMLSecurityManager(true);
+                try {
+                    super.setProperty(SECURITY_MANAGER, fSecurityManager);
+                } catch (SAXException e) {
+                    throw new UnsupportedOperationException(
+                        SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
+                        "property-not-recognized", new Object [] {SECURITY_MANAGER}), e);
+                }
+            }
             if (fSecurityPropertyMgr == null) {
                 fSecurityPropertyMgr = new XMLSecurityPropertyManager();
                 try {
@@ -421,7 +434,7 @@
                 } catch (SAXException e) {
                     throw new UnsupportedOperationException(
                         SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
-                        "property-not-recognized", new Object [] {SECURITY_MANAGER}), e);
+                        "property-not-recognized", new Object [] {XML_SECURITY_PROPERTY_MANAGER}), e);
                 }
             }
         }
@@ -439,7 +452,8 @@
             }
             if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
                 try {
-                    setProperty(SECURITY_MANAGER, value ? new SecurityManager() : null);
+                    fSecurityManager.setSecureProcessing(value);
+                    setProperty(SECURITY_MANAGER, fSecurityManager);
                 }
                 catch (SAXNotRecognizedException exc) {
                     // If the property is not supported
@@ -475,13 +489,7 @@
                 throw new NullPointerException();
             }
             if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
-                try {
-                    return (super.getProperty(SECURITY_MANAGER) != null);
-                }
-                // If the property is not supported the value must be false.
-                catch (SAXException exc) {
-                    return false;
-                }
+                return fSecurityManager.isSecureProcessing();
             }
             return super.getFeature(name);
         }
@@ -560,17 +568,21 @@
             if (fSAXParser != null && fSAXParser.fSchemaValidator != null) {
                 setSchemaValidatorProperty(name, value);
             }
-            /** Check to see if the property is managed by the property manager **/
-            int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(name) : -1;
-            if (index > -1) {
-                fSecurityPropertyMgr.setValue(index,
-                        XMLSecurityPropertyManager.State.APIPROPERTY, (String)value);
-            } else {
-                if (!fInitProperties.containsKey(name)) {
-                    fInitProperties.put(name, super.getProperty(name));
+
+            //check if the property is managed by security manager
+            if (fSecurityManager == null ||
+                    !fSecurityManager.setLimit(name, XMLSecurityManager.State.APIPROPERTY, value)) {
+                //check if the property is managed by security property manager
+                if (fSecurityPropertyMgr == null ||
+                        !fSecurityPropertyMgr.setValue(name, XMLSecurityPropertyManager.State.APIPROPERTY, value)) {
+                    //fall back to the existing property manager
+                    if (!fInitProperties.containsKey(name)) {
+                        fInitProperties.put(name, super.getProperty(name));
+                    }
+                    super.setProperty(name, value);
                 }
-                super.setProperty(name, value);
             }
+
         }
 
         public synchronized Object getProperty(String name)
@@ -583,9 +595,18 @@
                 // JAXP 1.2 support
                 return fSAXParser.schemaLanguage;
             }
-            int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(name) : -1;
-            if (index > -1) {
-                return fSecurityPropertyMgr.getValueByIndex(index);
+
+            /** Check to see if the property is managed by the security manager **/
+            String propertyValue = (fSecurityManager != null) ?
+                    fSecurityManager.getLimitAsString(name) : null;
+            if (propertyValue != null) {
+                return propertyValue;
+            } else {
+                propertyValue = (fSecurityPropertyMgr != null) ?
+                    fSecurityPropertyMgr.getValue(name) : null;
+                if (propertyValue != null) {
+                    return propertyValue;
+                }
             }
 
             return super.getProperty(name);
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java
index f398e03..5af27e2 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java
@@ -26,6 +26,7 @@
 package com.sun.org.apache.xerces.internal.jaxp.validation;
 
 import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import java.io.IOException;
 
 import javax.xml.transform.Result;
@@ -73,6 +74,19 @@
                     SAXTransformerFactory tf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
                                     (SAXTransformerFactory)SAXTransformerFactory.newInstance()
                                     : (SAXTransformerFactory) TransformerFactory.newInstance(DEFAULT_TRANSFORMER_IMPL, StAXValidatorHelper.class.getClassLoader());
+                    XMLSecurityManager securityManager = (XMLSecurityManager)fComponentManager.getProperty(Constants.SECURITY_MANAGER);
+                    if (securityManager != null) {
+                        for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
+                            if (securityManager.isSet(limit.ordinal())){
+                                tf.setAttribute(limit.apiProperty(),
+                                        securityManager.getLimitValueAsString(limit));
+                            }
+                        }
+                        if (securityManager.printEntityCountInfo()) {
+                            tf.setAttribute(Constants.JDK_ENTITY_COUNT_INFO, "yes");
+                        }
+                    }
+
                     identityTransformer1 = tf.newTransformer();
                     identityTransformer2 = tf.newTransformerHandler();
                 } catch (TransformerConfigurationException e) {
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java
index c3f1b67..d6c04fd 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java
@@ -20,28 +20,27 @@
 
 package com.sun.org.apache.xerces.internal.jaxp.validation;
 
-import java.lang.ref.SoftReference;
-import java.io.IOException;
-
-import javax.xml.transform.Result;
-import javax.xml.transform.Source;
-import javax.xml.transform.sax.SAXTransformerFactory;
-import javax.xml.transform.sax.TransformerHandler;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-import javax.xml.XMLConstants;
-
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
 import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.XNIException;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLParseException;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration;
+import java.io.IOException;
+import java.lang.ref.SoftReference;
+import javax.xml.XMLConstants;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.sax.SAXTransformerFactory;
+import javax.xml.transform.sax.TransformerHandler;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
 import org.xml.sax.SAXException;
 
 /**
@@ -86,6 +85,11 @@
         Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
 
     private static final String DEFAULT_TRANSFORMER_IMPL = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
+
+    /** Property id: security manager. */
+    private static final String SECURITY_MANAGER =
+        Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
+
     //
     // Data
     //
@@ -165,6 +169,9 @@
 
     private XMLParserConfiguration initialize() {
         XML11Configuration config = new XML11Configuration();
+        if (fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
+            config.setProperty(SECURITY_MANAGER, new XMLSecurityManager());
+        }
         config.setProperty(ENTITY_RESOLVER, fComponentManager.getProperty(ENTITY_RESOLVER));
         config.setProperty(ERROR_HANDLER, fComponentManager.getProperty(ERROR_HANDLER));
         XMLErrorReporter errorReporter = (XMLErrorReporter) fComponentManager.getProperty(ERROR_REPORTER);
@@ -182,6 +189,8 @@
         config.setDTDContentModelHandler(null);
         config.setProperty(Constants.XML_SECURITY_PROPERTY_MANAGER,
                 fComponentManager.getProperty(Constants.XML_SECURITY_PROPERTY_MANAGER));
+        config.setProperty(Constants.SECURITY_MANAGER,
+                fComponentManager.getProperty(Constants.SECURITY_MANAGER));
         fConfiguration = new SoftReference(config);
         return config;
     }
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java
index 8add5d2..9a14e5d 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java
@@ -49,10 +49,10 @@
 import com.sun.org.apache.xerces.internal.util.SAXMessageFormatter;
 import com.sun.org.apache.xerces.internal.util.Status;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.URI;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl;
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
@@ -679,10 +679,12 @@
                                     SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
                     spf.setNamespaceAware(true);
                     try {
+                        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                                fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
                         reader = spf.newSAXParser().getXMLReader();
                         // If this is a Xerces SAX parser, set the security manager if there is one
                         if (reader instanceof com.sun.org.apache.xerces.internal.parsers.SAXParser) {
-                           SecurityManager securityManager = (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
+                           XMLSecurityManager securityManager = (XMLSecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
                            if (securityManager != null) {
                                try {
                                    reader.setProperty(SECURITY_MANAGER, securityManager);
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java
index a19088d..45f2346 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java
@@ -41,10 +41,10 @@
 import com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper;
 import com.sun.org.apache.xerces.internal.util.SAXInputSource;
 import com.sun.org.apache.xerces.internal.util.SAXMessageFormatter;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.StAXInputSource;
 import com.sun.org.apache.xerces.internal.util.Status;
 import com.sun.org.apache.xerces.internal.util.XMLGrammarPoolImpl;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.XNIException;
 import com.sun.org.apache.xerces.internal.xni.grammars.Grammar;
@@ -79,7 +79,7 @@
     private static final String XMLGRAMMAR_POOL =
         Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
 
-    /** Property identifier: SecurityManager. */
+    /** Property identifier: XMLSecurityManager. */
     private static final String SECURITY_MANAGER =
         Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
 
@@ -87,7 +87,6 @@
     private static final String XML_SECURITY_PROPERTY_MANAGER =
             Constants.XML_SECURITY_PROPERTY_MANAGER;
 
-
     //
     // Data
     //
@@ -108,7 +107,7 @@
     private ErrorHandlerWrapper fErrorHandlerWrapper;
 
     /** The SecurityManager. */
-    private SecurityManager fSecurityManager;
+    private XMLSecurityManager fSecurityManager;
 
     /** The Security property manager. */
     private XMLSecurityPropertyManager fSecurityPropertyMgr;
@@ -122,8 +121,6 @@
      * Note the default value (false) is the safe option..
      */
     private final boolean fUseServicesMechanism;
-
-
     public XMLSchemaFactory() {
         this(true);
     }
@@ -141,7 +138,7 @@
         fXMLSchemaLoader.setErrorHandler(fErrorHandlerWrapper);
 
         // Enable secure processing feature by default
-        fSecurityManager = new SecurityManager();
+        fSecurityManager = new XMLSecurityManager(true);
         fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
 
         fSecurityPropertyMgr = new XMLSecurityPropertyManager();
@@ -301,7 +298,7 @@
                     "FeatureNameNull", null));
         }
         if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
-            return (fSecurityManager != null);
+            return (fSecurityManager !=null && fSecurityManager.isSecureProcessing());
         }
         try {
             return fXMLSchemaLoader.getFeature(name);
@@ -365,17 +362,15 @@
                         SAXMessageFormatter.formatMessage(null,
                         "jaxp-secureprocessing-feature", null));
             }
-            if (value) {
-                fSecurityManager = new SecurityManager();
 
+            fSecurityManager.setSecureProcessing(value);
+            if (value) {
                 if (Constants.IS_JDK8_OR_ABOVE) {
                     fSecurityPropertyMgr.setValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD,
                             XMLSecurityPropertyManager.State.FSP, Constants.EXTERNAL_ACCESS_DEFAULT_FSP);
                     fSecurityPropertyMgr.setValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA,
                             XMLSecurityPropertyManager.State.FSP, Constants.EXTERNAL_ACCESS_DEFAULT_FSP);
                 }
-            } else {
-                fSecurityManager = null;
             }
 
             fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
@@ -410,7 +405,7 @@
                     "ProperyNameNull", null));
         }
         if (name.equals(SECURITY_MANAGER)) {
-            fSecurityManager = (SecurityManager) object;
+            fSecurityManager = (XMLSecurityManager) object;
             fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
             return;
         }
@@ -420,12 +415,15 @@
                     "property-not-supported", new Object [] {name}));
         }
         try {
-            int index = fSecurityPropertyMgr.getIndex(name);
-            if (index > -1) {
-                fSecurityPropertyMgr.setValue(index,
-                        XMLSecurityPropertyManager.State.APIPROPERTY, (String)object);
-            } else {
-                fXMLSchemaLoader.setProperty(name, object);
+            //check if the property is managed by security manager
+            if (fSecurityManager == null ||
+                    !fSecurityManager.setLimit(name, XMLSecurityManager.State.APIPROPERTY, object)) {
+                //check if the property is managed by security property manager
+                if (fSecurityPropertyMgr == null ||
+                        !fSecurityPropertyMgr.setValue(name, XMLSecurityPropertyManager.State.APIPROPERTY, object)) {
+                    //fall back to the existing property manager
+                    fXMLSchemaLoader.setProperty(name, object);
+                }
             }
         }
         catch (XMLConfigurationException e) {
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java
index 74e30da..7440b72 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java
@@ -39,9 +39,9 @@
 import com.sun.org.apache.xerces.internal.util.NamespaceSupport;
 import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
 import com.sun.org.apache.xerces.internal.util.PropertyState;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.Status;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
 import com.sun.org.apache.xerces.internal.xni.XNIException;
@@ -181,7 +181,7 @@
     private final HashMap fInitProperties = new HashMap();
 
     /** Stores the initial security manager. */
-    private final SecurityManager fInitSecurityManager;
+    private XMLSecurityManager fInitSecurityManager;
 
     /** Stores the initial security property manager. */
     private final XMLSecurityPropertyManager fSecurityPropertyMgr;
@@ -221,12 +221,6 @@
         fComponents.put(ENTITY_RESOLVER, null);
         fComponents.put(ERROR_HANDLER, null);
 
-        if (System.getSecurityManager() != null) {
-            _isSecureMode = true;
-            setProperty(SECURITY_MANAGER, new SecurityManager());
-        } else {
-            fComponents.put(SECURITY_MANAGER, null);
-        }
         fComponents.put(SYMBOL_TABLE, new SymbolTable());
 
         // setup grammar pool
@@ -241,15 +235,21 @@
         addRecognizedParamsAndSetDefaults(fErrorReporter, grammarContainer);
         addRecognizedParamsAndSetDefaults(fSchemaValidator, grammarContainer);
 
-        // if the secure processing feature is set to true, add a security manager to the configuration
-        Boolean secureProcessing = grammarContainer.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
-        if (Boolean.TRUE.equals(secureProcessing)) {
-            fInitSecurityManager = new SecurityManager();
+        boolean secureProcessing = grammarContainer.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
+        if (System.getSecurityManager() != null) {
+            _isSecureMode = true;
+            secureProcessing = true;
         }
-        else {
-            fInitSecurityManager = null;
+
+        fInitSecurityManager = (XMLSecurityManager)
+                grammarContainer.getProperty(SECURITY_MANAGER);
+        if (fInitSecurityManager != null ) {
+            fInitSecurityManager.setSecureProcessing(secureProcessing);
+        } else {
+            fInitSecurityManager = new XMLSecurityManager(secureProcessing);
         }
-        fComponents.put(SECURITY_MANAGER, fInitSecurityManager);
+
+        setProperty(SECURITY_MANAGER, fInitSecurityManager);
 
         //pass on properties set on SchemaFactory
         fSecurityPropertyMgr = (XMLSecurityPropertyManager)
@@ -281,7 +281,7 @@
             return FeatureState.is(fUseGrammarPoolOnly);
         }
         else if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(featureId)) {
-            return FeatureState.is(getProperty(SECURITY_MANAGER) != null);
+            return FeatureState.is(fInitSecurityManager.isSecureProcessing());
         }
         else if (SCHEMA_ELEMENT_DEFAULT.equals(featureId)) {
             return FeatureState.is(true); //pre-condition: VALIDATION and SCHEMA_VALIDATION are always true
@@ -311,7 +311,8 @@
             if (_isSecureMode && !value) {
                 throw new XMLConfigurationException(Status.NOT_ALLOWED, XMLConstants.FEATURE_SECURE_PROCESSING);
             }
-            setProperty(SECURITY_MANAGER, value ? new SecurityManager() : null);
+            fInitSecurityManager.setSecureProcessing(value);
+            setProperty(SECURITY_MANAGER, fInitSecurityManager);
 
             if (value && Constants.IS_JDK8_OR_ABOVE) {
                 fSecurityPropertyMgr.setValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD,
@@ -390,10 +391,20 @@
             fComponents.put(propertyId, value);
             return;
         }
-        if (!fInitProperties.containsKey(propertyId)) {
-            fInitProperties.put(propertyId, super.getProperty(propertyId));
+
+        //check if the property is managed by security manager
+        if (fInitSecurityManager == null ||
+                !fInitSecurityManager.setLimit(propertyId, XMLSecurityManager.State.APIPROPERTY, value)) {
+            //check if the property is managed by security property manager
+            if (fSecurityPropertyMgr == null ||
+                    !fSecurityPropertyMgr.setValue(propertyId, XMLSecurityPropertyManager.State.APIPROPERTY, value)) {
+                //fall back to the existing property manager
+                if (!fInitProperties.containsKey(propertyId)) {
+                    fInitProperties.put(propertyId, super.getProperty(propertyId));
+                }
+                super.setProperty(propertyId, value);
+            }
         }
-        super.setProperty(propertyId, value);
     }
 
     /**
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/AbstractSAXParser.java b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/AbstractSAXParser.java
index 726f31e..eea7057 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/AbstractSAXParser.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/AbstractSAXParser.java
@@ -20,18 +20,15 @@
 
 package com.sun.org.apache.xerces.internal.parsers;
 
-import java.io.IOException;
-import java.util.Locale;
-
 import com.sun.org.apache.xerces.internal.impl.Constants;
-import com.sun.org.apache.xerces.internal.util.Status;
-import com.sun.org.apache.xerces.internal.xs.PSVIProvider;
-import com.sun.org.apache.xerces.internal.util.EntityResolverWrapper;
 import com.sun.org.apache.xerces.internal.util.EntityResolver2Wrapper;
+import com.sun.org.apache.xerces.internal.util.EntityResolverWrapper;
 import com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper;
 import com.sun.org.apache.xerces.internal.util.SAXMessageFormatter;
+import com.sun.org.apache.xerces.internal.util.Status;
 import com.sun.org.apache.xerces.internal.util.SymbolHash;
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
 import com.sun.org.apache.xerces.internal.xni.QName;
@@ -48,15 +45,17 @@
 import com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration;
 import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
 import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
+import com.sun.org.apache.xerces.internal.xs.PSVIProvider;
+import java.io.IOException;
+import java.util.Locale;
+import javax.xml.XMLConstants;
 import org.xml.sax.AttributeList;
-import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.DTDHandler;
 import org.xml.sax.DocumentHandler;
 import org.xml.sax.EntityResolver;
 import org.xml.sax.ErrorHandler;
 import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
 import org.xml.sax.Parser;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
@@ -131,6 +130,10 @@
     protected static final String DOM_NODE =
         Constants.SAX_PROPERTY_PREFIX + Constants.DOM_NODE_PROPERTY;
 
+    /** Property id: security manager. */
+    private static final String SECURITY_MANAGER =
+        Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
+
     /** Recognized properties. */
     private static final String[] RECOGNIZED_PROPERTIES = {
         LEXICAL_HANDLER,
@@ -1645,19 +1648,13 @@
                 // Drop through and perform default processing
                 //
             }
-
-            //
-            // Xerces Features
-            //
-
-            /*
-            else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
-                String feature = featureId.substring(XERCES_FEATURES_PREFIX.length());
-                //
-                // Drop through and perform default processing
-                //
+            else if (featureId.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
+                if (state) {
+                    if (fConfiguration.getProperty(SECURITY_MANAGER )==null) {
+                        fConfiguration.setProperty(SECURITY_MANAGER, new XMLSecurityManager());
+                    }
+                }
             }
-            */
 
             //
             // Default handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SAXParser.java b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SAXParser.java
index cf9e9a7..8432b54 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SAXParser.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SAXParser.java
@@ -22,6 +22,7 @@
 
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarPool;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration;
@@ -76,6 +77,8 @@
         XMLGRAMMAR_POOL,
     };
 
+    XMLSecurityManager securityManager;
+    XMLSecurityPropertyManager securityPropertyManager;
     //
     // Constructors
     //
@@ -129,18 +132,30 @@
      */
     public void setProperty(String name, Object value)
         throws SAXNotRecognizedException, SAXNotSupportedException {
-        XMLSecurityPropertyManager spm = new XMLSecurityPropertyManager();
-        int index = spm.getIndex(name);
+        if (securityPropertyManager == null) {
+            securityPropertyManager = new XMLSecurityPropertyManager();
+        }
+        int index = securityPropertyManager.getIndex(name);
         if (index > -1) {
             /**
              * this is a direct call to this parser, not a subclass since
              * internally the support of this property is done through
              * XMLSecurityPropertyManager
              */
-            spm.setValue(index, XMLSecurityPropertyManager.State.APIPROPERTY, (String)value);
-            super.setProperty(Constants.XML_SECURITY_PROPERTY_MANAGER, spm);
+            securityPropertyManager.setValue(index, XMLSecurityPropertyManager.State.APIPROPERTY, (String)value);
+            super.setProperty(Constants.XML_SECURITY_PROPERTY_MANAGER, securityPropertyManager);
         } else {
-            super.setProperty(name, value);
+            if (securityManager == null) {
+                securityManager = new XMLSecurityManager(true);
+            }
+
+            //check if the property is managed by security manager
+            if (securityManager.setLimit(name, XMLSecurityManager.State.APIPROPERTY, value)) {
+                super.setProperty(Constants.SECURITY_MANAGER, securityManager);
+            } else {
+                super.setProperty(name, value);
+            }
+
         }
     }
 } // class SAXParser
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SecurityConfiguration.java b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SecurityConfiguration.java
index df32bfa..65c85d1 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SecurityConfiguration.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/SecurityConfiguration.java
@@ -23,8 +23,8 @@
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarPool;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 
 /**
  * This configuration allows Xerces to behave in a security-conscious manner; that is,
@@ -44,6 +44,7 @@
  *
  * @author Neil Graham, IBM
  *
+ * @version $Id: SecurityConfiguration.java,v 1.6 2010-11-01 04:40:09 joehw Exp $
  */
 public class SecurityConfiguration extends XIncludeAwareParserConfiguration
 {
@@ -107,7 +108,7 @@
         super(symbolTable, grammarPool, parentSettings);
 
         // create the SecurityManager property:
-        setProperty(SECURITY_MANAGER_PROPERTY, new SecurityManager());
+        setProperty(SECURITY_MANAGER_PROPERTY, new XMLSecurityManager(true));
     } // <init>(SymbolTable,XMLGrammarPool)
 
 } // class SecurityConfiguration
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java
index 993ef61..9d0ce8a 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java
@@ -52,6 +52,7 @@
 import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
 import com.sun.org.apache.xerces.internal.util.PropertyState;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
 import com.sun.org.apache.xerces.internal.xni.XMLDTDContentModelHandler;
 import com.sun.org.apache.xerces.internal.xni.XMLDTDHandler;
@@ -279,6 +280,8 @@
     private static final String XML_SECURITY_PROPERTY_MANAGER =
             Constants.XML_SECURITY_PROPERTY_MANAGER;
 
+    /** Property identifier: Security manager. */
+    private static final String SECURITY_MANAGER = Constants.SECURITY_MANAGER;
 
     // debugging
 
@@ -289,33 +292,33 @@
     // Data
     //
 
-        protected SymbolTable fSymbolTable;
+    protected SymbolTable fSymbolTable;
     protected XMLInputSource fInputSource;
     protected ValidationManager fValidationManager;
-        protected XMLVersionDetector fVersionDetector;
+    protected XMLVersionDetector fVersionDetector;
     protected XMLLocator fLocator;
-        protected Locale fLocale;
+    protected Locale fLocale;
 
-        /** XML 1.0 Components. */
-        protected ArrayList fComponents;
+    /** XML 1.0 Components. */
+    protected ArrayList fComponents;
 
-        /** XML 1.1. Components. */
-        protected ArrayList fXML11Components = null;
+    /** XML 1.1. Components. */
+    protected ArrayList fXML11Components = null;
 
-        /** Common components: XMLEntityManager, XMLErrorReporter, XMLSchemaValidator */
-        protected ArrayList fCommonComponents = null;
+    /** Common components: XMLEntityManager, XMLErrorReporter, XMLSchemaValidator */
+    protected ArrayList fCommonComponents = null;
 
-        /** The document handler. */
-        protected XMLDocumentHandler fDocumentHandler;
+    /** The document handler. */
+    protected XMLDocumentHandler fDocumentHandler;
 
-        /** The DTD handler. */
-        protected XMLDTDHandler fDTDHandler;
+    /** The DTD handler. */
+    protected XMLDTDHandler fDTDHandler;
 
-        /** The DTD content model handler. */
-        protected XMLDTDContentModelHandler fDTDContentModelHandler;
+    /** The DTD content model handler. */
+    protected XMLDTDContentModelHandler fDTDContentModelHandler;
 
-        /** Last component in the document pipeline */
-        protected XMLDocumentSource fLastComponent;
+    /** Last component in the document pipeline */
+    protected XMLDocumentSource fLastComponent;
 
     /**
      * True if a parse is in progress. This state is needed because
@@ -495,31 +498,31 @@
                 fFeatures.put(SCHEMA_ELEMENT_DEFAULT, Boolean.TRUE);
                 fFeatures.put(NORMALIZE_DATA, Boolean.TRUE);
                 fFeatures.put(SCHEMA_AUGMENT_PSVI, Boolean.TRUE);
-                fFeatures.put(GENERATE_SYNTHETIC_ANNOTATIONS, Boolean.FALSE);
-                fFeatures.put(VALIDATE_ANNOTATIONS, Boolean.FALSE);
-                fFeatures.put(HONOUR_ALL_SCHEMALOCATIONS, Boolean.FALSE);
-                fFeatures.put(NAMESPACE_GROWTH, Boolean.FALSE);
-                fFeatures.put(TOLERATE_DUPLICATES, Boolean.FALSE);
-                fFeatures.put(USE_GRAMMAR_POOL_ONLY, Boolean.FALSE);
+        fFeatures.put(GENERATE_SYNTHETIC_ANNOTATIONS, Boolean.FALSE);
+        fFeatures.put(VALIDATE_ANNOTATIONS, Boolean.FALSE);
+        fFeatures.put(HONOUR_ALL_SCHEMALOCATIONS, Boolean.FALSE);
+        fFeatures.put(NAMESPACE_GROWTH, Boolean.FALSE);
+        fFeatures.put(TOLERATE_DUPLICATES, Boolean.FALSE);
+        fFeatures.put(USE_GRAMMAR_POOL_ONLY, Boolean.FALSE);
                 fFeatures.put(PARSER_SETTINGS, Boolean.TRUE);
                 fFeatures.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
 
         // add default recognized properties
         final String[] recognizedProperties =
             {
-                SYMBOL_TABLE,
-                ERROR_HANDLER,
-                ENTITY_RESOLVER,
+                                SYMBOL_TABLE,
+                                ERROR_HANDLER,
+                                ENTITY_RESOLVER,
                 ERROR_REPORTER,
                 ENTITY_MANAGER,
                 DOCUMENT_SCANNER,
                 DTD_SCANNER,
                 DTD_PROCESSOR,
                 DTD_VALIDATOR,
-                DATATYPE_VALIDATOR_FACTORY,
-                VALIDATION_MANAGER,
-                SCHEMA_VALIDATOR,
-                XML_STRING,
+                                DATATYPE_VALIDATOR_FACTORY,
+                                VALIDATION_MANAGER,
+                                SCHEMA_VALIDATOR,
+                                XML_STRING,
                 XMLGRAMMAR_POOL,
                 JAXP_SCHEMA_SOURCE,
                 JAXP_SCHEMA_LANGUAGE,
@@ -531,19 +534,20 @@
                 SCHEMA_NONS_LOCATION,
                 LOCALE,
                 SCHEMA_DV_FACTORY,
+                SECURITY_MANAGER,
                 XML_SECURITY_PROPERTY_MANAGER
         };
         addRecognizedProperties(recognizedProperties);
 
-        if (symbolTable == null) {
-                symbolTable = new SymbolTable();
-        }
-        fSymbolTable = symbolTable;
-        fProperties.put(SYMBOL_TABLE, fSymbolTable);
+                if (symbolTable == null) {
+                        symbolTable = new SymbolTable();
+                }
+                fSymbolTable = symbolTable;
+                fProperties.put(SYMBOL_TABLE, fSymbolTable);
 
         fGrammarPool = grammarPool;
         if (fGrammarPool != null) {
-            fProperties.put(XMLGRAMMAR_POOL, fGrammarPool);
+                        fProperties.put(XMLGRAMMAR_POOL, fGrammarPool);
         }
 
         fEntityManager = new XMLEntityManager();
@@ -581,6 +585,8 @@
 
         fProperties.put(XML_SECURITY_PROPERTY_MANAGER, new XMLSecurityPropertyManager());
 
+        fProperties.put(SECURITY_MANAGER, new XMLSecurityManager(true));
+
         // add message formatters
         if (fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) {
             XMLMessageFormatter xmft = new XMLMessageFormatter();
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/util/SecurityManager.java b/jaxp/src/com/sun/org/apache/xerces/internal/util/SecurityManager.java
deleted file mode 100644
index dd510b6..0000000
--- a/jaxp/src/com/sun/org/apache/xerces/internal/util/SecurityManager.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * The Apache Software License, Version 1.1
- *
- *
- * Copyright (c) 2003 The Apache Software Foundation.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Xerces" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation and was
- * originally based on software copyright (c) 1999, International
- * Business Machines, Inc., http://www.apache.org.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- */
-
-package com.sun.org.apache.xerces.internal.util;
-import com.sun.org.apache.xerces.internal.impl.Constants;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-/**
- * This class is a container for parser settings that relate to
- * security, or more specifically, it is intended to be used to prevent denial-of-service
- * attacks from being launched against a system running Xerces.
- * Any component that is aware of a denial-of-service attack that can arise
- * from its processing of a certain kind of document may query its Component Manager
- * for the property (http://apache.org/xml/properties/security-manager)
- * whose value will be an instance of this class.
- * If no value has been set for the property, the component should proceed in the "usual" (spec-compliant)
- * manner.  If a value has been set, then it must be the case that the component in
- * question needs to know what method of this class to query.  This class
- * will provide defaults for all known security issues, but will also provide
- * setters so that those values can be tailored by applications that care.
- *
- * @author  Neil Graham, IBM
- *
- * @version $Id: SecurityManager.java,v 1.5 2010-11-01 04:40:14 joehw Exp $
- */
-public final class SecurityManager {
-
-    //
-    // Constants
-    //
-
-    // default value for entity expansion limit
-    private final static int DEFAULT_ENTITY_EXPANSION_LIMIT = 64000;
-
-    /** Default value of number of nodes created. **/
-    private final static int DEFAULT_MAX_OCCUR_NODE_LIMIT = 5000;
-
-    //
-    // Data
-    //
-
-        private final static int DEFAULT_ELEMENT_ATTRIBUTE_LIMIT = 10000;
-
-    /** Entity expansion limit. **/
-    private int entityExpansionLimit;
-
-    /** W3C XML Schema maxOccurs limit. **/
-    private int maxOccurLimit;
-
-        private int fElementAttributeLimit;
-    // default constructor.  Establishes default values for
-    // all known security holes.
-    /**
-     * Default constructor.  Establishes default values
-     * for known security vulnerabilities.
-     */
-    public SecurityManager() {
-        entityExpansionLimit = DEFAULT_ENTITY_EXPANSION_LIMIT;
-        maxOccurLimit = DEFAULT_MAX_OCCUR_NODE_LIMIT ;
-                fElementAttributeLimit = DEFAULT_ELEMENT_ATTRIBUTE_LIMIT;
-                //We are reading system properties only once ,
-                //at the time of creation of this object ,
-                readSystemProperties();
-    }
-
-    /**
-     * <p>Sets the number of entity expansions that the
-     * parser should permit in a document.</p>
-     *
-     * @param limit the number of entity expansions
-     * permitted in a document
-     */
-    public void setEntityExpansionLimit(int limit) {
-        entityExpansionLimit = limit;
-    }
-
-    /**
-     * <p>Returns the number of entity expansions
-     * that the parser permits in a document.</p>
-     *
-     * @return the number of entity expansions
-     * permitted in a document
-     */
-    public int getEntityExpansionLimit() {
-        return entityExpansionLimit;
-    }
-
-    /**
-     * <p>Sets the limit of the number of content model nodes
-     * that may be created when building a grammar for a W3C
-     * XML Schema that contains maxOccurs attributes with values
-     * other than "unbounded".</p>
-     *
-     * @param limit the maximum value for maxOccurs other
-     * than "unbounded"
-     */
-    public void setMaxOccurNodeLimit(int limit){
-        maxOccurLimit = limit;
-    }
-
-    /**
-     * <p>Returns the limit of the number of content model nodes
-     * that may be created when building a grammar for a W3C
-     * XML Schema that contains maxOccurs attributes with values
-     * other than "unbounded".</p>
-     *
-     * @return the maximum value for maxOccurs other
-     * than "unbounded"
-     */
-    public int getMaxOccurNodeLimit(){
-        return maxOccurLimit;
-    }
-
-    public int getElementAttrLimit(){
-                return fElementAttributeLimit;
-        }
-
-        public void setElementAttrLimit(int limit){
-                fElementAttributeLimit = limit;
-        }
-
-        private void readSystemProperties(){
-
-            //TODO: also read SYSTEM_PROPERTY_ELEMENT_ATTRIBUTE_LIMIT
-            try {
-                    String value = getSystemProperty(Constants.ENTITY_EXPANSION_LIMIT);
-                    if(value != null && !value.equals("")){
-                            entityExpansionLimit = Integer.parseInt(value);
-                            if (entityExpansionLimit < 0)
-                                    entityExpansionLimit = DEFAULT_ENTITY_EXPANSION_LIMIT;
-                    }
-                    else
-                            entityExpansionLimit = DEFAULT_ENTITY_EXPANSION_LIMIT;
-            }catch(Exception ex){}
-
-            try {
-                    String value = getSystemProperty(Constants.MAX_OCCUR_LIMIT);
-                    if(value != null && !value.equals("")){
-                            maxOccurLimit = Integer.parseInt(value);
-                            if (maxOccurLimit < 0)
-                                    maxOccurLimit = DEFAULT_MAX_OCCUR_NODE_LIMIT;
-                    }
-                    else
-                            maxOccurLimit = DEFAULT_MAX_OCCUR_NODE_LIMIT;
-            }catch(Exception ex){}
-
-            try {
-                    String value = getSystemProperty(Constants.SYSTEM_PROPERTY_ELEMENT_ATTRIBUTE_LIMIT);
-                    if(value != null && !value.equals("")){
-                            fElementAttributeLimit = Integer.parseInt(value);
-                            if ( fElementAttributeLimit < 0)
-                                    fElementAttributeLimit = DEFAULT_ELEMENT_ATTRIBUTE_LIMIT;
-                    }
-                    else
-                            fElementAttributeLimit = DEFAULT_ELEMENT_ATTRIBUTE_LIMIT;
-
-                }catch(Exception ex){}
-
-        }
-
-    private String getSystemProperty(final String propName) {
-        return AccessController.doPrivileged(new PrivilegedAction<String>() {
-            public String run() {
-                return System.getProperty(propName);
-            }
-        });
-    }
-} // class SecurityManager
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/util/SymbolTable.java b/jaxp/src/com/sun/org/apache/xerces/internal/util/SymbolTable.java
index b3d9ed7..8e62c1f 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/util/SymbolTable.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/util/SymbolTable.java
@@ -173,7 +173,7 @@
         for (int i = 0; i < length; i++) {
             code = code * 37 + symbol.charAt(i);
         }
-        return code & 0x7FFFFFF;
+        return code & 0x7FFFFFFF;
 
     } // hash(String):int
 
@@ -194,7 +194,7 @@
         for (int i = 0; i < length; i++) {
             code = code * 37 + buffer[offset + i];
         }
-        return code & 0x7FFFFFF;
+        return code & 0x7FFFFFFF;
 
     } // hash(char[],int,int):int
 
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java b/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java
new file mode 100644
index 0000000..41724b6
--- /dev/null
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java
@@ -0,0 +1,236 @@
+/*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
+ *
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * The contents of this file are subject to the terms of either the GNU
+ * General Public License Version 2 only ("GPL") or the Common Development
+ * and Distribution License("CDDL") (collectively, the "License").  You
+ * may not use this file except in compliance with the License.  You can
+ * obtain a copy of the License at
+ * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
+ * or packager/legal/LICENSE.txt.  See the License for the specific
+ * language governing permissions and limitations under the License.
+ *
+ * When distributing the software, include this License Header Notice in each
+ * file and include the License file at packager/legal/LICENSE.txt.
+ *
+ * GPL Classpath Exception:
+ * Oracle designates this particular file as subject to the "Classpath"
+ * exception as provided by Oracle in the GPL Version 2 section of the License
+ * file that accompanied this code.
+ *
+ * Modifications:
+ * If applicable, add the following below the License Header, with the fields
+ * enclosed by brackets [] replaced by your own identifying information:
+ * "Portions Copyright [year] [name of copyright owner]"
+ *
+ * Contributor(s):
+ * If you wish your version of this file to be governed by only the CDDL or
+ * only the GPL Version 2, indicate your decision by adding "[Contributor]
+ * elects to include this software in this distribution under the [CDDL or GPL
+ * Version 2] license."  If you don't indicate a single choice of license, a
+ * recipient has the option to distribute your version of this file under
+ * either the CDDL, the GPL Version 2 or to extend the choice of license to
+ * its licensees as provided above.  However, if you add GPL Version 2 code
+ * and therefore, elected the GPL Version 2 license, then the option applies
+ * only if the new code is made subject to such option by the copyright
+ * holder.
+ */
+package com.sun.org.apache.xerces.internal.utils;
+
+import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager.Limit;
+import java.util.Formatter;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A helper for analyzing entity expansion limits
+ *
+ * @author Joe Wang Oracle Corp.
+ *
+ */
+public final class XMLLimitAnalyzer {
+
+    /**
+     * Map old property names with the new ones
+     */
+    public static enum NameMap {
+        ENTITY_EXPANSION_LIMIT(Constants.SP_ENTITY_EXPANSION_LIMIT, Constants.ENTITY_EXPANSION_LIMIT),
+        MAX_OCCUR_NODE_LIMIT(Constants.SP_MAX_OCCUR_LIMIT, Constants.MAX_OCCUR_LIMIT),
+        ELEMENT_ATTRIBUTE_LIMIT(Constants.SP_ELEMENT_ATTRIBUTE_LIMIT, Constants.ELEMENT_ATTRIBUTE_LIMIT);
+
+        final String newName;
+        final String oldName;
+
+        NameMap(String newName, String oldName) {
+            this.newName = newName;
+            this.oldName = oldName;
+        }
+
+        String getOldName(String newName) {
+            if (newName.equals(this.newName)) {
+                return oldName;
+            }
+            return null;
+        }
+    }
+
+    private XMLSecurityManager securityManager;
+    /**
+     * Max value accumulated for each property
+     */
+    private final int[] values;
+    /**
+     * Names of the entities corresponding to their max values
+     */
+    private final String[] names;
+    /**
+     * Total value of accumulated entities
+     */
+    private final int[] totalValue;
+
+    /**
+     * Maintain values of the top 10 elements in the process of parsing
+     */
+    private final Map[] caches;
+
+    private String entityStart, entityEnd;
+    /**
+     * Default constructor. Establishes default values for known security
+     * vulnerabilities.
+     */
+    public XMLLimitAnalyzer(XMLSecurityManager securityManager) {
+        this.securityManager = securityManager;
+        values = new int[Limit.values().length];
+        totalValue = new int[Limit.values().length];
+        names = new String[Limit.values().length];
+        caches = new Map[Limit.values().length];
+    }
+
+    /**
+     * Add the value to the current max count for the specified property
+     * To find the max value of all entities, set no limit
+     *
+     * @param limit the type of the property
+     * @param entityName the name of the entity
+     * @param value the value of the entity
+     */
+    public void addValue(Limit limit, String entityName, int value) {
+        addValue(limit.ordinal(), entityName, value);
+    }
+
+    /**
+     * Add the value to the current count by the index of the property
+     * @param index the index of the property
+     * @param entityName the name of the entity
+     * @param value the value of the entity
+     */
+    public void addValue(int index, String entityName, int value) {
+        if (index == Limit.ENTITY_EXPANSION_LIMIT.ordinal() ||
+                index == Limit.MAX_OCCUR_NODE_LIMIT.ordinal() ||
+                index == Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal()) {
+            totalValue[index] += value;
+            return;
+        }
+
+        Map<String, Integer> cache;
+        if (caches[index] == null) {
+            cache = new HashMap<String, Integer>(10);
+            caches[index] = cache;
+        } else {
+            cache = caches[index];
+        }
+
+        int accumulatedValue = value;
+        if (cache.containsKey(entityName)) {
+            accumulatedValue += cache.get(entityName).intValue();
+            cache.put(entityName, Integer.valueOf(accumulatedValue));
+        } else {
+            cache.put(entityName, Integer.valueOf(value));
+        }
+
+        if (accumulatedValue > values[index]) {
+            values[index] = accumulatedValue;
+            names[index] = entityName;
+        }
+
+
+        if (index == Limit.GENEAL_ENTITY_SIZE_LIMIT.ordinal() ||
+                index == Limit.PARAMETER_ENTITY_SIZE_LIMIT.ordinal()) {
+            totalValue[Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal()] += value;
+        }
+    }
+
+    /**
+     * Return the value of the current max count for the specified property
+     *
+     * @param limit the property
+     * @return the value of the property
+     */
+    public int getValue(Limit limit) {
+        return values[limit.ordinal()];
+    }
+
+    public int getValue(int index) {
+        return values[index];
+    }
+    /**
+     * Return the total value accumulated so far
+     *
+     * @param limit the property
+     * @return the accumulated value of the property
+     */
+    public int getTotalValue(Limit limit) {
+        return totalValue[limit.ordinal()];
+    }
+
+    public int getTotalValue(int index) {
+        return totalValue[index];
+    }
+    /**
+     * Return the current max value (count or length) by the index of a property
+     * @param index the index of a property
+     * @return count of a property
+     */
+    public int getValueByIndex(int index) {
+        return values[index];
+    }
+
+    public void startEntity(String name) {
+        entityStart = name;
+    }
+
+    public boolean isTracking(String name) {
+        return entityStart.equals(name);
+    }
+    /**
+     * Stop tracking the entity
+     * @param limit the limit property
+     * @param name the name of an entity
+     */
+    public void endEntity(Limit limit, String name) {
+        entityStart = "";
+        Map<String, Integer> cache = caches[limit.ordinal()];
+        if (cache != null) {
+            cache.remove(name);
+        }
+    }
+
+    public void debugPrint() {
+        Formatter formatter = new Formatter();
+        System.out.println(formatter.format("%30s %15s %15s %15s %30s",
+                "Property","Limit","Total size","Size","Entity Name"));
+
+        for (Limit limit : Limit.values()) {
+            formatter = new Formatter();
+            System.out.println(formatter.format("%30s %15d %15d %15d %30s",
+                    limit.name(),
+                    securityManager.getLimit(limit),
+                    totalValue[limit.ordinal()],
+                    values[limit.ordinal()],
+                    names[limit.ordinal()]));
+        }
+    }
+}
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java b/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java
new file mode 100644
index 0000000..1ddb651
--- /dev/null
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java
@@ -0,0 +1,521 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.org.apache.xerces.internal.utils;
+
+import com.sun.org.apache.xerces.internal.impl.Constants;
+
+/**
+ * This class manages standard and implementation-specific limitations.
+ *
+ */
+public final class XMLSecurityManager {
+
+    /**
+     * States of the settings of a property, in the order: default value, value
+     * set by FEATURE_SECURE_PROCESSING, jaxp.properties file, jaxp system
+     * properties, and jaxp api properties
+     */
+    public static enum State {
+        //this order reflects the overriding order
+
+        DEFAULT("default"), FSP("FEATURE_SECURE_PROCESSING"),
+        JAXPDOTPROPERTIES("jaxp.properties"), SYSTEMPROPERTY("system property"),
+        APIPROPERTY("property");
+
+        final String literal;
+        State(String literal) {
+            this.literal = literal;
+        }
+
+        String literal() {
+            return literal;
+        }
+    }
+
+    /**
+     * Limits managed by the security manager
+     */
+    public static enum Limit {
+
+        ENTITY_EXPANSION_LIMIT(Constants.JDK_ENTITY_EXPANSION_LIMIT, Constants.SP_ENTITY_EXPANSION_LIMIT, 0, 64000),
+        MAX_OCCUR_NODE_LIMIT(Constants.JDK_MAX_OCCUR_LIMIT, Constants.SP_MAX_OCCUR_LIMIT, 0, 5000),
+        ELEMENT_ATTRIBUTE_LIMIT(Constants.JDK_ELEMENT_ATTRIBUTE_LIMIT, Constants.SP_ELEMENT_ATTRIBUTE_LIMIT, 0, 10000),
+        TOTAL_ENTITY_SIZE_LIMIT(Constants.JDK_TOTAL_ENTITY_SIZE_LIMIT, Constants.SP_TOTAL_ENTITY_SIZE_LIMIT, 0, 50000000),
+        GENEAL_ENTITY_SIZE_LIMIT(Constants.JDK_GENEAL_ENTITY_SIZE_LIMIT, Constants.SP_GENEAL_ENTITY_SIZE_LIMIT, 0, 0),
+        PARAMETER_ENTITY_SIZE_LIMIT(Constants.JDK_PARAMETER_ENTITY_SIZE_LIMIT, Constants.SP_PARAMETER_ENTITY_SIZE_LIMIT, 0, 1000000);
+
+        final String apiProperty;
+        final String systemProperty;
+        final int defaultValue;
+        final int secureValue;
+
+        Limit(String apiProperty, String systemProperty, int value, int secureValue) {
+            this.apiProperty = apiProperty;
+            this.systemProperty = systemProperty;
+            this.defaultValue = value;
+            this.secureValue = secureValue;
+        }
+
+        public boolean equalsAPIPropertyName(String propertyName) {
+            return (propertyName == null) ? false : apiProperty.equals(propertyName);
+        }
+
+        public boolean equalsSystemPropertyName(String propertyName) {
+            return (propertyName == null) ? false : systemProperty.equals(propertyName);
+        }
+
+        public String apiProperty() {
+            return apiProperty;
+        }
+
+        String systemProperty() {
+            return systemProperty;
+        }
+
+        int defaultValue() {
+            return defaultValue;
+        }
+
+        int secureValue() {
+            return secureValue;
+        }
+    }
+
+    /**
+     * Map old property names with the new ones
+     */
+    public static enum NameMap {
+
+        ENTITY_EXPANSION_LIMIT(Constants.SP_ENTITY_EXPANSION_LIMIT, Constants.ENTITY_EXPANSION_LIMIT),
+        MAX_OCCUR_NODE_LIMIT(Constants.SP_MAX_OCCUR_LIMIT, Constants.MAX_OCCUR_LIMIT),
+        ELEMENT_ATTRIBUTE_LIMIT(Constants.SP_ELEMENT_ATTRIBUTE_LIMIT, Constants.ELEMENT_ATTRIBUTE_LIMIT);
+        final String newName;
+        final String oldName;
+
+        NameMap(String newName, String oldName) {
+            this.newName = newName;
+            this.oldName = oldName;
+        }
+
+        String getOldName(String newName) {
+            if (newName.equals(this.newName)) {
+                return oldName;
+            }
+            return null;
+        }
+    }
+    private static final int NO_LIMIT = 0;
+    /**
+     * Values of the properties
+     */
+    private final int[] values;
+    /**
+     * States of the settings for each property
+     */
+    private State[] states;
+    /**
+     * Flag indicating if secure processing is set
+     */
+    boolean secureProcessing;
+
+    /**
+     * States that determine if properties are set explicitly
+     */
+    private boolean[] isSet;
+
+
+    private XMLLimitAnalyzer limitAnalyzer;
+    /**
+     * Index of the special entityCountInfo property
+     */
+    private int indexEntityCountInfo = 10000;
+    private String printEntityCountInfo = "";
+
+    /**
+     * Default constructor. Establishes default values for known security
+     * vulnerabilities.
+     */
+    public XMLSecurityManager() {
+        this(false);
+    }
+
+    /**
+     * Instantiate Security Manager in accordance with the status of
+     * secure processing
+     * @param secureProcessing
+     */
+    public XMLSecurityManager(boolean secureProcessing) {
+        limitAnalyzer = new XMLLimitAnalyzer(this);
+        values = new int[Limit.values().length];
+        states = new State[Limit.values().length];
+        isSet = new boolean[Limit.values().length];
+        this.secureProcessing = secureProcessing;
+        for (Limit limit : Limit.values()) {
+            if (secureProcessing) {
+                values[limit.ordinal()] = limit.secureValue;
+                states[limit.ordinal()] = State.FSP;
+            } else {
+                values[limit.ordinal()] = limit.defaultValue();
+                states[limit.ordinal()] = State.DEFAULT;
+            }
+        }
+        //read system properties or jaxp.properties
+        readSystemProperties();
+    }
+
+    /**
+     * Setting FEATURE_SECURE_PROCESSING explicitly
+     */
+    public void setSecureProcessing(boolean secure) {
+        secureProcessing = secure;
+        for (Limit limit : Limit.values()) {
+            if (secure) {
+                setLimit(limit.ordinal(), State.FSP, limit.secureValue());
+            } else {
+                setLimit(limit.ordinal(), State.FSP, limit.defaultValue());
+            }
+        }
+    }
+
+    /**
+     * Return the state of secure processing
+     * @return the state of secure processing
+     */
+    public boolean isSecureProcessing() {
+        return secureProcessing;
+    }
+
+
+    /**
+     * Set limit by property name and state
+     * @param propertyName property name
+     * @param state the state of the property
+     * @param value the value of the property
+     * @return true if the property is managed by the security manager; false
+     *              if otherwise.
+     */
+    public boolean setLimit(String propertyName, State state, Object value) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            setLimit(index, state, value);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Set the value for a specific limit.
+     *
+     * @param limit the limit
+     * @param state the state of the property
+     * @param value the value of the property
+     */
+    public void setLimit(Limit limit, State state, int value) {
+        setLimit(limit.ordinal(), state, value);
+    }
+
+    /**
+     * Set the value of a property by its index
+     *
+     * @param index the index of the property
+     * @param state the state of the property
+     * @param value the value of the property
+     */
+    public void setLimit(int index, State state, Object value) {
+        if (index == indexEntityCountInfo) {
+            printEntityCountInfo = (String)value;
+        } else {
+            int temp = 0;
+            try {
+                temp = Integer.parseInt((String) value);
+                if (temp < 0) {
+                    temp = 0;
+                }
+            } catch (NumberFormatException e) {}
+            setLimit(index, state, temp);
+        }
+    }
+
+    /**
+     * Set the value of a property by its index
+     *
+     * @param index the index of the property
+     * @param state the state of the property
+     * @param value the value of the property
+     */
+    public void setLimit(int index, State state, int value) {
+        if (index == indexEntityCountInfo) {
+            //if it's explicitly set, it's treated as yes no matter the value
+            printEntityCountInfo = Constants.JDK_YES;
+        } else {
+            //only update if it shall override
+            if (state.compareTo(states[index]) >= 0) {
+                values[index] = value;
+                states[index] = state;
+                isSet[index] = true;
+            }
+        }
+    }
+
+    /**
+     * Return the value of the specified property
+     *
+     * @param propertyName the property name
+     * @return the value of the property as a string. If a property is managed
+     * by this manager, its value shall not be null.
+     */
+    public String getLimitAsString(String propertyName) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            return getLimitValueByIndex(index);
+        }
+
+        return null;
+    }
+    /**
+     * Return the value of the specified property
+     *
+     * @param limit the property
+     * @return the value of the property
+     */
+    public int getLimit(Limit limit) {
+        return values[limit.ordinal()];
+    }
+
+    /**
+     * Return the value of a property by its ordinal
+     *
+     * @param limit the property
+     * @return value of a property
+     */
+    public String getLimitValueAsString(Limit limit) {
+        return Integer.toString(values[limit.ordinal()]);
+    }
+
+    /**
+     * Return the value of a property by its ordinal
+     *
+     * @param index the index of a property
+     * @return limit of a property as a string
+     */
+    public String getLimitValueByIndex(int index) {
+        if (index == indexEntityCountInfo) {
+            return printEntityCountInfo;
+        }
+
+        return Integer.toString(values[index]);
+    }
+
+    /**
+     * Return the state of the limit property
+     *
+     * @param limit the limit
+     * @return the state of the limit property
+     */
+    public State getState(Limit limit) {
+        return states[limit.ordinal()];
+    }
+
+    /**
+     * Return the state of the limit property
+     *
+     * @param limit the limit
+     * @return the state of the limit property
+     */
+    public String getStateLiteral(Limit limit) {
+        return states[limit.ordinal()].literal();
+    }
+
+    /**
+     * Get the index by property name
+     *
+     * @param propertyName property name
+     * @return the index of the property if found; return -1 if not
+     */
+    public int getIndex(String propertyName) {
+        for (Limit limit : Limit.values()) {
+            if (limit.equalsAPIPropertyName(propertyName)) {
+                //internally, ordinal is used as index
+                return limit.ordinal();
+            }
+        }
+        //special property to return entity count info
+        if (propertyName.equals(Constants.JDK_ENTITY_COUNT_INFO)) {
+            return indexEntityCountInfo;
+        }
+        return -1;
+    }
+
+    /**
+     * Check if there's no limit defined by the Security Manager
+     * @param limit
+     * @return
+     */
+    public boolean isNoLimit(int limit) {
+        return limit==NO_LIMIT;
+    }
+    /**
+     * Check if the size (length or count) of the specified limit property is
+     * over the limit
+     *
+     * @param limit the type of the limit property
+     * @param entityName the name of the entity
+     * @param size the size (count or length) of the entity
+     * @return true if the size is over the limit, false otherwise
+     */
+    public boolean isOverLimit(Limit limit, String entityName, int size) {
+        return isOverLimit(limit.ordinal(), entityName, size);
+    }
+
+    /**
+     * Check if the value (length or count) of the specified limit property is
+     * over the limit
+     *
+     * @param index the index of the limit property
+     * @param entityName the name of the entity
+     * @param size the size (count or length) of the entity
+     * @return true if the size is over the limit, false otherwise
+     */
+    public boolean isOverLimit(int index, String entityName, int size) {
+        if (values[index] == NO_LIMIT) {
+            return false;
+        }
+        if (size > values[index]) {
+            limitAnalyzer.addValue(index, entityName, size);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Check against cumulated value
+     *
+     * @param limit the type of the limit property
+     * @param size the size (count or length) of the entity
+     * @return true if the size is over the limit, false otherwise
+     */
+    public boolean isOverLimit(Limit limit) {
+        return isOverLimit(limit.ordinal());
+    }
+
+    public boolean isOverLimit(int index) {
+        if (values[index] == NO_LIMIT) {
+            return false;
+        }
+
+        if (index==Limit.ELEMENT_ATTRIBUTE_LIMIT.ordinal() ||
+                index==Limit.ENTITY_EXPANSION_LIMIT.ordinal() ||
+                index==Limit.TOTAL_ENTITY_SIZE_LIMIT.ordinal()) {
+            return (limitAnalyzer.getTotalValue(index) > values[index]);
+        } else {
+            return (limitAnalyzer.getValue(index) > values[index]);
+        }
+    }
+
+    public void debugPrint() {
+        if (printEntityCountInfo.equals(Constants.JDK_YES)) {
+            limitAnalyzer.debugPrint();
+        }
+    }
+
+    /**
+     * Return the limit analyzer
+     *
+     * @return the limit analyzer
+     */
+    public XMLLimitAnalyzer getLimitAnalyzer() {
+        return limitAnalyzer;
+    }
+
+    /**
+     * Set limit analyzer
+     *
+     * @param analyzer a limit analyzer
+     */
+    public void setLimitAnalyzer(XMLLimitAnalyzer analyzer) {
+        limitAnalyzer = analyzer;
+    }
+
+    /**
+     * Indicate if a property is set explicitly
+     * @param index
+     * @return
+     */
+    public boolean isSet(int index) {
+        return isSet[index];
+    }
+
+    public boolean printEntityCountInfo() {
+        return printEntityCountInfo.equals(Constants.JDK_YES);
+    }
+
+    /**
+     * Read from system properties, or those in jaxp.properties
+     */
+    private void readSystemProperties() {
+
+        for (Limit limit : Limit.values()) {
+            if (!getSystemProperty(limit, limit.systemProperty())) {
+                //if system property is not found, try the older form if any
+                for (NameMap nameMap : NameMap.values()) {
+                    String oldName = nameMap.getOldName(limit.systemProperty());
+                    if (oldName != null) {
+                        getSystemProperty(limit, oldName);
+                    }
+                }
+            }
+        }
+
+    }
+
+    /**
+     * Read from system properties, or those in jaxp.properties
+     *
+     * @param property the type of the property
+     * @param sysPropertyName the name of system property
+     */
+    private boolean getSystemProperty(Limit limit, String sysPropertyName) {
+        try {
+            String value = SecuritySupport.getSystemProperty(sysPropertyName);
+            if (value != null && !value.equals("")) {
+                values[limit.ordinal()] = Integer.parseInt(value);
+                states[limit.ordinal()] = State.SYSTEMPROPERTY;
+                return true;
+            }
+
+            value = SecuritySupport.readJAXPProperty(sysPropertyName);
+            if (value != null && !value.equals("")) {
+                values[limit.ordinal()] = Integer.parseInt(value);
+                states[limit.ordinal()] = State.JAXPDOTPROPERTIES;
+                return true;
+            }
+        } catch (NumberFormatException e) {
+            //invalid setting
+            throw new NumberFormatException("Invalid setting for system property: " + limit.systemProperty());
+        }
+        return false;
+    }
+}
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java b/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java
index c6bb031..4286f04 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java
@@ -91,6 +91,24 @@
         readSystemProperties();
     }
 
+
+    /**
+     * Set limit by property name and state
+     * @param propertyName property name
+     * @param state the state of the property
+     * @param value the value of the property
+     * @return true if the property is managed by the security property manager;
+     *         false if otherwise.
+     */
+    public boolean setValue(String propertyName, State state, Object value) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            setValue(index, state, (String)value);
+            return true;
+        }
+        return false;
+    }
+
     /**
      * Set the value for a specific property.
      *
@@ -119,6 +137,23 @@
             states[index] = state;
         }
     }
+
+
+    /**
+     * Return the value of the specified property
+     *
+     * @param propertyName the property name
+     * @return the value of the property as a string
+     */
+    public String getValue(String propertyName) {
+        int index = getIndex(propertyName);
+        if (index > -1) {
+            return getValueByIndex(index);
+        }
+
+        return null;
+    }
+
     /**
      * Return the value of the specified property
      *
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xinclude/XIncludeHandler.java b/jaxp/src/com/sun/org/apache/xerces/internal/xinclude/XIncludeHandler.java
index fe39457..3e9f4a5 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xinclude/XIncludeHandler.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xinclude/XIncludeHandler.java
@@ -37,7 +37,6 @@
 import com.sun.org.apache.xerces.internal.util.HTTPInputSource;
 import com.sun.org.apache.xerces.internal.util.IntStack;
 import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
-import com.sun.org.apache.xerces.internal.util.SecurityManager;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
 import com.sun.org.apache.xerces.internal.util.URI;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl;
@@ -45,6 +44,7 @@
 import com.sun.org.apache.xerces.internal.util.XMLChar;
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
 import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
 import com.sun.org.apache.xerces.internal.xni.QName;
@@ -289,7 +289,7 @@
     protected SymbolTable fSymbolTable;
     protected XMLErrorReporter fErrorReporter;
     protected XMLEntityResolver fEntityResolver;
-    protected SecurityManager fSecurityManager;
+    protected XMLSecurityManager fSecurityManager;
     protected XMLSecurityPropertyManager fSecurityPropertyMgr;
 
     // these are needed for text include processing
@@ -517,8 +517,8 @@
 
         // Get security manager.
         try {
-            SecurityManager value =
-                (SecurityManager)componentManager.getProperty(
+            XMLSecurityManager value =
+                (XMLSecurityManager)componentManager.getProperty(
                     SECURITY_MANAGER);
 
             if (value != null) {
@@ -674,7 +674,7 @@
             return;
         }
         if (propertyId.equals(SECURITY_MANAGER)) {
-            fSecurityManager = (SecurityManager)value;
+            fSecurityManager = (XMLSecurityManager)value;
             if (fChildConfig != null) {
                 fChildConfig.setProperty(propertyId, value);
             }
diff --git a/jaxp/src/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java b/jaxp/src/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java
index cab4f46..a9c9aab 100644
--- a/jaxp/src/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java
+++ b/jaxp/src/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java
@@ -25,12 +25,15 @@
 import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
+import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import java.util.HashMap;
+
 import javax.xml.XMLConstants;
 import javax.xml.parsers.FactoryConfigurationError;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParserFactory;
 import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.XMLReaderFactory;
 
@@ -63,11 +66,15 @@
     private HashMap m_inUse;
 
     private boolean m_useServicesMechanism = true;
+
+    private boolean _secureProcessing;
      /**
      * protocols allowed for external DTD references in source file and/or stylesheet.
      */
     private String _accessExternalDTD = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
 
+    private XMLSecurityManager _xmlSecurityManager;
+
     /**
      * Hidden constructor
      */
@@ -118,7 +125,12 @@
                     // TransformerFactory creates a reader via the
                     // XMLReaderFactory if setXMLReader is not used
                     reader = XMLReaderFactory.createXMLReader();
-
+                    try {
+                        reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _secureProcessing);
+                    } catch (SAXNotRecognizedException e) {
+                        System.err.println("Warning:  " + reader.getClass().getName() + ": "
+                                + e.getMessage());
+                    }
                 } catch (Exception e) {
                    try {
                         // If unable to create an instance, let's try to use
@@ -164,6 +176,21 @@
                         + se.getMessage());
         }
 
+        try {
+            if (_xmlSecurityManager != null) {
+                for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
+                    reader.setProperty(limit.apiProperty(),
+                            _xmlSecurityManager.getLimitValueAsString(limit));
+                }
+                if (_xmlSecurityManager.printEntityCountInfo()) {
+                    reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
+                }
+            }
+        } catch (SAXException se) {
+            System.err.println("Warning:  " + reader.getClass().getName() + ": "
+                        + se.getMessage());
+        }
+
         return reader;
     }
 
@@ -195,11 +222,22 @@
     }
 
     /**
+     * Set feature
+     */
+    public void setFeature(String name, boolean value) {
+        if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
+            _secureProcessing = value;
+        }
+    }
+
+    /**
      * Get property value
      */
-    public String getProperty(String name) {
+    public Object getProperty(String name) {
         if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
             return _accessExternalDTD;
+        } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
+            return _xmlSecurityManager;
         }
         return null;
     }
@@ -207,9 +245,11 @@
     /**
      * Set property.
      */
-    public void setProperty(String name, String value) {
+    public void setProperty(String name, Object value) {
         if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
             _accessExternalDTD = (String)value;
+        } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
+            _xmlSecurityManager = (XMLSecurityManager)value;
         }
     }
 }
diff --git a/jaxp/src/javax/xml/stream/FactoryFinder.java b/jaxp/src/javax/xml/stream/FactoryFinder.java
index bcfeba1..996ba02 100644
--- a/jaxp/src/javax/xml/stream/FactoryFinder.java
+++ b/jaxp/src/javax/xml/stream/FactoryFinder.java
@@ -204,13 +204,15 @@
      *                              a property name
      * @param fallbackClassName     Implementation class name, if nothing else
      *                              is found.  Use null to mean no fallback.
+     * @param standardId            Indicate whether the factoryId is standard
+     *                              or user specified.
      *
      * Package private so this code can be shared.
      */
-    static Object find(String factoryId, String fallbackClassName)
+    static Object find(String factoryId, String fallbackClassName, boolean standardId)
         throws ConfigurationError
     {
-        return find(factoryId, null, fallbackClassName);
+        return find(factoryId, null, fallbackClassName, standardId);
     }
 
     /**
@@ -227,23 +229,34 @@
      * @param fallbackClassName     Implementation class name, if nothing else
      *                              is found.  Use null to mean no fallback.
      *
+     * @param standardId            Indicate whether the factoryId is standard
+     *                              or user specified.
+     *
      * Package private so this code can be shared.
      */
-    static Object find(String factoryId, ClassLoader cl, String fallbackClassName)
+    static Object find(String factoryId, ClassLoader cl, String fallbackClassName,
+            boolean standardId)
         throws ConfigurationError
     {
         dPrint("find factoryId =" + factoryId);
 
         // Use the system property first
         try {
-            String systemProp = ss.getSystemProperty(factoryId);
+            String systemProp;
+            if (standardId) {
+                systemProp = ss.getSystemProperty(factoryId);
+            } else {
+                systemProp = System.getProperty(factoryId);
+            }
+
             if (systemProp != null) {
                 dPrint("found system property, value=" + systemProp);
                 return newInstance(systemProp, null, true);
             }
         }
         catch (SecurityException se) {
-            if (debug) se.printStackTrace();
+            throw new ConfigurationError(
+                "Failed to read factoryId '" + factoryId + "'", se);
         }
 
         // Try read $java.home/lib/stax.properties followed by
diff --git a/jaxp/src/javax/xml/stream/XMLEventFactory.java b/jaxp/src/javax/xml/stream/XMLEventFactory.java
index f92d778..e86e530 100644
--- a/jaxp/src/javax/xml/stream/XMLEventFactory.java
+++ b/jaxp/src/javax/xml/stream/XMLEventFactory.java
@@ -60,9 +60,7 @@
   public static XMLEventFactory newInstance()
     throws FactoryConfigurationError
   {
-    return (XMLEventFactory) FactoryFinder.find(
-      JAXPFACTORYID,
-      DEFAULIMPL);
+    return (XMLEventFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true);
   }
 
   /**
@@ -93,9 +91,7 @@
   public static XMLEventFactory newFactory()
     throws FactoryConfigurationError
   {
-    return (XMLEventFactory) FactoryFinder.find(
-      JAXPFACTORYID,
-      DEFAULIMPL);
+    return (XMLEventFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true);
   }
 
   /**
@@ -118,7 +114,8 @@
           throws FactoryConfigurationError {
       try {
           //do not fallback if given classloader can't find the class, throw exception
-          return (XMLEventFactory) FactoryFinder.find(factoryId, classLoader, null);
+            return (XMLEventFactory) FactoryFinder.find(factoryId, classLoader,
+                    null, factoryId.equals(JAXPFACTORYID) ? true : false);
       } catch (FactoryFinder.ConfigurationError e) {
           throw new FactoryConfigurationError(e.getException(),
                   e.getMessage());
@@ -145,7 +142,8 @@
           throws FactoryConfigurationError {
       try {
           //do not fallback if given classloader can't find the class, throw exception
-          return (XMLEventFactory) FactoryFinder.find(factoryId, classLoader, null);
+            return (XMLEventFactory) FactoryFinder.find(factoryId, classLoader,
+                    null, factoryId.equals(JAXPFACTORYID) ? true : false);
       } catch (FactoryFinder.ConfigurationError e) {
           throw new FactoryConfigurationError(e.getException(),
                   e.getMessage());
diff --git a/jaxp/src/javax/xml/stream/XMLInputFactory.java b/jaxp/src/javax/xml/stream/XMLInputFactory.java
index 3bef387..d50adc4 100644
--- a/jaxp/src/javax/xml/stream/XMLInputFactory.java
+++ b/jaxp/src/javax/xml/stream/XMLInputFactory.java
@@ -139,6 +139,7 @@
   public static final String ALLOCATOR=
     "javax.xml.stream.allocator";
 
+  static final String JAXPFACTORYID = "javax.xml.stream.XMLInputFactory";
   static final String DEFAULIMPL = "com.sun.xml.internal.stream.XMLInputFactoryImpl";
 
   protected XMLInputFactory(){}
@@ -150,9 +151,7 @@
   public static XMLInputFactory newInstance()
     throws FactoryConfigurationError
   {
-    return (XMLInputFactory) FactoryFinder.find(
-      "javax.xml.stream.XMLInputFactory",
-      DEFAULIMPL);
+    return (XMLInputFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true);
   }
 
   /**
@@ -183,9 +182,7 @@
   public static XMLInputFactory newFactory()
     throws FactoryConfigurationError
   {
-    return (XMLInputFactory) FactoryFinder.find(
-      "javax.xml.stream.XMLInputFactory",
-      DEFAULIMPL);
+    return (XMLInputFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true);
   }
 
   /**
@@ -208,7 +205,8 @@
           throws FactoryConfigurationError {
       try {
           //do not fallback if given classloader can't find the class, throw exception
-          return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader, null);
+          return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader,
+                  null, factoryId.equals(JAXPFACTORYID) ? true : false);
       } catch (FactoryFinder.ConfigurationError e) {
           throw new FactoryConfigurationError(e.getException(),
                   e.getMessage());
@@ -235,7 +233,8 @@
           throws FactoryConfigurationError {
       try {
           //do not fallback if given classloader can't find the class, throw exception
-          return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader, null);
+          return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader,
+                  null, factoryId.equals(JAXPFACTORYID) ? true : false);
       } catch (FactoryFinder.ConfigurationError e) {
           throw new FactoryConfigurationError(e.getException(),
                   e.getMessage());
diff --git a/jaxp/src/javax/xml/stream/XMLOutputFactory.java b/jaxp/src/javax/xml/stream/XMLOutputFactory.java
index b0d4f0b..503fe8b 100644
--- a/jaxp/src/javax/xml/stream/XMLOutputFactory.java
+++ b/jaxp/src/javax/xml/stream/XMLOutputFactory.java
@@ -115,6 +115,7 @@
   public static final String IS_REPAIRING_NAMESPACES=
     "javax.xml.stream.isRepairingNamespaces";
 
+  static final String JAXPFACTORYID = "javax.xml.stream.XMLOutputFactory";
   static final String DEFAULIMPL = "com.sun.xml.internal.stream.XMLOutputFactoryImpl";
 
   protected XMLOutputFactory(){}
@@ -126,8 +127,7 @@
   public static XMLOutputFactory newInstance()
     throws FactoryConfigurationError
   {
-    return (XMLOutputFactory) FactoryFinder.find("javax.xml.stream.XMLOutputFactory",
-                                                 DEFAULIMPL);
+    return (XMLOutputFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true);
   }
 
   /**
@@ -158,8 +158,7 @@
   public static XMLOutputFactory newFactory()
     throws FactoryConfigurationError
   {
-    return (XMLOutputFactory) FactoryFinder.find("javax.xml.stream.XMLOutputFactory",
-                                                 DEFAULIMPL);
+    return (XMLOutputFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true);
   }
 
   /**
@@ -181,7 +180,8 @@
           throws FactoryConfigurationError {
       try {
           //do not fallback if given classloader can't find the class, throw exception
-          return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader, null);
+          return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader,
+                  null, factoryId.equals(JAXPFACTORYID) ? true : false);
       } catch (FactoryFinder.ConfigurationError e) {
           throw new FactoryConfigurationError(e.getException(),
                   e.getMessage());
@@ -210,7 +210,8 @@
           throws FactoryConfigurationError {
       try {
           //do not fallback if given classloader can't find the class, throw exception
-          return (XMLOutputFactory) FactoryFinder.find(factoryId, classLoader, null);
+          return (XMLOutputFactory) FactoryFinder.find(factoryId, classLoader,
+                  null, factoryId.equals(JAXPFACTORYID) ? true : false);
       } catch (FactoryFinder.ConfigurationError e) {
           throw new FactoryConfigurationError(e.getException(),
                   e.getMessage());
diff --git a/jaxws/.hgtags b/jaxws/.hgtags
index 430e407..0e2f181 100644
--- a/jaxws/.hgtags
+++ b/jaxws/.hgtags
@@ -302,6 +302,22 @@
 0cd0d4e7331f7fc9f9ee77f2275113571bcf67cf jdk7u25-b09
 105cdfd4f40837917d0065e3e58052d2854df7da jdk7u25-b10
 6de7fec036abf91ce962c74f11a6266491df3fd8 jdk7u25-b11
+a367ebf0c21512867f4ab5cdd206dd8c7817c004 jdk7u14-b16
+74c34f35912d8d7145b3ff34fefea2d2f189f2b4 jdk7u14-b17
+c93a35b3638f45de91013d65543217a002577684 jdk7u14-b18
+82be38857de3b2f6d8def98034f3e7b0827fd9f0 jdk7u14-b19
+82be38857de3b2f6d8def98034f3e7b0827fd9f0 jdk7u14-b19
+d63b21e6c3d29305400dbfc1500090cab89f25d1 jdk7u14-b19
+dd695ad6c5ec797fe61db31600a3fd2dbc62247b jdk7u14-b20
+97bbac299eb801709a924fe777b3ee9c96829d8b jdk7u14-b21
+6e74b3e1773cfbac99998431a5a54c70baaf1dc5 jdk7u14-b22
+e9bbdf789d2b512550e0ca80629980e96f02146d jdk7u40-b23
+adaf9cf486fab1b14c5af9fc6525565760bb9c11 jdk7u40-b24
+aafab1efbd4ced5e05695aa1887813f9f5de9d5c jdk7u40-b25
+6581f9739031120bb7515d3b09fa3501653d11af jdk7u40-b26
+46ebac943288218b14d7ce3df23aa42a70fa4cf9 jdk7u40-b27
+016957700ac905ebf3432ae8ba17d3576a51e585 jdk7u40-b28
+15a82c84d9f7f6c99310380d4766fc68a3882671 jdk7u40-b29
 4c5d242efa0d6e0cdb688e41e722bff671dfbfec jdk7u25-b12
 6b4a165221304d809f678a18f51c7a8cb042d60b jdk7u25-b13
 03073e4e6d3f600102d31e862154f56730838b11 jdk7u25-b14
@@ -336,3 +352,9 @@
 9f74e1f33e6cc89256eb2c61964558460d9d7efe jdk7u40-b35
 b75c19a170c7a1a7b846e4e793e62546b2c54646 jdk7u40-b36
 918e6c87b006e32c80a937c7b0f2f9c65edbecdb jdk7u40-b37
+7ae2e9ed2c448a683f2df8673df145d20f13d585 jdk7u40-b38
+000becfcb945d8592cfdef6ef1704b532af56762 jdk7u45-b01
+817632baca26f7566e36c7708455494c15113d88 jdk7u45-b02
+f65baba9400aec6cb29bc06b3139623bb4663225 jdk7u45-b03
+80ff2468f520ed1940915815ceb85e05bd2bc568 jdk7u45-b04
+1128d3934b643660a219532aa1ca554877d89375 jdk7u45-b05
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/InstanceResolver.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/InstanceResolver.java
index 5fc2b26..7c11e64 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/InstanceResolver.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/InstanceResolver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -232,7 +232,7 @@
             public Object invoke(Packet p, Method m, Object... args) throws InvocationTargetException, IllegalAccessException {
                 T t = resolve(p);
                 try {
-                    return m.invoke(t, args );
+                    return MethodUtil.invoke(t, m, args );
                 } finally {
                     postInvoke(p,t);
                 }
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/MethodUtil.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/MethodUtil.java
new file mode 100644
index 0000000..c849705
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/MethodUtil.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.api.server;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Utility class to invoke sun.reflect.misc.MethodUtil.invoke() if available. If not (other then Oracle JDK) fallbacks
+ * to java.lang,reflect.Method.invoke()
+ *
+ * Be careful, copy of this class exists in several packages, iny modification must be done to other copies too!
+ */
+class MethodUtil {
+
+    private static final Logger LOGGER = Logger.getLogger(MethodUtil.class.getName());
+    private static final Method INVOKE_METHOD;
+
+    static {
+        Method method;
+        try {
+            Class<?> clazz = Class.forName("sun.reflect.misc.MethodUtil");
+            method = clazz.getMethod("invoke", Method.class, Object.class, Object[].class);
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil found; it will be used to invoke methods.");
+            }
+        } catch (Throwable t) {
+            method = null;
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil not found, probably non-Oracle JVM");
+            }
+        }
+        INVOKE_METHOD = method;
+    }
+
+    static Object invoke(Object target, Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
+        if (INVOKE_METHOD != null) {
+            // sun.reflect.misc.MethodUtil.invoke(method, owner, args)
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method using sun.reflect.misc.MethodUtil");
+            }
+            try {
+                return INVOKE_METHOD.invoke(null, method, target, args);
+            } catch (InvocationTargetException ite) {
+                // unwrap invocation exception added by reflection code ...
+                throw unwrapException(ite);
+            }
+        } else {
+            // other then Oracle JDK ...
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method directly, probably non-Oracle JVM");
+            }
+            return method.invoke(target, args);
+        }
+    }
+
+    private static InvocationTargetException unwrapException(InvocationTargetException ite) {
+        Throwable targetException = ite.getTargetException();
+        if (targetException != null && targetException instanceof InvocationTargetException) {
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Unwrapping invocation target exception");
+            }
+            return (InvocationTargetException) targetException;
+        } else {
+            return ite;
+        }
+    }
+
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/MethodUtil.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/MethodUtil.java
new file mode 100644
index 0000000..f0daea5
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/MethodUtil.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.client.sei;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Utility class to invoke sun.reflect.misc.MethodUtil.invoke() if available. If not (other then Oracle JDK) fallbacks
+ * to java.lang,reflect.Method.invoke()
+ * <p/>
+ * Be careful, copy of this class exists in several packages, iny modification must be done to other copies too!
+ */
+class MethodUtil {
+
+    private static final Logger LOGGER = Logger.getLogger(MethodUtil.class.getName());
+    private static final Method INVOKE_METHOD;
+
+    static {
+        Method method;
+        try {
+            Class<?> clazz = Class.forName("sun.reflect.misc.MethodUtil");
+            method = clazz.getMethod("invoke", Method.class, Object.class, Object[].class);
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil found; it will be used to invoke methods.");
+            }
+        } catch (Throwable t) {
+            method = null;
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil not found, probably non-Oracle JVM");
+            }
+        }
+        INVOKE_METHOD = method;
+    }
+
+    static Object invoke(Object target, Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
+        if (INVOKE_METHOD != null) {
+            // sun.reflect.misc.MethodUtil.invoke(method, owner, args)
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method using sun.reflect.misc.MethodUtil");
+            }
+            try {
+                return INVOKE_METHOD.invoke(null, method, target, args);
+            } catch (InvocationTargetException ite) {
+                // unwrap invocation exception added by reflection code ...
+                throw unwrapException(ite);
+            }
+        } else {
+            // other then Oracle JDK ...
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method directly, probably non-Oracle JVM");
+            }
+            return method.invoke(target, args);
+        }
+    }
+
+    private static InvocationTargetException unwrapException(InvocationTargetException ite) {
+        Throwable targetException = ite.getTargetException();
+        if (targetException != null && targetException instanceof InvocationTargetException) {
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Unwrapping invocation target exception");
+            }
+            return (InvocationTargetException) targetException;
+        } else {
+            return ite;
+        }
+    }
+
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/SEIStub.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/SEIStub.java
index 69fdc75..3148156 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/SEIStub.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/SEIStub.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,17 +28,20 @@
 import com.sun.istack.internal.NotNull;
 import com.sun.istack.internal.Nullable;
 import com.sun.xml.internal.ws.api.SOAPVersion;
-import com.sun.xml.internal.ws.api.client.WSPortInfo;
 import com.sun.xml.internal.ws.api.addressing.WSEndpointReference;
+import com.sun.xml.internal.ws.api.client.WSPortInfo;
 import com.sun.xml.internal.ws.api.message.Header;
 import com.sun.xml.internal.ws.api.message.Headers;
 import com.sun.xml.internal.ws.api.message.Packet;
 import com.sun.xml.internal.ws.api.model.MEP;
 import com.sun.xml.internal.ws.api.model.wsdl.WSDLBoundOperation;
-import com.sun.xml.internal.ws.api.pipe.Tube;
 import com.sun.xml.internal.ws.api.pipe.Fiber;
+import com.sun.xml.internal.ws.api.pipe.Tube;
 import com.sun.xml.internal.ws.binding.BindingImpl;
-import com.sun.xml.internal.ws.client.*;
+import com.sun.xml.internal.ws.client.RequestContext;
+import com.sun.xml.internal.ws.client.ResponseContextReceiver;
+import com.sun.xml.internal.ws.client.Stub;
+import com.sun.xml.internal.ws.client.WSServiceDelegate;
 import com.sun.xml.internal.ws.model.JavaMethodImpl;
 import com.sun.xml.internal.ws.model.SOAPSEIModel;
 import com.sun.xml.internal.ws.wsdl.OperationDispatcher;
@@ -47,6 +50,8 @@
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -124,13 +129,14 @@
     private final Map<Method, MethodHandler> methodHandlers = new HashMap<Method, MethodHandler>();
 
     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+        validateInputs(proxy, method);
         MethodHandler handler = methodHandlers.get(method);
         if (handler != null) {
             return handler.invoke(proxy, args);
         } else {
             // we handle the other method invocations by ourselves
             try {
-                return method.invoke(this, args);
+                return MethodUtil.invoke(this, method, args);
             } catch (IllegalAccessException e) {
                 // impossible
                 throw new AssertionError(e);
@@ -142,6 +148,17 @@
         }
     }
 
+    private void validateInputs(Object proxy, Method method) {
+        if (proxy == null || !Proxy.isProxyClass(proxy.getClass())) {
+            throw new IllegalStateException("Passed object is not proxy!");
+        }
+        Class<?> declaringClass = method.getDeclaringClass();
+        if (method == null || declaringClass == null
+                || Modifier.isStatic(method.getModifiers())) {
+            throw new IllegalStateException("Invoking static method is not allowed!");
+        }
+    }
+
     public final Packet doProcess(Packet request, RequestContext rc, ResponseContextReceiver receiver) {
         return super.process(request, rc, receiver);
     }
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/MethodUtil.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/MethodUtil.java
new file mode 100644
index 0000000..ad2ad4a
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/MethodUtil.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.policy.privateutil;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Utility class to invoke sun.reflect.misc.MethodUtil.invoke() if available. If not (other then Oracle JDK) fallbacks
+ * to java.lang,reflect.Method.invoke()
+ */
+class MethodUtil {
+
+    private static final Logger LOGGER = Logger.getLogger(MethodUtil.class.getName());
+    private static final Method INVOKE_METHOD;
+
+    static {
+        Method method;
+        try {
+            Class<?> clazz = Class.forName("sun.reflect.misc.MethodUtil");
+            method = clazz.getMethod("invoke", Method.class, Object.class, Object[].class);
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil found; it will be used to invoke methods.");
+            }
+        } catch (Throwable t) {
+            method = null;
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil not found, probably non-Oracle JVM");
+            }
+        }
+        INVOKE_METHOD = method;
+    }
+
+    static Object invoke(Object target, Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
+        if (INVOKE_METHOD != null) {
+            // sun.reflect.misc.MethodUtil.invoke(method, owner, args)
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method using sun.reflect.misc.MethodUtil");
+            }
+            try {
+                return INVOKE_METHOD.invoke(null, method, target, args);
+            } catch (InvocationTargetException ite) {
+                // unwrap invocation exception added by reflection code ...
+                throw unwrapException(ite);
+            }
+        } else {
+            // other then Oracle JDK ...
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method directly, probably non-Oracle JVM");
+            }
+            return method.invoke(target, args);
+        }
+    }
+
+    private static InvocationTargetException unwrapException(InvocationTargetException ite) {
+        Throwable targetException = ite.getTargetException();
+        if (targetException != null && targetException instanceof InvocationTargetException) {
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Unwrapping invocation target exception");
+            }
+            return (InvocationTargetException) targetException;
+        } else {
+            return ite;
+        }
+    }
+
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/PolicyUtils.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/PolicyUtils.java
index d3a2752..ec537d8 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/PolicyUtils.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/privateutil/PolicyUtils.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -282,13 +282,13 @@
     /**
      * Reflection utilities wrapper
      */
-    public static class Reflection {
+    static class Reflection {
         private static final PolicyLogger LOGGER = PolicyLogger.getLogger(PolicyUtils.Reflection.class);
 
         /**
          * Reflectively invokes specified method on the specified target
          */
-        public static <T> T invoke(final Object target, final String methodName,
+        static <T> T invoke(final Object target, final String methodName,
                 final Class<T> resultClass, final Object... parameters) throws RuntimePolicyUtilsException {
             Class[] parameterTypes;
             if (parameters != null && parameters.length > 0) {
@@ -311,7 +311,7 @@
                 final Object[] parameters, final Class[] parameterTypes) throws RuntimePolicyUtilsException {
             try {
                 final Method method = target.getClass().getMethod(methodName, parameterTypes);
-                final Object result = method.invoke(target, parameters);
+                final Object result = MethodUtil.invoke(target, method,parameters);
 
                 return resultClass.cast(result);
             } catch (IllegalArgumentException e) {
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/AbstractInstanceResolver.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/AbstractInstanceResolver.java
index 0b72517..2e53b9b 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/AbstractInstanceResolver.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/AbstractInstanceResolver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -157,7 +157,7 @@
                     if (!method.isAccessible()) {
                         method.setAccessible(true);
                     }
-                    method.invoke(instance,args);
+                    MethodUtil.invoke(instance,method,args);
                 } catch (IllegalAccessException e) {
                     throw new ServerRtException("server.rt.err",e);
                 } catch (InvocationTargetException e) {
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/MethodUtil.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/MethodUtil.java
new file mode 100644
index 0000000..ecef086
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/MethodUtil.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.server;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Utility class to invoke sun.reflect.misc.MethodUtil.invoke() if available. If not (other then Oracle JDK) fallbacks
+ * to java.lang,reflect.Method.invoke()
+ *
+ * Be careful, copy of this class exists in several packages, iny modification must be done to other copies too!
+ */
+class MethodUtil {
+
+    private static final Logger LOGGER = Logger.getLogger(MethodUtil.class.getName());
+    private static final Method INVOKE_METHOD;
+
+    static {
+        Method method;
+        try {
+            Class<?> clazz = Class.forName("sun.reflect.misc.MethodUtil");
+            method = clazz.getMethod("invoke", Method.class, Object.class, Object[].class);
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil found; it will be used to invoke methods.");
+            }
+        } catch (Throwable t) {
+            method = null;
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Class sun.reflect.misc.MethodUtil not found, probably non-Oracle JVM");
+            }
+        }
+        INVOKE_METHOD = method;
+    }
+
+    static Object invoke(Object target, Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
+        if (INVOKE_METHOD != null) {
+            // sun.reflect.misc.MethodUtil.invoke(method, owner, args)
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method using sun.reflect.misc.MethodUtil");
+            }
+            try {
+                return INVOKE_METHOD.invoke(null, method, target, args);
+            } catch (InvocationTargetException ite) {
+                // unwrap invocation exception added by reflection code ...
+                throw unwrapException(ite);
+            }
+        } else {
+            // other then Oracle JDK ...
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Invoking method directly, probably non-Oracle JVM");
+            }
+            return method.invoke(target, args);
+        }
+    }
+
+    private static InvocationTargetException unwrapException(InvocationTargetException ite) {
+        Throwable targetException = ite.getTargetException();
+        if (targetException != null && targetException instanceof InvocationTargetException) {
+            if (LOGGER.isLoggable(Level.FINE)) {
+                LOGGER.log(Level.FINE, "Unwrapping invocation target exception");
+            }
+            return (InvocationTargetException) targetException;
+        } else {
+            return ite;
+        }
+    }
+
+}
diff --git a/jdk/.hgtags b/jdk/.hgtags
index 3ef500e..c14ed33 100644
--- a/jdk/.hgtags
+++ b/jdk/.hgtags
@@ -335,3 +335,10 @@
 0931b4a280b1e9b3b12936222d1bc6d427310f79 jdk7u40-b35
 cd7a4d0b218f98511068d8336aa3f4cbaf10b128 jdk7u40-b36
 04036faa7fc4ec11a268c190cf1712d19c77b4ba jdk7u40-b37
+070b277e1b43cc4b6a4e1ae419d1273970f718ed jdk7u40-b38
+55f01444cf58c8004df9a9634c1bd7ff87caa370 jdk7u25-b32
+b06abd965701459a868e88af9a3e564c0301971c jdk7u45-b01
+d23a877da2d5dad6520a268c83f183295a9e7299 jdk7u45-b02
+a56eb4f801232c409d34cd1190df4eec5fefe8a9 jdk7u45-b03
+702c8d83dd8c5b6c76fe53a694244a36d23fa860 jdk7u45-b04
+a70540e8a5e96773b83c7dc0accdb323d946c045 jdk7u45-b05
diff --git a/jdk/make/com/sun/jmx/Makefile b/jdk/make/com/sun/jmx/Makefile
index 6243575..24c4630 100644
--- a/jdk/make/com/sun/jmx/Makefile
+++ b/jdk/make/com/sun/jmx/Makefile
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -115,6 +115,8 @@
 
 ifeq ($(CROSS_COMPILE_ARCH),)
 RMIC = $(RMIC_JAVA) $(JAVA_TOOLS_FLAGS) -cp $(OUTPUTDIR)/classes sun.rmi.rmic.Main
+else
+RMIC = $(BOOT_JAVA_CMD)  $(JAVA_TOOLS_FLAGS) -cp $(OUTPUTDIR)/classes sun.rmi.rmic.Main
 endif  
 
 $(CLASSDESTDIR)/%_Stub.class: $(CLASSDESTDIR)/%.class
@@ -130,11 +132,13 @@
 	$(RMIC) -classpath "$(CLASSDESTDIR)"    \
                 -d $(CLASSDESTDIR)              \
                 -iiop -v1.2                     \
+                -emitPermissionCheck            \
                 $(subst /,.,$(<:$(CLASSDESTDIR)/%.class=%))
 	$(RMIC) $(HOTSPOT_INTERPRETER_FLAG) -classpath "$(CLASSDESTDIR)"    \
                 -d $(CLASSDESTDIR)              \
                 -iiop -v1.2                     \
                 -standardPackage                \
+                -emitPermissionCheck            \
                 $(subst /,.,$(<:$(CLASSDESTDIR)/%.class=%))
 	@$(java-vm-cleanup)
 
diff --git a/jdk/make/common/Program.gmk b/jdk/make/common/Program.gmk
index 091800d..c377b69 100644
--- a/jdk/make/common/Program.gmk
+++ b/jdk/make/common/Program.gmk
@@ -101,17 +101,14 @@
   ifeq ($(PLATFORM), solaris)
     ifeq ($(ARCH_DATA_MODEL), 32)
       LDFLAGS += -R \$$ORIGIN/../lib/$(LIBARCH)/jli
-      LDFLAGS += -R \$$ORIGIN/../jre/lib/$(LIBARCH)/jli
     else # ! ARCH_DATA_MODEL 64-bit
       LDFLAGS += -R \$$ORIGIN/../../lib/$(LIBARCH)/jli
-      LDFLAGS += -R \$$ORIGIN/../../jre/lib/$(LIBARCH)/jli
     endif # ARCH_DATA_MODEL
   endif # PLATFORM SOLARIS
   ifeq ($(PLATFORM), linux)
     LDFLAGS += $(LDFLAG_Z_ORIGIN)
     LDFLAGS += -Wl,--allow-shlib-undefined
     LDFLAGS += -Wl,-rpath -Wl,\$$ORIGIN/../lib/$(LIBARCH)/jli
-    LDFLAGS += -Wl,-rpath -Wl,\$$ORIGIN/../jre/lib/$(LIBARCH)/jli
   endif # PLATFORM LINUX
 endif # PLATFORM linux solaris
 
diff --git a/jdk/make/common/Release.gmk b/jdk/make/common/Release.gmk
index 84371df..4c91818 100644
--- a/jdk/make/common/Release.gmk
+++ b/jdk/make/common/Release.gmk
@@ -982,6 +982,11 @@
   endif
 	$(RM) -rf $(JDK_IMAGE_DIR)/jre/man
 	$(CHMOD) a+rx `$(FIND) $(JDK_IMAGE_DIR) -type d`
+  ifneq (,$(findstring $(PLATFORM), linux solaris)) # If linux or solaris 
+	($(CD) $(LIBDIR)/.. && $(TAR) cf - \
+	    `$(FIND) lib -name $(LIB_PREFIX)jli.$(LIB_SUFFIX) -print `) | \
+	    ($(CD) $(JDK_IMAGE_DIR) && $(TAR) xf -)
+  endif # PLATFORM
 
 initial-image-jdk64-bindemos:
 	for dir in bin demo ; do \
@@ -1030,7 +1035,7 @@
 		    initial-image-jdk-db \
 		    $(JDK_DOCFILES) \
 		    $(JDK_DEMOS_AND_SAMPLES_DOCFILES)
-	$(MKDIR) $(JDK_IMAGE_DIR)/lib
+	$(MKDIR) -p $(JDK_IMAGE_DIR)/lib
 	@#
 	@# Copy in the jars in lib that only belong in the JDK
 	@#
diff --git a/jdk/make/java/management/mapfile-vers b/jdk/make/java/management/mapfile-vers
index 21b92d4..0ba8189 100644
--- a/jdk/make/java/management/mapfile-vers
+++ b/jdk/make/java/management/mapfile-vers
@@ -53,7 +53,7 @@
 	    Java_sun_management_GcInfoBuilder_fillGcAttributeInfo;
 	    Java_sun_management_GcInfoBuilder_getLastGcInfo0;
 	    Java_sun_management_GcInfoBuilder_getNumGcExtAttributes;
-	    Java_sun_management_HotSpotDiagnostic_dumpHeap;
+	    Java_sun_management_HotSpotDiagnostic_dumpHeap0;
 	    Java_sun_management_HotspotThread_getInternalThreadCount;
 	    Java_sun_management_HotspotThread_getInternalThreadTimes0;
 	    Java_sun_management_MemoryImpl_getMemoryManagers0;
diff --git a/jdk/make/sun/awt/FILES_c_macosx.gmk b/jdk/make/sun/awt/FILES_c_macosx.gmk
deleted file mode 100644
index adf5a9a..0000000
--- a/jdk/make/sun/awt/FILES_c_macosx.gmk
+++ /dev/null
@@ -1,28 +0,0 @@
-#
-# Copyright (c) 1995, 2011, 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.
-#
-
-FILES_AWT_objc = \
-        $(TARGDIR)MacOSXResourceBundle.m
-
diff --git a/jdk/make/sun/awt/FILES_export_macosx.gmk b/jdk/make/sun/awt/FILES_export_macosx.gmk
deleted file mode 100644
index 8975d6d..0000000
--- a/jdk/make/sun/awt/FILES_export_macosx.gmk
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# Copyright (c) 1995, 2011, 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.
-#
-
-# FILES_export definitions for Mac OS X
-
-FILES_export += \
-	com/apple/resources/MacOSXResourceBundle.java
diff --git a/jdk/make/sun/awt/Makefile b/jdk/make/sun/awt/Makefile
index 98b9a97..392aad3 100644
--- a/jdk/make/sun/awt/Makefile
+++ b/jdk/make/sun/awt/Makefile
@@ -145,8 +145,6 @@
 #
 # Files
 #
-include FILES_c_macosx.gmk
-include FILES_export_macosx.gmk
 
 FILES_objc = $(FILES_AWT_objc)
 OTHER_LDLIBS = -lmlib_image $(JVMLIB) $(LIBM) \
diff --git a/jdk/make/sun/font/Makefile b/jdk/make/sun/font/Makefile
index e224fe3..3375a37 100644
--- a/jdk/make/sun/font/Makefile
+++ b/jdk/make/sun/font/Makefile
@@ -36,7 +36,11 @@
 CPLUSPLUSLIBRARY=true
 
 # Use higher optimization level
-OPTIMIZATION_LEVEL = HIGHER
+ifeq ($(PLATFORM), windows)
+  OPTIMIZATION_LEVEL = HIGHEST
+else
+  OPTIMIZATION_LEVEL = HIGHER
+endif
 
 include $(BUILDDIR)/common/Defs.gmk
 
diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaLookAndFeel.java b/jdk/src/macosx/classes/com/apple/laf/AquaLookAndFeel.java
index ae34e79..0b283f7 100644
--- a/jdk/src/macosx/classes/com/apple/laf/AquaLookAndFeel.java
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaLookAndFeel.java
@@ -37,8 +37,6 @@
 import sun.swing.*;
 import apple.laf.*;
 
-import com.apple.resources.MacOSXResourceBundle;
-
 public class AquaLookAndFeel extends BasicLookAndFeel {
     static final String sOldPropertyPrefix = "com.apple.macos."; // old prefix for things like 'useScreenMenuBar'
     static final String sPropertyPrefix = "apple.laf."; // new prefix for things like 'useScreenMenuBar'
@@ -246,7 +244,7 @@
         table.setDefaultLocale(Locale.getDefault());
         table.addResourceBundle(PKG_PREFIX + "resources.aqua");
         try {
-            final ResourceBundle aquaProperties = MacOSXResourceBundle.getMacResourceBundle(PKG_PREFIX + "resources.aqua");
+            final ResourceBundle aquaProperties = ResourceBundle.getBundle(PKG_PREFIX + "resources.aqua");
             final Enumeration<String> propertyKeys = aquaProperties.getKeys();
 
             while (propertyKeys.hasMoreElements()) {
diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java
index 0592da7..a5f5501 100644
--- a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 import java.awt.image.*;
 import java.lang.ref.SoftReference;
 import java.lang.reflect.Method;
+import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.*;
 
@@ -41,56 +42,68 @@
 import sun.lwawt.macosx.CImage;
 import sun.lwawt.macosx.CImage.Creator;
 import sun.lwawt.macosx.CPlatformWindow;
+import sun.misc.Launcher;
+import sun.reflect.misc.ReflectUtil;
+import sun.security.action.GetPropertyAction;
 import sun.swing.SwingUtilities2;
 
 import com.apple.laf.AquaImageFactory.SlicedImageControl;
 
-public class AquaUtils {
-    final static String ANIMATIONS_SYSTEM_PROPERTY = "swing.enableAnimations";
+final class AquaUtils {
 
-    /*
+    private static final String ANIMATIONS_PROPERTY = "swing.enableAnimations";
+
+    /**
+     * Suppresses default constructor, ensuring non-instantiability.
+     */
+    private AquaUtils() {
+    }
+
+    /**
      * Convenience function for determining ComponentOrientation.  Helps us
      * avoid having Munge directives throughout the code.
      */
-    public static boolean isLeftToRight(final Component c) {
+    static boolean isLeftToRight(final Component c) {
         return c.getComponentOrientation().isLeftToRight();
     }
 
-    public static void enforceComponentOrientation(Component c, ComponentOrientation orientation) {
+    static void enforceComponentOrientation(final Component c, final ComponentOrientation orientation) {
         c.setComponentOrientation(orientation);
         if (c instanceof Container) {
-            for (Component child : ((Container)c).getComponents()) {
+            for (final Component child : ((Container)c).getComponents()) {
                 enforceComponentOrientation(child, orientation);
             }
         }
     }
 
-    private static CImage.Creator getCImageCreatorInternal() {
-        return java.security.AccessController.doPrivileged(new PrivilegedAction<CImage.Creator>() {
+    private static Creator getCImageCreatorInternal() {
+        return AccessController.doPrivileged(new PrivilegedAction<Creator>() {
+            @Override
             public Creator run() {
                 try {
                     final Method getCreatorMethod = CImage.class.getDeclaredMethod("getCreator", new Class[] {});
                     getCreatorMethod.setAccessible(true);
-                    return (CImage.Creator)getCreatorMethod.invoke(null, new Object[] {});
-                } catch (final Exception e) {
+                    return (Creator)getCreatorMethod.invoke(null, new Object[] {});
+                } catch (final Exception ignored) {
                     return null;
                 }
             }
         });
     }
 
-    private static final RecyclableSingleton<CImage.Creator> cImageCreator = new RecyclableSingleton<CImage.Creator>() {
+    private static final RecyclableSingleton<Creator> cImageCreator = new RecyclableSingleton<Creator>() {
         @Override
         protected Creator getInstance() {
             return getCImageCreatorInternal();
         }
     };
-    static CImage.Creator getCImageCreator() {
+    static Creator getCImageCreator() {
         return cImageCreator.get();
     }
 
-    protected static Image generateSelectedDarkImage(final Image image) {
+    static Image generateSelectedDarkImage(final Image image) {
         final ImageProducer prod = new FilteredImageSource(image.getSource(), new IconImageFilter() {
+            @Override
             int getGreyFor(final int gray) {
                 return gray * 75 / 100;
             }
@@ -98,8 +111,9 @@
         return Toolkit.getDefaultToolkit().createImage(prod);
     }
 
-    protected static Image generateDisabledImage(final Image image) {
+    static Image generateDisabledImage(final Image image) {
         final ImageProducer prod = new FilteredImageSource(image.getSource(), new IconImageFilter() {
+            @Override
             int getGreyFor(final int gray) {
                 return 255 - ((255 - gray) * 65 / 100);
             }
@@ -107,19 +121,20 @@
         return Toolkit.getDefaultToolkit().createImage(prod);
     }
 
-    protected static Image generateLightenedImage(final Image image, final int percent) {
+    static Image generateLightenedImage(final Image image, final int percent) {
         final GrayFilter filter = new GrayFilter(true, percent);
         final ImageProducer prod = new FilteredImageSource(image.getSource(), filter);
         return Toolkit.getDefaultToolkit().createImage(prod);
     }
 
-    static abstract class IconImageFilter extends RGBImageFilter {
-        public IconImageFilter() {
+    private abstract static class IconImageFilter extends RGBImageFilter {
+        IconImageFilter() {
             super();
             canFilterIndexColorModel = true;
         }
 
-        public int filterRGB(final int x, final int y, final int rgb) {
+        @Override
+        public final int filterRGB(final int x, final int y, final int rgb) {
             final int red = (rgb >> 16) & 0xff;
             final int green = (rgb >> 8) & 0xff;
             final int blue = rgb & 0xff;
@@ -135,14 +150,14 @@
             return result;
         }
 
-        abstract int getGreyFor(final int gray);
+        abstract int getGreyFor(int gray);
     }
 
-    public abstract static class RecyclableObject<T> {
-        protected SoftReference<T> objectRef = null;
+    abstract static class RecyclableObject<T> {
+        private SoftReference<T> objectRef;
 
-        public T get() {
-            T referent = null;
+        T get() {
+            T referent;
             if (objectRef != null && (referent = objectRef.get()) != null) return referent;
             referent = create();
             objectRef = new SoftReference<T>(referent);
@@ -152,8 +167,8 @@
         protected abstract T create();
     }
 
-    public abstract static class RecyclableSingleton<T> {
-        public T get() {
+    abstract static class RecyclableSingleton<T> {
+        final T get() {
             final AppContext appContext = AppContext.getAppContext();
             SoftReference<T> ref = (SoftReference<T>) appContext.get(this);
             if (ref != null) {
@@ -166,38 +181,36 @@
             return object;
         }
 
-        public void reset() {
-            AppContext appContext = AppContext.getAppContext();
-            appContext.remove(this);
+        void reset() {
+            AppContext.getAppContext().remove(this);
         }
 
-        protected abstract T getInstance();
+        abstract T getInstance();
     }
 
-    public static class RecyclableSingletonFromDefaultConstructor<T> extends RecyclableSingleton<T> {
-        protected final Class<T> clazz;
+    static class RecyclableSingletonFromDefaultConstructor<T> extends RecyclableSingleton<T> {
+        private final Class<T> clazz;
 
-        public RecyclableSingletonFromDefaultConstructor(final Class<T> clazz) {
+        RecyclableSingletonFromDefaultConstructor(final Class<T> clazz) {
             this.clazz = clazz;
         }
 
-        protected T getInstance() {
+        @Override
+        T getInstance() {
             try {
+                ReflectUtil.checkPackageAccess(clazz);
                 return clazz.newInstance();
-            } catch (final InstantiationException e) {
-                e.printStackTrace();
-            } catch (final IllegalAccessException e) {
-                e.printStackTrace();
+            } catch (InstantiationException | IllegalAccessException ignored) {
             }
             return null;
         }
     }
 
-    public abstract static class LazyKeyedSingleton<K, V> {
-        protected Map<K, V> refs;
+    abstract static class LazyKeyedSingleton<K, V> {
+        private Map<K, V> refs;
 
-        public V get(final K key) {
-            if (refs == null) refs = new HashMap<K, V>();
+        V get(final K key) {
+            if (refs == null) refs = new HashMap<>();
 
             final V cachedValue = refs.get(key);
             if (cachedValue != null) return cachedValue;
@@ -207,44 +220,45 @@
             return value;
         }
 
-        protected abstract V getInstance(final K key);
+        protected abstract V getInstance(K key);
     }
 
-    static final RecyclableSingleton<Boolean> enableAnimations = new RecyclableSingleton<Boolean>() {
+    private static final RecyclableSingleton<Boolean> enableAnimations = new RecyclableSingleton<Boolean>() {
         @Override
         protected Boolean getInstance() {
-            final String sizeProperty = (String)java.security.AccessController.doPrivileged((PrivilegedAction<?>)new sun.security.action.GetPropertyAction(ANIMATIONS_SYSTEM_PROPERTY));
-            return new Boolean(!"false".equals(sizeProperty)); // should be true by default
+            final String sizeProperty = (String) AccessController.doPrivileged((PrivilegedAction<?>)new GetPropertyAction(
+                    ANIMATIONS_PROPERTY));
+            return !"false".equals(sizeProperty); // should be true by default
         }
     };
-    static boolean animationsEnabled() {
+    private static boolean animationsEnabled() {
         return enableAnimations.get();
     }
 
-    static final int MENU_BLINK_DELAY = 50; // 50ms == 3/60 sec, according to the spec
-    protected static void blinkMenu(final Selectable selectable) {
+    private static final int MENU_BLINK_DELAY = 50; // 50ms == 3/60 sec, according to the spec
+    static void blinkMenu(final Selectable selectable) {
         if (!animationsEnabled()) return;
         try {
             selectable.paintSelected(false);
             Thread.sleep(MENU_BLINK_DELAY);
             selectable.paintSelected(true);
             Thread.sleep(MENU_BLINK_DELAY);
-        } catch (final InterruptedException e) { }
+        } catch (final InterruptedException ignored) { }
     }
 
     interface Selectable {
-        void paintSelected(final boolean selected);
+        void paintSelected(boolean selected);
     }
 
     interface JComponentPainter {
-        public void paint(JComponent c, Graphics g, int x, int y, int w, int h);
+        void paint(JComponent c, Graphics g, int x, int y, int w, int h);
     }
 
     interface Painter {
-        public void paint(final Graphics g, int x, int y, int w, int h);
+        void paint(Graphics g, int x, int y, int w, int h);
     }
 
-    public static void paintDropShadowText(final Graphics g, final JComponent c, final Font font, final FontMetrics metrics, final int x, final int y, final int offsetX, final int offsetY, final Color textColor, final Color shadowColor, final String text) {
+    static void paintDropShadowText(final Graphics g, final JComponent c, final Font font, final FontMetrics metrics, final int x, final int y, final int offsetX, final int offsetY, final Color textColor, final Color shadowColor, final String text) {
         g.setFont(font);
         g.setColor(shadowColor);
         SwingUtilities2.drawString(c, g, text, x + offsetX, y + offsetY + metrics.getAscent());
@@ -252,22 +266,22 @@
         SwingUtilities2.drawString(c, g, text, x, y + metrics.getAscent());
     }
 
-    public static class ShadowBorder implements Border {
-        final Painter prePainter;
-        final Painter postPainter;
+    static class ShadowBorder implements Border {
+        private final Painter prePainter;
+        private final Painter postPainter;
 
-        final int offsetX;
-        final int offsetY;
-        final float distance;
-        final int blur;
-        final Insets insets;
-        final ConvolveOp blurOp;
+        private final int offsetX;
+        private final int offsetY;
+        private final float distance;
+        private final int blur;
+        private final Insets insets;
+        private final ConvolveOp blurOp;
 
-        public ShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur) {
+        ShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur) {
             this.prePainter = prePainter; this.postPainter = postPainter;
             this.offsetX = offsetX; this.offsetY = offsetY; this.distance = distance; this.blur = blur;
             final int halfBlur = blur / 2;
-            this.insets = new Insets(halfBlur - offsetY, halfBlur - offsetX, halfBlur + offsetY, halfBlur + offsetX);
+            insets = new Insets(halfBlur - offsetY, halfBlur - offsetX, halfBlur + offsetY, halfBlur + offsetX);
 
             final float blurry = intensity / (blur * blur);
             final float[] blurKernel = new float[blur * blur];
@@ -275,14 +289,17 @@
             blurOp = new ConvolveOp(new Kernel(blur, blur, blurKernel));
         }
 
-        public boolean isBorderOpaque() {
+        @Override
+        public final boolean isBorderOpaque() {
             return false;
         }
 
-        public Insets getBorderInsets(final Component c) {
+        @Override
+        public final Insets getBorderInsets(final Component c) {
             return insets;
         }
 
+        @Override
         public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
             final BufferedImage img = new BufferedImage(width + blur * 2, height + blur * 2, BufferedImage.TYPE_INT_ARGB_PRE);
             paintToImage(img, x, y, width, height);
@@ -290,7 +307,7 @@
             g.drawImage(img, -blur, -blur, null);
         }
 
-        protected void paintToImage(final BufferedImage img, final int x, final int y, final int width, final int height) {
+        private void paintToImage(final BufferedImage img, final int x, final int y, final int width, final int height) {
             // clear the prior image
             Graphics2D imgG = (Graphics2D)img.getGraphics();
             imgG.setComposite(AlphaComposite.Clear);
@@ -319,10 +336,10 @@
         }
     }
 
-    public static class SlicedShadowBorder extends ShadowBorder {
-        final SlicedImageControl slices;
+    static class SlicedShadowBorder extends ShadowBorder {
+        private final SlicedImageControl slices;
 
-        public SlicedShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur, final int templateWidth, final int templateHeight, final int leftCut, final int topCut, final int rightCut, final int bottomCut) {
+        SlicedShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur, final int templateWidth, final int templateHeight, final int leftCut, final int topCut, final int rightCut, final int bottomCut) {
             super(prePainter, postPainter, offsetX, offsetY, distance, intensity, blur);
 
             final BufferedImage i = new BufferedImage(templateWidth, templateHeight, BufferedImage.TYPE_INT_ARGB_PRE);
@@ -331,15 +348,12 @@
             slices = new SlicedImageControl(i, leftCut, topCut, rightCut, bottomCut, false);
         }
 
+        @Override
         public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
             slices.paint(g, x, y, width, height);
         }
     }
 
-    public interface NineSliceMetricsProvider {
-
-    }
-
 //    static void debugFrame(String name, Image image) {
 //        JFrame f = new JFrame(name);
 //        f.setContentPane(new JLabel(new ImageIcon(image)));
@@ -350,28 +364,30 @@
     // special casing naughty applications, like InstallAnywhere
     // <rdar://problem/4851533> REGR: JButton: Myst IV: the buttons of 1.0.3 updater have redraw issue
     static boolean shouldUseOpaqueButtons() {
-        final ClassLoader launcherClassLoader = sun.misc.Launcher.getLauncher().getClassLoader();
+        final ClassLoader launcherClassLoader = Launcher.getLauncher().getClassLoader();
         if (classExists(launcherClassLoader, "com.installshield.wizard.platform.macosx.MacOSXUtils")) return true;
         return false;
     }
 
-    static boolean classExists(final ClassLoader classLoader, final String clazzName) {
+    private static boolean classExists(final ClassLoader classLoader, final String clazzName) {
         try {
             return Class.forName(clazzName, false, classLoader) != null;
-        } catch (final Throwable e) { }
+        } catch (final Throwable ignored) { }
         return false;
     }
 
-    private static RecyclableSingleton<Method> getJComponentGetFlagMethod = new RecyclableSingleton<Method>() {
+    private static final RecyclableSingleton<Method> getJComponentGetFlagMethod = new RecyclableSingleton<Method>() {
+        @Override
         protected Method getInstance() {
-            return java.security.AccessController.doPrivileged(
+            return AccessController.doPrivileged(
                 new PrivilegedAction<Method>() {
+                    @Override
                     public Method run() {
                         try {
                             final Method method = JComponent.class.getDeclaredMethod("getFlag", new Class[] { int.class });
                             method.setAccessible(true);
                             return method;
-                        } catch (final Throwable e) {
+                        } catch (final Throwable ignored) {
                             return null;
                         }
                     }
@@ -380,18 +396,18 @@
         }
     };
 
-    private static final Integer OPAQUE_SET_FLAG = new Integer(24); // private int JComponent.OPAQUE_SET
-    protected static boolean hasOpaqueBeenExplicitlySet(final JComponent c) {
+    private static final Integer OPAQUE_SET_FLAG = 24; // private int JComponent.OPAQUE_SET
+    static boolean hasOpaqueBeenExplicitlySet(final JComponent c) {
         final Method method = getJComponentGetFlagMethod.get();
         if (method == null) return false;
         try {
             return Boolean.TRUE.equals(method.invoke(c, OPAQUE_SET_FLAG));
-        } catch (final Throwable e) {
+        } catch (final Throwable ignored) {
             return false;
         }
     }
 
-    protected static boolean isWindowTextured(final Component c) {
+    private static boolean isWindowTextured(final Component c) {
         if (!(c instanceof JComponent)) {
             return false;
         }
@@ -412,13 +428,12 @@
         return new Color(color.getRed(), color.getGreen(), color.getBlue(), 0);
     }
 
-    protected static void fillRect(final Graphics g, final Component c) {
+    static void fillRect(final Graphics g, final Component c) {
         fillRect(g, c, c.getBackground(), 0, 0, c.getWidth(), c.getHeight());
     }
 
-    protected static void fillRect(final Graphics g, final Component c,
-                                   final Color color, final int x, final int y,
-                                   final int w, final int h) {
+    static void fillRect(final Graphics g, final Component c, final Color color,
+                         final int x, final int y, final int w, final int h) {
         if (!(g instanceof Graphics2D)) {
             return;
         }
diff --git a/jdk/src/macosx/classes/com/apple/resources/MacOSXResourceBundle.java b/jdk/src/macosx/classes/com/apple/resources/MacOSXResourceBundle.java
deleted file mode 100644
index eaf93c2..0000000
--- a/jdk/src/macosx/classes/com/apple/resources/MacOSXResourceBundle.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.apple.resources;
-
-import java.security.*;
-import java.util.PropertyResourceBundle;
-import java.util.ResourceBundle;
-import java.io.*;
-
-public class MacOSXResourceBundle extends PropertyResourceBundle {
-    MacOSXResourceBundle(InputStream stream) throws IOException {
-        super(stream);
-    }
-
-    void setItsParent(ResourceBundle rb) {
-        setParent(rb);
-    }
-
-    public static ResourceBundle getMacResourceBundle(String baseJavaBundle) throws Exception {
-        return getMacResourceBundle(baseJavaBundle, null);
-    }
-
-    public static ResourceBundle getMacResourceBundle(String baseJavaBundle, String filename) throws Exception {
-        LoadNativeBundleAction lnba = new LoadNativeBundleAction(baseJavaBundle, filename);
-        return (ResourceBundle)java.security.AccessController.doPrivileged(lnba);
-    }
-}
-
-class LoadNativeBundleAction implements PrivilegedExceptionAction {
-    String mBaseJavaBundle;
-    String mFilenameOverride;
-
-    LoadNativeBundleAction(String baseJavaBundle, String filenameOverride) {
-        mBaseJavaBundle = baseJavaBundle;
-        mFilenameOverride = filenameOverride;
-    }
-
-    public Object run() {
-        java.util.ResourceBundle returnValue = null;
-        MacOSXResourceBundle macOSrb = null;
-
-        // Load the Mac OS X resources.
-        // Use a base filename if we were given one. Otherwise, we will look for the last piece of the bundle path
-        // with '.properties' appended. Either way, the native method will take care of the extension.
-        String filename = mFilenameOverride;
-
-        if (filename == null) {
-            filename = mBaseJavaBundle.substring(mBaseJavaBundle.lastIndexOf('.') + 1);
-        }
-
-        File propsFile = null;
-        String propertyFileName = getPathToBundleFile(filename);
-        InputStream stream = null;
-
-        try {
-            propsFile = new File(propertyFileName);
-            stream = new FileInputStream(propsFile);
-            stream = new java.io.BufferedInputStream(stream);
-            macOSrb = new MacOSXResourceBundle(stream);
-        } catch (Exception e) {
-            //e.printStackTrace();
-            //System.out.println("Failed to create resources from application bundle.  Using Java-based resources.");
-        } finally {
-            try {
-                if (stream != null) stream.close();
-                stream = null;
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        }
-
-        returnValue = ResourceBundle.getBundle(mBaseJavaBundle);
-
-        // If we have a platform-specific bundle, make it the parent of the generic bundle, so failures propagate up to the parent.
-        if (returnValue != null) {
-            if (macOSrb != null) {
-                macOSrb.setItsParent(returnValue);
-                returnValue = macOSrb;
-            }
-        }
-
-        return returnValue;
-    }
-
-    private static native String getPathToBundleFile(String filename);
-}
-
diff --git a/jdk/src/macosx/native/com/apple/resources/MacOSXResourceBundle.m b/jdk/src/macosx/native/com/apple/resources/MacOSXResourceBundle.m
deleted file mode 100644
index 783d747..0000000
--- a/jdk/src/macosx/native/com/apple/resources/MacOSXResourceBundle.m
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2011, 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.
- */
-
-#import <dlfcn.h>
-#import <Cocoa/Cocoa.h>
-#import <JavaNativeFoundation/JavaNativeFoundation.h>
-
-#ifndef MAXPATHLEN
-#define MAXPATHLEN PATH_MAX
-#endif
-
-static jboolean
-GetPathFromCurrentBinary(char *buf, jint bufsize)
-{
-    Dl_info dlinfo;
-    dladdr((void *)GetPathFromCurrentBinary, &dlinfo);
-    if (realpath(dlinfo.dli_fname, buf) == NULL) {
-//      fprintf(stderr, "Error: realpath(`%s') failed.\n", dlinfo.dli_fname);
-        return JNI_FALSE;
-    }
-
-    const char *libawt = "lib/libawt.dylib";
-    int strLen, libawtLen;
-
-    strLen = strlen(buf);
-    libawtLen = strlen(libawt);
-
-    if (strLen < libawtLen ||
-        strcmp(buf + strLen - libawtLen, libawt) != 0) {
-        return JNI_FALSE;
-    }
-
-    buf[strLen - libawtLen] = '\0';
-
-    return JNI_TRUE;
-}
-
-#define JAVA_DLL "libjava.dylib"
-
-static jboolean
-GetJREPath(char *buf, jint bufsize)
-{
-    /* try to get the path from the current binary, if not, bail to the framework */
-    if (GetPathFromCurrentBinary(buf, bufsize) == JNI_TRUE) {
-        /* does the rest of the JRE exist? */
-        char libjava[MAXPATHLEN];
-        snprintf(libjava, MAXPATHLEN, "%s/lib/" JAVA_DLL, buf);
-        if (access(libjava, F_OK) == 0) {
-            return JNI_TRUE;
-        }
-    }
-
-    return JNI_FALSE;
-}
-
-static NSString *getRunningJavaBundle()
-{
-    char path[MAXPATHLEN];
-    GetJREPath(path, MAXPATHLEN);
-    return [[NSString alloc] initWithFormat:@"%@/bundle", [NSString stringWithUTF8String:path]];
-}
-
-/*
- * Class:     com_apple_resources_LoadNativeBundleAction
- * Method:    getPathToBundleFile
- * Signature: (Ljava/lang/String)Ljava/lang/String;
- */
-JNIEXPORT jstring JNICALL
-Java_com_apple_resources_LoadNativeBundleAction_getPathToBundleFile
-    (JNIEnv *env, jclass klass, jstring filename)
-{
-    jstring returnVal = NULL;
-    if (filename == NULL) {
-        return NULL;
-    }
-
-JNF_COCOA_ENTER(env);
-    NSBundle *javaBundle = [NSBundle bundleWithPath:getRunningJavaBundle()];
-    NSString *baseFilename = JNFJavaToNSString(env, filename);
-    NSString *propertyFilePath = [javaBundle pathForResource:baseFilename ofType:@"properties"];
-
-    if (propertyFilePath != nil) {
-        returnVal = JNFNSToJavaString(env, propertyFilePath);
-    }
-JNF_COCOA_EXIT(env);
-
-    return returnVal;
-}
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java
index 4af003d..caef979 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -280,22 +280,6 @@
             return new DHParameterSpec(this.p, this.g);
     }
 
-    public String toString() {
-        String LINE_SEP = System.getProperty("line.separator");
-
-        StringBuffer strbuf
-            = new StringBuffer("SunJCE Diffie-Hellman Private Key:"
-                               + LINE_SEP + "x:" + LINE_SEP
-                               + Debug.toHexString(this.x)
-                               + LINE_SEP + "p:" + LINE_SEP
-                               + Debug.toHexString(this.p)
-                               + LINE_SEP + "g:" + LINE_SEP
-                               + Debug.toHexString(this.g));
-        if (this.l != 0)
-            strbuf.append(LINE_SEP + "l:" + LINE_SEP + "    " + this.l);
-        return strbuf.toString();
-    }
-
     private void parseKeyBits() throws InvalidKeyException {
         try {
             DerInputStream in = new DerInputStream(this.key);
diff --git a/jdk/src/share/classes/com/sun/demo/jvmti/hprof/Tracker.java b/jdk/src/share/classes/com/sun/demo/jvmti/hprof/Tracker.java
index f2e33d7..9695087 100644
--- a/jdk/src/share/classes/com/sun/demo/jvmti/hprof/Tracker.java
+++ b/jdk/src/share/classes/com/sun/demo/jvmti/hprof/Tracker.java
@@ -53,7 +53,10 @@
 
     public static void ObjectInit(Object obj)
     {
-        if ( engaged != 0 ) {
+        if ( engaged != 0) {
+            if (obj == null) {
+                throw new IllegalArgumentException("Null object.");
+            }
             nativeObjectInit(Thread.currentThread(), obj);
         }
     }
@@ -66,7 +69,10 @@
 
     public static void NewArray(Object obj)
     {
-        if ( engaged != 0 ) {
+        if ( engaged != 0) {
+            if (obj == null) {
+                throw new IllegalArgumentException("Null object.");
+            }
             nativeNewArray(Thread.currentThread(), obj);
         }
     }
@@ -82,6 +88,14 @@
     public static void CallSite(int cnum, int mnum)
     {
         if ( engaged != 0 ) {
+            if (cnum < 0) {
+                throw new IllegalArgumentException("Negative class index");
+            }
+
+            if (mnum < 0) {
+                throw new IllegalArgumentException("Negative method index");
+            }
+
             nativeCallSite(Thread.currentThread(), cnum, mnum);
         }
     }
@@ -95,6 +109,14 @@
     public static void ReturnSite(int cnum, int mnum)
     {
         if ( engaged != 0 ) {
+            if (cnum < 0) {
+                throw new IllegalArgumentException("Negative class index");
+            }
+
+            if (mnum < 0) {
+                throw new IllegalArgumentException("Negative method index");
+            }
+
             nativeReturnSite(Thread.currentThread(), cnum, mnum);
         }
     }
diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java
index e151179..bc4839e 100644
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java
@@ -1160,6 +1160,11 @@
             target = imRas;
         }
         int [] bandSizes = target.getSampleModel().getSampleSize();
+        for (int i = 0; i < bandSizes.length; i++) {
+            if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
+                throw new IIOException("Illegal band size: should be 0 < size <= 8");
+            }
+        }
 
         /*
          * If the process is sequential, and we have restart markers,
diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java
index 8fdce8d..b2ab2fb 100644
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java
@@ -490,8 +490,8 @@
             // handle <= 8-bit samples.  We now check the band sizes and throw
             // an exception for images, such as USHORT_GRAY, with > 8 bits
             // per sample.
-            if (bandSizes[i] > 8) {
-                throw new IIOException("Sample size must be <= 8");
+            if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
+                throw new IIOException("Illegal band size: should be 0 < size <= 8");
             }
             // 4450894 part 2: We expand IndexColorModel images to full 24-
             // or 32-bit in grabPixels() for each scanline.  For indexed
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/VersionHelper12.java b/jdk/src/share/classes/com/sun/jndi/ldap/VersionHelper12.java
index 47646d1..339b6c4 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/VersionHelper12.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/VersionHelper12.java
@@ -25,11 +25,12 @@
 
 package com.sun.jndi.ldap;
 
-import java.net.URL;
 import java.net.URLClassLoader;
 import java.net.MalformedURLException;
+import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import sun.misc.SharedSecrets;
 
 final class VersionHelper12 extends VersionHelper {
 
@@ -82,12 +83,16 @@
     }
 
     Thread createThread(final Runnable r) {
-        return (Thread) AccessController.doPrivileged(
-            new PrivilegedAction() {
-                public Object run() {
-                    return new Thread(r);
+        final AccessControlContext acc = AccessController.getContext();
+        // 4290486: doPrivileged is needed to create a thread in
+        // an environment that restricts "modifyThreadGroup".
+        return AccessController.doPrivileged(
+                new PrivilegedAction<Thread>() {
+                    public Thread run() {
+                        return SharedSecrets.getJavaLangAccess()
+                                .newThreadWithAcc(r, acc);
+                    }
                 }
-            }
         );
     }
 }
diff --git a/jdk/src/share/classes/com/sun/management/HotSpotDiagnosticMXBean.java b/jdk/src/share/classes/com/sun/management/HotSpotDiagnosticMXBean.java
index 2fe8835..eaf5447 100644
--- a/jdk/src/share/classes/com/sun/management/HotSpotDiagnosticMXBean.java
+++ b/jdk/src/share/classes/com/sun/management/HotSpotDiagnosticMXBean.java
@@ -66,6 +66,11 @@
      *                     cannot be created, opened, or written to.
      * @throws UnsupportedOperationException if this operation is not supported.
      * @throws NullPointerException if <tt>outputFile</tt> is <tt>null</tt>.
+     * @throws SecurityException
+     *         If a security manager exists and its {@link
+     *         java.lang.SecurityManager#checkWrite(java.lang.String)}
+     *         method denies write access to the named file
+     *         or the caller does not have ManagmentPermission("control").
      */
     public void dumpHeap(String outputFile, boolean live) throws java.io.IOException;
 
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java
index bfba75d..e98351f 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java
@@ -44,6 +44,9 @@
     }
 
     public void write(byte[] arg0) {
+        if ((Integer.MAX_VALUE - pos) < arg0.length) {
+            throw new OutOfMemoryError();
+        }
         int newPos = pos + arg0.length;
         if (newPos > size) {
             expandSize(newPos);
@@ -53,6 +56,9 @@
     }
 
     public void write(byte[] arg0, int arg1, int arg2) {
+        if ((Integer.MAX_VALUE - pos) < arg2) {
+            throw new OutOfMemoryError();
+        }
         int newPos = pos + arg2;
         if (newPos > size) {
             expandSize(newPos);
@@ -62,6 +68,9 @@
     }
 
     public void write(int arg0) {
+        if ((Integer.MAX_VALUE - pos) == 0) {
+            throw new OutOfMemoryError();
+        }
         int newPos = pos + 1;
         if (newPos > size) {
             expandSize(newPos);
@@ -82,7 +91,11 @@
     private void expandSize(int newPos) {
         int newSize = size;
         while (newPos > newSize) {
-            newSize = newSize<<2;
+            newSize = newSize << 1;
+            // Deal with overflow
+            if (newSize < 0) {
+                newSize = Integer.MAX_VALUE;
+            }
         }
         byte newBuf[] = new byte[newSize];
         System.arraycopy(buf, 0, newBuf, 0, pos);
diff --git a/jdk/src/share/classes/com/sun/script/util/InterfaceImplementor.java b/jdk/src/share/classes/com/sun/script/util/InterfaceImplementor.java
index 7e94c96..f4850b0 100644
--- a/jdk/src/share/classes/com/sun/script/util/InterfaceImplementor.java
+++ b/jdk/src/share/classes/com/sun/script/util/InterfaceImplementor.java
@@ -28,6 +28,7 @@
 import javax.script.*;
 import java.lang.reflect.*;
 import java.security.*;
+import sun.reflect.misc.ReflectUtil;
 
 /*
  * java.lang.reflect.Proxy based interface implementor. This is meant
@@ -85,8 +86,18 @@
         if (! isImplemented(thiz, iface)) {
             return null;
         }
+
+        if (System.getSecurityManager() != null &&
+           !Modifier.isPublic(iface.getModifiers())) {
+            throw new SecurityException("attempt to implement non-public interface");
+        }
+
+        // make sure restricted package interfaces are not attempted.
+        ReflectUtil.checkPackageAccess(iface.getName());
+
         AccessControlContext accCtxt = AccessController.getContext();
-        return iface.cast(Proxy.newProxyInstance(iface.getClassLoader(),
+        return iface.cast(Proxy.newProxyInstance(
+            getLoaderForProxy(iface),
             new Class[]{iface},
             new InterfaceImplementorInvocationHandler(thiz, accCtxt)));
     }
@@ -108,4 +119,20 @@
         // default is identity conversion
         return args;
     }
+
+    // get appropriate ClassLoader for generated Proxy class
+    private static ClassLoader getLoaderForProxy(Class<?> iface) {
+        ClassLoader loader = iface.getClassLoader();
+
+        // if bootstrap class, try TCCL
+        if (loader == null) {
+            loader = Thread.currentThread().getContextClassLoader();
+        }
+
+        // if TCCL is also null, try System class loader
+        if (loader == null) {
+            loader = ClassLoader.getSystemClassLoader();
+        }
+        return loader;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/AllClassesQuery.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/AllClassesQuery.java
index d44a8fc..bdf01b8 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/AllClassesQuery.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/AllClassesQuery.java
@@ -84,7 +84,7 @@
             lastPackage = pkg;
             printClass(clazz);
             if (clazz.getId() != -1) {
-                out.print(" [" + clazz.getIdString() + "]");
+                print(" [" + clazz.getIdString() + "]");
             }
             out.println("<br>");
         }
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/ClassQuery.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/ClassQuery.java
index 1d57823..f13572a 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/ClassQuery.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/ClassQuery.java
@@ -112,12 +112,12 @@
         out.println("<h2>Instances</h2>");
 
         printAnchorStart();
-        out.print("instances/" + encodeForURL(clazz));
+        print("instances/" + encodeForURL(clazz));
         out.print("\">");
         out.println("Exclude subclasses</a><br>");
 
         printAnchorStart();
-        out.print("allInstances/" + encodeForURL(clazz));
+        print("allInstances/" + encodeForURL(clazz));
         out.print("\">");
         out.println("Include subclasses</a><br>");
 
@@ -126,19 +126,19 @@
             out.println("<h2>New Instances</h2>");
 
             printAnchorStart();
-            out.print("newInstances/" + encodeForURL(clazz));
+            print("newInstances/" + encodeForURL(clazz));
             out.print("\">");
             out.println("Exclude subclasses</a><br>");
 
             printAnchorStart();
-            out.print("allNewInstances/" + encodeForURL(clazz));
+            print("allNewInstances/" + encodeForURL(clazz));
             out.print("\">");
             out.println("Include subclasses</a><br>");
         }
 
         out.println("<h2>References summary by Type</h2>");
         printAnchorStart();
-        out.print("refsByType/" + encodeForURL(clazz));
+        print("refsByType/" + encodeForURL(clazz));
         out.print("\">");
         out.println("References summary by type</a>");
 
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/HttpReader.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/HttpReader.java
index f86c8ca..f08c987 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/HttpReader.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/HttpReader.java
@@ -41,21 +41,17 @@
 
 
 import java.net.Socket;
-import java.net.ServerSocket;
-import java.net.InetAddress;
 
 import java.io.InputStream;
 import java.io.BufferedInputStream;
 import java.io.IOException;
-import java.io.Writer;
 import java.io.BufferedWriter;
 import java.io.PrintWriter;
-import java.io.OutputStream;
 import java.io.OutputStreamWriter;
-import java.io.BufferedOutputStream;
 
 import com.sun.tools.hat.internal.model.Snapshot;
 import com.sun.tools.hat.internal.oql.OQLEngine;
+import com.sun.tools.hat.internal.util.Misc;
 
 public class HttpReader implements Runnable {
 
@@ -87,7 +83,7 @@
                 outputError("Protocol error");
             }
             int data;
-            StringBuffer queryBuf = new StringBuffer();
+            StringBuilder queryBuf = new StringBuilder();
             while ((data = in.read()) != -1 && data != ' ') {
                 char ch = (char) data;
                 queryBuf.append(ch);
@@ -217,7 +213,7 @@
     private void outputError(String msg) {
         out.println();
         out.println("<html><body bgcolor=\"#ffffff\">");
-        out.println(msg);
+        out.println(Misc.encodeHtml(msg));
         out.println("</body></html>");
     }
 
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/InstancesCountQuery.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/InstancesCountQuery.java
index 724b549..7e87543 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/InstancesCountQuery.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/InstancesCountQuery.java
@@ -102,7 +102,7 @@
             int count = clazz.getInstancesCount(false);
             print("" + count);
             printAnchorStart();
-            out.print("instances/" + encodeForURL(classes[i]));
+            print("instances/" + encodeForURL(classes[i]));
             out.print("\"> ");
             if (count == 1) {
                 print("instance");
@@ -121,7 +121,7 @@
                 }
                 print("(");
                 printAnchorStart();
-                out.print("newInstances/" + encodeForURL(classes[i]));
+                print("newInstances/" + encodeForURL(classes[i]));
                 out.print("\">");
                 print("" + newInst + " new");
                 out.print("</a>) ");
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLHelp.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLHelp.java
index 6aaa909..730d2b7 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLHelp.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLHelp.java
@@ -54,10 +54,7 @@
                 out.print((char)ch);
             }
         } catch (Exception exp) {
-            out.println(exp.getMessage());
-            out.println("<pre>");
-            exp.printStackTrace(out);
-            out.println("</pre>");
+            printException(exp);
         }
     }
 }
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLQuery.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLQuery.java
index 8e5ec5e..3e99bbc 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLQuery.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/OQLQuery.java
@@ -32,10 +32,7 @@
 
 package com.sun.tools.hat.internal.server;
 
-import com.sun.tools.hat.internal.model.*;
 import com.sun.tools.hat.internal.oql.*;
-import com.sun.tools.hat.internal.util.ArraySorter;
-import com.sun.tools.hat.internal.util.Comparer;
 
 /**
  * This handles Object Query Language (OQL) queries.
@@ -68,7 +65,7 @@
         out.println("<p align='center'>");
         out.println("<textarea name='query' cols=80 rows=10>");
         if (oql != null) {
-            out.println(oql);
+            println(oql);
         }
         out.println("</textarea>");
         out.println("</p>");
@@ -91,10 +88,7 @@
                          try {
                              out.println(engine.toHtml(o));
                          } catch (Exception e) {
-                             out.println(e.getMessage());
-                             out.println("<pre>");
-                             e.printStackTrace(out);
-                             out.println("</pre>");
+                             printException(e);
                          }
                          out.println("</td></tr>");
                          return false;
@@ -102,10 +96,7 @@
                  });
             out.println("</table>");
         } catch (OQLException exp) {
-            out.println(exp.getMessage());
-            out.println("<pre>");
-            exp.printStackTrace(out);
-            out.println("</pre>");
+            printException(exp);
         }
     }
 
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/QueryHandler.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/QueryHandler.java
index deda0f4..9a6d93d 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/QueryHandler.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/QueryHandler.java
@@ -36,6 +36,7 @@
 
 import com.sun.tools.hat.internal.model.*;
 import com.sun.tools.hat.internal.util.Misc;
+import java.io.StringWriter;
 
 import java.net.URLEncoder;
 import java.io.UnsupportedEncodingException;
@@ -96,7 +97,7 @@
     }
 
     protected void error(String msg) {
-        out.println(msg);
+        println(msg);
     }
 
     protected void printAnchorStart() {
@@ -160,7 +161,6 @@
             out.println("null");
             return;
         }
-        String name = clazz.getName();
         printAnchorStart();
         out.print("class/");
         print(encodeForURL(clazz));
@@ -208,6 +208,15 @@
         }
     }
 
+    protected void printException(Throwable t) {
+        println(t.getMessage());
+        out.println("<pre>");
+        StringWriter sw = new StringWriter();
+        t.printStackTrace(new PrintWriter(sw));
+        print(sw.toString());
+        out.println("</pre>");
+    }
+
     protected void printHex(long addr) {
         if (snapshot.getIdentifierSize() == 4) {
             out.print(Misc.toHex((int)addr));
@@ -223,4 +232,8 @@
     protected void print(String str) {
         out.print(Misc.encodeHtml(str));
     }
+
+    protected void println(String str) {
+        out.println(Misc.encodeHtml(str));
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java
index 5e7de9a..3337b47 100644
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java
@@ -89,7 +89,7 @@
             out.println("<p align='center'>");
             printClass(clazz);
             if (clazz.getId() != -1) {
-                out.println("[" + clazz.getIdString() + "]");
+                println("[" + clazz.getIdString() + "]");
             }
             out.println("</p>");
 
@@ -125,9 +125,9 @@
             JavaClass clazz = classes[i];
             out.println("<tr><td>");
             out.print("<a href='/refsByType/");
-            out.print(clazz.getIdString());
+            print(clazz.getIdString());
             out.print("'>");
-            out.print(clazz.getName());
+            print(clazz.getName());
             out.println("</a>");
             out.println("</td><td>");
             out.println(map.get(clazz));
diff --git a/jdk/src/share/classes/java/awt/datatransfer/DataFlavor.java b/jdk/src/share/classes/java/awt/datatransfer/DataFlavor.java
index 20ead5e..3418aaf 100644
--- a/jdk/src/share/classes/java/awt/datatransfer/DataFlavor.java
+++ b/jdk/src/share/classes/java/awt/datatransfer/DataFlavor.java
@@ -25,12 +25,14 @@
 
 package java.awt.datatransfer;
 
-import java.awt.Toolkit;
 import java.io.*;
 import java.nio.*;
 import java.util.*;
 
 import sun.awt.datatransfer.DataTransferer;
+import sun.reflect.misc.ReflectUtil;
+
+import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION;
 
 /**
  * A {@code DataFlavor} provides meta information about data. {@code DataFlavor}
@@ -117,27 +119,33 @@
                                                    ClassLoader fallback)
         throws ClassNotFoundException
     {
-        ClassLoader systemClassLoader = (ClassLoader)
-            java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
-                    public Object run() {
-                        ClassLoader cl = Thread.currentThread().
-                            getContextClassLoader();
-                        return (cl != null)
-                            ? cl
-                            : ClassLoader.getSystemClassLoader();
-                    }
-                    });
-
+        ReflectUtil.checkPackageAccess(className);
         try {
-            return Class.forName(className, true, systemClassLoader);
-        } catch (ClassNotFoundException e2) {
-            if (fallback != null) {
-                return Class.forName(className, true, fallback);
-            } else {
-                throw new ClassNotFoundException(className);
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null) {
+                sm.checkPermission(GET_CLASSLOADER_PERMISSION);
             }
+            ClassLoader loader = ClassLoader.getSystemClassLoader();
+            try {
+                // bootstrap class loader and system class loader if present
+                return Class.forName(className, true, loader);
+            }
+            catch (ClassNotFoundException exception) {
+                // thread context class loader if and only if present
+                loader = Thread.currentThread().getContextClassLoader();
+                if (loader != null) {
+                    try {
+                        return Class.forName(className, true, loader);
+                    }
+                    catch (ClassNotFoundException e) {
+                        // fallback to user's class loader
+                    }
+                }
+            }
+        } catch (SecurityException exception) {
+            // ignore secured class loaders
         }
+        return Class.forName(className, true, fallback);
     }
 
     /*
diff --git a/jdk/src/share/classes/java/beans/Beans.java b/jdk/src/share/classes/java/beans/Beans.java
index 03f0dc8..95263ef 100644
--- a/jdk/src/share/classes/java/beans/Beans.java
+++ b/jdk/src/share/classes/java/beans/Beans.java
@@ -42,6 +42,8 @@
 import java.io.ObjectStreamClass;
 import java.io.StreamCorruptedException;
 
+import java.lang.reflect.Modifier;
+
 import java.net.URL;
 
 import java.security.AccessController;
@@ -222,6 +224,10 @@
                 throw ex;
             }
 
+            if (!Modifier.isPublic(cl.getModifiers())) {
+                throw new ClassNotFoundException("" + cl + " : no public access");
+            }
+
             /*
              * Try to instantiate the class.
              */
diff --git a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java
index 951d972..d0f0833 100644
--- a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java
+++ b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java
@@ -220,6 +220,9 @@
     // Write out the properties of this instance.
     private void initBean(Class type, Object oldInstance, Object newInstance, Encoder out) {
         for (Field field : type.getFields()) {
+            if (!ReflectUtil.isPackageAccessible(field.getDeclaringClass())) {
+                continue;
+            }
             int mod = field.getModifiers();
             if (Modifier.isFinal(mod) || Modifier.isStatic(mod) || Modifier.isTransient(mod)) {
                 continue;
diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java
index 0c59c39..e2ccf5b 100644
--- a/jdk/src/share/classes/java/beans/MetaData.java
+++ b/jdk/src/share/classes/java/beans/MetaData.java
@@ -42,6 +42,7 @@
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.lang.reflect.InvocationTargetException;
 
 import java.security.AccessController;
@@ -56,7 +57,7 @@
 
 import sun.swing.PrintColorUIResource;
 
-import java.util.Objects;
+import static sun.reflect.misc.ReflectUtil.isPackageAccessible;
 
 /*
  * Like the <code>Intropector</code>, the <code>MetaData</code> class
@@ -850,13 +851,15 @@
 
 static class StaticFieldsPersistenceDelegate extends PersistenceDelegate {
     protected void installFields(Encoder out, Class<?> cls) {
-        Field fields[] = cls.getFields();
-        for(int i = 0; i < fields.length; i++) {
-            Field field = fields[i];
-            // Don't install primitives, their identity will not be preserved
-            // by wrapping.
-            if (Object.class.isAssignableFrom(field.getType())) {
-                out.writeExpression(new Expression(field, "get", new Object[]{null}));
+        if (Modifier.isPublic(cls.getModifiers()) && isPackageAccessible(cls)) {
+            Field fields[] = cls.getFields();
+            for(int i = 0; i < fields.length; i++) {
+                Field field = fields[i];
+                // Don't install primitives, their identity will not be preserved
+                // by wrapping.
+                if (Object.class.isAssignableFrom(field.getType())) {
+                    out.writeExpression(new Expression(field, "get", new Object[]{null}));
+                }
             }
         }
     }
diff --git a/jdk/src/share/classes/java/io/ObjectInputStream.java b/jdk/src/share/classes/java/io/ObjectInputStream.java
index eb93a70..ef2511e 100644
--- a/jdk/src/share/classes/java/io/ObjectInputStream.java
+++ b/jdk/src/share/classes/java/io/ObjectInputStream.java
@@ -490,11 +490,12 @@
     public void defaultReadObject()
         throws IOException, ClassNotFoundException
     {
-        if (curContext == null) {
+        SerialCallbackContext ctx = curContext;
+        if (ctx == null) {
             throw new NotActiveException("not in call to readObject");
         }
-        Object curObj = curContext.getObj();
-        ObjectStreamClass curDesc = curContext.getDesc();
+        Object curObj = ctx.getObj();
+        ObjectStreamClass curDesc = ctx.getDesc();
         bin.setBlockDataMode(false);
         defaultReadFields(curObj, curDesc);
         bin.setBlockDataMode(true);
@@ -528,11 +529,12 @@
     public ObjectInputStream.GetField readFields()
         throws IOException, ClassNotFoundException
     {
-        if (curContext == null) {
+        SerialCallbackContext ctx = curContext;
+        if (ctx == null) {
             throw new NotActiveException("not in call to readObject");
         }
-        Object curObj = curContext.getObj();
-        ObjectStreamClass curDesc = curContext.getDesc();
+        Object curObj = ctx.getObj();
+        ObjectStreamClass curDesc = ctx.getDesc();
         bin.setBlockDataMode(false);
         GetFieldImpl getField = new GetFieldImpl(curDesc);
         getField.readFields();
@@ -1965,7 +1967,6 @@
     private void defaultReadFields(Object obj, ObjectStreamClass desc)
         throws IOException
     {
-        // REMIND: is isInstance check necessary?
         Class cl = desc.forClass();
         if (cl != null && obj != null && !cl.isInstance(obj)) {
             throw new ClassCastException();
diff --git a/jdk/src/share/classes/java/io/ObjectOutputStream.java b/jdk/src/share/classes/java/io/ObjectOutputStream.java
index 8667663..c5b7a18 100644
--- a/jdk/src/share/classes/java/io/ObjectOutputStream.java
+++ b/jdk/src/share/classes/java/io/ObjectOutputStream.java
@@ -430,11 +430,12 @@
      *          <code>OutputStream</code>
      */
     public void defaultWriteObject() throws IOException {
-        if ( curContext == null ) {
+        SerialCallbackContext ctx = curContext;
+        if (ctx == null) {
             throw new NotActiveException("not in call to writeObject");
         }
-        Object curObj = curContext.getObj();
-        ObjectStreamClass curDesc = curContext.getDesc();
+        Object curObj = ctx.getObj();
+        ObjectStreamClass curDesc = ctx.getDesc();
         bout.setBlockDataMode(false);
         defaultWriteFields(curObj, curDesc);
         bout.setBlockDataMode(true);
@@ -452,11 +453,12 @@
      */
     public ObjectOutputStream.PutField putFields() throws IOException {
         if (curPut == null) {
-            if (curContext == null) {
+            SerialCallbackContext ctx = curContext;
+            if (ctx == null) {
                 throw new NotActiveException("not in call to writeObject");
             }
-            Object curObj = curContext.getObj();
-            ObjectStreamClass curDesc = curContext.getDesc();
+            Object curObj = ctx.getObj();
+            ObjectStreamClass curDesc = ctx.getDesc();
             curPut = new PutFieldImpl(curDesc);
         }
         return curPut;
@@ -1516,7 +1518,11 @@
     private void defaultWriteFields(Object obj, ObjectStreamClass desc)
         throws IOException
     {
-        // REMIND: perform conservative isInstance check here?
+        Class<?> cl = desc.forClass();
+        if (cl != null && obj != null && !cl.isInstance(obj)) {
+            throw new ClassCastException();
+        }
+
         desc.checkDefaultSerialize();
 
         int primDataSize = desc.getPrimDataSize();
diff --git a/jdk/src/share/classes/java/lang/Class.java b/jdk/src/share/classes/java/lang/Class.java
index cb5b702..423e656 100644
--- a/jdk/src/share/classes/java/lang/Class.java
+++ b/jdk/src/share/classes/java/lang/Class.java
@@ -1096,7 +1096,17 @@
      * @return the declaring class for this class
      * @since JDK1.1
      */
-    public native Class<?> getDeclaringClass();
+    @CallerSensitive
+    public Class<?> getDeclaringClass() {
+        final Class<?> candidate = getDeclaringClass0();
+
+        if (candidate != null)
+            candidate.checkPackageAccess(
+                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
+        return candidate;
+    }
+
+    private native Class<?> getDeclaringClass0();
 
 
     /**
diff --git a/jdk/src/share/classes/java/lang/ClassLoader.java b/jdk/src/share/classes/java/lang/ClassLoader.java
index 0814bda..426034a 100644
--- a/jdk/src/share/classes/java/lang/ClassLoader.java
+++ b/jdk/src/share/classes/java/lang/ClassLoader.java
@@ -58,6 +58,7 @@
 import sun.misc.VM;
 import sun.reflect.CallerSensitive;
 import sun.reflect.Reflection;
+import sun.reflect.misc.ReflectUtil;
 import sun.security.util.SecurityConstants;
 
 /**
@@ -487,6 +488,13 @@
     private void checkPackageAccess(Class cls, ProtectionDomain pd) {
         final SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
+            if (ReflectUtil.isNonPublicProxyClass(cls)) {
+                for (Class intf: cls.getInterfaces()) {
+                    checkPackageAccess(intf, pd);
+                }
+                return;
+            }
+
             final String name = cls.getName();
             final int i = name.lastIndexOf('.');
             if (i != -1) {
diff --git a/jdk/src/share/classes/java/lang/System.java b/jdk/src/share/classes/java/lang/System.java
index c0b5818..381e6d8 100644
--- a/jdk/src/share/classes/java/lang/System.java
+++ b/jdk/src/share/classes/java/lang/System.java
@@ -25,6 +25,7 @@
 package java.lang;
 
 import java.io.*;
+import java.security.AccessControlContext;
 import java.util.Properties;
 import java.util.PropertyPermission;
 import java.util.StringTokenizer;
@@ -1202,6 +1203,9 @@
             public int getStringHash32(String string) {
                 return string.hash32();
             }
+            public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
+                return new Thread(target, acc);
+            }
         });
     }
 }
diff --git a/jdk/src/share/classes/java/lang/Thread.java b/jdk/src/share/classes/java/lang/Thread.java
index 8541bfe..cf67c8e 100644
--- a/jdk/src/share/classes/java/lang/Thread.java
+++ b/jdk/src/share/classes/java/lang/Thread.java
@@ -341,6 +341,15 @@
     }
 
     /**
+     * Initializes a Thread with the current AccessControlContext.
+     * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext)
+     */
+    private void init(ThreadGroup g, Runnable target, String name,
+                      long stackSize) {
+        init(g, target, name, stackSize, null);
+    }
+
+    /**
      * Initializes a Thread.
      *
      * @param g the Thread group
@@ -348,9 +357,11 @@
      * @param name the name of the new Thread
      * @param stackSize the desired stack size for the new thread, or
      *        zero to indicate that this parameter is to be ignored.
+     * @param acc the AccessControlContext to inherit, or
+     *            AccessController.getContext() if null
      */
     private void init(ThreadGroup g, Runnable target, String name,
-                      long stackSize) {
+                      long stackSize, AccessControlContext acc) {
         if (name == null) {
             throw new NullPointerException("name cannot be null");
         }
@@ -396,7 +407,8 @@
             this.contextClassLoader = parent.getContextClassLoader();
         else
             this.contextClassLoader = parent.contextClassLoader;
-        this.inheritedAccessControlContext = AccessController.getContext();
+        this.inheritedAccessControlContext =
+                acc != null ? acc : AccessController.getContext();
         this.target = target;
         setPriority(priority);
         if (parent.inheritableThreadLocals != null)
@@ -449,6 +461,14 @@
     }
 
     /**
+     * Creates a new Thread that inherits the given AccessControlContext.
+     * This is not a public constructor.
+     */
+    Thread(Runnable target, AccessControlContext acc) {
+        init(null, target, "Thread-" + nextThreadNum(), 0, acc);
+    }
+
+    /**
      * Allocates a new {@code Thread} object. This constructor has the same
      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
      * {@code (group, target, gname)} ,where {@code gname} is a newly generated
diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java
index c6941f2..48d8d17 100644
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java
@@ -456,6 +456,7 @@
         case "getDeclaredField":
         case "getDeclaredMethod":
         case "getDeclaredConstructor":
+        case "getDeclaringClass":
         case "getEnclosingClass":
         case "getEnclosingMethod":
         case "getEnclosingConstructor":
@@ -491,6 +492,7 @@
             return defc == java.lang.ClassLoader.class;
         case "registerAsParallelCapable":
             return defc == java.lang.ClassLoader.class;
+        case "getInvocationHandler":
         case "getProxyClass":
         case "newProxyInstance":
             return defc == java.lang.reflect.Proxy.class;
diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
index 2984501..0f7252e 100644
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
@@ -426,7 +426,7 @@
 
         Lookup(Class<?> lookupClass) {
             this(lookupClass, ALL_MODES);
-            checkUnprivilegedlookupClass(lookupClass);
+            checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
         }
 
         private Lookup(Class<?> lookupClass, int allowedModes) {
@@ -480,7 +480,7 @@
                 // No permissions.
                 newModes = 0;
             }
-            checkUnprivilegedlookupClass(requestedLookupClass);
+            checkUnprivilegedlookupClass(requestedLookupClass, newModes);
             return new Lookup(requestedLookupClass, newModes);
         }
 
@@ -496,10 +496,19 @@
         /** Package-private version of lookup which is trusted. */
         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
 
-        private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
+        private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
             String name = lookupClass.getName();
             if (name.startsWith("java.lang.invoke."))
                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
+
+            // For caller-sensitive MethodHandles.lookup()
+            // disallow lookup more restricted packages
+            if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
+                if (name.startsWith("java.") ||
+                        (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
+                    throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
+                }
+            }
         }
 
         /**
diff --git a/jdk/src/share/classes/java/lang/reflect/Proxy.java b/jdk/src/share/classes/java/lang/reflect/Proxy.java
index 26cfed0..1853f10 100644
--- a/jdk/src/share/classes/java/lang/reflect/Proxy.java
+++ b/jdk/src/share/classes/java/lang/reflect/Proxy.java
@@ -788,6 +788,7 @@
      * @throws  IllegalArgumentException if the argument is not a
      *          proxy instance
      */
+    @CallerSensitive
     public static InvocationHandler getInvocationHandler(Object proxy)
         throws IllegalArgumentException
     {
@@ -798,8 +799,19 @@
             throw new IllegalArgumentException("not a proxy instance");
         }
 
-        Proxy p = (Proxy) proxy;
-        return p.h;
+        final Proxy p = (Proxy) proxy;
+        final InvocationHandler ih = p.h;
+        if (System.getSecurityManager() != null) {
+            Class<?> ihClass = ih.getClass();
+            Class<?> caller = Reflection.getCallerClass();
+            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
+                                                    ihClass.getClassLoader()))
+            {
+                ReflectUtil.checkPackageAccess(ihClass);
+            }
+        }
+
+        return ih;
     }
 
     private static native Class defineClass0(ClassLoader loader, String name,
diff --git a/jdk/src/share/classes/java/net/Inet6Address.java b/jdk/src/share/classes/java/net/Inet6Address.java
index b5a4ced..92be0ec 100644
--- a/jdk/src/share/classes/java/net/Inet6Address.java
+++ b/jdk/src/share/classes/java/net/Inet6Address.java
@@ -26,6 +26,8 @@
 package java.net;
 
 import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamField;
 import java.io.IOException;
 import java.io.InvalidObjectException;
 import java.util.Enumeration;
@@ -171,36 +173,196 @@
      */
     private transient int cached_scope_id = 0;
 
-    /**
-     * Holds a 128-bit (16 bytes) IPv6 address.
-     *
-     * @serial
-     */
-    byte[] ipaddress;
+    private class Inet6AddressHolder {
 
-    /**
-     * scope_id. The scope specified when the object is created. If the object is created
-     * with an interface name, then the scope_id is not determined until the time it is needed.
-     */
-    private int scope_id = 0;
+        private Inet6AddressHolder() {
+            ipaddress = new byte[INADDRSZ];
+        }
 
-    /**
-     * This will be set to true when the scope_id field contains a valid
-     * integer scope_id.
-     */
-    private boolean scope_id_set = false;
+        private Inet6AddressHolder(
+            byte[] ipaddress, int scope_id, boolean scope_id_set,
+            NetworkInterface ifname, boolean scope_ifname_set)
+        {
+            this.ipaddress = ipaddress;
+            this.scope_id = scope_id;
+            this.scope_id_set = scope_id_set;
+            this.scope_ifname_set = scope_ifname_set;
+            this.scope_ifname = ifname;
+        }
 
-    /**
-     * scoped interface. scope_id is derived from this as the scope_id of the first
-     * address whose scope is the same as this address for the named interface.
-     */
-    private transient NetworkInterface scope_ifname = null;
+        /**
+         * Holds a 128-bit (16 bytes) IPv6 address.
+         */
+        byte[] ipaddress;
 
-    /**
-     * set if the object is constructed with a scoped interface instead of a
-     * numeric scope id.
-     */
-    private boolean scope_ifname_set = false;
+        /**
+         * scope_id. The scope specified when the object is created. If the object is created
+         * with an interface name, then the scope_id is not determined until the time it is needed.
+         */
+        int scope_id = 0;
+
+        /**
+         * This will be set to true when the scope_id field contains a valid
+         * integer scope_id.
+         */
+        boolean scope_id_set = false;
+
+        /**
+         * scoped interface. scope_id is derived from this as the scope_id of the first
+         * address whose scope is the same as this address for the named interface.
+         */
+        NetworkInterface scope_ifname = null;
+
+        /**
+         * set if the object is constructed with a scoped interface instead of a
+         * numeric scope id.
+         */
+        boolean scope_ifname_set = false;
+
+        void setAddr(byte addr[]) {
+            if (addr.length == INADDRSZ) { // normal IPv6 address
+                System.arraycopy(addr, 0, ipaddress, 0, INADDRSZ);
+            }
+        }
+
+        void init(byte addr[], int scope_id) {
+            setAddr(addr);
+
+            if (scope_id >= 0) {
+                this.scope_id = scope_id;
+                this.scope_id_set = true;
+            }
+        }
+
+        void init(byte addr[], NetworkInterface nif)
+            throws UnknownHostException
+        {
+            setAddr(addr);
+
+            if (nif != null) {
+                this.scope_id = deriveNumericScope(ipaddress, nif);
+                this.scope_id_set = true;
+                this.scope_ifname = nif;
+                this.scope_ifname_set = true;
+            }
+        }
+
+        String getHostAddress() {
+            String s = numericToTextFormat(ipaddress);
+            if (scope_ifname_set) { /* must check this first */
+                s = s + "%" + scope_ifname.getName();
+            } else if (scope_id_set) {
+                s = s + "%" + scope_id;
+            }
+            return s;
+        }
+
+        public boolean equals(Object o) {
+            if (! (o instanceof Inet6AddressHolder)) {
+                return false;
+            }
+            Inet6AddressHolder that = (Inet6AddressHolder)o;
+
+            for (int i = 0; i < INADDRSZ; i++) {
+                if (this.ipaddress[i] != that.ipaddress[i])
+                    return false;
+            }
+
+            return true;
+        }
+
+        public int hashCode() {
+            if (ipaddress != null) {
+
+                int hash = 0;
+                int i=0;
+                while (i<INADDRSZ) {
+                    int j=0;
+                    int component=0;
+                    while (j<4 && i<INADDRSZ) {
+                        component = (component << 8) + ipaddress[i];
+                        j++;
+                        i++;
+                    }
+                    hash += component;
+                }
+                return hash;
+
+            } else {
+                return 0;
+            }
+        }
+
+        boolean isIPv4CompatibleAddress() {
+            if ((ipaddress[0] == 0x00) && (ipaddress[1] == 0x00) &&
+                (ipaddress[2] == 0x00) && (ipaddress[3] == 0x00) &&
+                (ipaddress[4] == 0x00) && (ipaddress[5] == 0x00) &&
+                (ipaddress[6] == 0x00) && (ipaddress[7] == 0x00) &&
+                (ipaddress[8] == 0x00) && (ipaddress[9] == 0x00) &&
+                (ipaddress[10] == 0x00) && (ipaddress[11] == 0x00))  {
+                return true;
+            }
+            return false;
+        }
+
+        boolean isMulticastAddress() {
+            return ((ipaddress[0] & 0xff) == 0xff);
+        }
+
+        boolean isAnyLocalAddress() {
+            byte test = 0x00;
+            for (int i = 0; i < INADDRSZ; i++) {
+                test |= ipaddress[i];
+            }
+            return (test == 0x00);
+        }
+
+        boolean isLoopbackAddress() {
+            byte test = 0x00;
+            for (int i = 0; i < 15; i++) {
+                test |= ipaddress[i];
+            }
+            return (test == 0x00) && (ipaddress[15] == 0x01);
+        }
+
+        boolean isLinkLocalAddress() {
+            return ((ipaddress[0] & 0xff) == 0xfe
+                    && (ipaddress[1] & 0xc0) == 0x80);
+        }
+
+
+        boolean isSiteLocalAddress() {
+            return ((ipaddress[0] & 0xff) == 0xfe
+                    && (ipaddress[1] & 0xc0) == 0xc0);
+        }
+
+        boolean isMCGlobal() {
+            return ((ipaddress[0] & 0xff) == 0xff
+                    && (ipaddress[1] & 0x0f) == 0x0e);
+        }
+
+        boolean isMCNodeLocal() {
+            return ((ipaddress[0] & 0xff) == 0xff
+                    && (ipaddress[1] & 0x0f) == 0x01);
+        }
+
+        boolean isMCLinkLocal() {
+            return ((ipaddress[0] & 0xff) == 0xff
+                    && (ipaddress[1] & 0x0f) == 0x02);
+        }
+
+        boolean isMCSiteLocal() {
+            return ((ipaddress[0] & 0xff) == 0xff
+                    && (ipaddress[1] & 0x0f) == 0x05);
+        }
+
+        boolean isMCOrgLocal() {
+            return ((ipaddress[0] & 0xff) == 0xff
+                    && (ipaddress[1] & 0x0f) == 0x08);
+        }
+    }
+
+    private final transient Inet6AddressHolder holder6;
 
     private static final long serialVersionUID = 6880410070516793377L;
 
@@ -213,37 +375,33 @@
 
     Inet6Address() {
         super();
-        holder().hostName = null;
-        ipaddress = new byte[INADDRSZ];
-        holder().family = IPv6;
+        holder.init(null, IPv6);
+        holder6 = new Inet6AddressHolder();
     }
 
     /* checking of value for scope_id should be done by caller
      * scope_id must be >= 0, or -1 to indicate not being set
      */
     Inet6Address(String hostName, byte addr[], int scope_id) {
-        holder().hostName = hostName;
-        if (addr.length == INADDRSZ) { // normal IPv6 address
-            holder().family = IPv6;
-            ipaddress = addr.clone();
-        }
-        if (scope_id >= 0) {
-            this.scope_id = scope_id;
-            scope_id_set = true;
-        }
+        holder.init(hostName, IPv6);
+        holder6 = new Inet6AddressHolder();
+        holder6.init(addr, scope_id);
     }
 
     Inet6Address(String hostName, byte addr[]) {
+        holder6 = new Inet6AddressHolder();
         try {
             initif (hostName, addr, null);
         } catch (UnknownHostException e) {} /* cant happen if ifname is null */
     }
 
     Inet6Address (String hostName, byte addr[], NetworkInterface nif) throws UnknownHostException {
+        holder6 = new Inet6AddressHolder();
         initif (hostName, addr, nif);
     }
 
     Inet6Address (String hostName, byte addr[], String ifname) throws UnknownHostException {
+        holder6 = new Inet6AddressHolder();
         initstr (hostName, addr, ifname);
     }
 
@@ -325,17 +483,13 @@
     }
 
     private void initif(String hostName, byte addr[],NetworkInterface nif) throws UnknownHostException {
-        holder().hostName = hostName;
+        int family = -1;
+        holder6.init(addr, nif);
+
         if (addr.length == INADDRSZ) { // normal IPv6 address
-            holder().family = IPv6;
-            ipaddress = addr.clone();
+            family = IPv6;
         }
-        if (nif != null) {
-            this.scope_ifname = nif;
-            scope_ifname_set = true;
-            scope_id = deriveNumericScope (nif);
-            scope_id_set = true;
-        }
+        holder.init(hostName, family);
     }
 
     /* check the two Ipv6 addresses and return false if they are both
@@ -343,18 +497,21 @@
      * (ie. one is sitelocal and the other linklocal)
      * return true otherwise.
      */
-    private boolean differentLocalAddressTypes(Inet6Address other) {
+    private static boolean differentLocalAddressTypes(
+        byte[] thisAddr, byte[] otherAddr) {
 
-        if (isLinkLocalAddress() && !other.isLinkLocalAddress()) {
+        if (Inet6Address.isLinkLocalAddress(thisAddr) &&
+                !Inet6Address.isLinkLocalAddress(otherAddr)) {
             return false;
         }
-        if (isSiteLocalAddress() && !other.isSiteLocalAddress()) {
+        if (Inet6Address.isSiteLocalAddress(thisAddr) &&
+                !Inet6Address.isSiteLocalAddress(otherAddr)) {
             return false;
         }
         return true;
     }
 
-    private int deriveNumericScope (NetworkInterface ifc) throws UnknownHostException {
+    private static int deriveNumericScope (byte[] thisAddr, NetworkInterface ifc) throws UnknownHostException {
         Enumeration<InetAddress> addresses = ifc.getInetAddresses();
         while (addresses.hasMoreElements()) {
             InetAddress addr = addresses.nextElement();
@@ -363,12 +520,12 @@
             }
             Inet6Address ia6_addr = (Inet6Address)addr;
             /* check if site or link local prefixes match */
-            if (!differentLocalAddressTypes(ia6_addr)){
+            if (!differentLocalAddressTypes(thisAddr, ia6_addr.getAddress())){
                 /* type not the same, so carry on searching */
                 continue;
             }
             /* found a matching address - return its scope_id */
-            return ia6_addr.scope_id;
+            return ia6_addr.getScopeId();
         }
         throw new UnknownHostException ("no scope_id found");
     }
@@ -383,41 +540,61 @@
         while (en.hasMoreElements()) {
             NetworkInterface ifc = en.nextElement();
             if (ifc.getName().equals (ifname)) {
-                Enumeration addresses = ifc.getInetAddresses();
-                while (addresses.hasMoreElements()) {
-                    InetAddress addr = (InetAddress)addresses.nextElement();
-                    if (!(addr instanceof Inet6Address)) {
-                        continue;
-                    }
-                    Inet6Address ia6_addr = (Inet6Address)addr;
-                    /* check if site or link local prefixes match */
-                    if (!differentLocalAddressTypes(ia6_addr)){
-                        /* type not the same, so carry on searching */
-                        continue;
-                    }
-                    /* found a matching address - return its scope_id */
-                    return ia6_addr.scope_id;
-                }
+                return deriveNumericScope(holder6.ipaddress, ifc);
             }
         }
         throw new UnknownHostException ("No matching address found for interface : " +ifname);
     }
 
     /**
+     * @serialField ipaddress byte[]
+     * @serialField scope_id int
+     * @serialField scope_id_set boolean
+     * @serialField scope_ifname_set boolean
+     * @serialField ifname String
+     */
+
+    private static final ObjectStreamField[] serialPersistentFields = {
+         new ObjectStreamField("ipaddress", byte[].class),
+         new ObjectStreamField("scope_id", int.class),
+         new ObjectStreamField("scope_id_set", boolean.class),
+         new ObjectStreamField("scope_ifname_set", boolean.class),
+         new ObjectStreamField("ifname", String.class)
+    };
+
+    private static final long FIELDS_OFFSET;
+    private static final sun.misc.Unsafe UNSAFE;
+
+    static {
+        try {
+            sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
+            FIELDS_OFFSET = unsafe.objectFieldOffset(
+                    Inet6Address.class.getDeclaredField("holder6"));
+            UNSAFE = unsafe;
+        } catch (ReflectiveOperationException e) {
+            throw new Error(e);
+        }
+    }
+
+    /**
      * restore the state of this object from stream
      * including the scope information, only if the
      * scoped interface name is valid on this system
      */
     private void readObject(ObjectInputStream s)
         throws IOException, ClassNotFoundException {
-        scope_ifname = null;
-        scope_ifname_set = false;
+        NetworkInterface scope_ifname = null;
 
         if (getClass().getClassLoader() != null) {
             throw new SecurityException ("invalid address type");
         }
 
-        s.defaultReadObject();
+        ObjectInputStream.GetField gf = s.readFields();
+        byte[] ipaddress = (byte[])gf.get("ipaddress", null);
+        int scope_id = (int)gf.get("scope_id", -1);
+        boolean scope_id_set = (boolean)gf.get("scope_id_set", false);
+        boolean scope_ifname_set = (boolean)gf.get("scope_ifname_set", false);
+        String ifname = (String)gf.get("ifname", null);
 
         if (ifname != null && !"".equals (ifname)) {
             try {
@@ -430,7 +607,7 @@
                     scope_id = 0;
                 } else {
                     try {
-                        scope_id = deriveNumericScope (scope_ifname);
+                        scope_id = deriveNumericScope (ipaddress, scope_ifname);
                     } catch (UnknownHostException e) {
                         // typically should not happen, but it may be that
                         // the machine being used for deserialization has
@@ -438,8 +615,8 @@
                     }
                 }
             } catch (SocketException e) {}
-
         }
+
         /* if ifname was not supplied, then the numeric info is used */
 
         ipaddress = ipaddress.clone();
@@ -450,9 +627,37 @@
                                              ipaddress.length);
         }
 
-        if (holder().getFamily() != IPv6) {
+        if (holder.getFamily() != IPv6) {
             throw new InvalidObjectException("invalid address family type");
         }
+
+        Inet6AddressHolder h = new Inet6AddressHolder(
+            ipaddress, scope_id, scope_id_set, scope_ifname, scope_ifname_set
+        );
+
+        UNSAFE.putObject(this, FIELDS_OFFSET, h);
+    }
+
+    /**
+     * default behavior is overridden in order to write the
+     * scope_ifname field as a String, rather than a NetworkInterface
+     * which is not serializable
+     */
+    private synchronized void writeObject(ObjectOutputStream s)
+        throws IOException
+    {
+            String ifname = null;
+
+        if (holder6.scope_ifname_set) {
+            ifname = holder6.scope_ifname.getName();
+        }
+        ObjectOutputStream.PutField pfields = s.putFields();
+        pfields.put("ipaddress", holder6.ipaddress);
+        pfields.put("scope_id", holder6.scope_id);
+        pfields.put("scope_id_set", holder6.scope_id_set);
+        pfields.put("scope_ifname_set", holder6.scope_ifname_set);
+        pfields.put("ifname", ifname);
+        s.writeFields();
     }
 
     /**
@@ -466,7 +671,7 @@
      */
     @Override
     public boolean isMulticastAddress() {
-        return ((ipaddress[0] & 0xff) == 0xff);
+        return holder6.isMulticastAddress();
     }
 
     /**
@@ -477,11 +682,7 @@
      */
     @Override
     public boolean isAnyLocalAddress() {
-        byte test = 0x00;
-        for (int i = 0; i < INADDRSZ; i++) {
-            test |= ipaddress[i];
-        }
-        return (test == 0x00);
+        return holder6.isAnyLocalAddress();
     }
 
     /**
@@ -493,11 +694,7 @@
      */
     @Override
     public boolean isLoopbackAddress() {
-        byte test = 0x00;
-        for (int i = 0; i < 15; i++) {
-            test |= ipaddress[i];
-        }
-        return (test == 0x00) && (ipaddress[15] == 0x01);
+        return holder6.isLoopbackAddress();
     }
 
     /**
@@ -509,6 +706,11 @@
      */
     @Override
     public boolean isLinkLocalAddress() {
+        return holder6.isLinkLocalAddress();
+    }
+
+    /* static version of above */
+    static boolean isLinkLocalAddress(byte[] ipaddress) {
         return ((ipaddress[0] & 0xff) == 0xfe
                 && (ipaddress[1] & 0xc0) == 0x80);
     }
@@ -522,6 +724,11 @@
      */
     @Override
     public boolean isSiteLocalAddress() {
+        return holder6.isSiteLocalAddress();
+    }
+
+    /* static version of above */
+    static boolean isSiteLocalAddress(byte[] ipaddress) {
         return ((ipaddress[0] & 0xff) == 0xfe
                 && (ipaddress[1] & 0xc0) == 0xc0);
     }
@@ -536,8 +743,7 @@
      */
     @Override
     public boolean isMCGlobal() {
-        return ((ipaddress[0] & 0xff) == 0xff
-                && (ipaddress[1] & 0x0f) == 0x0e);
+        return holder6.isMCGlobal();
     }
 
     /**
@@ -550,8 +756,7 @@
      */
     @Override
     public boolean isMCNodeLocal() {
-        return ((ipaddress[0] & 0xff) == 0xff
-                && (ipaddress[1] & 0x0f) == 0x01);
+        return holder6.isMCNodeLocal();
     }
 
     /**
@@ -564,8 +769,7 @@
      */
     @Override
     public boolean isMCLinkLocal() {
-        return ((ipaddress[0] & 0xff) == 0xff
-                && (ipaddress[1] & 0x0f) == 0x02);
+        return holder6.isMCLinkLocal();
     }
 
     /**
@@ -578,8 +782,7 @@
      */
     @Override
     public boolean isMCSiteLocal() {
-        return ((ipaddress[0] & 0xff) == 0xff
-                && (ipaddress[1] & 0x0f) == 0x05);
+        return holder6.isMCSiteLocal();
     }
 
     /**
@@ -593,10 +796,8 @@
      */
     @Override
     public boolean isMCOrgLocal() {
-        return ((ipaddress[0] & 0xff) == 0xff
-                && (ipaddress[1] & 0x0f) == 0x08);
+        return holder6.isMCOrgLocal();
     }
-
     /**
      * Returns the raw IP address of this <code>InetAddress</code>
      * object. The result is in network byte order: the highest order
@@ -606,7 +807,7 @@
      */
     @Override
     public byte[] getAddress() {
-        return ipaddress.clone();
+        return holder6.ipaddress.clone();
     }
 
     /**
@@ -617,7 +818,7 @@
      * @since 1.5
      */
      public int getScopeId () {
-        return scope_id;
+        return holder6.scope_id;
      }
 
     /**
@@ -628,7 +829,7 @@
      * @since 1.5
      */
      public NetworkInterface getScopedInterface () {
-        return scope_ifname;
+        return holder6.scope_ifname;
      }
 
     /**
@@ -641,13 +842,7 @@
      */
     @Override
     public String getHostAddress() {
-        String s = numericToTextFormat(ipaddress);
-        if (scope_ifname_set) { /* must check this first */
-            s = s + "%" + scope_ifname.getName();
-        } else if (scope_id_set) {
-            s = s + "%" + scope_id;
-        }
-        return s;
+        return holder6.getHostAddress();
     }
 
     /**
@@ -657,25 +852,7 @@
      */
     @Override
     public int hashCode() {
-        if (ipaddress != null) {
-
-            int hash = 0;
-            int i=0;
-            while (i<INADDRSZ) {
-                int j=0;
-                int component=0;
-                while (j<4 && i<INADDRSZ) {
-                    component = (component << 8) + ipaddress[i];
-                    j++;
-                    i++;
-                }
-                hash += component;
-            }
-            return hash;
-
-        } else {
-            return 0;
-        }
+        return holder6.hashCode();
     }
 
     /**
@@ -702,12 +879,7 @@
 
         Inet6Address inetAddr = (Inet6Address)obj;
 
-        for (int i = 0; i < INADDRSZ; i++) {
-            if (ipaddress[i] != inetAddr.ipaddress[i])
-                return false;
-        }
-
-        return true;
+        return holder6.equals(inetAddr.holder6);
     }
 
     /**
@@ -719,15 +891,7 @@
      * @since 1.4
      */
     public boolean isIPv4CompatibleAddress() {
-        if ((ipaddress[0] == 0x00) && (ipaddress[1] == 0x00) &&
-            (ipaddress[2] == 0x00) && (ipaddress[3] == 0x00) &&
-            (ipaddress[4] == 0x00) && (ipaddress[5] == 0x00) &&
-            (ipaddress[6] == 0x00) && (ipaddress[7] == 0x00) &&
-            (ipaddress[8] == 0x00) && (ipaddress[9] == 0x00) &&
-            (ipaddress[10] == 0x00) && (ipaddress[11] == 0x00))  {
-            return true;
-        }
-        return false;
+        return holder6.isIPv4CompatibleAddress();
     }
 
     // Utilities
@@ -757,23 +921,4 @@
      * Perform class load-time initializations.
      */
     private static native void init();
-
-    /**
-     * Following field is only used during (de)/serialization
-     */
-    private String ifname;
-
-    /**
-     * default behavior is overridden in order to write the
-     * scope_ifname field as a String, rather than a NetworkInterface
-     * which is not serializable
-     */
-    private synchronized void writeObject(java.io.ObjectOutputStream s)
-        throws IOException
-    {
-        if (scope_ifname_set) {
-            ifname = scope_ifname.getName();
-        }
-        s.defaultWriteObject();
-    }
 }
diff --git a/jdk/src/share/classes/java/net/InetAddress.java b/jdk/src/share/classes/java/net/InetAddress.java
index 3ea28e4..1034169 100644
--- a/jdk/src/share/classes/java/net/InetAddress.java
+++ b/jdk/src/share/classes/java/net/InetAddress.java
@@ -213,6 +213,13 @@
             this.family = family;
         }
 
+        void init(String hostName, int family) {
+            this.hostName = hostName;
+            if (family != -1) {
+                this.family = family;
+            }
+        }
+
         String hostName;
 
         String getHostName() {
diff --git a/jdk/src/share/classes/java/util/TimeZone.java b/jdk/src/share/classes/java/util/TimeZone.java
index 63f1028..697ea2c 100644
--- a/jdk/src/share/classes/java/util/TimeZone.java
+++ b/jdk/src/share/classes/java/util/TimeZone.java
@@ -165,6 +165,11 @@
     // Proclaim serialization compatibility with JDK 1.1
     static final long serialVersionUID = 3581463369166924961L;
 
+    // TimeZone.setDefault maintains the compatible behavior of the AppContext-based
+    // default setting for untrusted code if allowSetDefault is true.
+    private static final boolean allowSetDefault = AccessController.doPrivileged(
+        new sun.security.action.GetPropertyAction("jdk.util.TimeZone.allowSetDefault")) != null;
+
     /**
      * Gets the time zone offset, for current date, modified in case of
      * daylight savings. This is the offset to add to UTC to get local time.
@@ -689,6 +694,9 @@
                 sm.checkPermission(new PropertyPermission
                                    ("user.timezone", "write"));
             } catch (SecurityException e) {
+                if (!allowSetDefault) {
+                    throw e;
+                }
                 hasPermission = false;
             }
         }
@@ -719,6 +727,7 @@
      * Returns the default TimeZone in an AppContext if any AppContext
      * has ever used. null is returned if any AppContext hasn't been
      * used or if the AppContext doesn't have the default TimeZone.
+     * null is also returned if allowSetDefault is false.
      *
      * Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't
      * been loaded. If so, it implies that AWTSecurityManager is not our
@@ -726,18 +735,20 @@
      * This works around a build time issue.
      */
     private static TimeZone getDefaultInAppContext() {
-        // JavaAWTAccess provides access implementation-private methods without using reflection.
-        JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
-        if (javaAWTAccess == null) {
-            return mainAppContextDefault;
-        } else {
-            if (!javaAWTAccess.isDisposed()) {
-                TimeZone tz = (TimeZone)
-                    javaAWTAccess.get(TimeZone.class);
-                if (tz == null && javaAWTAccess.isMainAppContext()) {
-                    return mainAppContextDefault;
-                } else {
-                    return tz;
+        if (allowSetDefault) {
+            // JavaAWTAccess provides access implementation-private methods without using reflection.
+            JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
+            if (javaAWTAccess == null) {
+                return mainAppContextDefault;
+            } else {
+                if (!javaAWTAccess.isDisposed()) {
+                    TimeZone tz = (TimeZone)
+                        javaAWTAccess.get(TimeZone.class);
+                    if (tz == null && javaAWTAccess.isMainAppContext()) {
+                        return mainAppContextDefault;
+                    } else {
+                        return tz;
+                    }
                 }
             }
         }
@@ -745,9 +756,9 @@
     }
 
     /**
-     * Sets the default TimeZone in the AppContext to the given
-     * tz. null is handled special: do nothing if any AppContext
-     * hasn't been used, remove the default TimeZone in the
+     * Sets the default TimeZone in the AppContext to the given tz if
+     * allowSetDefault is true. null is handled special: do nothing if any
+     * AppContext hasn't been used, remove the default TimeZone in the
      * AppContext otherwise.
      *
      * Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't
@@ -756,15 +767,17 @@
      * This works around a build time issue.
      */
     private static void setDefaultInAppContext(TimeZone tz) {
-        // JavaAWTAccess provides access implementation-private methods without using reflection.
-        JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
-        if (javaAWTAccess == null) {
-            mainAppContextDefault = tz;
-        } else {
-            if (!javaAWTAccess.isDisposed()) {
-                javaAWTAccess.put(TimeZone.class, tz);
-                if (javaAWTAccess.isMainAppContext()) {
-                    mainAppContextDefault = null;
+        if (allowSetDefault) {
+            // JavaAWTAccess provides access implementation-private methods without using reflection.
+            JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
+            if (javaAWTAccess == null) {
+                mainAppContextDefault = tz;
+            } else {
+                if (!javaAWTAccess.isDisposed()) {
+                    javaAWTAccess.put(TimeZone.class, tz);
+                    if (javaAWTAccess.isMainAppContext()) {
+                        mainAppContextDefault = null;
+                    }
                 }
             }
         }
diff --git a/jdk/src/share/classes/javax/management/BadAttributeValueExpException.java b/jdk/src/share/classes/javax/management/BadAttributeValueExpException.java
index 9ed27e9..2c924f5 100644
--- a/jdk/src/share/classes/javax/management/BadAttributeValueExpException.java
+++ b/jdk/src/share/classes/javax/management/BadAttributeValueExpException.java
@@ -25,6 +25,9 @@
 
 package javax.management;
 
+import java.io.IOException;
+import java.io.ObjectInputStream;
+
 
 /**
  * Thrown when an invalid MBean attribute is passed to a query
@@ -51,7 +54,7 @@
      * @param val the inappropriate value.
      */
     public BadAttributeValueExpException (Object val) {
-        this.val = val;
+        this.val = val == null ? null : val.toString();
     }
 
 
@@ -62,4 +65,25 @@
         return "BadAttributeValueException: " + val;
     }
 
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField gf = ois.readFields();
+        Object valObj = gf.get("val", null);
+
+        if (valObj == null) {
+            val = null;
+        } else if (valObj instanceof String) {
+            val= valObj;
+        } else if (System.getSecurityManager() == null
+                || valObj instanceof Long
+                || valObj instanceof Integer
+                || valObj instanceof Float
+                || valObj instanceof Double
+                || valObj instanceof Byte
+                || valObj instanceof Short
+                || valObj instanceof Boolean) {
+            val = valObj.toString();
+        } else { // the serialized object is from a version without JDK-8019292 fix
+            val = System.identityHashCode(valObj) + "@" + valObj.getClass().getName();
+        }
+    }
  }
diff --git a/jdk/src/share/classes/javax/management/MBeanNotificationInfo.java b/jdk/src/share/classes/javax/management/MBeanNotificationInfo.java
index b4bbbe8..e3b4aba 100644
--- a/jdk/src/share/classes/javax/management/MBeanNotificationInfo.java
+++ b/jdk/src/share/classes/javax/management/MBeanNotificationInfo.java
@@ -25,6 +25,9 @@
 
 package javax.management;
 
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
 import java.util.Arrays;
 
 /**
@@ -67,7 +70,7 @@
     /**
      * @serial The different types of the notification.
      */
-    private final String[] types;
+    private String[] types;
 
     /** @see MBeanInfo#arrayGettersSafe */
     private final transient boolean arrayGettersSafe;
@@ -114,9 +117,8 @@
            notifType, though it doesn't explicitly allow it
            either.  */
 
-        if (notifTypes == null)
-            notifTypes = NO_TYPES;
-        this.types = notifTypes;
+        this.types = (notifTypes != null && notifTypes.length > 0) ?
+                        notifTypes.clone() : NO_TYPES;
         this.arrayGettersSafe =
             MBeanInfo.arrayGettersSafe(this.getClass(),
                                        MBeanNotificationInfo.class);
@@ -203,4 +205,11 @@
             hash ^= types[i].hashCode();
         return hash;
     }
+
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField gf = ois.readFields();
+        String[] t = (String[])gf.get("types", null);
+
+        types = (t != null && t.length != 0) ? t.clone() : NO_TYPES;
+    }
 }
diff --git a/jdk/src/share/classes/javax/management/MBeanTrustPermission.java b/jdk/src/share/classes/javax/management/MBeanTrustPermission.java
index 040f0dd..605201a 100644
--- a/jdk/src/share/classes/javax/management/MBeanTrustPermission.java
+++ b/jdk/src/share/classes/javax/management/MBeanTrustPermission.java
@@ -26,6 +26,9 @@
 package javax.management;
 
 import java.security.BasicPermission;
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
 
 /**
  * This permission represents "trust" in a signer or codebase.
@@ -75,15 +78,31 @@
      */
     public MBeanTrustPermission(String name, String actions) {
         super(name, actions);
-        /* Check that actions is a null empty string */
-        if (actions != null && actions.length() > 0)
-            throw new IllegalArgumentException("MBeanTrustPermission " +
-                                               "actions must be null: " +
-                                               actions);
+        validate(name,actions);
+    }
 
-        if (!name.equals("register") && !name.equals("*"))
-            throw new IllegalArgumentException("MBeanTrustPermission: " +
-                                               "Unknown target name " +
+    private static void validate(String name, String actions) {
+        /* Check that actions is a null empty string */
+        if (actions != null && actions.length() > 0) {
+            throw new IllegalArgumentException("MBeanTrustPermission actions must be null: " +
+                                               actions);
+        }
+
+        if (!name.equals("register") && !name.equals("*")) {
+            throw new IllegalArgumentException("MBeanTrustPermission: Unknown target name " +
                                                "[" + name + "]");
+        }
+    }
+
+    private void readObject(ObjectInputStream in)
+         throws IOException, ClassNotFoundException {
+
+        // Reading private fields of base class
+        in.defaultReadObject();
+        try {
+            validate(super.getName(),super.getActions());
+        } catch (IllegalArgumentException e) {
+            throw new InvalidObjectException(e.getMessage());
+        }
     }
 }
diff --git a/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java b/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java
index 039ff9d..0afd70f 100644
--- a/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java
+++ b/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -298,11 +298,15 @@
                     RequiredModelMBean.class.getName(),
                 "setModelMBeanInfo(ModelMBeanInfo)",
                 "Setting ModelMBeanInfo to " + printModelMBeanInfo(mbi));
+            int noOfNotifications = 0;
+            if (mbi.getNotifications() != null) {
+                noOfNotifications = mbi.getNotifications().length;
+            }
             MODELMBEAN_LOGGER.logp(Level.FINER,
                     RequiredModelMBean.class.getName(),
                 "setModelMBeanInfo(ModelMBeanInfo)",
                 "ModelMBeanInfo notifications has " +
-                (mbi.getNotifications()).length + " elements");
+                noOfNotifications + " elements");
         }
 
         modelMBeanInfo = (ModelMBeanInfo)mbi.clone();
@@ -2997,4 +3001,4 @@
             Void.class.getName()
         };
     }
-}
\ No newline at end of file
+}
diff --git a/jdk/src/share/classes/javax/management/remote/JMXPrincipal.java b/jdk/src/share/classes/javax/management/remote/JMXPrincipal.java
index 258c537..5cb0c37 100644
--- a/jdk/src/share/classes/javax/management/remote/JMXPrincipal.java
+++ b/jdk/src/share/classes/javax/management/remote/JMXPrincipal.java
@@ -26,6 +26,9 @@
 
 package javax.management.remote;
 
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
 import java.io.Serializable;
 import java.security.Principal;
 
@@ -64,9 +67,7 @@
      * <code>null</code>.
      */
     public JMXPrincipal(String name) {
-        if (name == null)
-            throw new NullPointerException("illegal null input");
-
+        validate(name);
         this.name = name;
     }
 
@@ -130,4 +131,20 @@
     public int hashCode() {
         return name.hashCode();
     }
+
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField gf = ois.readFields();
+        String principalName = (String)gf.get("name", null);
+        try {
+            validate(principalName);
+            this.name = principalName;
+        } catch (NullPointerException e) {
+            throw new InvalidObjectException(e.getMessage());
+        }
+    }
+
+    private static void validate(String name) throws NullPointerException {
+        if (name == null)
+            throw new NullPointerException("illegal null input");
+    }
 }
diff --git a/jdk/src/share/classes/javax/management/remote/JMXServiceURL.java b/jdk/src/share/classes/javax/management/remote/JMXServiceURL.java
index 143966b..4b1c376 100644
--- a/jdk/src/share/classes/javax/management/remote/JMXServiceURL.java
+++ b/jdk/src/share/classes/javax/management/remote/JMXServiceURL.java
@@ -29,6 +29,9 @@
 
 import com.sun.jmx.remote.util.ClassLogger;
 import com.sun.jmx.remote.util.EnvHelp;
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
 
 import java.io.Serializable;
 import java.net.InetAddress;
@@ -297,7 +300,7 @@
                If we're given an explicit host name that is illegal we
                have to reject it.  (Bug 5057532.)  */
             try {
-                validateHost(host);
+                validateHost(host, port);
             } catch (MalformedURLException e) {
                 if (logger.fineOn()) {
                     logger.fine("JMXServiceURL",
@@ -336,36 +339,82 @@
         validate();
     }
 
-    private void validate() throws MalformedURLException {
+    private static final String INVALID_INSTANCE_MSG =
+            "Trying to deserialize an invalid instance of JMXServiceURL";
+    private void readObject(ObjectInputStream  inputStream) throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField gf = inputStream.readFields();
+        String h = (String)gf.get("host", null);
+        int p = (int)gf.get("port", -1);
+        String proto = (String)gf.get("protocol", null);
+        String url = (String)gf.get("urlPath", null);
 
+        if (proto == null || url == null || h == null) {
+            StringBuilder sb = new StringBuilder(INVALID_INSTANCE_MSG).append('[');
+            boolean empty = true;
+            if (proto == null) {
+                sb.append("protocol=null");
+                empty = false;
+            }
+            if (h == null) {
+                sb.append(empty ? "" : ",").append("host=null");
+                empty = false;
+            }
+            if (url == null) {
+                sb.append(empty ? "" : ",").append("urlPath=null");
+            }
+            sb.append(']');
+            throw new InvalidObjectException(sb.toString());
+        }
+
+        if (h.contains("[") || h.contains("]")) {
+            throw new InvalidObjectException("Invalid host name: " + h);
+        }
+
+        try {
+            validate(proto, h, p, url);
+            this.protocol = proto;
+            this.host = h;
+            this.port = p;
+            this.urlPath = url;
+        } catch (MalformedURLException e) {
+            throw new InvalidObjectException(INVALID_INSTANCE_MSG + ": " +
+                                             e.getMessage());
+        }
+
+    }
+
+    private void validate(String proto, String h, int p, String url)
+        throws MalformedURLException {
         // Check protocol
-
-        final int protoEnd = indexOfFirstNotInSet(protocol, protocolBitSet, 0);
-        if (protoEnd == 0 || protoEnd < protocol.length()
-            || !alphaBitSet.get(protocol.charAt(0))) {
+        final int protoEnd = indexOfFirstNotInSet(proto, protocolBitSet, 0);
+        if (protoEnd == 0 || protoEnd < proto.length()
+            || !alphaBitSet.get(proto.charAt(0))) {
             throw new MalformedURLException("Missing or invalid protocol " +
-                                            "name: \"" + protocol + "\"");
+                                            "name: \"" + proto + "\"");
         }
 
         // Check host
-
-        validateHost();
+        validateHost(h, p);
 
         // Check port
-
-        if (port < 0)
-            throw new MalformedURLException("Bad port: " + port);
+        if (p < 0)
+            throw new MalformedURLException("Bad port: " + p);
 
         // Check URL path
-
-        if (urlPath.length() > 0) {
-            if (!urlPath.startsWith("/") && !urlPath.startsWith(";"))
-                throw new MalformedURLException("Bad URL path: " + urlPath);
+        if (url.length() > 0) {
+            if (!url.startsWith("/") && !url.startsWith(";"))
+                throw new MalformedURLException("Bad URL path: " + url);
         }
     }
 
-    private void validateHost() throws MalformedURLException {
-        if (host.length() == 0) {
+    private void validate() throws MalformedURLException {
+        validate(this.protocol, this.host, this.port, this.urlPath);
+    }
+
+    private static void validateHost(String h, int port)
+            throws MalformedURLException {
+
+        if (h.length() == 0) {
             if (port != 0) {
                 throw new MalformedURLException("Cannot give port number " +
                                                 "without host name");
@@ -373,12 +422,6 @@
             return;
         }
 
-        validateHost(host);
-    }
-
-    private static void validateHost(String h)
-            throws MalformedURLException {
-
         if (isNumericIPv6Address(h)) {
             /* We assume J2SE >= 1.4 here.  Otherwise you can't
                use the address anyway.  We can't call
@@ -663,22 +706,22 @@
     /**
      * The value returned by {@link #getProtocol()}.
      */
-    private final String protocol;
+    private String protocol;
 
     /**
      * The value returned by {@link #getHost()}.
      */
-    private final String host;
+    private String host;
 
     /**
      * The value returned by {@link #getPort()}.
      */
-    private final int port;
+    private int port;
 
     /**
      * The value returned by {@link #getURLPath()}.
      */
-    private final String urlPath;
+    private String urlPath;
 
     /**
      * Cached result of {@link #toString()}.
diff --git a/jdk/src/share/classes/javax/management/remote/NotificationResult.java b/jdk/src/share/classes/javax/management/remote/NotificationResult.java
index cbc7975..ff3978d 100644
--- a/jdk/src/share/classes/javax/management/remote/NotificationResult.java
+++ b/jdk/src/share/classes/javax/management/remote/NotificationResult.java
@@ -25,6 +25,9 @@
 
 package javax.management.remote;
 
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
 import java.io.Serializable;
 
 /**
@@ -76,17 +79,7 @@
     public NotificationResult(long earliestSequenceNumber,
                               long nextSequenceNumber,
                               TargetedNotification[] targetedNotifications) {
-        if (targetedNotifications == null) {
-            final String msg = "Notifications null";
-            throw new IllegalArgumentException(msg);
-        }
-
-        if (earliestSequenceNumber < 0 || nextSequenceNumber < 0)
-            throw new IllegalArgumentException("Bad sequence numbers");
-        /* We used to check nextSequenceNumber >= earliestSequenceNumber
-           here.  But in fact the opposite can legitimately be true if
-           notifications have been lost.  */
-
+        validate(targetedNotifications, earliestSequenceNumber, nextSequenceNumber);
         this.earliestSequenceNumber = earliestSequenceNumber;
         this.nextSequenceNumber = nextSequenceNumber;
         this.targetedNotifications = (targetedNotifications.length == 0 ? targetedNotifications : targetedNotifications.clone());
@@ -138,7 +131,40 @@
             getTargetedNotifications().length;
     }
 
-    private final long earliestSequenceNumber;
-    private final long nextSequenceNumber;
-    private final TargetedNotification[] targetedNotifications;
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        ois.defaultReadObject();
+        try {
+            validate(
+                this.targetedNotifications,
+                this.earliestSequenceNumber,
+                this.nextSequenceNumber
+            );
+
+            this.targetedNotifications = this.targetedNotifications.length == 0 ?
+                                            this.targetedNotifications :
+                                            this.targetedNotifications.clone();
+        } catch (IllegalArgumentException e) {
+            throw new InvalidObjectException(e.getMessage());
+        }
+    }
+
+    private long earliestSequenceNumber;
+    private long nextSequenceNumber;
+    private TargetedNotification[] targetedNotifications;
+
+    private static void validate(TargetedNotification[] targetedNotifications,
+                                 long earliestSequenceNumber,
+                                 long nextSequenceNumber)
+        throws IllegalArgumentException {
+        if (targetedNotifications == null) {
+            final String msg = "Notifications null";
+            throw new IllegalArgumentException(msg);
+        }
+
+        if (earliestSequenceNumber < 0 || nextSequenceNumber < 0)
+            throw new IllegalArgumentException("Bad sequence numbers");
+        /* We used to check nextSequenceNumber >= earliestSequenceNumber
+           here.  But in fact the opposite can legitimately be true if
+           notifications have been lost.  */
+    }
 }
diff --git a/jdk/src/share/classes/javax/management/remote/TargetedNotification.java b/jdk/src/share/classes/javax/management/remote/TargetedNotification.java
index c4b58df..cc3d0dc 100644
--- a/jdk/src/share/classes/javax/management/remote/TargetedNotification.java
+++ b/jdk/src/share/classes/javax/management/remote/TargetedNotification.java
@@ -26,6 +26,9 @@
 
 package javax.management.remote;
 
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
 import java.io.Serializable;
 import javax.management.Notification;
 
@@ -73,12 +76,9 @@
      */
     public TargetedNotification(Notification notification,
                                 Integer listenerID) {
+        validate(notification, listenerID);
         // If we replace integer with int...
         // this(notification,intValue(listenerID));
-        if (notification == null) throw new
-            IllegalArgumentException("Invalid notification: null");
-        if (listenerID == null) throw new
-            IllegalArgumentException("Invalid listener ID: null");
         this.notif = notification;
         this.id = listenerID;
     }
@@ -115,13 +115,13 @@
      * @serial A notification to transmit to the other side.
      * @see #getNotification()
      **/
-    private final Notification notif;
+    private Notification notif;
     /**
      * @serial The ID of the listener to which the notification is
      *         targeted.
      * @see #getListenerID()
      **/
-    private final Integer id;
+    private Integer id;
     //private final int id;
 
 // Needed if we use int instead of Integer...
@@ -130,4 +130,22 @@
 //          IllegalArgumentException("Invalid listener ID: null");
 //      return id.intValue();
 //     }
+
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        ois.defaultReadObject();
+        try {
+            validate(this.notif, this.id);
+        } catch (IllegalArgumentException e) {
+            throw new InvalidObjectException(e.getMessage());
+        }
+    }
+
+    private static void validate(Notification notif, Integer id) throws IllegalArgumentException {
+        if (notif == null) {
+            throw new IllegalArgumentException("Invalid notification: null");
+        }
+        if (id == null) {
+            throw new IllegalArgumentException("Invalid listener ID: null");
+        }
+    }
 }
diff --git a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java
index dec148a..4ddfb8f 100644
--- a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java
+++ b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -61,6 +61,7 @@
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.security.PrivilegedExceptionAction;
+import java.security.PrivilegedActionException;
 import java.security.ProtectionDomain;
 import java.util.Arrays;
 import java.util.Collections;
@@ -128,7 +129,6 @@
             Map<String, ?> environment) {
         if (rmiServer == null && address == null) throw new
                 IllegalArgumentException("rmiServer and jmxServiceURL both null");
-
         initTransients();
 
         this.rmiServer = rmiServer;
@@ -239,10 +239,21 @@
     //--------------------------------------------------------------------
     // implements JMXConnector interface
     //--------------------------------------------------------------------
+
+    /**
+     * @throws IOException if the connection could not be made because of a
+     *   communication problem, or in the case of the {@code iiop} protocol,
+     *   that RMI/IIOP is not supported
+     */
     public void connect() throws IOException {
         connect(null);
     }
 
+    /**
+     * @throws IOException if the connection could not be made because of a
+     *   communication problem, or in the case of the {@code iiop} protocol,
+     *   that RMI/IIOP is not supported
+     */
     public synchronized void connect(Map<String,?> environment)
     throws IOException {
         final boolean tracing = logger.traceOn();
@@ -2359,13 +2370,21 @@
         }
     }
 
-    private static RMIConnection shadowIiopStub(Object stub)
+  private static RMIConnection shadowIiopStub(Object stub)
     throws InstantiationException, IllegalAccessException {
-        Object proxyStub = proxyStubClass.newInstance();
+        Object proxyStub = null;
+        try {
+            proxyStub = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
+                public Object run() throws Exception {
+                    return proxyStubClass.newInstance();
+                }
+            });
+        } catch (PrivilegedActionException e) {
+            throw new InternalError();
+        }
         IIOPHelper.setDelegate(proxyStub, IIOPHelper.getDelegate(stub));
         return (RMIConnection) proxyStub;
     }
-
     private static RMIConnection getConnection(RMIServer server,
             Object credentials,
             boolean checkStub)
diff --git a/jdk/src/share/classes/javax/security/auth/Subject.java b/jdk/src/share/classes/javax/security/auth/Subject.java
index 56e864c..02dcc72 100644
--- a/jdk/src/share/classes/javax/security/auth/Subject.java
+++ b/jdk/src/share/classes/javax/security/auth/Subject.java
@@ -1296,8 +1296,14 @@
         {
             ObjectInputStream.GetField fields = ois.readFields();
             subject = (Subject) fields.get("this$0", null);
-            elements = (LinkedList<E>) fields.get("elements", null);
             which = fields.get("which", 0);
+
+            LinkedList<E> tmp = (LinkedList<E>) fields.get("elements", null);
+            if (tmp.getClass() != LinkedList.class) {
+                elements = new LinkedList<E>(tmp);
+            } else {
+                elements = tmp;
+            }
         }
     }
 
diff --git a/jdk/src/share/classes/javax/swing/JTable.java b/jdk/src/share/classes/javax/swing/JTable.java
index 9313cc9..b205afc 100644
--- a/jdk/src/share/classes/javax/swing/JTable.java
+++ b/jdk/src/share/classes/javax/swing/JTable.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -52,6 +52,7 @@
 
 import javax.print.attribute.*;
 import javax.print.PrintService;
+import sun.reflect.misc.ReflectUtil;
 
 import sun.swing.SwingUtilities2;
 import sun.swing.SwingUtilities2.Section;
@@ -5460,14 +5461,16 @@
             // they have the option to replace the value with
             // null or use escape to restore the original.
             // For Strings, return "" for backward compatibility.
-            if ("".equals(s)) {
-                if (constructor.getDeclaringClass() == String.class) {
-                    value = s;
-                }
-                return super.stopCellEditing();
-            }
 
             try {
+                if ("".equals(s)) {
+                    if (constructor.getDeclaringClass() == String.class) {
+                        value = s;
+                    }
+                    return super.stopCellEditing();
+                }
+
+                SwingUtilities2.checkAccess(constructor.getModifiers());
                 value = constructor.newInstance(new Object[]{s});
             }
             catch (Exception e) {
@@ -5491,6 +5494,8 @@
                 if (type == Object.class) {
                     type = String.class;
                 }
+                ReflectUtil.checkPackageAccess(type);
+                SwingUtilities2.checkAccess(type.getModifiers());
                 constructor = type.getConstructor(argTypes);
             }
             catch (Exception e) {
diff --git a/jdk/src/share/classes/javax/swing/UIDefaults.java b/jdk/src/share/classes/javax/swing/UIDefaults.java
index 9f304e7..3bd1297 100644
--- a/jdk/src/share/classes/javax/swing/UIDefaults.java
+++ b/jdk/src/share/classes/javax/swing/UIDefaults.java
@@ -53,6 +53,7 @@
 
 import sun.reflect.misc.MethodUtil;
 import sun.reflect.misc.ReflectUtil;
+import sun.swing.SwingUtilities2;
 import sun.util.CoreResourceBundleControl;
 
 /**
@@ -1101,7 +1102,7 @@
                         }
                         ReflectUtil.checkPackageAccess(className);
                         c = Class.forName(className, true, (ClassLoader)cl);
-                        checkAccess(c.getModifiers());
+                        SwingUtilities2.checkAccess(c.getModifiers());
                         if (methodName != null) {
                             Class[] types = getClassArray(args);
                             Method m = c.getMethod(methodName, types);
@@ -1109,7 +1110,7 @@
                         } else {
                             Class[] types = getClassArray(args);
                             Constructor constructor = c.getConstructor(types);
-                            checkAccess(constructor.getModifiers());
+                            SwingUtilities2.checkAccess(constructor.getModifiers());
                             return constructor.newInstance(args);
                         }
                     } catch(Exception e) {
@@ -1124,13 +1125,6 @@
             }, acc);
         }
 
-        private void checkAccess(int modifiers) {
-            if(System.getSecurityManager() != null &&
-                    !Modifier.isPublic(modifiers)) {
-                throw new SecurityException("Resource is not accessible");
-            }
-        }
-
         /*
          * Coerce the array of class types provided into one which
          * looks the way the Reflection APIs expect.  This is done
diff --git a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java
index b67966a..ac5bc72 100644
--- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java
+++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java
@@ -24,7 +24,8 @@
  */
 package javax.swing.text;
 
-import sun.reflect.misc.ConstructorUtil;
+import sun.reflect.misc.ReflectUtil;
+import sun.swing.SwingUtilities2;
 
 import java.io.Serializable;
 import java.lang.reflect.*;
@@ -247,7 +248,9 @@
             Constructor cons;
 
             try {
-                cons = ConstructorUtil.getConstructor(vc, new Class[]{String.class});
+                ReflectUtil.checkPackageAccess(vc);
+                SwingUtilities2.checkAccess(vc.getModifiers());
+                cons = vc.getConstructor(new Class[]{String.class});
 
             } catch (NoSuchMethodException nsme) {
                 cons = null;
@@ -255,6 +258,7 @@
 
             if (cons != null) {
                 try {
+                    SwingUtilities2.checkAccess(cons.getModifiers());
                     return cons.newInstance(new Object[] { string });
                 } catch (Throwable ex) {
                     throw new ParseException("Error creating instance", 0);
diff --git a/jdk/src/share/classes/javax/swing/text/NumberFormatter.java b/jdk/src/share/classes/javax/swing/text/NumberFormatter.java
index 9500dcc..672a92e 100644
--- a/jdk/src/share/classes/javax/swing/text/NumberFormatter.java
+++ b/jdk/src/share/classes/javax/swing/text/NumberFormatter.java
@@ -27,6 +27,8 @@
 import java.lang.reflect.*;
 import java.text.*;
 import java.util.*;
+import sun.reflect.misc.ReflectUtil;
+import sun.swing.SwingUtilities2;
 
 /**
  * <code>NumberFormatter</code> subclasses <code>InternationalFormatter</code>
@@ -427,10 +429,12 @@
                         valueClass = value.getClass();
                     }
                     try {
+                        ReflectUtil.checkPackageAccess(valueClass);
+                        SwingUtilities2.checkAccess(valueClass.getModifiers());
                         Constructor cons = valueClass.getConstructor(
                                               new Class[] { String.class });
-
                         if (cons != null) {
+                            SwingUtilities2.checkAccess(cons.getModifiers());
                             return cons.newInstance(new Object[]{string});
                         }
                     } catch (Throwable ex) { }
diff --git a/jdk/src/share/classes/javax/swing/text/html/ObjectView.java b/jdk/src/share/classes/javax/swing/text/html/ObjectView.java
index 4e43cfb..00d3a42 100644
--- a/jdk/src/share/classes/javax/swing/text/html/ObjectView.java
+++ b/jdk/src/share/classes/javax/swing/text/html/ObjectView.java
@@ -31,6 +31,9 @@
 import java.beans.*;
 import java.lang.reflect.*;
 
+import sun.reflect.misc.MethodUtil;
+import sun.reflect.misc.ReflectUtil;
+
 /**
  * Component decorator that implements the view interface
  * for &lt;object&gt; elements.
@@ -87,6 +90,7 @@
         AttributeSet attr = getElement().getAttributes();
         String classname = (String) attr.getAttribute(HTML.Attribute.CLASSID);
         try {
+            ReflectUtil.checkPackageAccess(classname);
             Class c = Class.forName(classname, true,Thread.currentThread().
                                     getContextClassLoader());
             Object o = c.newInstance();
@@ -116,28 +120,6 @@
     }
 
     /**
-     * Get a Class object to use for loading the
-     * classid.  If possible, the Classloader
-     * used to load the associated Document is used.
-     * This would typically be the same as the ClassLoader
-     * used to load the EditorKit.  If the documents
-     * ClassLoader is null,
-     * <code>Class.forName</code> is used.
-     */
-    private Class getClass(String classname) throws ClassNotFoundException {
-        Class klass;
-
-        Class docClass = getDocument().getClass();
-        ClassLoader loader = docClass.getClassLoader();
-        if (loader != null) {
-            klass = loader.loadClass(classname);
-        } else {
-            klass = Class.forName(classname);
-        }
-        return klass;
-    }
-
-    /**
      * Initialize this component according the KEY/VALUEs passed in
      * via the &lt;param&gt; elements in the corresponding
      * &lt;object&gt; element.
@@ -170,7 +152,7 @@
                 }
                 Object [] args = { value };
                 try {
-                    writer.invoke(comp, args);
+                    MethodUtil.invoke(writer, comp, args);
                 } catch (Exception ex) {
                     System.err.println("Invocation failed");
                     // invocation code
diff --git a/jdk/src/share/classes/sun/font/FileFont.java b/jdk/src/share/classes/sun/font/FileFont.java
index 0a9ce92..ae68003 100644
--- a/jdk/src/share/classes/sun/font/FileFont.java
+++ b/jdk/src/share/classes/sun/font/FileFont.java
@@ -170,7 +170,9 @@
                 }
             }
         }
-        scaler.dispose();
+        if (scaler != null) {
+            scaler.dispose();
+        }
         scaler = FontScaler.getNullScaler();
     }
 
diff --git a/jdk/src/share/classes/sun/font/GlyphLayout.java b/jdk/src/share/classes/sun/font/GlyphLayout.java
index 538da04..525ff72 100644
--- a/jdk/src/share/classes/sun/font/GlyphLayout.java
+++ b/jdk/src/share/classes/sun/font/GlyphLayout.java
@@ -468,9 +468,10 @@
                         _gvdata.grow();
                     }
                 }
-                if (_gvdata._count < 0) {
-                    break;
-                }
+            }
+            // Break out of the outer for loop if layout fails.
+            if (_gvdata._count < 0) {
+                break;
             }
         }
 
diff --git a/jdk/src/share/classes/sun/font/StandardGlyphVector.java b/jdk/src/share/classes/sun/font/StandardGlyphVector.java
index c452dd9..6600168 100644
--- a/jdk/src/share/classes/sun/font/StandardGlyphVector.java
+++ b/jdk/src/share/classes/sun/font/StandardGlyphVector.java
@@ -1740,8 +1740,9 @@
                                                      tx,
                                                      sgv.font.getStyle(),
                                                      aa, fm);
-
-            FontStrike strike = sgv.font2D.getStrike(desc);  // !!! getStrike(desc, false)
+            // Get the strike via the handle. Shouldn't matter
+            // if we've invalidated the font but its an extra precaution.
+            FontStrike strike = sgv.font2D.handle.font2D.getStrike(desc);  // !!! getStrike(desc, false)
 
             return new GlyphStrike(sgv, strike, dx, dy);
         }
diff --git a/jdk/src/share/classes/sun/font/TrueTypeFont.java b/jdk/src/share/classes/sun/font/TrueTypeFont.java
index 419c4c1..abd97f4 100644
--- a/jdk/src/share/classes/sun/font/TrueTypeFont.java
+++ b/jdk/src/share/classes/sun/font/TrueTypeFont.java
@@ -1037,6 +1037,9 @@
             if (head_Table != null && head_Table.capacity() >= 18) {
                 ShortBuffer sb = head_Table.asShortBuffer();
                 upem = sb.get(9) & 0xffff;
+                if (upem < 16 || upem > 16384) {
+                    upem = 2048;
+                }
             }
 
             ByteBuffer os2_Table = getTableBuffer(os_2Tag);
diff --git a/jdk/src/share/classes/sun/java2d/Disposer.java b/jdk/src/share/classes/sun/java2d/Disposer.java
index 8395102..2e195d7 100644
--- a/jdk/src/share/classes/sun/java2d/Disposer.java
+++ b/jdk/src/share/classes/sun/java2d/Disposer.java
@@ -150,8 +150,7 @@
                 rec = null;
                 clearDeferredRecords();
             } catch (Exception e) {
-                System.out.println("Exception while removing reference: " + e);
-                e.printStackTrace();
+                System.out.println("Exception while removing reference.");
             }
         }
     }
@@ -177,7 +176,6 @@
                 rec.dispose();
             } catch (Exception e) {
                 System.out.println("Exception while disposing deferred rec.");
-                e.printStackTrace();
             }
         }
         deferredRecords.clear();
@@ -228,8 +226,7 @@
                 }
             }
         } catch (Exception e) {
-            System.out.println("Exception while removing reference: " + e);
-            e.printStackTrace();
+            System.out.println("Exception while removing reference.");
         } finally {
             pollingQueue = false;
         }
diff --git a/jdk/src/share/classes/sun/management/HotSpotDiagnostic.java b/jdk/src/share/classes/sun/management/HotSpotDiagnostic.java
index bdff020..9bed3f6 100644
--- a/jdk/src/share/classes/sun/management/HotSpotDiagnostic.java
+++ b/jdk/src/share/classes/sun/management/HotSpotDiagnostic.java
@@ -40,7 +40,17 @@
     public HotSpotDiagnostic() {
     }
 
-    public native void dumpHeap(String outputFile, boolean live) throws IOException;
+    public void dumpHeap(String outputFile, boolean live) throws IOException {
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            security.checkWrite(outputFile);
+            Util.checkControlAccess();
+        }
+
+        dumpHeap0(outputFile, live);
+    }
+
+    private native void dumpHeap0(String outputFile, boolean live) throws IOException;
 
     public List<VMOption> getDiagnosticOptions() {
         List<Flag> allFlags = Flag.getAllFlags();
diff --git a/jdk/src/share/classes/sun/misc/JavaLangAccess.java b/jdk/src/share/classes/sun/misc/JavaLangAccess.java
index 45a37ab..3c169f2 100644
--- a/jdk/src/share/classes/sun/misc/JavaLangAccess.java
+++ b/jdk/src/share/classes/sun/misc/JavaLangAccess.java
@@ -25,6 +25,7 @@
 
 package sun.misc;
 
+import java.security.AccessControlContext;
 import sun.reflect.ConstantPool;
 import sun.reflect.annotation.AnnotationType;
 import sun.nio.ch.Interruptible;
@@ -88,4 +89,10 @@
      * Returns the murmur hash value for the specified String.
      */
     int getStringHash32(String string);
+
+    /**
+     * Returns a new Thread with the given Runnable and an
+     * inherited AccessControlContext.
+     */
+    Thread newThreadWithAcc(Runnable target, AccessControlContext acc);
 }
diff --git a/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java b/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java
index 81468c2..ab43e05 100644
--- a/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java
+++ b/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java
@@ -26,8 +26,10 @@
 
 package sun.reflect.misc;
 
+import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.lang.reflect.Proxy;
+import java.util.Arrays;
 import sun.reflect.Reflection;
 
 public final class ReflectUtil {
@@ -249,4 +251,50 @@
         String pkg = (i != -1) ? name.substring(0, i) : "";
         return Proxy.isProxyClass(cls) && !pkg.equals(PROXY_PACKAGE);
     }
+
+    /**
+     * Check if the given method is a method declared in the proxy interface
+     * implemented by the given proxy instance.
+     *
+     * @param proxy a proxy instance
+     * @param method an interface method dispatched to a InvocationHandler
+     *
+     * @throws IllegalArgumentException if the given proxy or method is invalid.
+     */
+    public static void checkProxyMethod(Object proxy, Method method) {
+        // check if it is a valid proxy instance
+        if (proxy == null || !Proxy.isProxyClass(proxy.getClass())) {
+            throw new IllegalArgumentException("Not a Proxy instance");
+}
+        if (Modifier.isStatic(method.getModifiers())) {
+            throw new IllegalArgumentException("Can't handle static method");
+        }
+
+        Class<?> c = method.getDeclaringClass();
+        if (c == Object.class) {
+            String name = method.getName();
+            if (name.equals("hashCode") || name.equals("equals") || name.equals("toString")) {
+                return;
+            }
+        }
+
+        if (isSuperInterface(proxy.getClass(), c)) {
+            return;
+        }
+
+        // disallow any method not declared in one of the proxy intefaces
+        throw new IllegalArgumentException("Can't handle: " + method);
+    }
+
+    private static boolean isSuperInterface(Class<?> c, Class<?> intf) {
+        for (Class<?> i : c.getInterfaces()) {
+            if (i == intf) {
+                return true;
+            }
+            if (isSuperInterface(i, intf)) {
+                return true;
+            }
+        }
+        return false;
+    }
 }
diff --git a/jdk/src/share/classes/sun/security/ec/ECPrivateKeyImpl.java b/jdk/src/share/classes/sun/security/ec/ECPrivateKeyImpl.java
index fb309d3..38d85f6 100644
--- a/jdk/src/share/classes/sun/security/ec/ECPrivateKeyImpl.java
+++ b/jdk/src/share/classes/sun/security/ec/ECPrivateKeyImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2013 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -153,12 +153,4 @@
             throw new InvalidKeyException("Invalid EC private key", e);
         }
     }
-
-    // return a string representation of this key for debugging
-    public String toString() {
-        return "Sun EC private key, " + params.getCurve().getField().getFieldSize()
-            + " bits\n  private value:  "
-            + s + "\n  parameters: " + params;
-    }
-
 }
diff --git a/jdk/src/share/classes/sun/security/jgss/GSSCredentialImpl.java b/jdk/src/share/classes/sun/security/jgss/GSSCredentialImpl.java
index f483fc2..6ef887f 100644
--- a/jdk/src/share/classes/sun/security/jgss/GSSCredentialImpl.java
+++ b/jdk/src/share/classes/sun/security/jgss/GSSCredentialImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -630,7 +630,7 @@
                 buffer.append(element.isAcceptorCredential() ?
                               " Accept" : "");
                 buffer.append(" [");
-                buffer.append(element.toString());
+                buffer.append(element.getClass());
                 buffer.append(']');
             } catch (GSSException e) {
                 // skip to next element
diff --git a/jdk/src/share/classes/sun/security/krb5/KdcComm.java b/jdk/src/share/classes/sun/security/krb5/KdcComm.java
index 281cac4..57a1bba 100644
--- a/jdk/src/share/classes/sun/security/krb5/KdcComm.java
+++ b/jdk/src/share/classes/sun/security/krb5/KdcComm.java
@@ -239,11 +239,15 @@
                 savedException = e;
             }
         }
-        if (ibuf == null && savedException != null) {
-            if (savedException instanceof IOException) {
-                throw (IOException) savedException;
+        if (ibuf == null) {
+            if (savedException != null) {
+                if (savedException instanceof IOException) {
+                    throw (IOException) savedException;
+                } else {
+                    throw (KrbException) savedException;
+                }
             } else {
-                throw (KrbException) savedException;
+                throw new IOException("Cannot get a KDC reply");
             }
         }
         return ibuf;
diff --git a/jdk/src/share/classes/sun/security/krb5/internal/NetClient.java b/jdk/src/share/classes/sun/security/krb5/internal/NetClient.java
index 2e9da75..2df1c6e 100644
--- a/jdk/src/share/classes/sun/security/krb5/internal/NetClient.java
+++ b/jdk/src/share/classes/sun/security/krb5/internal/NetClient.java
@@ -31,6 +31,8 @@
 
 package sun.security.krb5.internal;
 
+import sun.misc.IOUtils;
+
 import java.io.*;
 import java.net.*;
 
@@ -102,17 +104,15 @@
             return null;
         }
 
-        byte data[] = new byte[len];
-        count = readFully(data, len);
-        if (count != len) {
+        try {
+            return IOUtils.readFully(in, len, true);
+        } catch (IOException ioe) {
             if (Krb5.DEBUG) {
                 System.out.println(
                     ">>>DEBUG: TCPClient could not read complete packet (" +
                     len + "/" + count + ")");
             }
             return null;
-        } else {
-            return data;
         }
     }
 
diff --git a/jdk/src/share/classes/sun/security/pkcs/PKCS8Key.java b/jdk/src/share/classes/sun/security/pkcs/PKCS8Key.java
index 6405c9fc..d30872b 100644
--- a/jdk/src/share/classes/sun/security/pkcs/PKCS8Key.java
+++ b/jdk/src/share/classes/sun/security/pkcs/PKCS8Key.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -304,17 +304,6 @@
         return encodedKey.clone();
     }
 
-    /*
-     * Returns a printable representation of the key
-     */
-    public String toString ()
-    {
-        HexDumpEncoder  encoder = new HexDumpEncoder ();
-
-        return "algorithm = " + algid.toString ()
-            + ", unparsed keybits = \n" + encoder.encodeBuffer (key);
-    }
-
     /**
      * Initialize an PKCS8Key object from an input stream.  The data
      * on that input stream must be encoded using DER, obeying the
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java
index 072be42..f7e7857 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -542,27 +542,6 @@
             fetchValues();
             return coeff;
         }
-        public String toString() {
-            fetchValues();
-            StringBuilder sb = new StringBuilder(super.toString());
-            sb.append("\n  modulus:          ");
-            sb.append(n);
-            sb.append("\n  public exponent:  ");
-            sb.append(e);
-            sb.append("\n  private exponent: ");
-            sb.append(d);
-            sb.append("\n  prime p:          ");
-            sb.append(p);
-            sb.append("\n  prime q:          ");
-            sb.append(q);
-            sb.append("\n  prime exponent p: ");
-            sb.append(pe);
-            sb.append("\n  prime exponent q: ");
-            sb.append(qe);
-            sb.append("\n  crt coefficient:  ");
-            sb.append(coeff);
-            return sb.toString();
-        }
     }
 
     // RSA non-CRT private key
@@ -616,15 +595,6 @@
             fetchValues();
             return d;
         }
-        public String toString() {
-            fetchValues();
-            StringBuilder sb = new StringBuilder(super.toString());
-            sb.append("\n  modulus:          ");
-            sb.append(n);
-            sb.append("\n  private exponent: ");
-            sb.append(d);
-            return sb.toString();
-        }
     }
 
     private static final class P11RSAPublicKey extends P11Key
@@ -794,11 +764,6 @@
             fetchValues();
             return params;
         }
-        public String toString() {
-            fetchValues();
-            return super.toString() +  "\n  x: " + x + "\n  p: " + params.getP()
-                + "\n  q: " + params.getQ() + "\n  g: " + params.getG();
-        }
     }
 
     private static final class P11DHPrivateKey extends P11Key
@@ -856,11 +821,6 @@
             fetchValues();
             return params;
         }
-        public String toString() {
-            fetchValues();
-            return super.toString() +  "\n  x: " + x + "\n  p: " + params.getP()
-                + "\n  g: " + params.getG();
-        }
     }
 
     private static final class P11DHPublicKey extends P11Key
@@ -977,12 +937,6 @@
             fetchValues();
             return params;
         }
-        public String toString() {
-            fetchValues();
-        return super.toString()
-            + "\n  private value:  " + s
-            + "\n  parameters: " + params;
-        }
     }
 
     private static final class P11ECPublicKey extends P11Key
diff --git a/jdk/src/share/classes/sun/security/provider/DSAPrivateKey.java b/jdk/src/share/classes/sun/security/provider/DSAPrivateKey.java
index b521e3d..97e7ef8 100644
--- a/jdk/src/share/classes/sun/security/provider/DSAPrivateKey.java
+++ b/jdk/src/share/classes/sun/security/provider/DSAPrivateKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -142,11 +142,6 @@
         }
     }
 
-    public String toString() {
-        return "Sun DSA Private Key \nparameters:" + algid + "\nx: " +
-            Debug.toHexString(x) + "\n";
-    }
-
     protected void parseKeyBits() throws InvalidKeyException {
         try {
             DerInputStream in = new DerInputStream(key);
diff --git a/jdk/src/share/classes/sun/security/rsa/RSAPrivateCrtKeyImpl.java b/jdk/src/share/classes/sun/security/rsa/RSAPrivateCrtKeyImpl.java
index b289ef2..7e68c42 100644
--- a/jdk/src/share/classes/sun/security/rsa/RSAPrivateCrtKeyImpl.java
+++ b/jdk/src/share/classes/sun/security/rsa/RSAPrivateCrtKeyImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -225,29 +225,4 @@
         }
         return b;
     }
-
-    // return a string representation of this key for debugging
-    public String toString() {
-        StringBuffer sb = new StringBuffer();
-        sb.append("Sun RSA private CRT key, ");
-        sb.append(n.bitLength());
-        sb.append(" bits\n  modulus:          ");
-        sb.append(n);
-        sb.append("\n  public exponent:  ");
-        sb.append(e);
-        sb.append("\n  private exponent: ");
-        sb.append(d);
-        sb.append("\n  prime p:          ");
-        sb.append(p);
-        sb.append("\n  prime q:          ");
-        sb.append(q);
-        sb.append("\n  prime exponent p: ");
-        sb.append(pe);
-        sb.append("\n  prime exponent q: ");
-        sb.append(qe);
-        sb.append("\n  crt coefficient:  ");
-        sb.append(coeff);
-        return sb.toString();
-    }
-
 }
diff --git a/jdk/src/share/classes/sun/security/rsa/RSAPrivateKeyImpl.java b/jdk/src/share/classes/sun/security/rsa/RSAPrivateKeyImpl.java
index f9a7c34..1a7df13 100644
--- a/jdk/src/share/classes/sun/security/rsa/RSAPrivateKeyImpl.java
+++ b/jdk/src/share/classes/sun/security/rsa/RSAPrivateKeyImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -98,11 +98,4 @@
     public BigInteger getPrivateExponent() {
         return d;
     }
-
-    // return a string representation of this key for debugging
-    public String toString() {
-        return "Sun RSA private key, " + n.bitLength() + " bits\n  modulus: "
-                + n + "\n  private exponent: " + d;
-    }
-
 }
diff --git a/jdk/src/share/classes/sun/swing/SwingLazyValue.java b/jdk/src/share/classes/sun/swing/SwingLazyValue.java
index 2d1aa9c..a9e6f2c 100644
--- a/jdk/src/share/classes/sun/swing/SwingLazyValue.java
+++ b/jdk/src/share/classes/sun/swing/SwingLazyValue.java
@@ -30,6 +30,7 @@
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import javax.swing.UIDefaults;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * SwingLazyValue is a copy of ProxyLazyValue that does not snapshot the
@@ -63,7 +64,7 @@
 
     public Object createValue(final UIDefaults table) {
         try {
-            Object cl;
+            ReflectUtil.checkPackageAccess(className);
             Class<?> c = Class.forName(className, true, null);
             if (methodName != null) {
                 Class[] types = getClassArray(args);
diff --git a/jdk/src/share/classes/sun/swing/SwingUtilities2.java b/jdk/src/share/classes/sun/swing/SwingUtilities2.java
index bfa4297..270952b 100644
--- a/jdk/src/share/classes/sun/swing/SwingUtilities2.java
+++ b/jdk/src/share/classes/sun/swing/SwingUtilities2.java
@@ -1301,6 +1301,19 @@
     }
 
     /**
+     * Utility method that throws SecurityException if SecurityManager is set
+     * and modifiers are not public
+     *
+     * @param modifiers a set of modifiers
+     */
+    public static void checkAccess(int modifiers) {
+        if (System.getSecurityManager() != null
+                && !Modifier.isPublic(modifiers)) {
+            throw new SecurityException("Resource is not accessible");
+        }
+    }
+
+    /**
      * Returns true if EventQueue.getCurrentEvent() has the permissions to
      * access the system clipboard and if it is allowed gesture (if
      * checkGesture true)
diff --git a/jdk/src/share/demo/jvmti/hprof/hprof_class.c b/jdk/src/share/demo/jvmti/hprof/hprof_class.c
index d89a804..0dc69d3 100644
--- a/jdk/src/share/demo/jvmti/hprof/hprof_class.c
+++ b/jdk/src/share/demo/jvmti/hprof/hprof_class.c
@@ -527,7 +527,12 @@
     jmethodID  method;
 
     info = get_info(index);
-    HPROF_ASSERT(mnum < info->method_count);
+    if (mnum >= info->method_count) {
+        jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        (*env)->ThrowNew(env, newExcCls, "Illegal mnum");
+
+        return NULL;
+    }
     method = info->method[mnum].method_id;
     if ( method == NULL ) {
         char * name;
@@ -535,7 +540,12 @@
         jclass clazz;
 
         name  = (char *)string_get(info->method[mnum].name_index);
-        HPROF_ASSERT(name!=NULL);
+        if (name==NULL) {
+            jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            (*env)->ThrowNew(env, newExcCls, "Name not found");
+
+            return NULL;
+        }
         sig   = (char *)string_get(info->method[mnum].sig_index);
         HPROF_ASSERT(sig!=NULL);
         clazz = class_get_class(env, index);
diff --git a/jdk/src/share/demo/jvmti/hprof/hprof_event.c b/jdk/src/share/demo/jvmti/hprof/hprof_event.c
index 66d89e7..fd8b0b0 100644
--- a/jdk/src/share/demo/jvmti/hprof/hprof_event.c
+++ b/jdk/src/share/demo/jvmti/hprof/hprof_event.c
@@ -195,7 +195,12 @@
 
     HPROF_ASSERT(env!=NULL);
     HPROF_ASSERT(thread!=NULL);
-    HPROF_ASSERT(cnum!=0 && cnum!=gdata->tracker_cnum);
+    if (cnum == 0 || cnum == gdata->tracker_cnum) {
+        jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        (*env)->ThrowNew(env, newExcCls, "Illegal cnum.");
+
+        return;
+    }
 
     /* Prevent recursion into any BCI function for this thread (pstatus). */
     if ( tls_get_tracker_status(env, thread, JNI_FALSE,
@@ -204,8 +209,10 @@
 
         (*pstatus) = 1;
         method      = class_get_methodID(env, cnum, mnum);
-        HPROF_ASSERT(method!=NULL);
-        tls_push_method(tls_index, method);
+        if (method != NULL) {
+            tls_push_method(tls_index, method);
+        }
+
         (*pstatus) = 0;
     }
 }
@@ -248,7 +255,13 @@
 
     HPROF_ASSERT(env!=NULL);
     HPROF_ASSERT(thread!=NULL);
-    HPROF_ASSERT(cnum!=0 && cnum!=gdata->tracker_cnum);
+
+    if (cnum == 0 || cnum == gdata->tracker_cnum) {
+        jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        (*env)->ThrowNew(env, newExcCls, "Illegal cnum.");
+
+        return;
+    }
 
     /* Prevent recursion into any BCI function for this thread (pstatus). */
     if ( tls_get_tracker_status(env, thread, JNI_FALSE,
@@ -257,8 +270,10 @@
 
         (*pstatus) = 1;
         method      = class_get_methodID(env, cnum, mnum);
-        HPROF_ASSERT(method!=NULL);
-        tls_pop_method(tls_index, thread, method);
+        if (method != NULL) {
+            tls_pop_method(tls_index, thread, method);
+        }
+
         (*pstatus) = 0;
     }
 }
diff --git a/jdk/src/share/lib/security/java.security-linux b/jdk/src/share/lib/security/java.security-linux
index 1cd9cc1..01bceac 100644
--- a/jdk/src/share/lib/security/java.security-linux
+++ b/jdk/src/share/lib/security/java.security-linux
@@ -129,6 +129,7 @@
                com.sun.istack.internal.,\
                com.sun.jmx.,\
                com.sun.proxy.,\
+               com.sun.script.,\
                com.sun.org.apache.bcel.internal.,\
                com.sun.org.apache.regexp.internal.,\
                com.sun.org.apache.xerces.internal.,\
@@ -166,6 +167,7 @@
                    com.sun.istack.internal.,\
                    com.sun.jmx.,\
                    com.sun.proxy.,\
+                   com.sun.script.,\
                    com.sun.org.apache.bcel.internal.,\
                    com.sun.org.apache.regexp.internal.,\
                    com.sun.org.apache.xerces.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-macosx b/jdk/src/share/lib/security/java.security-macosx
index 86d4957..e6b3f4c 100644
--- a/jdk/src/share/lib/security/java.security-macosx
+++ b/jdk/src/share/lib/security/java.security-macosx
@@ -130,6 +130,7 @@
                com.sun.istack.internal.,\
                com.sun.jmx.,\
                com.sun.proxy.,\
+               com.sun.script.,\
                com.sun.org.apache.bcel.internal.,\
                com.sun.org.apache.regexp.internal.,\
                com.sun.org.apache.xerces.internal.,\
@@ -169,6 +170,7 @@
                    com.sun.istack.internal.,\
                    com.sun.jmx.,\
                    com.sun.proxy.,\
+                   com.sun.script.,\
                    com.sun.org.apache.bcel.internal.,\
                    com.sun.org.apache.regexp.internal.,\
                    com.sun.org.apache.xerces.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-solaris b/jdk/src/share/lib/security/java.security-solaris
index 0c49341..e12229d 100644
--- a/jdk/src/share/lib/security/java.security-solaris
+++ b/jdk/src/share/lib/security/java.security-solaris
@@ -131,6 +131,7 @@
                com.sun.istack.internal.,\
                com.sun.jmx.,\
                com.sun.proxy.,\
+               com.sun.script.,\
                com.sun.org.apache.bcel.internal.,\
                com.sun.org.apache.regexp.internal.,\
                com.sun.org.apache.xerces.internal.,\
@@ -169,6 +170,7 @@
                    com.sun.istack.internal.,\
                    com.sun.jmx.,\
                    com.sun.proxy.,\
+                   com.sun.script.,\
                    com.sun.org.apache.bcel.internal.,\
                    com.sun.org.apache.regexp.internal.,\
                    com.sun.org.apache.xerces.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-windows b/jdk/src/share/lib/security/java.security-windows
index 89dcf3f..e496bcc 100644
--- a/jdk/src/share/lib/security/java.security-windows
+++ b/jdk/src/share/lib/security/java.security-windows
@@ -130,6 +130,7 @@
                com.sun.istack.internal.,\
                com.sun.jmx.,\
                com.sun.proxy.,\
+               com.sun.script.,\
                com.sun.org.apache.bcel.internal.,\
                com.sun.org.apache.regexp.internal.,\
                com.sun.org.apache.xerces.internal.,\
@@ -169,6 +170,7 @@
                    com.sun.istack.internal.,\
                    com.sun.jmx.,\
                    com.sun.proxy.,\
+                   com.sun.script.,\
                    com.sun.org.apache.bcel.internal.,\
                    com.sun.org.apache.regexp.internal.,\
                    com.sun.org.apache.xerces.internal.,\
diff --git a/jdk/src/share/native/com/sun/java/util/jar/pack/zip.cpp b/jdk/src/share/native/com/sun/java/util/jar/pack/zip.cpp
index 93bf330..f7b95b4 100644
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/zip.cpp
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/zip.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -340,6 +340,10 @@
   struct tm sbuf;
   (void)memset((void*)&sbuf,0, sizeof(sbuf));
   struct tm* s = gmtime_r(&t, &sbuf);
+  if (s == NULL) {
+    fprintf(u->errstrm, "Error: gmtime failure, invalid input archive\n");
+    exit(2);
+  }
   modtime_cache = modtime;
   dostime_cache = dostime(s->tm_year + 1900, s->tm_mon + 1, s->tm_mday,
                           s->tm_hour, s->tm_min, s->tm_sec);
@@ -384,7 +388,7 @@
   }
 
   deflated.empty();
-  zs.next_out  = (uchar*) deflated.grow(len + (len/2));
+  zs.next_out  = (uchar*) deflated.grow(add_size(len, (len/2)));
   zs.avail_out = (int)deflated.size();
 
   zs.next_in = (uchar*)head.ptr;
diff --git a/jdk/src/share/native/java/lang/Class.c b/jdk/src/share/native/java/lang/Class.c
index 3e595e7..30c40d3 100644
--- a/jdk/src/share/native/java/lang/Class.c
+++ b/jdk/src/share/native/java/lang/Class.c
@@ -70,7 +70,7 @@
     {"getProtectionDomain0", "()" PD,       (void *)&JVM_GetProtectionDomain},
     {"setProtectionDomain0", "(" PD ")V",   (void *)&JVM_SetProtectionDomain},
     {"getDeclaredClasses0",  "()[" CLS,      (void *)&JVM_GetDeclaredClasses},
-    {"getDeclaringClass",   "()" CLS,      (void *)&JVM_GetDeclaringClass},
+    {"getDeclaringClass0",   "()" CLS,      (void *)&JVM_GetDeclaringClass},
     {"getGenericSignature", "()" STR,       (void *)&JVM_GetClassSignature},
     {"getRawAnnotations",      "()" BA,        (void *)&JVM_GetClassAnnotations},
     {"getConstantPool",     "()" CPL,       (void *)&JVM_GetClassConstantPool},
diff --git a/jdk/src/share/native/java/net/Inet6Address.c b/jdk/src/share/native/java/net/Inet6Address.c
index 7b04c67..a85b79c 100644
--- a/jdk/src/share/native/java/net/Inet6Address.c
+++ b/jdk/src/share/native/java/net/Inet6Address.c
@@ -33,6 +33,8 @@
  */
 
 jclass ia6_class;
+jfieldID ia6_holder6ID;
+
 jfieldID ia6_ipaddressID;
 jfieldID ia6_scopeidID;
 jfieldID ia6_cachedscopeidID;
@@ -48,21 +50,26 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_Inet6Address_init(JNIEnv *env, jclass cls) {
+    jclass ia6h_class;
     jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
     CHECK_NULL(c);
     ia6_class = (*env)->NewGlobalRef(env, c);
     CHECK_NULL(ia6_class);
-    ia6_ipaddressID = (*env)->GetFieldID(env, ia6_class, "ipaddress", "[B");
+    ia6h_class = (*env)->FindClass(env, "java/net/Inet6Address$Inet6AddressHolder");
+    CHECK_NULL(ia6h_class);
+    ia6_holder6ID = (*env)->GetFieldID(env, ia6_class, "holder6", "Ljava/net/Inet6Address$Inet6AddressHolder;");
+    CHECK_NULL(ia6_holder6ID);
+    ia6_ipaddressID = (*env)->GetFieldID(env, ia6h_class, "ipaddress", "[B");
     CHECK_NULL(ia6_ipaddressID);
-    ia6_scopeidID = (*env)->GetFieldID(env, ia6_class, "scope_id", "I");
+    ia6_scopeidID = (*env)->GetFieldID(env, ia6h_class, "scope_id", "I");
     CHECK_NULL(ia6_scopeidID);
     ia6_cachedscopeidID = (*env)->GetFieldID(env, ia6_class, "cached_scope_id", "I");
     CHECK_NULL(ia6_cachedscopeidID);
-    ia6_scopeidsetID = (*env)->GetFieldID(env, ia6_class, "scope_id_set", "Z");
+    ia6_scopeidsetID = (*env)->GetFieldID(env, ia6h_class, "scope_id_set", "Z");
     CHECK_NULL(ia6_scopeidID);
-    ia6_scopeifnameID = (*env)->GetFieldID(env, ia6_class, "scope_ifname", "Ljava/net/NetworkInterface;");
+    ia6_scopeifnameID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname", "Ljava/net/NetworkInterface;");
     CHECK_NULL(ia6_scopeifnameID);
-    ia6_scopeifnamesetID = (*env)->GetFieldID(env, ia6_class, "scope_ifname_set", "Z");
+    ia6_scopeifnamesetID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname_set", "Z");
     CHECK_NULL(ia6_scopeifnamesetID);
     ia6_ctrID = (*env)->GetMethodID(env, ia6_class, "<init>", "()V");
     CHECK_NULL(ia6_ctrID);
diff --git a/jdk/src/share/native/java/net/net_util.c b/jdk/src/share/native/java/net/net_util.c
index 2f99a34..318e34d 100644
--- a/jdk/src/share/native/java/net/net_util.c
+++ b/jdk/src/share/native/java/net/net_util.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -94,6 +94,111 @@
 extern jfieldID iac_addressID;
 extern jfieldID iac_familyID;
 
+/**
+ * set_ methods return JNI_TRUE on success JNI_FALSE on error
+ * get_ methods that return +ve int return -1 on error
+ * get_ methods that return objects return NULL on error.
+ */
+jobject getInet6Address_scopeifname(JNIEnv *env, jobject iaObj) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, NULL);
+    return (*env)->GetObjectField(env, holder, ia6_scopeifnameID);
+}
+
+int setInet6Address_scopeifname(JNIEnv *env, jobject iaObj, jobject scopeifname) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, JNI_FALSE);
+    (*env)->SetObjectField(env, holder, ia6_scopeifnameID, scopeifname);
+    return JNI_TRUE;
+}
+
+int getInet6Address_scopeifname_set(JNIEnv *env, jobject iaObj) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, -1);
+    return (*env)->GetBooleanField(env, holder, ia6_scopeifnamesetID);
+}
+
+int setInet6Address_scopeifname_set(JNIEnv *env, jobject iaObj, int scopeifname_set) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, JNI_FALSE);
+    (*env)->SetBooleanField(env, holder, ia6_scopeifnamesetID, scopeifname_set);
+    return JNI_TRUE;
+}
+
+int getInet6Address_scopeid_set(JNIEnv *env, jobject iaObj) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, -1);
+    return (*env)->GetBooleanField(env, holder, ia6_scopeidsetID);
+}
+
+int getInet6Address_scopeid(JNIEnv *env, jobject iaObj) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, -1);
+    return (*env)->GetIntField(env, holder, ia6_scopeidID);
+}
+
+int setInet6Address_scopeid(JNIEnv *env, jobject iaObj, int scopeid) {
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, JNI_FALSE);
+    (*env)->SetIntField(env, holder, ia6_scopeidID, scopeid);
+    if (scopeid > 0) {
+            (*env)->SetBooleanField(env, holder, ia6_scopeidsetID, JNI_TRUE);
+    }
+    return JNI_TRUE;
+}
+
+
+int getInet6Address_ipaddress(JNIEnv *env, jobject iaObj, char *dest) {
+    jobject holder, addr;
+    jbyteArray barr;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, JNI_FALSE);
+    addr =  (*env)->GetObjectField(env, holder, ia6_ipaddressID);
+    CHECK_NULL_RETURN(addr, JNI_FALSE);
+    (*env)->GetByteArrayRegion(env, addr, 0, 16, (jbyte *)dest);
+    return JNI_TRUE;
+}
+
+int setInet6Address_ipaddress(JNIEnv *env, jobject iaObj, char *address) {
+    jobject holder;
+    jbyteArray addr;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    CHECK_NULL_RETURN(holder, JNI_FALSE);
+    addr =  (jbyteArray)(*env)->GetObjectField(env, holder, ia6_ipaddressID);
+    if (addr == NULL) {
+        addr = (*env)->NewByteArray(env, 16);
+        CHECK_NULL_RETURN(addr, JNI_FALSE);
+        (*env)->SetObjectField(env, holder, ia6_ipaddressID, addr);
+    }
+    (*env)->SetByteArrayRegion(env, addr, 0, 16, (jbyte *)address);
+    return JNI_TRUE;
+}
+
 void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address) {
     jobject holder;
     initInetAddrs(env);
@@ -168,6 +273,7 @@
         } else {
             static jclass inet6Cls = 0;
             jint scope;
+            int ret;
             if (inet6Cls == 0) {
                 jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
                 CHECK_NULL_RETURN(c, NULL);
@@ -177,18 +283,11 @@
             }
             iaObj = (*env)->NewObject(env, inet6Cls, ia6_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
-            ipaddress = (*env)->NewByteArray(env, 16);
-            CHECK_NULL_RETURN(ipaddress, NULL);
-            (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
-                                       (jbyte *)&(him6->sin6_addr));
-
-            (*env)->SetObjectField(env, iaObj, ia6_ipaddressID, ipaddress);
-
+            ret = setInet6Address_ipaddress(env, iaObj, (char *)&(him6->sin6_addr));
+            CHECK_NULL_RETURN(ret, NULL);
             setInetAddress_family(env, iaObj, IPv6);
             scope = getScopeID(him);
-            (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
-            if (scope > 0)
-                (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
+            setInet6Address_scopeid(env, iaObj, scope);
         }
         *port = ntohs(him6->sin6_port);
     } else
@@ -248,9 +347,8 @@
             if (family == AF_INET) {
                 return JNI_FALSE;
             }
-            ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
-            scope = (*env)->GetIntField(env, iaObj, ia6_scopeidID);
-            (*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddrCur);
+            scope = getInet6Address_scopeid(env, iaObj);
+            getInet6Address_ipaddress(env, iaObj, (char *)caddrCur);
             if (NET_IsEqual(caddrNew, caddrCur) && cmpScopeID(scope, him)) {
                 return JNI_TRUE;
             } else {
diff --git a/jdk/src/share/native/java/net/net_util.h b/jdk/src/share/native/java/net/net_util.h
index 604c83d..ed127c6 100644
--- a/jdk/src/share/native/java/net/net_util.h
+++ b/jdk/src/share/native/java/net/net_util.h
@@ -58,6 +58,22 @@
 extern jfieldID iac_hostNameID;
 extern jfieldID ia_preferIPv6AddressID;
 
+/** (Inet6Address accessors)
+ * set_ methods return JNI_TRUE on success JNI_FALSE on error
+ * get_ methods that return int/boolean, return -1 on error
+ * get_ methods that return objects return NULL on error.
+ */
+extern jobject getInet6Address_scopeifname(JNIEnv *env, jobject ia6Obj);
+extern int setInet6Address_scopeifname(JNIEnv *env, jobject ia6Obj, jobject scopeifname);
+extern int getInet6Address_scopeifname_set(JNIEnv *env, jobject ia6Obj);
+extern int setInet6Address_scopeifname_set(JNIEnv *env, jobject ia6Obj,
+        int scopeifname_set);
+extern int getInet6Address_scopeid_set(JNIEnv *env, jobject ia6Obj);
+extern int getInet6Address_scopeid(JNIEnv *env, jobject ia6Obj);
+extern int setInet6Address_scopeid(JNIEnv *env, jobject ia6Obj, int scopeid);
+extern int getInet6Address_ipaddress(JNIEnv *env, jobject ia6Obj, char *dest);
+extern int setInet6Address_ipaddress(JNIEnv *env, jobject ia6Obj, char *address);
+
 extern void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address);
 extern void setInetAddress_family(JNIEnv *env, jobject iaObj, int family);
 extern void setInetAddress_hostName(JNIEnv *env, jobject iaObj, jobject h);
@@ -93,6 +109,7 @@
 
 /* Inet6Address fields */
 extern jclass ia6_class;
+extern jfieldID ia6_holder6ID;
 extern jfieldID ia6_ipaddressID;
 extern jfieldID ia6_scopeidID;
 extern jfieldID ia6_cachedscopeidID;
diff --git a/jdk/src/share/native/sun/awt/image/awt_parseImage.c b/jdk/src/share/native/sun/awt/image/awt_parseImage.c
index 24526af..58658f1 100644
--- a/jdk/src/share/native/sun/awt/image/awt_parseImage.c
+++ b/jdk/src/share/native/sun/awt/image/awt_parseImage.c
@@ -808,363 +808,204 @@
     return 1;
 }
 
-/*
- * This routine will fill in a buffer of data for either 1 band or all
- * bands (if band == -1).
- */
 #define MAX_TO_GRAB (10240)
 
-int awt_getPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
-                     unsigned char *bufferP) {
-    int w = rasterP->width;
-    int h = rasterP->height;
-    int numBands = rasterP->numBands;
+typedef union {
+    void *pv;
+    unsigned char *pb;
+    unsigned short *ps;
+} PixelData_t;
+
+
+int awt_getPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP) {
+    const int w = rasterP->width;
+    const int h = rasterP->height;
+    const int numBands = rasterP->numBands;
     int y;
     int i;
-    int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
+    int maxLines;
     jobject jsm;
-    int off;
+    int off = 0;
     jarray jdata = NULL;
     jobject jdatabuffer;
     int *dataP;
-    int maxBytes = w;
+    int maxSamples;
+    PixelData_t p;
+
+    if (bufferP == NULL) {
+        return -1;
+    }
+
+    if (rasterP->dataType != BYTE_DATA_TYPE &&
+        rasterP->dataType != SHORT_DATA_TYPE)
+    {
+        return -1;
+    }
+
+    p.pv = bufferP;
+
+    if (!SAFE_TO_MULT(w, numBands)) {
+        return -1;
+    }
+    maxSamples = w * numBands;
+
+    maxLines = maxSamples > MAX_TO_GRAB ? 1 : (MAX_TO_GRAB / maxSamples);
+    if (maxLines > h) {
+        maxLines = h;
+    }
+
+    if (!SAFE_TO_MULT(maxSamples, maxLines)) {
+        return -1;
+    }
+
+    maxSamples *= maxLines;
 
     jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
     jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
                                          g_RasterDataBufferID);
-    jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
+
+    jdata = (*env)->NewIntArray(env, maxSamples);
     if (JNU_IsNull(env, jdata)) {
         JNU_ThrowOutOfMemoryError(env, "Out of Memory");
         return -1;
     }
 
-    /* Here is the generic code */
-    if (band >= 0) {
-        int dOff;
-        if (band >= numBands) {
+    for (y = 0; y < h; y += maxLines) {
+        if (y + maxLines > h) {
+            maxLines = h - y;
+            maxSamples = w * numBands * maxLines;
+        }
+
+        (*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
+                                 0, y, w,
+                                 maxLines, jdata, jdatabuffer);
+
+        if ((*env)->ExceptionOccurred(env)) {
             (*env)->DeleteLocalRef(env, jdata);
-            JNU_ThrowInternalError(env, "Band out of range.");
             return -1;
         }
-        off = 0;
-        for (y=0; y < h; ) {
-            (*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
-                                     0, y, w,
-                                     maxLines, jdata, jdatabuffer);
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
-            dOff = band;
-            for (i=0; i < maxBytes; i++, dOff += numBands) {
-                bufferP[off++] = (unsigned char) dataP[dOff];
-            }
 
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-
-            if (y+maxLines < h) {
-                y += maxLines;
-            }
-            else {
-                y++;
-                maxBytes = w;
-            }
-        }
-    }
-    else {
-        off = 0;
-        maxBytes *= numBands;
-        for (y=0; y < h; ) {
-            (*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
-                                     0, y, w,
-                                     maxLines, jdata, jdatabuffer);
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
-            for (i=0; i < maxBytes; i++) {
-                bufferP[off++] = (unsigned char) dataP[i];
-            }
-
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-
-            if (y+maxLines < h) {
-                y += maxLines;
-            }
-            else {
-                y++;
-                maxBytes = w*numBands;
-            }
-        }
-
-    }
-    (*env)->DeleteLocalRef(env, jdata);
-
-    return 0;
-}
-int awt_setPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
-                     unsigned char *bufferP) {
-    int w = rasterP->width;
-    int h = rasterP->height;
-    int numBands = rasterP->numBands;
-    int y;
-    int i;
-    int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
-    jobject jsm;
-    int off;
-    jarray jdata = NULL;
-    jobject jdatabuffer;
-    int *dataP;
-    int maxBytes = w;
-
-    jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
-    jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
-                                         g_RasterDataBufferID);
-    /* Here is the generic code */
-    jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
-    if (JNU_IsNull(env, jdata)) {
-        JNU_ThrowOutOfMemoryError(env, "Out of Memory");
-        return -1;
-    }
-    if (band >= 0) {
-        int dOff;
-        if (band >= numBands) {
+        dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
+                                                          NULL);
+        if (dataP == NULL) {
             (*env)->DeleteLocalRef(env, jdata);
-            JNU_ThrowInternalError(env, "Band out of range.");
             return -1;
         }
-        off = 0;
-        for (y=0; y < h; y+=maxLines) {
-            if (y+maxLines > h) {
-                maxBytes = w*numBands;
-                maxLines = h - y;
-            }
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
-            dOff = band;
-            for (i=0; i < maxBytes; i++, dOff += numBands) {
-                dataP[dOff] = bufferP[off++];
-            }
 
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-
-            (*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
-                                   0, y, w,
-                                   maxLines, jdata, jdatabuffer);
-        }
-    }
-    else {
-        off = 0;
-        maxBytes *= numBands;
-        for (y=0; y < h; y+=maxLines) {
-            if (y+maxLines > h) {
-                maxBytes = w*numBands;
-                maxLines = h - y;
+        switch (rasterP->dataType) {
+        case BYTE_DATA_TYPE:
+            for (i = 0; i < maxSamples; i ++) {
+                p.pb[off++] = (unsigned char) dataP[i];
             }
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
+            break;
+        case SHORT_DATA_TYPE:
+            for (i = 0; i < maxSamples; i ++) {
+                p.ps[off++] = (unsigned short) dataP[i];
             }
-            for (i=0; i < maxBytes; i++) {
-                dataP[i] = bufferP[off++];
-            }
-
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-
-            (*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
-                                     0, y, w,
-                                     maxLines, jdata, jdatabuffer);
+            break;
         }
 
+        (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
+                                              JNI_ABORT);
     }
-
     (*env)->DeleteLocalRef(env, jdata);
 
-    return 0;
+    return 1;
 }
-int awt_getPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
-                     unsigned short *bufferP) {
-    int w = rasterP->width;
-    int h = rasterP->height;
-    int numBands = rasterP->numBands;
+
+int awt_setPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP) {
+    const int w = rasterP->width;
+    const int h = rasterP->height;
+    const int numBands = rasterP->numBands;
+
     int y;
     int i;
-    int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
+    int maxLines;
     jobject jsm;
-    int off;
+    int off = 0;
     jarray jdata = NULL;
     jobject jdatabuffer;
     int *dataP;
-    int maxBytes = w*maxLines;
+    int maxSamples;
+    PixelData_t p;
+
+    if (bufferP == NULL) {
+        return -1;
+    }
+
+    if (rasterP->dataType != BYTE_DATA_TYPE &&
+        rasterP->dataType != SHORT_DATA_TYPE)
+    {
+        return -1;
+    }
+
+    p.pv = bufferP;
+
+    if (!SAFE_TO_MULT(w, numBands)) {
+        return -1;
+    }
+    maxSamples = w * numBands;
+
+    maxLines = maxSamples > MAX_TO_GRAB ? 1 : (MAX_TO_GRAB / maxSamples);
+    if (maxLines > h) {
+        maxLines = h;
+    }
+
+    if (!SAFE_TO_MULT(maxSamples, maxLines)) {
+        return -1;
+    }
+
+    maxSamples *= maxLines;
 
     jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
     jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
                                          g_RasterDataBufferID);
-    jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
+
+    jdata = (*env)->NewIntArray(env, maxSamples);
     if (JNU_IsNull(env, jdata)) {
         JNU_ThrowOutOfMemoryError(env, "Out of Memory");
         return -1;
     }
-    /* Here is the generic code */
-    if (band >= 0) {
-        int dOff;
-        if (band >= numBands) {
+
+    for (y = 0; y < h; y += maxLines) {
+        if (y + maxLines > h) {
+            maxLines = h - y;
+            maxSamples = w * numBands * maxLines;
+        }
+        dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
+                                                          NULL);
+        if (dataP == NULL) {
             (*env)->DeleteLocalRef(env, jdata);
-            JNU_ThrowInternalError(env, "Band out of range.");
             return -1;
         }
-        off = 0;
-        for (y=0; y < h; y += maxLines) {
-            if (y+maxLines > h) {
-                maxBytes = w*numBands;
-                maxLines = h - y;
-            }
-            (*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
-                                     0, y, w,
-                                     maxLines, jdata, jdatabuffer);
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
 
-            dOff = band;
-            for (i=0; i < maxBytes; i++, dOff += numBands) {
-                bufferP[off++] = (unsigned short) dataP[dOff];
+        switch (rasterP->dataType) {
+        case BYTE_DATA_TYPE:
+            for (i = 0; i < maxSamples; i ++) {
+                dataP[i] = p.pb[off++];
             }
-
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-        }
-    }
-    else {
-        off = 0;
-        maxBytes *= numBands;
-        for (y=0; y < h; y+=maxLines) {
-            if (y+maxLines > h) {
-                maxBytes = w*numBands;
-                maxLines = h - y;
+            break;
+        case SHORT_DATA_TYPE:
+            for (i = 0; i < maxSamples; i ++) {
+                dataP[i] = p.ps[off++];
             }
-            (*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
-                                     0, y, w,
-                                     maxLines, jdata, jdatabuffer);
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
-            for (i=0; i < maxBytes; i++) {
-                bufferP[off++] = (unsigned short) dataP[i];
-            }
-
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
+            break;
         }
 
+        (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
+                                              JNI_ABORT);
+
+        (*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
+                               0, y, w,
+                               maxLines, jdata, jdatabuffer);
+
+        if ((*env)->ExceptionOccurred(env)) {
+            (*env)->DeleteLocalRef(env, jdata);
+            return -1;
+        }
     }
 
     (*env)->DeleteLocalRef(env, jdata);
-    return 0;
-}
-int awt_setPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
-                      unsigned short *bufferP) {
-    int w = rasterP->width;
-    int h = rasterP->height;
-    int numBands = rasterP->numBands;
-    int y;
-    int i;
-    int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
-    jobject jsm;
-    int off;
-    jarray jdata = NULL;
-    jobject jdatabuffer;
-    int *dataP;
-    int maxBytes = w;
 
-    jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
-    jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
-                                         g_RasterDataBufferID);
-    if (band >= numBands) {
-        JNU_ThrowInternalError(env, "Band out of range.");
-        return -1;
-    }
-    /* Here is the generic code */
-    jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
-    if (JNU_IsNull(env, jdata)) {
-        JNU_ThrowOutOfMemoryError(env, "Out of Memory");
-        return -1;
-    }
-    if (band >= 0) {
-        int dOff;
-        off = 0;
-        for (y=0; y < h; y+=maxLines) {
-            if (y+maxLines > h) {
-                maxBytes = w*numBands;
-                maxLines = h - y;
-            }
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
-            dOff = band;
-            for (i=0; i < maxBytes; i++, dOff += numBands) {
-                dataP[dOff] = bufferP[off++];
-            }
-
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-
-            (*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
-                                   0, y, w,
-                                   maxLines, jdata, jdatabuffer);
-        }
-    }
-    else {
-        off = 0;
-        maxBytes *= numBands;
-        for (y=0; y < h; y+=maxLines) {
-            if (y+maxLines > h) {
-                maxBytes = w*numBands;
-                maxLines = h - y;
-            }
-            dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
-                                                              NULL);
-            if (dataP == NULL) {
-                (*env)->DeleteLocalRef(env, jdata);
-                return -1;
-            }
-            for (i=0; i < maxBytes; i++) {
-                dataP[i] = bufferP[off++];
-            }
-
-            (*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
-                                                  JNI_ABORT);
-
-            (*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
-                                   0, y, w,
-                                   maxLines, jdata, jdatabuffer);
-        }
-
-    }
-
-    (*env)->DeleteLocalRef(env, jdata);
-    return 0;
+    return 1;
 }
diff --git a/jdk/src/share/native/sun/awt/image/awt_parseImage.h b/jdk/src/share/native/sun/awt/image/awt_parseImage.h
index b92bb0c..02dfd1a 100644
--- a/jdk/src/share/native/sun/awt/image/awt_parseImage.h
+++ b/jdk/src/share/native/sun/awt/image/awt_parseImage.h
@@ -188,13 +188,8 @@
 
 void awt_freeParsedImage(BufImageS_t *imageP, int freeImageP);
 
-int awt_getPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
-                     unsigned char *bufferP);
-int awt_setPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
-                     unsigned char *bufferP);
-int awt_getPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
-                     unsigned short *bufferP);
-int awt_setPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
-                      unsigned short *bufferP);
+int awt_getPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP);
+
+int awt_setPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP);
 
 #endif /* AWT_PARSE_IMAGE_H */
diff --git a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
index c4fbbb6..60cbb75 100644
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
@@ -2702,6 +2702,15 @@
     bandSize = (*env)->GetIntArrayElements(env, bandSizes, NULL);
 
     for (i = 0; i < numBands; i++) {
+        if (bandSize[i] <= 0 || bandSize[i] > JPEG_BAND_SIZE) {
+            (*env)->ReleaseIntArrayElements(env, bandSizes,
+                                            bandSize, JNI_ABORT);
+            JNU_ThrowByName(env, "javax/imageio/IIOException", "Invalid Image");
+            return JNI_FALSE;;
+        }
+    }
+
+    for (i = 0; i < numBands; i++) {
         if (bandSize[i] != JPEG_BAND_SIZE) {
             if (scale == NULL) {
                 scale = (UINT8**) calloc(numBands, sizeof(UINT8*));
diff --git a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
index 003ad8d..887c7bd 100644
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
@@ -700,22 +700,7 @@
 
     /* Means that we couldn't write directly into the destination buffer */
     if (ddata == NULL) {
-        unsigned char *bdataP;
-        unsigned short *sdataP;
-
-        /* Punt for now */
-        switch (dstRasterP->dataType) {
-        case BYTE_DATA_TYPE:
-            bdataP  = (unsigned char *) mlib_ImageGetData(dst);
-            retStatus = (awt_setPixelByte(env, -1, dstRasterP, bdataP) >= 0) ;
-            break;
-        case SHORT_DATA_TYPE:
-            sdataP  = (unsigned short *) mlib_ImageGetData(dst);
-            retStatus = (awt_setPixelShort(env, -1, dstRasterP, sdataP) >= 0) ;
-            break;
-        default:
-            retStatus = 0;
-        }
+        retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
     }
 
     /* Release the pinned memory */
@@ -1119,24 +1104,9 @@
 
     /* Means that we couldn't write directly into the destination buffer */
     if (ddata == NULL) {
-        unsigned char *bdataP;
-        unsigned short *sdataP;
-
         /* Need to store it back into the array */
         if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
-            /* Punt for now */
-            switch (dst->type) {
-            case MLIB_BYTE:
-                bdataP  = (unsigned char *) mlib_ImageGetData(dst);
-                retStatus = (awt_setPixelByte(env, -1, dstRasterP, bdataP) >= 0) ;
-                break;
-            case MLIB_SHORT:
-                sdataP  = (unsigned short *) mlib_ImageGetData(dst);
-                retStatus = (awt_setPixelShort(env, -1, dstRasterP, sdataP) >= 0) ;
-                break;
-            default:
-                retStatus = 0;
-            }
+            retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
         }
     }
 
@@ -1704,21 +1674,7 @@
      * the destination buffer
      */
     if (ddata == NULL) {
-        unsigned char*  bdataP;
-        unsigned short* sdataP;
-
-        switch (dstRasterP->dataType) {
-          case BYTE_DATA_TYPE:
-            bdataP  = (unsigned char *) mlib_ImageGetData(dst);
-            retStatus = (awt_setPixelByte(env, -1, dstRasterP, bdataP) >= 0) ;
-            break;
-          case SHORT_DATA_TYPE:
-            sdataP  = (unsigned short *) mlib_ImageGetData(dst);
-            retStatus = (awt_setPixelShort(env, -1, dstRasterP, sdataP) >= 0) ;
-            break;
-          default:
-            retStatus = 0;
-        }
+        retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
     }
 
     /* Release the LUT */
@@ -2029,21 +1985,25 @@
     return 0;
 }
 
+#define NUM_LINES    10
+
 static int
 cvtCustomToDefault(JNIEnv *env, BufImageS_t *imageP, int component,
                    unsigned char *dataP) {
-    ColorModelS_t *cmP = &imageP->cmodel;
-    RasterS_t *rasterP = &imageP->raster;
+    const RasterS_t *rasterP = &imageP->raster;
+    const int w = rasterP->width;
+    const int h = rasterP->height;
+
     int y;
-    jobject jpixels = NULL;
+    jintArray jpixels = NULL;
     jint *pixels;
     unsigned char *dP = dataP;
-#define NUM_LINES    10
-    int numLines = NUM_LINES;
+    int numLines = h > NUM_LINES ? NUM_LINES : h;
+
     /* it is safe to calculate the scan length, because width has been verified
      * on creation of the mlib image
      */
-    int scanLength = rasterP->width * 4;
+    const int scanLength = w * 4;
 
     int nbytes = 0;
     if (!SAFE_TO_MULT(numLines, scanLength)) {
@@ -2052,42 +2012,70 @@
 
     nbytes = numLines * scanLength;
 
-    for (y=0; y < rasterP->height; y+=numLines) {
-        /* getData, one scanline at a time */
-        if (y+numLines > rasterP->height) {
-            numLines = rasterP->height - y;
+    jpixels = (*env)->NewIntArray(env, nbytes);
+    if (JNU_IsNull(env, jpixels)) {
+        JNU_ThrowOutOfMemoryError(env, "Out of Memory");
+        return -1;
+    }
+
+    for (y = 0; y < h; y += numLines) {
+        if (y + numLines > h) {
+            numLines = h - y;
             nbytes = numLines * scanLength;
         }
-        jpixels = (*env)->CallObjectMethod(env, imageP->jimage,
-                                           g_BImgGetRGBMID, 0, y,
-                                           rasterP->width, numLines,
-                                           jpixels,0, rasterP->width);
-        if (jpixels == NULL) {
-            JNU_ThrowInternalError(env, "Can't retrieve pixels.");
+
+        (*env)->CallObjectMethod(env, imageP->jimage,
+                                 g_BImgGetRGBMID, 0, y,
+                                 w, numLines,
+                                 jpixels, 0, w);
+        if ((*env)->ExceptionOccurred(env)) {
+            (*env)->DeleteLocalRef(env, jpixels);
             return -1;
         }
 
         pixels = (*env)->GetPrimitiveArrayCritical(env, jpixels, NULL);
+        if (pixels == NULL) {
+            (*env)->DeleteLocalRef(env, jpixels);
+            return -1;
+        }
+
         memcpy(dP, pixels, nbytes);
         dP += nbytes;
+
         (*env)->ReleasePrimitiveArrayCritical(env, jpixels, pixels,
                                               JNI_ABORT);
     }
+
+    /* Need to release the array */
+    (*env)->DeleteLocalRef(env, jpixels);
+
     return 0;
 }
 
 static int
 cvtDefaultToCustom(JNIEnv *env, BufImageS_t *imageP, int component,
                    unsigned char *dataP) {
-    ColorModelS_t *cmP = &imageP->cmodel;
-    RasterS_t *rasterP = &imageP->raster;
+    const RasterS_t *rasterP = &imageP->raster;
+    const int w = rasterP->width;
+    const int h = rasterP->height;
+
     int y;
+    jintArray jpixels = NULL;
     jint *pixels;
     unsigned char *dP = dataP;
-#define NUM_LINES    10
-    int numLines = NUM_LINES;
-    int nbytes = rasterP->width*4*NUM_LINES;
-    jintArray jpixels;
+    int numLines = h > NUM_LINES ? NUM_LINES : h;
+
+    /* it is safe to calculate the scan length, because width has been verified
+     * on creation of the mlib image
+     */
+    const int scanLength = w * 4;
+
+    int nbytes = 0;
+    if (!SAFE_TO_MULT(numLines, scanLength)) {
+        return -1;
+    }
+
+    nbytes = numLines * scanLength;
 
     jpixels = (*env)->NewIntArray(env, nbytes);
     if (JNU_IsNull(env, jpixels)) {
@@ -2095,14 +2083,15 @@
         return -1;
     }
 
-    for (y=0; y < rasterP->height; y+=NUM_LINES) {
-        if (y+numLines > rasterP->height) {
-            numLines = rasterP->height - y;
-            nbytes = rasterP->width*4*numLines;
+    for (y = 0; y < h; y += numLines) {
+        if (y + numLines > h) {
+            numLines = h - y;
+            nbytes = numLines * scanLength;
         }
+
         pixels = (*env)->GetPrimitiveArrayCritical(env, jpixels, NULL);
         if (pixels == NULL) {
-            /* JNI error */
+            (*env)->DeleteLocalRef(env, jpixels);
             return -1;
         }
 
@@ -2111,12 +2100,11 @@
 
        (*env)->ReleasePrimitiveArrayCritical(env, jpixels, pixels, 0);
 
-       /* setData, one scanline at a time */
-       /* Fix 4223648, 4184283 */
        (*env)->CallVoidMethod(env, imageP->jimage, g_BImgSetRGBMID, 0, y,
-                                rasterP->width, numLines, jpixels, 0,
-                                rasterP->width);
+                                w, numLines, jpixels,
+                                0, w);
        if ((*env)->ExceptionOccurred(env)) {
+           (*env)->DeleteLocalRef(env, jpixels);
            return -1;
        }
     }
@@ -2298,7 +2286,6 @@
                     mlib_image **mlibImagePP, void **dataPP, int isSrc) {
     void *dataP;
     unsigned char *cDataP;
-    unsigned short *sdataP;
     int dataType = BYTE_DATA_TYPE;
     int width;
     int height;
@@ -2484,8 +2471,7 @@
             return -1;
         }
         if (isSrc) {
-            cDataP  = (unsigned char *) mlib_ImageGetData(*mlibImagePP);
-            if (awt_getPixelByte(env, -1, rasterP, cDataP) < 0) {
+            if (awt_getPixels(env, rasterP, mlib_ImageGetData(*mlibImagePP)) < 0) {
                 (*sMlibSysFns.deleteImageFP)(*mlibImagePP);
                 return -1;
             }
@@ -2499,8 +2485,7 @@
             return -1;
         }
         if (isSrc) {
-            sdataP  = (unsigned short *) mlib_ImageGetData(*mlibImagePP);
-            if (awt_getPixelShort(env, -1, rasterP, sdataP) < 0) {
+            if (awt_getPixels(env, rasterP, mlib_ImageGetData(*mlibImagePP)) < 0) {
                 (*sMlibSysFns.deleteImageFP)(*mlibImagePP);
                 return -1;
             }
@@ -2550,60 +2535,6 @@
     }
 }
 
-static int
-storeDstArray(JNIEnv *env,  BufImageS_t *srcP, BufImageS_t *dstP,
-              mlibHintS_t *hintP, mlib_image *mlibImP, void *ddata) {
-    RasterS_t *rasterP = &dstP->raster;
-
-    /* Nothing to do since it is the same image type */
-    if (srcP->imageType == dstP->imageType
-        && srcP->imageType != java_awt_image_BufferedImage_TYPE_CUSTOM
-        && srcP->imageType != java_awt_image_BufferedImage_TYPE_BYTE_INDEXED
-        && srcP->imageType != java_awt_image_BufferedImage_TYPE_BYTE_BINARY) {
-        /* REMIND: Should check the ICM LUTS to see if it is the same */
-        return 0;
-    }
-
-    /* These types are compatible with TYPE_INT_RGB */
-    if (srcP->imageType == java_awt_image_BufferedImage_TYPE_INT_RGB
-        && (dstP->imageType == java_awt_image_BufferedImage_TYPE_INT_ARGB ||
-           dstP->imageType == java_awt_image_BufferedImage_TYPE_INT_ARGB_PRE)){
-        return 0;
-    }
-
-    if (hintP->cvtSrcToDefault &&
-        (srcP->cmodel.isAlphaPre == dstP->cmodel.isAlphaPre)) {
-        if (srcP->cmodel.isAlphaPre) {
-            if (dstP->imageType ==
-                java_awt_image_BufferedImage_TYPE_INT_ARGB_PRE)
-            {
-                return 0;
-            }
-            if (!srcP->cmodel.supportsAlpha &&
-                dstP->imageType == java_awt_image_BufferedImage_TYPE_INT_RGB){
-                return 0;
-            }
-        }
-        else {
-            /* REMIND: */
-        }
-    }
-
-    if (dstP->cmodel.cmType == DIRECT_CM_TYPE) {
-        /* Just need to move bits */
-        if (mlibImP->type == MLIB_BYTE) {
-            return awt_setPixelByte(env, -1, &dstP->raster,
-                                    (unsigned char *) mlibImP->data);
-        }
-        else if (mlibImP->type == MLIB_SHORT) {
-            return awt_setPixelByte(env, -1, &dstP->raster,
-                                    (unsigned char *) mlibImP->data);
-        }
-    }
-
-    return 0;
-}
-
 #define ERR_BAD_IMAGE_LAYOUT (-2)
 
 #define CHECK_DST_ARRAY(start_offset, elements_per_scan, elements_per_pixel) \
@@ -2709,8 +2640,7 @@
             }
         }
         else if (mlibImP->type == MLIB_SHORT) {
-            return awt_setPixelShort(env, -1, rasterP,
-                                    (unsigned short *) mlibImP->data);
+            return awt_setPixels(env, rasterP, mlibImP->data);
         }
     }
     else {
diff --git a/jdk/src/share/native/sun/font/layout/GlyphIterator.cpp b/jdk/src/share/native/sun/font/layout/GlyphIterator.cpp
index d0cd467..3ccf66f 100644
--- a/jdk/src/share/native/sun/font/layout/GlyphIterator.cpp
+++ b/jdk/src/share/native/sun/font/layout/GlyphIterator.cpp
@@ -66,6 +66,7 @@
         nextLimit = -1;
         prevLimit = glyphCount;
     }
+    filterResetCache();
 }
 
 GlyphIterator::GlyphIterator(GlyphIterator &that)
@@ -84,6 +85,7 @@
     glyphGroup  = that.glyphGroup;
     glyphClassDefinitionTable = that.glyphClassDefinitionTable;
     markAttachClassDefinitionTable = that.markAttachClassDefinitionTable;
+    filterResetCache();
 }
 
 GlyphIterator::GlyphIterator(GlyphIterator &that, FeatureMask newFeatureMask)
@@ -102,6 +104,7 @@
     glyphGroup  = 0;
     glyphClassDefinitionTable = that.glyphClassDefinitionTable;
     markAttachClassDefinitionTable = that.markAttachClassDefinitionTable;
+    filterResetCache();
 }
 
 GlyphIterator::GlyphIterator(GlyphIterator &that, le_uint16 newLookupFlags)
@@ -120,6 +123,7 @@
     glyphGroup  = that.glyphGroup;
     glyphClassDefinitionTable = that.glyphClassDefinitionTable;
     markAttachClassDefinitionTable = that.markAttachClassDefinitionTable;
+    filterResetCache();
 }
 
 GlyphIterator::~GlyphIterator()
@@ -133,6 +137,7 @@
     featureMask  = newFeatureMask;
     glyphGroup   = 0;
     lookupFlags  = newLookupFlags;
+    filterResetCache();
 }
 
 LEGlyphID *GlyphIterator::insertGlyphs(le_int32 count, LEErrorCode& success)
@@ -381,53 +386,68 @@
     glyphPositionAdjustments->setCursiveGlyph(position, baselineIsLogicalEnd());
 }
 
-le_bool GlyphIterator::filterGlyph(le_uint32 index) const
-{
-    LEErrorCode success = LE_NO_ERROR;
-    LEGlyphID glyphID = glyphStorage[index];
-    le_int32 glyphClass = gcdNoGlyphClass;
-
-    if (LE_GET_GLYPH(glyphID) >= 0xFFFE) {
-        return TRUE;
+void GlyphIterator::filterResetCache(void) {
+  filterCacheValid = FALSE;
     }
 
+le_bool GlyphIterator::filterGlyph(le_uint32 index)
+{
+    LEGlyphID glyphID = glyphStorage[index];
+
+    if (!filterCacheValid || filterCache.id != glyphID) {
+      filterCache.id = glyphID;
+
+      le_bool &filterResult = filterCache.result;  // NB: Making this a reference to accept the updated value, in case
+                                               // we want more fancy cacheing in the future.
+    if (LE_GET_GLYPH(glyphID) >= 0xFFFE) {
+        filterResult = TRUE;
+      } else {
+        LEErrorCode success = LE_NO_ERROR;
+        le_int32 glyphClass = gcdNoGlyphClass;
     if (glyphClassDefinitionTable.isValid()) {
       glyphClass = glyphClassDefinitionTable->getGlyphClass(glyphClassDefinitionTable, glyphID, success);
     }
-
-    switch (glyphClass)
-    {
+        switch (glyphClass) {
     case gcdNoGlyphClass:
-        return FALSE;
+          filterResult = FALSE;
+          break;
 
     case gcdSimpleGlyph:
-        return (lookupFlags & lfIgnoreBaseGlyphs) != 0;
+          filterResult = (lookupFlags & lfIgnoreBaseGlyphs) != 0;
+          break;
 
     case gcdLigatureGlyph:
-        return (lookupFlags & lfIgnoreLigatures) != 0;
+          filterResult = (lookupFlags & lfIgnoreLigatures) != 0;
+          break;
 
     case gcdMarkGlyph:
-    {
         if ((lookupFlags & lfIgnoreMarks) != 0) {
-            return TRUE;
-        }
-
+            filterResult = TRUE;
+          } else {
         le_uint16 markAttachType = (lookupFlags & lfMarkAttachTypeMask) >> lfMarkAttachTypeShift;
 
         if ((markAttachType != 0) && (markAttachClassDefinitionTable.isValid())) {
-          return markAttachClassDefinitionTable
-            -> getGlyphClass(markAttachClassDefinitionTable, glyphID, success) != markAttachType;
+              filterResult = (markAttachClassDefinitionTable
+                          -> getGlyphClass(markAttachClassDefinitionTable, glyphID, success) != markAttachType);
+            } else {
+              filterResult = FALSE;
         }
-
-        return FALSE;
     }
+          break;
 
     case gcdComponentGlyph:
-        return (lookupFlags & lfIgnoreBaseGlyphs) != 0;
+          filterResult = ((lookupFlags & lfIgnoreBaseGlyphs) != 0);
+          break;
 
     default:
-        return FALSE;
+          filterResult = FALSE;
+          break;
     }
+      }
+      filterCacheValid = TRUE;
+        }
+
+    return filterCache.result;
 }
 
 le_bool GlyphIterator::hasFeatureTag(le_bool matchGroup) const
diff --git a/jdk/src/share/native/sun/font/layout/GlyphIterator.h b/jdk/src/share/native/sun/font/layout/GlyphIterator.h
index d8db62a..666b94d 100644
--- a/jdk/src/share/native/sun/font/layout/GlyphIterator.h
+++ b/jdk/src/share/native/sun/font/layout/GlyphIterator.h
@@ -98,7 +98,7 @@
     le_int32 applyInsertions();
 
 private:
-    le_bool filterGlyph(le_uint32 index) const;
+    le_bool filterGlyph(le_uint32 index);
     le_bool hasFeatureTag(le_bool matchGroup) const;
     le_bool nextInternal(le_uint32 delta = 1);
     le_bool prevInternal(le_uint32 delta = 1);
@@ -121,6 +121,14 @@
     LEReferenceTo<MarkAttachClassDefinitionTable> markAttachClassDefinitionTable;
 
     GlyphIterator &operator=(const GlyphIterator &other); // forbid copying of this class
+
+    struct {
+      LEGlyphID   id;
+      le_bool     result;
+    } filterCache;
+    le_bool   filterCacheValid;
+
+    void filterResetCache(void);
 };
 
 U_NAMESPACE_END
diff --git a/jdk/src/share/native/sun/font/layout/LETableReference.h b/jdk/src/share/native/sun/font/layout/LETableReference.h
index b68abb0..e1258b7 100644
--- a/jdk/src/share/native/sun/font/layout/LETableReference.h
+++ b/jdk/src/share/native/sun/font/layout/LETableReference.h
@@ -377,7 +377,7 @@
    * @param success error status
    * @param atPtr location of reference - if NULL, will be at offset zero (i.e. downcast of parent). Otherwise must be a pointer within parent's bounds.
    */
-  LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr)
+ inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr)
     : LETableReference(parent, parent.ptrToOffset(atPtr, success), LE_UINTPTR_MAX, success) {
     verifyLength(0, LETableVarSizer<T>::getSize(), success);
     if(LE_FAILURE(success)) clear();
@@ -385,31 +385,31 @@
   /**
    * ptr plus offset
    */
- LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr, size_t offset)
+ inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr, size_t offset)
     : LETableReference(parent, parent.ptrToOffset(atPtr, success)+offset, LE_UINTPTR_MAX, success) {
     verifyLength(0, LETableVarSizer<T>::getSize(), success);
     if(LE_FAILURE(success)) clear();
   }
-  LEReferenceTo(const LETableReference &parent, LEErrorCode &success, size_t offset)
+ inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success, size_t offset)
     : LETableReference(parent, offset, LE_UINTPTR_MAX, success) {
     verifyLength(0, LETableVarSizer<T>::getSize(), success);
     if(LE_FAILURE(success)) clear();
   }
-  LEReferenceTo(const LETableReference &parent, LEErrorCode &success)
+ inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success)
     : LETableReference(parent, 0, LE_UINTPTR_MAX, success) {
     verifyLength(0, LETableVarSizer<T>::getSize(), success);
     if(LE_FAILURE(success)) clear();
   }
- LEReferenceTo(const LEFontInstance *font, LETag tableTag, LEErrorCode &success)
+ inline LEReferenceTo(const LEFontInstance *font, LETag tableTag, LEErrorCode &success)
    : LETableReference(font, tableTag, success) {
     verifyLength(0, LETableVarSizer<T>::getSize(), success);
     if(LE_FAILURE(success)) clear();
   }
- LEReferenceTo(const le_uint8 *data, size_t length = LE_UINTPTR_MAX) : LETableReference(data, length) {}
- LEReferenceTo(const T *data, size_t length = LE_UINTPTR_MAX) : LETableReference((const le_uint8*)data, length) {}
-  LEReferenceTo() : LETableReference(NULL) {}
+ inline LEReferenceTo(const le_uint8 *data, size_t length = LE_UINTPTR_MAX) : LETableReference(data, length) {}
+ inline LEReferenceTo(const T *data, size_t length = LE_UINTPTR_MAX) : LETableReference((const le_uint8*)data, length) {}
+ inline LEReferenceTo() : LETableReference(NULL) {}
 
-  LEReferenceTo<T>& operator=(const T* other) {
+ inline LEReferenceTo<T>& operator=(const T* other) {
     setRaw(other);
     return *this;
   }
diff --git a/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp b/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp
index f234e94..4d810df 100644
--- a/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp
+++ b/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp
@@ -79,6 +79,7 @@
 
 Offset OpenTypeUtilities::getTagOffset(LETag tag, const LEReferenceToArrayOf<TagAndOffsetRecord> &records, LEErrorCode &success)
 {
+  const TagAndOffsetRecord *r0 = (const TagAndOffsetRecord*)records.getAlias();
   if(LE_FAILURE(success)) return 0;
 
   le_uint32 recordCount = records.getCount();
@@ -89,17 +90,17 @@
   le_int32 index = 0;
 
   {
-    const ATag &aTag = records.getAlias(extra,success)->tag;
+    const ATag &aTag = (r0+extra)->tag;
     if (SWAPT(aTag) <= tag) {
       index = extra;
     }
   }
 
-  while (probe > (1 << 0) && LE_SUCCESS(success)) {
+  while (probe > (1 << 0)) {
     probe >>= 1;
 
     {
-      const ATag &aTag = records.getAlias(index+probe,success)->tag;
+      const ATag &aTag = (r0+index+probe)->tag;
       if (SWAPT(aTag) <= tag) {
         index += probe;
       }
@@ -107,9 +108,9 @@
   }
 
   {
-    const ATag &aTag = records.getAlias(index,success)->tag;
+    const ATag &aTag = (r0+index)->tag;
     if (SWAPT(aTag) == tag) {
-      return SWAPW(records.getAlias(index,success)->offset);
+      return SWAPW((r0+index)->offset);
     }
   }
 
diff --git a/jdk/src/share/native/sun/font/layout/SunLayoutEngine.cpp b/jdk/src/share/native/sun/font/layout/SunLayoutEngine.cpp
index b32f260..858e363 100644
--- a/jdk/src/share/native/sun/font/layout/SunLayoutEngine.cpp
+++ b/jdk/src/share/native/sun/font/layout/SunLayoutEngine.cpp
@@ -104,6 +104,10 @@
 
 int putGV(JNIEnv* env, jint gmask, jint baseIndex, jobject gvdata, const LayoutEngine* engine, int glyphCount) {
     int count = env->GetIntField(gvdata, gvdCountFID);
+    if (count < 0) {
+      JNU_ThrowInternalError(env, "count negative");
+      return 0;
+    }
 
     jarray glyphArray = (jarray)env->GetObjectField(gvdata, gvdGlyphsFID);
     if (IS_NULL(glyphArray)) {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
index 5bad907..a18d75c 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
@@ -1074,6 +1074,27 @@
 }
 
 
+static
+cmsBool SanityCheck(_cmsICCPROFILE* profile)
+{
+    cmsIOHANDLER* io = profile->IOhandler;
+    if (!io) {
+        return FALSE;
+    }
+
+    if (!io->Seek ||
+        !(io->Seek==NULLSeek || io->Seek==MemorySeek || io->Seek==FileSeek))
+    {
+        return FALSE;
+    }
+    if (!io->Read ||
+        !(io->Read==NULLRead || io->Read==MemoryRead || io->Read==FileRead))
+    {
+        return FALSE;
+    }
+
+    return TRUE;
+}
 
 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
 static
@@ -1087,6 +1108,7 @@
     cmsTagTypeSignature TypeBase;
     cmsTagTypeHandler* TypeHandler;
 
+    if (!SanityCheck(FileOrig)) return FALSE;
 
     for (i=0; i < Icc -> TagCount; i++) {
 
@@ -1292,8 +1314,8 @@
     // Should we just calculate the needed space?
     if (MemPtr == NULL) {
 
-           *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
-            return TRUE;
+        *BytesNeeded = cmsSaveProfileToIOhandler(hProfile, NULL);
+        return (*BytesNeeded == 0 ? FALSE : TRUE);
     }
 
     // That is a real write operation
diff --git a/jdk/src/share/native/sun/management/HotSpotDiagnostic.c b/jdk/src/share/native/sun/management/HotSpotDiagnostic.c
index 8d48b20..cfa9e9a 100644
--- a/jdk/src/share/native/sun/management/HotSpotDiagnostic.c
+++ b/jdk/src/share/native/sun/management/HotSpotDiagnostic.c
@@ -29,7 +29,7 @@
 #include "sun_management_HotSpotDiagnostic.h"
 
 JNIEXPORT void JNICALL
-Java_sun_management_HotSpotDiagnostic_dumpHeap
+Java_sun_management_HotSpotDiagnostic_dumpHeap0
   (JNIEnv *env, jobject dummy, jstring outputfile, jboolean live)
 {
     jmm_interface->DumpHeap0(env, outputfile, live);
diff --git a/jdk/src/solaris/native/java/net/Inet6AddressImpl.c b/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
index 4038504..9fc10ef 100644
--- a/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
+++ b/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
@@ -122,7 +122,6 @@
 static jclass ni_ia6cls;
 static jmethodID ni_ia4ctrID;
 static jmethodID ni_ia6ctrID;
-static jfieldID ni_ia6ipaddressID;
 static int initialized = 0;
 
 /*
@@ -158,7 +157,6 @@
       ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
       ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
       ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-      ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
       initialized = 1;
     }
 
@@ -306,6 +304,7 @@
             }
 
             while (iterator != NULL) {
+              int ret1;
               if (iterator->ai_family == AF_INET) {
                 jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
                 if (IS_NULL(iaObj)) {
@@ -318,20 +317,17 @@
                 inetIndex++;
               } else if (iterator->ai_family == AF_INET6) {
                 jint scope = 0;
-                jbyteArray ipaddress;
 
                 jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
                 if (IS_NULL(iaObj)) {
                   ret = NULL;
                   goto cleanupAndReturn;
                 }
-                ipaddress = (*env)->NewByteArray(env, 16);
-                if (IS_NULL(ipaddress)) {
-                  ret = NULL;
-                  goto cleanupAndReturn;
+                ret1 = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
+                if (!ret1) {
+                    ret = NULL;
+                    goto cleanupAndReturn;
                 }
-                (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
-                                           (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
 #ifdef __linux__
                 if (!kernelIsV22()) {
                   scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
@@ -340,10 +336,8 @@
                 scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
 #endif
                 if (scope != 0) { /* zero is default value, no need to set */
-                  (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
-                  (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
+                  setInet6Address_scopeid(env, iaObj, scope);
                 }
-                (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
                 setInetAddress_hostName(env, iaObj, host);
                 (*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
                 inet6Index++;
diff --git a/jdk/src/solaris/native/java/net/NetworkInterface.c b/jdk/src/solaris/native/java/net/NetworkInterface.c
index 6a31a61..ddf8bb4 100644
--- a/jdk/src/solaris/native/java/net/NetworkInterface.c
+++ b/jdk/src/solaris/native/java/net/NetworkInterface.c
@@ -118,7 +118,6 @@
 static jmethodID ni_ia4ctrID;
 static jmethodID ni_ia6ctrID;
 static jmethodID ni_ibctrID;
-static jfieldID ni_ia6ipaddressID;
 static jfieldID ni_ibaddressID;
 static jfieldID ni_ib4broadcastID;
 static jfieldID ni_ib4maskID;
@@ -193,7 +192,6 @@
     ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
     ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
     ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
-    ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
     ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address", "Ljava/net/InetAddress;");
     ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
     ni_ib4maskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
@@ -332,11 +330,9 @@
 #ifdef AF_INET6
                 if (family == AF_INET6) {
                     jbyte *bytes = (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr);
-                    jbyteArray ipaddress = (*env)->GetObjectField(env, iaObj, ni_ia6ipaddressID);
                     jbyte caddr[16];
                     int i;
-
-                    (*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
+                    getInet6Address_ipaddress(env, iaObj, (char *)caddr);
                     i = 0;
                     while (i < 16) {
                         if (caddr[i] != bytes[i]) {
@@ -670,21 +666,17 @@
             int scope=0;
             iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
             if (iaObj) {
-                jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
-                if (ipaddress == NULL) {
+                int ret = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
+                if (ret == JNI_FALSE) {
                     return NULL;
                 }
-                (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
-                                                                        (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
 
                 scope = ((struct sockaddr_in6*)addrP->addr)->sin6_scope_id;
 
                 if (scope != 0) { /* zero is default value, no need to set */
-                    (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
-                    (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
-                    (*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
+                    setInet6Address_scopeid(env, iaObj, scope);
+                    setInet6Address_scopeifname(env, iaObj, netifObj);
                 }
-                (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
             }
             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
             if (ibObj) {
diff --git a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
index 64f0b7b..2b542e7 100644
--- a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
@@ -2359,8 +2359,7 @@
             caddr[14] = ((address >> 8) & 0xff);
             caddr[15] = (address & 0xff);
         } else {
-            ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
-            (*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
+            getInet6Address_ipaddress(env, iaObj, caddr);
         }
 
         memcpy((void *)&(mname6.ipv6mr_multiaddr), caddr, sizeof(struct in6_addr));
diff --git a/jdk/src/solaris/native/java/net/net_util_md.c b/jdk/src/solaris/native/java/net/net_util_md.c
index 84b3156..1640676 100644
--- a/jdk/src/solaris/native/java/net/net_util_md.c
+++ b/jdk/src/solaris/native/java/net/net_util_md.c
@@ -823,7 +823,6 @@
     /* needs work. 1. family 2. clean up him6 etc deallocate memory */
     if (ipv6_available() && !(family == IPv4 && v4MappedAddress == JNI_FALSE)) {
         struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
-        jbyteArray ipaddress;
         jbyte caddr[16];
         jint address;
 
@@ -844,8 +843,7 @@
                 caddr[15] = (address & 0xff);
             }
         } else {
-            ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
-            (*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
+            getInet6Address_ipaddress(env, iaObj, (char *)caddr);
         }
         memset((char *)him6, 0, sizeof(struct sockaddr_in6));
         him6->sin6_port = htons(port);
@@ -882,7 +880,7 @@
                  */
                 if (!cached_scope_id) {
                     if (ia6_scopeidID) {
-                        scope_id = (int)(*env)->GetIntField(env,iaObj,ia6_scopeidID);
+                        scope_id = getInet6Address_scopeid(env, iaObj);
                     }
                     if (scope_id != 0) {
                         /* check user-specified value for loopback case
@@ -928,7 +926,7 @@
 
         if (family != IPv4) {
             if (ia6_scopeidID) {
-                him6->sin6_scope_id = (int)(*env)->GetIntField(env, iaObj, ia6_scopeidID);
+                him6->sin6_scope_id = getInet6Address_scopeid(env, iaObj);
             }
         }
 #endif
diff --git a/jdk/src/windows/native/java/net/Inet6AddressImpl.c b/jdk/src/windows/native/java/net/Inet6AddressImpl.c
index 8640128..fc3c51c 100644
--- a/jdk/src/windows/native/java/net/Inet6AddressImpl.c
+++ b/jdk/src/windows/native/java/net/Inet6AddressImpl.c
@@ -77,7 +77,6 @@
 static jclass ni_ia6cls;
 static jmethodID ni_ia4ctrID;
 static jmethodID ni_ia6ctrID;
-static jfieldID ni_ia6ipaddressID;
 static int initialized = 0;
 
 JNIEXPORT jobjectArray JNICALL
@@ -101,7 +100,6 @@
       ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
       ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
       ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-      ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
       initialized = 1;
     }
     if (IS_NULL(host)) {
@@ -242,26 +240,22 @@
               (*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj);
                 inetIndex ++;
             } else if (iterator->ai_family == AF_INET6) {
-              jint scope = 0;
-              jbyteArray ipaddress;
+              jint scope = 0, ret1;
               jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
               if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
               }
-              ipaddress = (*env)->NewByteArray(env, 16);
-              if (IS_NULL(ipaddress)) {
+              ret1 = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
+
+              if (ret1 == JNI_FALSE) {
                 ret = NULL;
                 goto cleanupAndReturn;
               }
-              (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
-                                         (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
               scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
               if (scope != 0) { /* zero is default value, no need to set */
-                (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
-                (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
+                setInet6Address_scopeid(env, iaObj, scope);
               }
-              (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
               setInetAddress_hostName(env, iaObj, host);
               (*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
               inet6Index ++;
diff --git a/jdk/src/windows/native/java/net/NetworkInterface.c b/jdk/src/windows/native/java/net/NetworkInterface.c
index 16e2f01..7c01845 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface.c
@@ -72,8 +72,6 @@
 
 jclass ni_ia6cls;           /* Inet6Address */
 jmethodID ni_ia6ctrID;      /* Inet6Address() */
-jfieldID ni_ia6ipaddressID;
-jfieldID ni_ia6ipaddressID;
 
 jclass ni_ibcls;            /* InterfaceAddress */
 jmethodID ni_ibctrID;       /* InterfaceAddress() */
@@ -482,7 +480,6 @@
     ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
     ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
     ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-    ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
 
     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
@@ -583,19 +580,16 @@
             int scope;
             iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
             if (iaObj) {
-                jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
-                if (ipaddress == NULL) {
+                int ret = setInet6Address_ipaddress(env, iaObj,  (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
+                if (ret == JNI_FALSE) {
                     return NULL;
                 }
-                (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
-                    (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
+
                 scope = addrs->addr.him6.sin6_scope_id;
                 if (scope != 0) { /* zero is default value, no need to set */
-                    (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
-                    (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
-                    (*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
+                    setInet6Address_scopeid(env, iaObj, scope);
+                    setInet6Address_scopeifname(env, iaObj, netifObj);
                 }
-                (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
                 ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
                 if (ibObj == NULL) {
                   free_netaddr(netaddrP);
diff --git a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
index d8e6484..f2e22fd 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
@@ -499,19 +499,15 @@
             int scope;
             iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
             if (iaObj) {
-                jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
-                if (ipaddress == NULL) {
+                int ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
+                if (ret == JNI_FALSE) {
                     return NULL;
                 }
-                (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
-                    (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
                 scope = addrs->addr.him6.sin6_scope_id;
                 if (scope != 0) { /* zero is default value, no need to set */
-                    (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
-                    (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
-                    (*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
+                    setInet6Address_scopeid(env, iaObj, scope);
+                    setInet6Address_scopeifname(env, iaObj, netifObj);
                 }
-                (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
                 ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
                 if (ibObj == NULL) {
                   free_netaddr(netaddrP);
diff --git a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
index eca2ae1..d0c7edd 100644
--- a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
@@ -728,7 +728,6 @@
         setInetAddress_family(env, socketAddressObj, IPv4);
         (*env)->SetObjectField(env, socket, psi_addressID, socketAddressObj);
     } else {
-        jbyteArray addr;
         /* AF_INET6 -> Inet6Address */
         if (inet6Cls == 0) {
             jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
@@ -751,10 +750,10 @@
             NET_SocketClose(fd);
             return;
         }
-        addr = (*env)->GetObjectField (env, socketAddressObj, ia6_ipaddressID);
-        (*env)->SetByteArrayRegion (env, addr, 0, 16, (const char *)&him.him6.sin6_addr);
+        setInet6Address_ipaddress(env, socketAddressObj, (const char *)&him.him6.sin6_addr);
+
         setInetAddress_family(env, socketAddressObj, IPv6);
-        (*env)->SetIntField(env, socketAddressObj, ia6_scopeidID, him.him6.sin6_scope_id);
+        setInet6Address_scopeid(env, socketAddressObj, him.him6.sin6_scope_id);
     }
     /* fields common to AF_INET and AF_INET6 */
 
diff --git a/jdk/src/windows/native/java/net/net_util_md.c b/jdk/src/windows/native/java/net/net_util_md.c
index 258e28d..bd87b53 100644
--- a/jdk/src/windows/native/java/net/net_util_md.c
+++ b/jdk/src/windows/native/java/net/net_util_md.c
@@ -851,7 +851,6 @@
     family = (iafam == IPv4)? AF_INET : AF_INET6;
     if (ipv6_available() && !(family == AF_INET && v4MappedAddress == JNI_FALSE)) {
         struct SOCKADDR_IN6 *him6 = (struct SOCKADDR_IN6 *)him;
-        jbyteArray ipaddress;
         jbyte caddr[16];
         jint address, scopeid = 0;
         jint cached_scope_id = 0;
@@ -872,10 +871,9 @@
                 caddr[15] = (address & 0xff);
             }
         } else {
-            ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
-            scopeid = (jint)(*env)->GetIntField(env, iaObj, ia6_scopeidID);
+            getInet6Address_ipaddress(env, iaObj, (char *)caddr);
+            scopeid = getInet6Address_scopeid(env, iaObj);
             cached_scope_id = (jint)(*env)->GetIntField(env, iaObj, ia6_cachedscopeidID);
-            (*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
         }
 
         memset((char *)him6, 0, sizeof(struct SOCKADDR_IN6));
diff --git a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java
index dbebe85..a6b2003 100644
--- a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java
+++ b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java
@@ -74,6 +74,7 @@
         "com.sun.org.apache.xml.internal.serializer.utils.",
         "com.sun.org.apache.xml.internal.utils.",
         "com.sun.org.glassfish.",
+        "com.sun.script.",
         "oracle.jrockit.jfr.",
         "org.jcp.xml.dsig.internal.",
     };
diff --git a/jdk/test/java/net/Inet6Address/serialize/Serialize.java b/jdk/test/java/net/Inet6Address/serialize/Serialize.java
index c563c8b..f7c6fe7 100644
--- a/jdk/test/java/net/Inet6Address/serialize/Serialize.java
+++ b/jdk/test/java/net/Inet6Address/serialize/Serialize.java
@@ -94,7 +94,26 @@
          } finally {
              ois.close();
          }
-         System.out.println(nobj);
+
+         nobj = (Inet6Address)InetAddress.getByAddress("foo.com", new byte[] {
+             (byte)0xfe,(byte)0x80,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
+             (byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)1
+         });
+         if (!test1(nobj, addr1)) {
+             throw new RuntimeException("failed with " + nobj.toString());
+         }
+         nobj = (Inet6Address)InetAddress.getByAddress("x.bar.com", new byte[] {
+             (byte)0xfe,(byte)0xC0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,
+             (byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)1
+         });
+         if (!test1(nobj, addr2)) {
+             throw new RuntimeException("failed with " + nobj.toString());
+         }
+         nobj = (Inet6Address)InetAddress.getByName("::1");
+         if (!test1(nobj, addr3)) {
+             throw new RuntimeException("failed with " + nobj.toString());
+         }
+
          System.out.println("All tests passed");
      }
 
@@ -113,4 +132,162 @@
              return false;
          }
      }
- }
+
+    static boolean test1 (Inet6Address obj, byte[] buf) throws Exception {
+         ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buf));
+         Inet6Address nobj = (Inet6Address) ois.readObject();
+         ois.close();
+
+         if (nobj.equals(obj)) {
+             return true;
+         } else {
+             return false;
+         }
+    }
+
+    // Inet6Address instances serialized with JDK 6
+
+    static byte[] addr1 = {
+        (byte)0xac,(byte)0xed,(byte)0x00,(byte)0x05,(byte)0x73,(byte)0x72,
+        (byte)0x00,(byte)0x15,(byte)0x6a,(byte)0x61,(byte)0x76,(byte)0x61,
+        (byte)0x2e,(byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x2e,(byte)0x49,
+        (byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x36,(byte)0x41,(byte)0x64,
+        (byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,(byte)0x73,(byte)0x5f,
+        (byte)0x7c,(byte)0x20,(byte)0x81,(byte)0x52,(byte)0x2c,(byte)0x80,
+        (byte)0x21,(byte)0x03,(byte)0x00,(byte)0x05,(byte)0x49,(byte)0x00,
+        (byte)0x08,(byte)0x73,(byte)0x63,(byte)0x6f,(byte)0x70,(byte)0x65,
+        (byte)0x5f,(byte)0x69,(byte)0x64,(byte)0x5a,(byte)0x00,(byte)0x0c,
+        (byte)0x73,(byte)0x63,(byte)0x6f,(byte)0x70,(byte)0x65,(byte)0x5f,
+        (byte)0x69,(byte)0x64,(byte)0x5f,(byte)0x73,(byte)0x65,(byte)0x74,
+        (byte)0x5a,(byte)0x00,(byte)0x10,(byte)0x73,(byte)0x63,(byte)0x6f,
+        (byte)0x70,(byte)0x65,(byte)0x5f,(byte)0x69,(byte)0x66,(byte)0x6e,
+        (byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x5f,(byte)0x73,(byte)0x65,
+        (byte)0x74,(byte)0x4c,(byte)0x00,(byte)0x06,(byte)0x69,(byte)0x66,
+        (byte)0x6e,(byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x74,(byte)0x00,
+        (byte)0x12,(byte)0x4c,(byte)0x6a,(byte)0x61,(byte)0x76,(byte)0x61,
+        (byte)0x2f,(byte)0x6c,(byte)0x61,(byte)0x6e,(byte)0x67,(byte)0x2f,
+        (byte)0x53,(byte)0x74,(byte)0x72,(byte)0x69,(byte)0x6e,(byte)0x67,
+        (byte)0x3b,(byte)0x5b,(byte)0x00,(byte)0x09,(byte)0x69,(byte)0x70,
+        (byte)0x61,(byte)0x64,(byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,
+        (byte)0x73,(byte)0x74,(byte)0x00,(byte)0x02,(byte)0x5b,(byte)0x42,
+        (byte)0x78,(byte)0x72,(byte)0x00,(byte)0x14,(byte)0x6a,(byte)0x61,
+        (byte)0x76,(byte)0x61,(byte)0x2e,(byte)0x6e,(byte)0x65,(byte)0x74,
+        (byte)0x2e,(byte)0x49,(byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x41,
+        (byte)0x64,(byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,(byte)0x73,
+        (byte)0x2d,(byte)0x9b,(byte)0x57,(byte)0xaf,(byte)0x9f,(byte)0xe3,
+        (byte)0xeb,(byte)0xdb,(byte)0x02,(byte)0x00,(byte)0x03,(byte)0x49,
+        (byte)0x00,(byte)0x07,(byte)0x61,(byte)0x64,(byte)0x64,(byte)0x72,
+        (byte)0x65,(byte)0x73,(byte)0x73,(byte)0x49,(byte)0x00,(byte)0x06,
+        (byte)0x66,(byte)0x61,(byte)0x6d,(byte)0x69,(byte)0x6c,(byte)0x79,
+        (byte)0x4c,(byte)0x00,(byte)0x08,(byte)0x68,(byte)0x6f,(byte)0x73,
+        (byte)0x74,(byte)0x4e,(byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x71,
+        (byte)0x00,(byte)0x7e,(byte)0x00,(byte)0x01,(byte)0x78,(byte)0x70,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x02,(byte)0x74,(byte)0x00,(byte)0x07,(byte)0x66,
+        (byte)0x6f,(byte)0x6f,(byte)0x2e,(byte)0x63,(byte)0x6f,(byte)0x6d,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x70,(byte)0x75,(byte)0x72,(byte)0x00,(byte)0x02,(byte)0x5b,
+        (byte)0x42,(byte)0xac,(byte)0xf3,(byte)0x17,(byte)0xf8,(byte)0x06,
+        (byte)0x08,(byte)0x54,(byte)0xe0,(byte)0x02,(byte)0x00,(byte)0x00,
+        (byte)0x78,(byte)0x70,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x10,
+        (byte)0xfe,(byte)0x80,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x78
+    };
+
+    static byte[] addr2 = {
+        (byte)0xac,(byte)0xed,(byte)0x00,(byte)0x05,(byte)0x73,(byte)0x72,
+        (byte)0x00,(byte)0x15,(byte)0x6a,(byte)0x61,(byte)0x76,(byte)0x61,
+        (byte)0x2e,(byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x2e,(byte)0x49,
+        (byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x36,(byte)0x41,(byte)0x64,
+        (byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,(byte)0x73,(byte)0x5f,
+        (byte)0x7c,(byte)0x20,(byte)0x81,(byte)0x52,(byte)0x2c,(byte)0x80,
+        (byte)0x21,(byte)0x03,(byte)0x00,(byte)0x05,(byte)0x49,(byte)0x00,
+        (byte)0x08,(byte)0x73,(byte)0x63,(byte)0x6f,(byte)0x70,(byte)0x65,
+        (byte)0x5f,(byte)0x69,(byte)0x64,(byte)0x5a,(byte)0x00,(byte)0x0c,
+        (byte)0x73,(byte)0x63,(byte)0x6f,(byte)0x70,(byte)0x65,(byte)0x5f,
+        (byte)0x69,(byte)0x64,(byte)0x5f,(byte)0x73,(byte)0x65,(byte)0x74,
+        (byte)0x5a,(byte)0x00,(byte)0x10,(byte)0x73,(byte)0x63,(byte)0x6f,
+        (byte)0x70,(byte)0x65,(byte)0x5f,(byte)0x69,(byte)0x66,(byte)0x6e,
+        (byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x5f,(byte)0x73,(byte)0x65,
+        (byte)0x74,(byte)0x4c,(byte)0x00,(byte)0x06,(byte)0x69,(byte)0x66,
+        (byte)0x6e,(byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x74,(byte)0x00,
+        (byte)0x12,(byte)0x4c,(byte)0x6a,(byte)0x61,(byte)0x76,(byte)0x61,
+        (byte)0x2f,(byte)0x6c,(byte)0x61,(byte)0x6e,(byte)0x67,(byte)0x2f,
+        (byte)0x53,(byte)0x74,(byte)0x72,(byte)0x69,(byte)0x6e,(byte)0x67,
+        (byte)0x3b,(byte)0x5b,(byte)0x00,(byte)0x09,(byte)0x69,(byte)0x70,
+        (byte)0x61,(byte)0x64,(byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,
+        (byte)0x73,(byte)0x74,(byte)0x00,(byte)0x02,(byte)0x5b,(byte)0x42,
+        (byte)0x78,(byte)0x72,(byte)0x00,(byte)0x14,(byte)0x6a,(byte)0x61,
+        (byte)0x76,(byte)0x61,(byte)0x2e,(byte)0x6e,(byte)0x65,(byte)0x74,
+        (byte)0x2e,(byte)0x49,(byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x41,
+        (byte)0x64,(byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,(byte)0x73,
+        (byte)0x2d,(byte)0x9b,(byte)0x57,(byte)0xaf,(byte)0x9f,(byte)0xe3,
+        (byte)0xeb,(byte)0xdb,(byte)0x02,(byte)0x00,(byte)0x03,(byte)0x49,
+        (byte)0x00,(byte)0x07,(byte)0x61,(byte)0x64,(byte)0x64,(byte)0x72,
+        (byte)0x65,(byte)0x73,(byte)0x73,(byte)0x49,(byte)0x00,(byte)0x06,
+        (byte)0x66,(byte)0x61,(byte)0x6d,(byte)0x69,(byte)0x6c,(byte)0x79,
+        (byte)0x4c,(byte)0x00,(byte)0x08,(byte)0x68,(byte)0x6f,(byte)0x73,
+        (byte)0x74,(byte)0x4e,(byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x71,
+        (byte)0x00,(byte)0x7e,(byte)0x00,(byte)0x01,(byte)0x78,(byte)0x70,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x02,(byte)0x74,(byte)0x00,(byte)0x09,(byte)0x78,
+        (byte)0x2e,(byte)0x62,(byte)0x61,(byte)0x72,(byte)0x2e,(byte)0x63,
+        (byte)0x6f,(byte)0x6d,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x70,(byte)0x75,(byte)0x72,(byte)0x00,
+        (byte)0x02,(byte)0x5b,(byte)0x42,(byte)0xac,(byte)0xf3,(byte)0x17,
+        (byte)0xf8,(byte)0x06,(byte)0x08,(byte)0x54,(byte)0xe0,(byte)0x02,
+        (byte)0x00,(byte)0x00,(byte)0x78,(byte)0x70,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x10,(byte)0xfe,(byte)0xc0,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,
+        (byte)0x78
+    };
+
+    static byte[] addr3 = {
+        (byte)0xac,(byte)0xed,(byte)0x00,(byte)0x05,(byte)0x73,(byte)0x72,
+        (byte)0x00,(byte)0x15,(byte)0x6a,(byte)0x61,(byte)0x76,(byte)0x61,
+        (byte)0x2e,(byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x2e,(byte)0x49,
+        (byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x36,(byte)0x41,(byte)0x64,
+        (byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,(byte)0x73,(byte)0x5f,
+        (byte)0x7c,(byte)0x20,(byte)0x81,(byte)0x52,(byte)0x2c,(byte)0x80,
+        (byte)0x21,(byte)0x03,(byte)0x00,(byte)0x05,(byte)0x49,(byte)0x00,
+        (byte)0x08,(byte)0x73,(byte)0x63,(byte)0x6f,(byte)0x70,(byte)0x65,
+        (byte)0x5f,(byte)0x69,(byte)0x64,(byte)0x5a,(byte)0x00,(byte)0x0c,
+        (byte)0x73,(byte)0x63,(byte)0x6f,(byte)0x70,(byte)0x65,(byte)0x5f,
+        (byte)0x69,(byte)0x64,(byte)0x5f,(byte)0x73,(byte)0x65,(byte)0x74,
+        (byte)0x5a,(byte)0x00,(byte)0x10,(byte)0x73,(byte)0x63,(byte)0x6f,
+        (byte)0x70,(byte)0x65,(byte)0x5f,(byte)0x69,(byte)0x66,(byte)0x6e,
+        (byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x5f,(byte)0x73,(byte)0x65,
+        (byte)0x74,(byte)0x4c,(byte)0x00,(byte)0x06,(byte)0x69,(byte)0x66,
+        (byte)0x6e,(byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x74,(byte)0x00,
+        (byte)0x12,(byte)0x4c,(byte)0x6a,(byte)0x61,(byte)0x76,(byte)0x61,
+        (byte)0x2f,(byte)0x6c,(byte)0x61,(byte)0x6e,(byte)0x67,(byte)0x2f,
+        (byte)0x53,(byte)0x74,(byte)0x72,(byte)0x69,(byte)0x6e,(byte)0x67,
+        (byte)0x3b,(byte)0x5b,(byte)0x00,(byte)0x09,(byte)0x69,(byte)0x70,
+        (byte)0x61,(byte)0x64,(byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,
+        (byte)0x73,(byte)0x74,(byte)0x00,(byte)0x02,(byte)0x5b,(byte)0x42,
+        (byte)0x78,(byte)0x72,(byte)0x00,(byte)0x14,(byte)0x6a,(byte)0x61,
+        (byte)0x76,(byte)0x61,(byte)0x2e,(byte)0x6e,(byte)0x65,(byte)0x74,
+        (byte)0x2e,(byte)0x49,(byte)0x6e,(byte)0x65,(byte)0x74,(byte)0x41,
+        (byte)0x64,(byte)0x64,(byte)0x72,(byte)0x65,(byte)0x73,(byte)0x73,
+        (byte)0x2d,(byte)0x9b,(byte)0x57,(byte)0xaf,(byte)0x9f,(byte)0xe3,
+        (byte)0xeb,(byte)0xdb,(byte)0x02,(byte)0x00,(byte)0x03,(byte)0x49,
+        (byte)0x00,(byte)0x07,(byte)0x61,(byte)0x64,(byte)0x64,(byte)0x72,
+        (byte)0x65,(byte)0x73,(byte)0x73,(byte)0x49,(byte)0x00,(byte)0x06,
+        (byte)0x66,(byte)0x61,(byte)0x6d,(byte)0x69,(byte)0x6c,(byte)0x79,
+        (byte)0x4c,(byte)0x00,(byte)0x08,(byte)0x68,(byte)0x6f,(byte)0x73,
+        (byte)0x74,(byte)0x4e,(byte)0x61,(byte)0x6d,(byte)0x65,(byte)0x71,
+        (byte)0x00,(byte)0x7e,(byte)0x00,(byte)0x01,(byte)0x78,(byte)0x70,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x02,(byte)0x70,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x70,(byte)0x75,(byte)0x72,
+        (byte)0x00,(byte)0x02,(byte)0x5b,(byte)0x42,(byte)0xac,(byte)0xf3,
+        (byte)0x17,(byte)0xf8,(byte)0x06,(byte)0x08,(byte)0x54,(byte)0xe0,
+        (byte)0x02,(byte)0x00,(byte)0x00,(byte)0x78,(byte)0x70,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x10,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
+        (byte)0x01,(byte)0x78
+    };
+}
diff --git a/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java b/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java
index b120c86..f1ab76c 100644
--- a/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java
+++ b/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 4915825 4921009 4934965 4977469
+ * @bug 4915825 4921009 4934965 4977469 8019584
  * @summary Tests behavior when client or server gets object of unknown class
  * @author Eamonn McManus
  * @run clean MissingClassTest SingleClassLoader
diff --git a/langtools/.hgtags b/langtools/.hgtags
index 7820b4a..e54ec43 100644
--- a/langtools/.hgtags
+++ b/langtools/.hgtags
@@ -301,6 +301,22 @@
 17ee569d0c0130824ba27bc1b090114e6075c5f2 jdk7u25-b09
 41c1b02cd6a8fa7746752cc911da3dd4d380098d jdk7u25-b10
 0da9ef0d9fc5b017f960d65ae0cd07860a259621 jdk7u25-b11
+cf80c545434cfe44034e667079673ce42cc9cdbf jdk7u14-b16
+aecd58f25d7f21827ae1b020ae8cfb44857c439f jdk7u14-b17
+577f9625ec558c18e9de6e3428fd0f9cca823033 jdk7u14-b18
+5168a2c7af619364ddb342674ff880874c3b7897 jdk7u14-b19
+5168a2c7af619364ddb342674ff880874c3b7897 jdk7u14-b19
+e8c876a77def120b5eeb26535d0777c9b9f842f8 jdk7u14-b19
+86ae75a68cc375cfc0559699b5270951aab09eb0 jdk7u14-b20
+c31648d7a6ac692371f1e9abe95bc2856a7dc51c jdk7u14-b21
+eb1c9eacea1f07c07e7e700db624649d3573dae4 jdk7u14-b22
+e84535d2c292032669ac75a6a0afc5f23c708064 jdk7u40-b23
+d2b78e3b352dfb9b0cbd808669f9332e898147ed jdk7u40-b24
+e5635f70fe67192142cb5166bee08cc915a18bc4 jdk7u40-b25
+5bd6f156bc01b6a4e901fc5607663dfc249e9105 jdk7u40-b26
+12506bba2b67cd4b229550da67ff85b984549a28 jdk7u40-b27
+9f2eea2fae59c5242d1bb4cbca967bb6fbb99865 jdk7u40-b28
+bfe3575143fddbf71c2e570b580afef007d171e4 jdk7u40-b29
 28358b2489b2ca29c1a6b79f643204da8924a3d7 jdk7u25-b12
 5ed8c453480063838b632c74f528924f529361a2 jdk7u25-b13
 c6342ec6a12f7283e2a73a80a44dcdd3683e2e8b jdk7u25-b14
@@ -336,3 +352,9 @@
 524b9f7e6cabc8f7bad1824090e9b0dbf14ece74 jdk7u40-b35
 6837776bcdfafd0f963667156633142d433860f3 jdk7u40-b36
 31908290e4c2241ae9a8000c2a80e0f5fbad2a2c jdk7u40-b37
+21672c0e6691cfa1a477e7f0065afecb4148ddff jdk7u40-b38
+9bbfba4981e1db5016bbfbc23025763966021c26 jdk7u45-b01
+61d5b73ae0ac46268490e2f0dfa1f69a5acda73f jdk7u45-b02
+2fe27ae865e723473225756f1920d9d76d47b903 jdk7u45-b03
+bede296dc848533abae859e61584a517df2773ae jdk7u45-b04
+e989f2f2b5cb639a23a5e67da0d52766acf549a2 jdk7u45-b05
diff --git a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java
index f0c549c..1100044 100644
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java
@@ -292,7 +292,7 @@
             script.addAttr(HtmlAttr.TYPE, "text/javascript");
             String scriptCode = "<!--" + DocletConstants.NL +
                     "    if (location.href.indexOf('is-external=true') == -1) {" + DocletConstants.NL +
-                    "        parent.document.title=\"" + winTitle + "\";" + DocletConstants.NL +
+                    "        parent.document.title=\"" + escapeJavaScriptChars(winTitle) + "\";" + DocletConstants.NL +
                     "    }" + DocletConstants.NL +
                     "//-->" + DocletConstants.NL;
             RawHtml scriptContent = new RawHtml(scriptCode);
@@ -302,6 +302,53 @@
     }
 
     /**
+     * Returns a String with escaped special JavaScript characters.
+     *
+     * @param s String that needs to be escaped
+     * @return a valid escaped JavaScript string
+     */
+    private static String escapeJavaScriptChars(String s) {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < s.length(); i++) {
+            char ch = s.charAt(i);
+            switch (ch) {
+                case '\b':
+                    sb.append("\\b");
+                    break;
+                case '\t':
+                    sb.append("\\t");
+                    break;
+                case '\n':
+                    sb.append("\\n");
+                    break;
+                case '\f':
+                    sb.append("\\f");
+                    break;
+                case '\r':
+                    sb.append("\\r");
+                    break;
+                case '"':
+                    sb.append("\\\"");
+                    break;
+                case '\'':
+                    sb.append("\\\'");
+                    break;
+                case '\\':
+                    sb.append("\\\\");
+                    break;
+                default:
+                    if (ch < 32 || ch >= 127) {
+                        sb.append(String.format("\\u%04X", (int)ch));
+                    } else {
+                        sb.append(ch);
+                    }
+                    break;
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
      * Returns a content tree for the SCRIPT tag for the main page(index.html).
      *
      * @return a content for the SCRIPT tag
diff --git a/langtools/src/share/classes/com/sun/tools/javac/parser/Scanner.java b/langtools/src/share/classes/com/sun/tools/javac/parser/Scanner.java
index f2d62db..6ed81fe 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/parser/Scanner.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/parser/Scanner.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -501,11 +501,10 @@
     private void scanIdent() {
         boolean isJavaIdentifierPart;
         char high;
+        if (sp == sbuf.length) putChar(ch); else sbuf[sp++] = ch;
+        // optimization, was: putChar(ch);
+        scanChar();
         do {
-            if (sp == sbuf.length) putChar(ch); else sbuf[sp++] = ch;
-            // optimization, was: putChar(ch);
-
-            scanChar();
             switch (ch) {
             case 'A': case 'B': case 'C': case 'D': case 'E':
             case 'F': case 'G': case 'H': case 'I': case 'J':
@@ -522,6 +521,7 @@
             case '$': case '_':
             case '0': case '1': case '2': case '3': case '4':
             case '5': case '6': case '7': case '8': case '9':
+                break;
             case '\u0000': case '\u0001': case '\u0002': case '\u0003':
             case '\u0004': case '\u0005': case '\u0006': case '\u0007':
             case '\u0008': case '\u000E': case '\u000F': case '\u0010':
@@ -529,30 +529,37 @@
             case '\u0015': case '\u0016': case '\u0017':
             case '\u0018': case '\u0019': case '\u001B':
             case '\u007F':
-                break;
+                scanChar();
+                continue;
             case '\u001A': // EOI is also a legal identifier part
                 if (bp >= buflen) {
                     name = names.fromChars(sbuf, 0, sp);
                     token = keywords.key(name);
                     return;
                 }
-                break;
+                scanChar();
+                continue;
             default:
                 if (ch < '\u0080') {
                     // all ASCII range chars already handled, above
                     isJavaIdentifierPart = false;
                 } else {
-                    high = scanSurrogates();
-                    if (high != 0) {
-                        if (sp == sbuf.length) {
-                            putChar(high);
-                        } else {
-                            sbuf[sp++] = high;
-                        }
-                        isJavaIdentifierPart = Character.isJavaIdentifierPart(
-                            Character.toCodePoint(high, ch));
+                    if (Character.isIdentifierIgnorable(ch)) {
+                        scanChar();
+                        continue;
                     } else {
-                        isJavaIdentifierPart = Character.isJavaIdentifierPart(ch);
+                        high = scanSurrogates();
+                        if (high != 0) {
+                            if (sp == sbuf.length) {
+                                putChar(high);
+                            } else {
+                                sbuf[sp++] = high;
+                            }
+                            isJavaIdentifierPart = Character.isJavaIdentifierPart(
+                                Character.toCodePoint(high, ch));
+                        } else {
+                            isJavaIdentifierPart = Character.isJavaIdentifierPart(ch);
+                        }
                     }
                 }
                 if (!isJavaIdentifierPart) {
@@ -561,6 +568,9 @@
                     return;
                 }
             }
+            if (sp == sbuf.length) putChar(ch); else sbuf[sp++] = ch;
+            // optimization, was: putChar(ch);
+            scanChar();
         } while (true);
     }
 
diff --git a/langtools/test/com/sun/javadoc/testWindowTitle/TestWindowTitle.java b/langtools/test/com/sun/javadoc/testWindowTitle/TestWindowTitle.java
new file mode 100644
index 0000000..ca4c96a
--- /dev/null
+++ b/langtools/test/com/sun/javadoc/testWindowTitle/TestWindowTitle.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8016675
+ * @summary Test for window title.
+ * @author Bhavesh Patel
+ * @library ../lib/
+ * @build JavadocTester TestWindowTitle
+ * @run main TestWindowTitle
+ */
+
+public class TestWindowTitle extends JavadocTester {
+
+    private static final String BUG_ID = "8016675";
+    private static final String WIN_TITLE =
+            "Testing \"Window 'Title'\" with a \\ backslash and a / " +
+            "forward slash and a \u00e8 unicode char also a    tab and also a " +
+            "\t special character another \u0002 unicode)";
+    private static final String[][] TEST = {
+        {BUG_ID + FS  + "overview-summary.html",
+            "parent.document.title=\"Overview (Testing \\\"Window \\\'Title\\\'\\\" " +
+            "with a \\\\ backslash and a / forward slash and a \\u00E8 unicode char " +
+            "also a    tab and also a \\t special character another \\u0002 unicode))\";"
+        },
+    };
+    private static final String[][] NEG_TEST = {
+        {BUG_ID + FS + "overview-summary.html",
+            "parent.document.title=\"Overview (Testing \"Window \'Title\'\" " +
+            "with a \\ backslash and a / forward slash and a \u00E8 unicode char " +
+            "also a    tab and also a \t special character another \u0002 unicode))\";"
+        },
+    };
+    private static final String[] ARGS = new String[]{
+        "-d", BUG_ID, "-windowtitle", WIN_TITLE, "-sourcepath", SRC_DIR, "p1", "p2"
+    };
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String[] args) {
+        TestWindowTitle tester = new TestWindowTitle();
+        run(tester, ARGS, TEST, NEG_TEST);
+        tester.printSummary();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugId() {
+        return BUG_ID;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugName() {
+        return getClass().getName();
+    }
+}
diff --git a/langtools/test/com/sun/javadoc/testWindowTitle/p1/C1.java b/langtools/test/com/sun/javadoc/testWindowTitle/p1/C1.java
new file mode 100644
index 0000000..239d7a6
--- /dev/null
+++ b/langtools/test/com/sun/javadoc/testWindowTitle/p1/C1.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package p1;
+
+public class C1 {
+}
diff --git a/langtools/test/com/sun/javadoc/testWindowTitle/p2/C2.java b/langtools/test/com/sun/javadoc/testWindowTitle/p2/C2.java
new file mode 100644
index 0000000..7d075a6
--- /dev/null
+++ b/langtools/test/com/sun/javadoc/testWindowTitle/p2/C2.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package p2;
+
+public class C2 {
+}
diff --git a/langtools/test/tools/javac/7144981/IgnoreIgnorableCharactersInInput.java b/langtools/test/tools/javac/7144981/IgnoreIgnorableCharactersInInput.java
new file mode 100644
index 0000000..95bce2a
--- /dev/null
+++ b/langtools/test/tools/javac/7144981/IgnoreIgnorableCharactersInInput.java
@@ -0,0 +1,92 @@
+
+/*
+ * @test  /nodynamiccopyright/
+ * @bug 7144981
+ * @summary javac should ignore ignorable characters in input
+ * @run main IgnoreIgnorableCharactersInInput
+ */
+
+import com.sun.source.util.JavacTask;
+import java.io.File;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.ToolProvider;
+
+public class IgnoreIgnorableCharactersInInput {
+
+    public static void main(String... args) throws Exception {
+        new IgnoreIgnorableCharactersInInput().run();
+    }
+
+    void run() throws Exception {
+        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
+        File classesDir = new File(System.getProperty("user.dir"), "classes");
+        classesDir.mkdirs();
+        JavaSource[] sources = new JavaSource[]{
+            new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"),
+            new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB")};
+        JavacTask ct = (JavacTask)comp.getTask(null, null, null,
+                Arrays.asList("-d", classesDir.getPath()),
+                null, Arrays.asList(sources));
+        try {
+            if (!ct.call()) {
+                throw new AssertionError("Error thrown when compiling test cases");
+            }
+        } catch (Throwable ex) {
+            throw new AssertionError("Error thrown when compiling test cases");
+        }
+        check(classesDir,
+                "TestOneIgnorableChar.class",
+                "TestOneIgnorableChar$AABB.class",
+                "TestMultipleIgnorableChar.class",
+                "TestMultipleIgnorableChar$AABB.class");
+        if (errors > 0)
+            throw new AssertionError("There are some errors in the test check the error output");
+    }
+
+    /**
+     *  Check that a directory contains the expected files.
+     */
+    void check(File dir, String... paths) {
+        Set<String> found = new TreeSet<String>(Arrays.asList(dir.list()));
+        Set<String> expect = new TreeSet<String>(Arrays.asList(paths));
+        if (found.equals(expect))
+            return;
+        for (String f: found) {
+            if (!expect.contains(f))
+                error("Unexpected file found: " + f);
+        }
+        for (String e: expect) {
+            if (!found.contains(e))
+                error("Expected file not found: " + e);
+        }
+    }
+
+    int errors;
+
+    void error(String msg) {
+        System.err.println(msg);
+        errors++;
+    }
+
+    class JavaSource extends SimpleJavaFileObject {
+
+        String internalSource =
+            "public class #O {public class #I {} }";
+        public JavaSource(String outerClassName, String innerClassName) {
+            super(URI.create(outerClassName + ".java"), JavaFileObject.Kind.SOURCE);
+            internalSource =
+                    internalSource.replace("#O", outerClassName).replace("#I", innerClassName);
+        }
+
+        @Override
+        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+            return internalSource;
+        }
+    }
+}