changeset 6832:5422806162e8

Merge
author lana
date Thu, 26 Dec 2013 14:39:02 -0800
parents fbe6fa9fb6c6 b148babc052a
children b1bcc999a8f1
files src/share/native/java/lang/ref/Finalizer.c
diffstat 37 files changed, 924 insertions(+), 421 deletions(-) [+]
line wrap: on
line diff
--- a/make/bridge/AccessBridgeJava/Makefile	Wed Dec 18 15:56:58 2013 -0800
+++ b/make/bridge/AccessBridgeJava/Makefile	Thu Dec 26 14:39:02 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# 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
@@ -51,7 +51,7 @@
 #
 # Java files to compile.
 #
-FILES_java = com/sun/java/accessibility/AccessBridge.java
+FILES_java = com/sun/java/accessibility/AccessBridgeLoader.java com/sun/java/accessibility/AccessBridge.java
 
 #
 # Location for the newly built classfiles.
@@ -68,7 +68,7 @@
 build: prebuild
 
 prebuild:
-	$(CP) $(CLOSED_PLATFORM_SRC)/classes/com/sun/java/accessibility/$(ABPLATFORM)/AccessBridge.java \
+	$(CP) $(CLOSED_PLATFORM_SRC)/classes/com/sun/java/accessibility/$(ABPLATFORM)/AccessBridgeLoader.java \
 		$(CLOSED_PLATFORM_SRC)/classes/com/sun/java/accessibility
 
 all : build $(JARFILE) 
--- a/make/java/java/FILES_c.gmk	Wed Dec 18 15:56:58 2013 -0800
+++ b/make/java/java/FILES_c.gmk	Thu Dec 26 14:39:02 2013 -0800
@@ -37,7 +37,6 @@
 	FileInputStream.c \
 	FileInputStream_md.c \
 	FileOutputStream_md.c \
-	Finalizer.c \
 	Float.c \
 	Object.c \
 	ObjectOutputStream.c \
--- a/make/java/java/mapfile-vers	Wed Dec 18 15:56:58 2013 -0800
+++ b/make/java/java/mapfile-vers	Thu Dec 26 14:39:02 2013 -0800
@@ -121,6 +121,7 @@
 		Java_java_io_UnixFileSystem_setReadOnly;
 		Java_java_io_UnixFileSystem_setPermission;
 		Java_java_lang_Class_forName0;
+                Java_java_lang_Class_getCheckMemberAccessMethod;
 		Java_java_lang_Class_getPrimitiveClass;
 		Java_java_lang_Class_isAssignableFrom;
 		Java_java_lang_Class_isInstance;
@@ -140,7 +141,6 @@
 		Java_java_lang_Double_doubleToRawLongBits;
 		Java_java_lang_reflect_Proxy_defineClass0;
 		Java_java_lang_Shutdown_runAllFinalizers;
-		Java_java_lang_ref_Finalizer_invokeFinalizeMethod;
 		Java_java_lang_Float_intBitsToFloat;
 		Java_java_lang_Float_floatToRawIntBits;
 		Java_java_lang_StrictMath_IEEEremainder;
--- a/make/java/java/reorder-i586	Wed Dec 18 15:56:58 2013 -0800
+++ b/make/java/java/reorder-i586	Thu Dec 26 14:39:02 2013 -0800
@@ -77,7 +77,6 @@
 text: .text%JNU_GetEnv;
 text: .text%Java_java_io_UnixFileSystem_checkAccess;
 text: .text%Java_sun_reflect_NativeMethodAccessorImpl_invoke0;
-text: .text%Java_java_lang_ref_Finalizer_invokeFinalizeMethod;
 text: .text%Java_java_io_FileInputStream_available;
 text: .text%Java_java_lang_reflect_Array_newArray;
 text: .text%Java_java_lang_Throwable_getStackTraceDepth;
--- a/make/java/java/reorder-sparc	Wed Dec 18 15:56:58 2013 -0800
+++ b/make/java/java/reorder-sparc	Thu Dec 26 14:39:02 2013 -0800
@@ -87,7 +87,6 @@
 text: .text%throwFileNotFoundException;
 text: .text%JNU_NotifyAll;
 # Test LoadFrame
-text: .text%Java_java_lang_ref_Finalizer_invokeFinalizeMethod;
 text: .text%JNU_CallMethodByName;
 text: .text%JNU_CallMethodByNameV;
 text: .text%Java_java_io_UnixFileSystem_createDirectory;
--- a/make/java/java/reorder-sparcv9	Wed Dec 18 15:56:58 2013 -0800
+++ b/make/java/java/reorder-sparcv9	Thu Dec 26 14:39:02 2013 -0800
@@ -77,7 +77,6 @@
 text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
 text: .text%JNU_GetEnv;
 text: .text%Java_java_io_UnixFileSystem_checkAccess;
-text: .text%Java_java_lang_ref_Finalizer_invokeFinalizeMethod;
 text: .text%Java_java_lang_reflect_Array_newArray;
 text: .text%Java_java_lang_Throwable_getStackTraceDepth;
 text: .text%Java_java_lang_Throwable_getStackTraceElement;
--- a/src/share/classes/java/lang/Class.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/classes/java/lang/Class.java	Thu Dec 26 14:39:02 2013 -0800
@@ -2207,14 +2207,53 @@
      */
     static native Class getPrimitiveClass(String name);
 
-    private static boolean isCheckMemberAccessOverridden(SecurityManager smgr) {
-        if (smgr.getClass() == SecurityManager.class) return false;
+    private static class SecurityManagerHelper {
+        final SecurityManager sm;
+        final boolean overrideCheckMemberAccess;
+        SecurityManagerHelper(SecurityManager sm) {
+            this.sm = sm;
 
-        Class<?>[] paramTypes = new Class<?>[] {Class.class, int.class};
-        return smgr.getClass().getMethod0("checkMemberAccess", paramTypes).
-                getDeclaringClass() != SecurityManager.class;
+            boolean overridden = false;
+            if (sm.getClass() != SecurityManager.class) {
+                try {
+                    overridden = getCheckMemberAccessMethod(sm.getClass()).
+                                     getDeclaringClass() != SecurityManager.class;
+                } catch (NoSuchMethodError e) {
+                    // fall back to invoke sm.checkMemberAccess for the member access check
+                }
+            }
+            this.overrideCheckMemberAccess = overridden;
+        }
+
     }
 
+    private static volatile SecurityManagerHelper smHelper;
+    private static boolean isCheckMemberAccessOverridden(SecurityManager sm) {
+        if (sm.getClass() == SecurityManager.class)  return false;
+
+        SecurityManagerHelper helper = smHelper;
+        if (helper == null || helper.sm != sm) {
+            helper = new SecurityManagerHelper(sm);
+            smHelper = helper;
+        }
+        return helper.overrideCheckMemberAccess;
+    }
+
+    /**
+     * Finds the checkMemberAccess method of the given SecurityManager class.
+     *
+     * This method calls JNI_GetMethodID to look up the checkMemberAccess method
+     * instead of Class.getMethod0 that may cause loading of classes referenced
+     * by the SecurityManager subclass and cause ClassCircularityError.
+     *
+     * JNI_GetMethodID may throw NoSuchMethodError if the given class
+     * has a static checkMemberAccess method.
+     *
+     * @throws NoSuchMethodError if the method cannot be found.
+     */
+    private static native Method getCheckMemberAccessMethod(Class<? extends SecurityManager> c)
+        throws NoSuchMethodError;
+
 
     /*
      * Check if client is allowed to access members.  If access is denied,
--- a/src/share/classes/java/lang/System.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/classes/java/lang/System.java	Thu Dec 26 14:39:02 2013 -0800
@@ -1206,6 +1206,9 @@
             public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
                 return new Thread(target, acc);
             }
+            public void invokeFinalize(Object o) throws Throwable {
+                o.finalize();
+            }
         });
     }
 }
--- a/src/share/classes/java/lang/ref/Finalizer.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/classes/java/lang/ref/Finalizer.java	Thu Dec 26 14:39:02 2013 -0800
@@ -27,17 +27,14 @@
 
 import java.security.PrivilegedAction;
 import java.security.AccessController;
-
+import sun.misc.JavaLangAccess;
+import sun.misc.SharedSecrets;
+import sun.misc.VM;
 
 final class Finalizer extends FinalReference { /* Package-private; must be in
                                                   same package as the Reference
                                                   class */
 
-    /* A native method that invokes an arbitrary object's finalize method is
-       required since the finalize method is protected
-     */
-    static native void invokeFinalizeMethod(Object o) throws Throwable;
-
     private static ReferenceQueue queue = new ReferenceQueue();
     private static Finalizer unfinalized = null;
     private static final Object lock = new Object();
@@ -90,7 +87,7 @@
         new Finalizer(finalizee);
     }
 
-    private void runFinalizer() {
+    private void runFinalizer(JavaLangAccess jla) {
         synchronized (this) {
             if (hasBeenFinalized()) return;
             remove();
@@ -98,7 +95,8 @@
         try {
             Object finalizee = this.get();
             if (finalizee != null && !(finalizee instanceof java.lang.Enum)) {
-                invokeFinalizeMethod(finalizee);
+                jla.invokeFinalize(finalizee);
+
                 /* Clear stack slot containing this variable, to decrease
                    the chances of false retention with a conservative GC */
                 finalizee = null;
@@ -141,16 +139,21 @@
 
     /* Called by Runtime.runFinalization() */
     static void runFinalization() {
+        if (!VM.isBooted()) {
+            return;
+        }
+
         forkSecondaryFinalizer(new Runnable() {
             private volatile boolean running;
             public void run() {
                 if (running)
                     return;
+                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
                 running = true;
                 for (;;) {
                     Finalizer f = (Finalizer)queue.poll();
                     if (f == null) break;
-                    f.runFinalizer();
+                    f.runFinalizer(jla);
                 }
             }
         });
@@ -158,11 +161,16 @@
 
     /* Invoked by java.lang.Shutdown */
     static void runAllFinalizers() {
+        if (!VM.isBooted()) {
+            return;
+        }
+
         forkSecondaryFinalizer(new Runnable() {
             private volatile boolean running;
             public void run() {
                 if (running)
                     return;
+                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
                 running = true;
                 for (;;) {
                     Finalizer f;
@@ -171,7 +179,7 @@
                         if (f == null) break;
                         unfinalized = f.next;
                     }
-                    f.runFinalizer();
+                    f.runFinalizer(jla);
                 }}});
     }
 
@@ -183,13 +191,25 @@
         public void run() {
             if (running)
                 return;
+
+            // Finalizer thread starts before System.initializeSystemClass
+            // is called.  Wait until JavaLangAccess is available
+            while (!VM.isBooted()) {
+                // delay until VM completes initialization
+                try {
+                    VM.awaitBooted();
+                } catch (InterruptedException x) {
+                    // ignore and continue
+                }
+            }
+            final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
             running = true;
             for (;;) {
                 try {
                     Finalizer f = (Finalizer)queue.remove();
-                    f.runFinalizer();
+                    f.runFinalizer(jla);
                 } catch (InterruptedException x) {
-                    continue;
+                    // ignore and continue
                 }
             }
         }
--- a/src/share/classes/sun/misc/JavaLangAccess.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/classes/sun/misc/JavaLangAccess.java	Thu Dec 26 14:39:02 2013 -0800
@@ -95,4 +95,9 @@
      * inherited AccessControlContext.
      */
     Thread newThreadWithAcc(Runnable target, AccessControlContext acc);
+
+    /**
+     * Invokes the finalize method of the given object.
+     */
+    void invokeFinalize(Object o) throws Throwable;
 }
--- a/src/share/classes/sun/misc/VM.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/classes/sun/misc/VM.java	Thu Dec 26 14:39:02 2013 -0800
@@ -147,6 +147,7 @@
 
 
     private static volatile boolean booted = false;
+    private static final Object lock = new Object();
 
     // Invoked by by System.initializeSystemClass just before returning.
     // Subsystems that are invoked during initialization can check this
@@ -154,13 +155,27 @@
     // application class loader has been set up.
     //
     public static void booted() {
-        booted = true;
+        synchronized (lock) {
+            booted = true;
+            lock.notifyAll();
+        }
     }
 
     public static boolean isBooted() {
         return booted;
     }
 
+    // Waits until VM completes initialization
+    //
+    // This method is invoked by the Finalizer thread
+    public static void awaitBooted() throws InterruptedException {
+        synchronized (lock) {
+            while (!booted) {
+                lock.wait();
+            }
+        }
+    }
+
     // A user-settable upper limit on the maximum amount of allocatable direct
     // buffer memory.  This value may be changed during VM initialization if
     // "java" is launched with "-XX:MaxDirectMemorySize=<size>".
--- a/src/share/classes/sun/security/krb5/Credentials.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/classes/sun/security/krb5/Credentials.java	Thu Dec 26 14:39:02 2013 -0800
@@ -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
@@ -62,7 +62,9 @@
     private static CredentialsCache cache;
     static boolean alreadyLoaded = false;
     private static boolean alreadyTried = false;
-    private static native Credentials acquireDefaultNativeCreds();
+
+    // Read native ticket with session key type in the given list
+    private static native Credentials acquireDefaultNativeCreds(int[] eTypes);
 
     public Credentials(Ticket new_ticket,
                        PrincipalName new_client,
@@ -373,6 +375,8 @@
     // It assumes that the GSS call has
     // the privilege to access the default cache file.
 
+    // This method is only called on Windows and Mac OS X, the native
+    // acquireDefaultNativeCreds is also available on these platforms.
     public static synchronized Credentials acquireDefaultCreds() {
         Credentials result = null;
 
@@ -416,10 +420,11 @@
             }
             if (alreadyLoaded) {
                 // There is some native code
-                if (DEBUG)
-                   System.out.println(">> Acquire default native Credentials");
-                result = acquireDefaultNativeCreds();
-                // only TGT with DES key will be returned by native method
+                if (DEBUG) {
+                    System.out.println(">> Acquire default native Credentials");
+                }
+                result = acquireDefaultNativeCreds(
+                        EType.getDefaults("default_tkt_enctypes"));
             }
         }
         return result;
--- a/src/share/native/java/lang/Class.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/native/java/lang/Class.c	Thu Dec 26 14:39:02 2013 -0800
@@ -187,3 +187,16 @@
 
     return result;
 }
+
+JNIEXPORT jobject JNICALL
+Java_java_lang_Class_getCheckMemberAccessMethod(JNIEnv *env, jclass cls, jclass smClass)
+{
+    jmethodID mid;
+
+    mid = (*env)->GetMethodID(env, smClass, "checkMemberAccess", "(Ljava/lang/Class;I)V");
+    if (mid == NULL) {
+        return NULL;
+    }
+    return (*env)->ToReflectedMethod(env, smClass, mid, JNI_FALSE);
+}
+
--- a/src/share/native/java/lang/ref/Finalizer.c	Wed Dec 18 15:56:58 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-#include "jni.h"
-#include "java_lang_ref_Finalizer.h"
-
-
-JNIEXPORT void JNICALL
-Java_java_lang_ref_Finalizer_invokeFinalizeMethod(JNIEnv *env, jclass clazz,
-                                                  jobject ob)
-{
-    jclass cls;
-    jmethodID mid;
-
-    cls = (*env)->GetObjectClass(env, ob);
-    if (cls == NULL) return;
-    mid = (*env)->GetMethodID(env, cls, "finalize", "()V");
-    if (mid == NULL) return;
-    (*env)->CallVoidMethod(env, ob, mid);
-}
--- a/src/share/native/sun/security/krb5/nativeccache.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/share/native/sun/security/krb5/nativeccache.c	Thu Dec 26 14:39:02 2013 -0800
@@ -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
@@ -264,13 +264,22 @@
 
 }
 
+int isIn(krb5_enctype e, int n, jint* etypes)
+{
+    int i;
+    for (i=0; i<n; i++) {
+        if (e == etypes[i]) return 1;
+    }
+    return 0;
+}
+
 /*
  * Class:     sun_security_krb5_Credentials
  * Method:    acquireDefaultNativeCreds
  * Signature: ()Lsun/security/krb5/Credentials;
  */
 JNIEXPORT jobject JNICALL Java_sun_security_krb5_Credentials_acquireDefaultNativeCreds
-(JNIEnv *env, jclass krbcredsClass)
+(JNIEnv *env, jclass krbcredsClass, jintArray jetypes)
 {
     jobject krbCreds = NULL;
     krb5_error_code err = 0;
@@ -279,6 +288,8 @@
     krb5_creds creds;
     krb5_flags flags = 0;
     krb5_context kcontext = NULL;
+    int netypes;
+    jint *etypes = NULL;
 
     /* Initialize the Kerberos 5 context */
     err = krb5_init_context (&kcontext);
@@ -295,6 +306,9 @@
         err = krb5_cc_start_seq_get (kcontext, ccache, &cursor);
     }
 
+    netypes = (*env)->GetArrayLength(env, jetypes);
+    etypes = (jint *) (*env)->GetIntArrayElements(env, jetypes, NULL);
+
     if (!err) {
         while ((err = krb5_cc_next_cred (kcontext, ccache, &cursor, &creds)) == 0) {
             char *serverName = NULL;
@@ -305,7 +319,8 @@
             }
 
             if (!err) {
-                if (strncmp (serverName, "krbtgt", strlen("krbtgt")) == 0) {
+                if (strncmp (serverName, "krbtgt", sizeof("krbtgt")-1) == 0 &&
+                        isIn(creds.keyblock.enctype, netypes, etypes)) {
                     jobject ticket, clientPrincipal, targetPrincipal, encryptionKey;
                     jobject ticketFlags, startTime, endTime;
                     jobject authTime, renewTillTime, hostAddresses;
@@ -321,7 +336,7 @@
                     targetPrincipal = BuildClientPrincipal(env, kcontext, creds.server);
                     if (targetPrincipal == NULL) goto cleanup;
 
-                    // Build a com.ibm.security.krb5.Ticket
+                    // Build a sun/security/krb5/internal/Ticket
                     ticket = BuildTicket(env, &creds.ticket);
                     if (ticket == NULL) goto cleanup;
 
@@ -353,7 +368,7 @@
                         krbcredsConstructor = (*env)->GetMethodID(env, krbcredsClass, "<init>",
                                                                   "(Lsun/security/krb5/internal/Ticket;Lsun/security/krb5/PrincipalName;Lsun/security/krb5/PrincipalName;Lsun/security/krb5/EncryptionKey;Lsun/security/krb5/internal/TicketFlags;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/HostAddresses;)V");
                         if (krbcredsConstructor == 0) {
-                            printf("Couldn't find com.ibm.security.krb5.Credentials constructor\n");
+                            printf("Couldn't find sun.security.krb5.internal.Ticket constructor\n");
                             break;
                         }
                     }
@@ -409,6 +424,10 @@
         printiferr (err, "while finishing ticket retrieval");
     }
 
+    if (etypes != NULL) {
+        (*env)->ReleaseIntArrayElements(env, jetypes, etypes, 0);
+    }
+
     krb5_free_context (kcontext);
     return krbCreds;
 }
--- a/src/solaris/classes/sun/awt/X11/XConstants.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/classes/sun/awt/X11/XConstants.java	Thu Dec 26 14:39:02 2013 -0800
@@ -699,9 +699,4 @@
     public static final long XkbModifierMapMask = (1L<<2);
     public static final long XkbVirtualModsMask = (1L<<6); //server map
 
-    /*****************************************************************
-     * X SHARED MEMORY EXTENSION FUNCTIONS
-     *****************************************************************/
-
-    public static final int X_ShmAttach = 1;
 }
--- a/src/solaris/classes/sun/awt/X11/XErrorHandler.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/classes/sun/awt/X11/XErrorHandler.java	Thu Dec 26 14:39:02 2013 -0800
@@ -42,29 +42,6 @@
         }
     }
 
-    /**
-     * This is a base synthetic error handler containing a boolean flag which allows
-     * to show that an error is handled or not.
-     */
-    public static class XErrorHandlerWithFlag extends XBaseErrorHandler {
-        private volatile boolean errorOccurred = false;
-
-        public boolean getErrorOccurredFlag() {
-            return errorOccurred;
-        }
-
-        /**
-         * Sets an internal boolean flag to a particular value. Should be always called
-         * with {@code false} value of the parameter {@code errorOccurred} before this
-         * error handler is set as current.
-         * @param errorOccurred {@code true} to indicate that an error was handled,
-         *     {@code false} to reset the internal boolean flag
-         */
-        public void setErrorOccurredFlag(boolean errorOccurred) {
-            this.errorOccurred = errorOccurred;
-        }
-    }
-
     /*
      * Instead of validating window id, we simply call XGetWindowProperty,
      * but temporary install this function as the error handler to ignore
@@ -99,75 +76,4 @@
             return theInstance;
         }
     }
-
-    /**
-     * This is a synthetic error handler for errors generated by the native function
-     * {@code XShmAttach}. If an error is handled, an internal boolean flag of the
-     * handler is set to {@code true}.
-     */
-    public static final class XShmAttachHandler extends XErrorHandlerWithFlag {
-        private XShmAttachHandler() {}
-
-        @Override
-        public int handleError(long display, XErrorEvent err) {
-            if (err.get_minor_code() == XConstants.X_ShmAttach) {
-                setErrorOccurredFlag(true);
-                return 0;
-            }
-            return super.handleError(display, err);
-        }
-
-        // Shared instance
-        private static XShmAttachHandler theInstance = new XShmAttachHandler();
-        public static XShmAttachHandler getInstance() {
-            return theInstance;
-        }
-    }
-
-    /**
-     * This is a synthetic error handler for {@code BadAlloc} errors generated by the
-     * native {@code glX*} functions. Its internal boolean flag is set to {@code true},
-     * if an error is handled.
-     */
-    public static final class GLXBadAllocHandler extends XErrorHandlerWithFlag {
-        private GLXBadAllocHandler() {}
-
-        @Override
-        public int handleError(long display, XErrorEvent err) {
-            if (err.get_error_code() == XConstants.BadAlloc) {
-                setErrorOccurredFlag(true);
-                return 0;
-            }
-            return super.handleError(display, err);
-        }
-
-        private static GLXBadAllocHandler theInstance = new GLXBadAllocHandler();
-        public static GLXBadAllocHandler getInstance() {
-            return theInstance;
-        }
-    }
-
-    /**
-     * This is a synthetic error handler for errors generated by the native function
-     * {@code XChangeWindowAttributes}. If an error is handled, an internal boolean
-     * flag of the handler is set to {@code true}.
-     */
-    public static final class XChangeWindowAttributesHandler extends XErrorHandlerWithFlag {
-        private XChangeWindowAttributesHandler() {}
-
-        @Override
-        public int handleError(long display, XErrorEvent err) {
-            if ((err.get_request_code() == XProtocolConstants.X_ChangeWindowAttributes) &&
-                (err.get_error_code() == XConstants.BadAccess)) {
-                setErrorOccurredFlag(true);
-                return 0;
-            }
-            return super.handleError(display, err);
-        }
-
-        private static XChangeWindowAttributesHandler theInstance = new XChangeWindowAttributesHandler();
-        public static XChangeWindowAttributesHandler getInstance() {
-            return theInstance;
-        }
-    }
 }
--- a/src/solaris/native/sun/awt/awt_GraphicsEnv.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/awt/awt_GraphicsEnv.c	Thu Dec 26 14:39:02 2013 -0800
@@ -978,6 +978,20 @@
 
 static jint canUseShmExt = UNSET_MITSHM;
 static jint canUseShmExtPixmaps = UNSET_MITSHM;
+static jboolean xshmAttachFailed = JNI_FALSE;
+
+int XShmAttachXErrHandler(Display *display, XErrorEvent *xerr) {
+    if (xerr->minor_code == X_ShmAttach) {
+        xshmAttachFailed = JNI_TRUE;
+    }
+    return 0;
+}
+jboolean isXShmAttachFailed() {
+    return xshmAttachFailed;
+}
+void resetXShmAttachFailed() {
+    xshmAttachFailed = JNI_FALSE;
+}
 
 extern int mitShmPermissionMask;
 
@@ -985,7 +999,6 @@
     XShmSegmentInfo shminfo;
     int XShmMajor, XShmMinor;
     int a, b, c;
-    jboolean xShmAttachResult;
 
     AWT_LOCK();
     if (canUseShmExt != UNSET_MITSHM) {
@@ -1024,14 +1037,21 @@
         }
         shminfo.readOnly = True;
 
-        xShmAttachResult = TryXShmAttach(env, awt_display, &shminfo);
+        resetXShmAttachFailed();
+        /**
+         * The J2DXErrHandler handler will set xshmAttachFailed
+         * to JNI_TRUE if any Shm error has occured.
+         */
+        EXEC_WITH_XERROR_HANDLER(XShmAttachXErrHandler,
+                                 XShmAttach(awt_display, &shminfo));
+
         /**
          * Get rid of the id now to reduce chances of leaking
          * system resources.
          */
         shmctl(shminfo.shmid, IPC_RMID, 0);
 
-        if (xShmAttachResult == JNI_TRUE) {
+        if (isXShmAttachFailed() == JNI_FALSE) {
             canUseShmExt = CAN_USE_MITSHM;
             /* check if we can use shared pixmaps */
             XShmQueryVersion(awt_display, &XShmMajor, &XShmMinor,
@@ -1046,23 +1066,6 @@
     }
     AWT_UNLOCK();
 }
-
-/*
- * Must be called with the acquired AWT lock.
- */
-jboolean TryXShmAttach(JNIEnv *env, Display *display, XShmSegmentInfo *shminfo) {
-    jboolean errorOccurredFlag = JNI_FALSE;
-    jobject errorHandlerRef;
-
-    /*
-     * XShmAttachHandler will set its internal flag to JNI_TRUE, if any Shm error occurs.
-     */
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$XShmAttachHandler",
-        "()Lsun/awt/X11/XErrorHandler$XShmAttachHandler;", JNI_TRUE,
-        errorHandlerRef, errorOccurredFlag,
-        XShmAttach(display, shminfo));
-    return errorOccurredFlag == JNI_FALSE ? JNI_TRUE : JNI_FALSE;
-}
 #endif /* MITSHM */
 
 /*
--- a/src/solaris/native/sun/awt/awt_GraphicsEnv.h	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/awt/awt_GraphicsEnv.h	Thu Dec 26 14:39:02 2013 -0800
@@ -53,7 +53,8 @@
 extern int XShmQueryExtension();
 
 void TryInitMITShm(JNIEnv *env, jint *shmExt, jint *shmPixmaps);
-jboolean TryXShmAttach(JNIEnv *env, Display *display, XShmSegmentInfo *shminfo);
+void resetXShmAttachFailed();
+jboolean isXShmAttachFailed();
 
 #endif /* MITSHM */
 
--- a/src/solaris/native/sun/awt/awt_util.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/awt/awt_util.c	Thu Dec 26 14:39:02 2013 -0800
@@ -57,6 +57,16 @@
 
 #include "java_awt_event_MouseWheelEvent.h"
 
+/*
+ * Called by "ToolkitErrorHandler" function in "XlibWrapper.c" file.
+ */
+XErrorHandler current_native_xerror_handler = NULL;
+
+/*
+ * A place for error handler to report the error code.
+ */
+unsigned char xerror_code = Success;
+
 extern jint getModifiers(uint32_t state, jint button, jint keyCode);
 extern jint getButton(uint32_t button);
 
--- a/src/solaris/native/sun/awt/awt_util.h	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/awt/awt_util.h	Thu Dec 26 14:39:02 2013 -0800
@@ -79,62 +79,42 @@
 void awt_util_delEmbeddedFrame(Widget embeddedFrame);
 Boolean awt_util_processEventForEmbeddedFrame(XEvent *ev);
 
-/*
- * Expected types of arguments of the macro.
- * (JNIEnv*, const char*, const char*, jboolean, jobject)
- */
-#define WITH_XERROR_HANDLER(env, handlerClassName, getInstanceSignature,                          \
-                            handlerHasFlag, handlerRef) do {                                      \
-    handlerRef = JNU_CallStaticMethodByName(env, NULL, handlerClassName, "getInstance",           \
-        getInstanceSignature).l;                                                                  \
-    if (handlerHasFlag == JNI_TRUE) {                                                             \
-        JNU_CallMethodByName(env, NULL, handlerRef, "setErrorOccurredFlag", "(Z)V", JNI_FALSE);   \
-    }                                                                                             \
-    JNU_CallStaticMethodByName(env, NULL, "sun/awt/X11/XErrorHandlerUtil", "WITH_XERROR_HANDLER", \
-        "(Lsun/awt/X11/XErrorHandler;)V", handlerRef);                                            \
+#define WITH_XERROR_HANDLER(f) do {             \
+    XSync(awt_display, False);                  \
+    xerror_code = Success;                      \
+    current_native_xerror_handler = (f);        \
+} while (0)
+
+/* Convenience macro for handlers to use */
+#define XERROR_SAVE(err) do {                   \
+    xerror_code = (err)->error_code;            \
+} while (0)
+
+#define RESTORE_XERROR_HANDLER do {             \
+    XSync(awt_display, False);                  \
+    current_native_xerror_handler = NULL;       \
+} while (0)
+
+#define EXEC_WITH_XERROR_HANDLER(f, code) do {  \
+    WITH_XERROR_HANDLER(f);                     \
+    do {                                        \
+        code;                                   \
+    } while (0);                                \
+    RESTORE_XERROR_HANDLER;                     \
 } while (0)
 
 /*
- * Expected types of arguments of the macro.
- * (JNIEnv*, jboolean)
+ * Called by "ToolkitErrorHandler" function in "XlibWrapper.c" file.
  */
-#define RESTORE_XERROR_HANDLER(env, doXSync) do {                                                 \
-    JNU_CallStaticMethodByName(env, NULL, "sun/awt/X11/XErrorHandlerUtil",                        \
-        "RESTORE_XERROR_HANDLER", "(Z)V", doXSync);                                               \
-} while (0)
+extern XErrorHandler current_native_xerror_handler;
 
 /*
- * Expected types of arguments of the macro.
- * (JNIEnv*, const char*, const char*, jboolean, jobject, jboolean, No type - C expression)
+ * A place for error handler to report the error code.
  */
-#define EXEC_WITH_XERROR_HANDLER(env, handlerClassName, getInstanceSignature, handlerHasFlag,     \
-                                 handlerRef, errorOccurredFlag, code) do {                        \
-    handlerRef = NULL;                                                                            \
-    WITH_XERROR_HANDLER(env, handlerClassName, getInstanceSignature, handlerHasFlag, handlerRef); \
-    do {                                                                                          \
-        code;                                                                                     \
-    } while (0);                                                                                  \
-    RESTORE_XERROR_HANDLER(env, JNI_TRUE);                                                        \
-    if (handlerHasFlag == JNI_TRUE) {                                                             \
-        errorOccurredFlag = GET_HANDLER_ERROR_OCCURRED_FLAG(env, handlerRef);                     \
-    }                                                                                             \
-} while (0)
+extern unsigned char xerror_code;
 
-/*
- * Expected types of arguments of the macro for jboolean expression.
- * (JNIEnv*, jobject)
- */
-#define GET_HANDLER_ERROR_OCCURRED_FLAG(env, handlerRef) (handlerRef != NULL ?                    \
-    JNU_CallMethodByName(env, NULL, handlerRef, "getErrorOccurredFlag", "()Z").z : JNI_FALSE)
+extern int xerror_ignore_bad_window(Display *dpy, XErrorEvent *err);
 
-/*
- * Expected types of arguments of the macro for jbyte expression.
- * (JNIEnv*, jobject)
- */
-#define GET_XERROR_CODE(env, savedError)                                                          \
-    ((savedError = JNU_GetStaticFieldByName(env, NULL, "sun/awt/X11/XErrorHandlerUtil",           \
-        "saved_error", "Lsun/awt/X11/XErrorEvent;").l) != NULL ?                                  \
-        JNU_CallMethodByName(env, NULL, savedError, "get_error_code", "()B").b : Success)
 #endif /* !HEADLESS */
 
 #ifndef INTERSECTS
--- a/src/solaris/native/sun/awt/awt_wm.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/awt/awt_wm.c	Thu Dec 26 14:39:02 2013 -0800
@@ -372,6 +372,21 @@
 \*****************************************************************************/
 
 /*
+ * Instead of validating window id, we simply call XGetWindowProperty,
+ * but temporary install this function as the error handler to ignore
+ * BadWindow error.
+ */
+int /* but ingored */
+xerror_ignore_bad_window(Display *dpy, XErrorEvent *err)
+{
+    XERROR_SAVE(err);
+    if (err->error_code == BadWindow) {
+        DTRACE_PRINTLN("IGNORING BadWindow");
+    }
+    return 0; /* ok to fail */
+}
+
+/*
  * Convenience wrapper for XGetWindowProperty for XA_ATOM properties.
  * E.g. WM_PROTOCOLS, _NET_WM_STATE, _OL_DECOR_DEL.
  * It's up to caller to XFree returned value.
@@ -439,19 +454,16 @@
     unsigned long nitems;
     unsigned long bytes_after;
     unsigned char *string;
-    JNIEnv* env;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
 
     /* BadWindow is ok and will be blocked by our special handler */
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$IgnoreBadWindowHandler",
-        "()Lsun/awt/X11/XErrorHandler$IgnoreBadWindowHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_ignore_bad_window);
+    {
         status = XGetWindowProperty(awt_display, w,
                      property, 0, 0xFFFF, False, property_type,
                      &actual_type, &actual_format, &nitems, &bytes_after,
-                     &string));
+                     &string);
+    }
+    RESTORE_XERROR_HANDLER;
 
     if (status != Success || string == NULL) {
         return NULL;
@@ -486,19 +498,16 @@
     unsigned long nitems;
     unsigned long bytes_after;
     long *data;                 /* NB: 64 bit: Format 32 props are 'long' */
-    JNIEnv* env;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
 
     /* BadWindow is ok and will be blocked by our special handler */
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$IgnoreBadWindowHandler",
-        "()Lsun/awt/X11/XErrorHandler$IgnoreBadWindowHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_ignore_bad_window);
+    {
         status = XGetWindowProperty(awt_display, w,
                      property, 0, 1, False, property_type,
                      &actual_type, &actual_format, &nitems, &bytes_after,
-                     (unsigned char **)&data));
+                     (unsigned char **)&data);
+    }
+    RESTORE_XERROR_HANDLER;
 
     if (status != Success || data == NULL) {
         return 0;
@@ -699,23 +708,20 @@
     unsigned long nitems;
     unsigned long bytes_after;
     unsigned char *data;
-    JNIEnv* env;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
 
     if (!awt_wm_atomInterned(&XA_ENLIGHTENMENT_COMMS, "ENLIGHTENMENT_COMMS")) {
         return False;
     }
 
     /* BadWindow is ok and will be blocked by our special handler */
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$IgnoreBadWindowHandler",
-        "()Lsun/awt/X11/XErrorHandler$IgnoreBadWindowHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_ignore_bad_window);
+    {
         status = XGetWindowProperty(awt_display, w,
                      XA_ENLIGHTENMENT_COMMS, 0, 14, False, XA_STRING,
                      &actual_type, &actual_format, &nitems, &bytes_after,
-                     &data));
+                     &data);
+    }
+    RESTORE_XERROR_HANDLER;
 
     if (status != Success || data == NULL) {
         DTRACE_PRINTLN("no ENLIGHTENMENT_COMMS");
@@ -795,9 +801,6 @@
     unsigned long nitems;
     unsigned long bytes_after;
     long *data;                 /* NB: 64 bit: Format 32 props are 'long' */
-    JNIEnv* env;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
 
     DTRACE_PRINT("WM: checking for CDE ...  ");
 
@@ -833,14 +836,14 @@
     }
 
     /* BadWindow is ok and will be blocked by our special handler */
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$IgnoreBadWindowHandler",
-        "()Lsun/awt/X11/XErrorHandler$IgnoreBadWindowHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_ignore_bad_window);
+    {
         status = XGetWindowProperty(awt_display, wmwin,
                      _XA_DT_SM_STATE_INFO, 0, 1, False, _XA_DT_SM_STATE_INFO,
                      &actual_type, &actual_format, &nitems, &bytes_after,
-                     (unsigned char **)&data));
+                     (unsigned char **)&data);
+    }
+    RESTORE_XERROR_HANDLER;
 
     if (status != Success || data == NULL) {
         DTRACE_PRINTLN("no _DT_SM_STATE_INFO");
@@ -1005,6 +1008,18 @@
 }
 
 /*
+ * Temporary error handler that ensures that we know if
+ * XChangeProperty succeeded or not.
+ */
+static int /* but ignored */
+xerror_verify_change_property(Display *dpy, XErrorEvent *err)
+{
+    XERROR_SAVE(err);
+    if (err->request_code == X_ChangeProperty) { }
+    return 0;
+}
+
+/*
  * Prepare IceWM check.
  *
  * The only way to detect IceWM, seems to be by setting
@@ -1031,11 +1046,6 @@
         'a','l','l','W','o','r','k','s','p','a','c','e','s','\0',
         '0','\0'
     };
-    JNIEnv* env;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
-    jobject savedError;
-    unsigned char xerror_code;
 
     DTRACE_PRINT("WM: scheduling check for IceWM ...  ");
 
@@ -1043,14 +1053,13 @@
         return False;
     }
 
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$VerifyChangePropertyHandler",
-        "()Lsun/awt/X11/XErrorHandler$VerifyChangePropertyHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_verify_change_property);
+    {
         XChangeProperty(awt_display, DefaultRootWindow(awt_display),
                         _XA_ICEWM_WINOPTHINT, _XA_ICEWM_WINOPTHINT, 8,
-                        PropModeReplace, opt, sizeof(opt)));
-    xerror_code = GET_XERROR_CODE(env, savedError);
+                        PropModeReplace, opt, sizeof(opt));
+    }
+    RESTORE_XERROR_HANDLER;
 
     if (xerror_code != Success) {
         DTRACE_PRINTLN1("can't set _ICEWM_WINOPTHINT, error = %d",
@@ -1140,6 +1149,25 @@
     return True;
 }
 
+static Boolean winmgr_running = False;
+
+/*
+ * Temporary error handler that checks if selecting for
+ * SubstructureRedirect failed.
+ */
+static int /* but ignored */
+xerror_detect_wm(Display *dpy, XErrorEvent *err)
+{
+    XERROR_SAVE(err);
+    if (err->request_code == X_ChangeWindowAttributes
+        && err->error_code == BadAccess)
+    {
+        DTRACE_PRINTLN("some WM is running (hmm, we'll see)");
+        winmgr_running = True;
+    }
+    return 0;
+}
+
 /*
  * Make an educated guess about running window manager.
  * XXX: ideally, we should detect wm restart.
@@ -1156,9 +1184,6 @@
     XSetWindowAttributes substruct;
     const char *vendor_string;
     Boolean doIsIceWM;
-    JNIEnv* env;
-    jboolean errorOccurredFlag = JNI_FALSE;
-    jobject errorHandlerRef;
 
     if (awt_wmgr != UNDETERMINED_WM) {
         return awt_wmgr;
@@ -1186,21 +1211,22 @@
      * can select for, and if the request fails, than some other WM is
      * already running.
      */
+    winmgr_running = 0;
     substruct.event_mask = SubstructureRedirectMask;
 
     DTRACE_PRINT("WM: trying SubstructureRedirect ...  ");
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$XChangeWindowAttributesHandler",
-        "()Lsun/awt/X11/XErrorHandler$XChangeWindowAttributesHandler;", JNI_TRUE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_detect_wm);
+    {
         XChangeWindowAttributes(awt_display, DefaultRootWindow(awt_display),
-                                CWEventMask, &substruct));
+                                CWEventMask, &substruct);
+    }
+    RESTORE_XERROR_HANDLER;
 
     /*
      * If no WM is running than our selection for SubstructureRedirect
      * succeeded and needs to be undone (hey we are *not* a WM ;-).
      */
-    if (errorOccurredFlag == JNI_FALSE) {
+    if (!winmgr_running) {
         DTRACE_PRINTLN("no WM is running");
         awt_wmgr = NO_WM;
         substruct.event_mask = 0;
@@ -2687,11 +2713,6 @@
     Boolean shaded;
     unsigned long nitems;
     unsigned long i;
-    JNIEnv* env;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
-    jobject savedError;
-    unsigned char xerror_code;
 
     net_wm_state = awt_getAtomListProperty(shell_win,
                                            _XA_NET_WM_STATE, &nitems);
@@ -2733,14 +2754,13 @@
     awt_wm_dtraceStateNet(net_wm_state, nitems);
 #endif
 
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$VerifyChangePropertyHandler",
-        "()Lsun/awt/X11/XErrorHandler$VerifyChangePropertyHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
+    WITH_XERROR_HANDLER(xerror_verify_change_property);
+    {
         XChangeProperty(dpy, shell_win,
                         _XA_NET_WM_STATE, XA_ATOM, 32, PropModeReplace,
-                        (unsigned char *)net_wm_state, nitems));
-    xerror_code = GET_XERROR_CODE(env, savedError);
+                        (unsigned char *)net_wm_state, nitems);
+    }
+    RESTORE_XERROR_HANDLER;
 
     if (xerror_code != Success) {
         DTRACE_PRINTLN1("WM:     XChangeProperty failed, error = %d",
--- a/src/solaris/native/sun/awt/awt_xembed_server.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/awt/awt_xembed_server.c	Thu Dec 26 14:39:02 2013 -0800
@@ -644,19 +644,12 @@
     return dim;
 }
 
-Boolean isMapped(JNIEnv* env, Window w) {
+Boolean isMapped(Window w) {
     XWindowAttributes attr;
     Status status = 0;
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
-    jobject savedError;
-    unsigned char xerror_code;
-
-    EXEC_WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$IgnoreBadWindowHandler",
-        "()Lsun/awt/X11/XErrorHandler$IgnoreBadWindowHandler;", JNI_FALSE,
-        errorHandlerRef, errorOccurredFlag,
-        status = XGetWindowAttributes(awt_display, w, &attr));
-    xerror_code = GET_XERROR_CODE(env, savedError);
+    WITH_XERROR_HANDLER(xerror_ignore_bad_window);
+    status = XGetWindowAttributes(awt_display, w, &attr);
+    RESTORE_XERROR_HANDLER;
     if (status == 0 || xerror_code != Success) {
         return False;
     }
@@ -692,7 +685,7 @@
             sdata->version = *data;
             flags = *(data+1);
             new_mapped = (flags & XEMBED_MAPPED) != 0;
-            currently_mapped = isMapped(env, sdata->handle);
+            currently_mapped = isMapped(sdata->handle);
             if (new_mapped != currently_mapped) {
                 if (new_mapped) {
                     XMapWindow(awt_display, sdata->handle);
--- a/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c	Thu Dec 26 14:39:02 2013 -0800
@@ -50,6 +50,8 @@
 extern void
     OGLSD_SetNativeDimensions(JNIEnv *env, OGLSDOps *oglsdo, jint w, jint h);
 
+jboolean surfaceCreationFailed = JNI_FALSE;
+
 #endif /* !HEADLESS */
 
 JNIEXPORT void JNICALL
@@ -391,6 +393,15 @@
     return JNI_TRUE;
 }
 
+static int
+GLXSD_BadAllocXErrHandler(Display *display, XErrorEvent *xerr)
+{
+    if (xerr->error_code == BadAlloc) {
+        surfaceCreationFailed = JNI_TRUE;
+    }
+    return 0;
+}
+
 JNIEXPORT jboolean JNICALL
 Java_sun_java2d_opengl_GLXSurfaceData_initPbuffer
     (JNIEnv *env, jobject glxsd,
@@ -406,8 +417,6 @@
     int attrlist[] = {GLX_PBUFFER_WIDTH, 0,
                       GLX_PBUFFER_HEIGHT, 0,
                       GLX_PRESERVED_CONTENTS, GL_FALSE, 0};
-    jboolean errorOccurredFlag;
-    jobject errorHandlerRef;
 
     J2dTraceLn3(J2D_TRACE_INFO,
                 "GLXSurfaceData_initPbuffer: w=%d h=%d opq=%d",
@@ -435,15 +444,12 @@
     attrlist[1] = width;
     attrlist[3] = height;
 
-    WITH_XERROR_HANDLER(env, "sun/awt/X11/XErrorHandler$GLXBadAllocHandler",
-        "()Lsun/awt/X11/XErrorHandler$GLXBadAllocHandler;", JNI_TRUE, errorHandlerRef);
-    pbuffer = j2d_glXCreatePbuffer(awt_display, glxinfo->fbconfig, attrlist);
-    // Call XSync without the acquired AWT lock to avoid a deadlock (see 8015730).
-    XSync(awt_display, False);
-    RESTORE_XERROR_HANDLER(env, JNI_FALSE);
-    errorOccurredFlag = GET_HANDLER_ERROR_OCCURRED_FLAG(env, errorHandlerRef);
-
-    if ((pbuffer == 0) || errorOccurredFlag) {
+    surfaceCreationFailed = JNI_FALSE;
+    EXEC_WITH_XERROR_HANDLER(
+        GLXSD_BadAllocXErrHandler,
+        pbuffer = j2d_glXCreatePbuffer(awt_display,
+                                       glxinfo->fbconfig, attrlist));
+    if ((pbuffer == 0) || surfaceCreationFailed) {
         J2dRlsTraceLn(J2D_TRACE_ERROR,
             "GLXSurfaceData_initPbuffer: could not create glx pbuffer");
         return JNI_FALSE;
--- a/src/solaris/native/sun/java2d/x11/X11SurfaceData.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/java2d/x11/X11SurfaceData.c	Thu Dec 26 14:39:02 2013 -0800
@@ -68,6 +68,7 @@
 #ifndef XAWT
 extern struct MComponentPeerIDs mComponentPeerIDs;
 #endif
+extern int XShmAttachXErrHandler(Display *display, XErrorEvent *xerr);
 extern AwtGraphicsConfigDataPtr
     getGraphicsConfigFromComponentPeer(JNIEnv *env, jobject this);
 extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs;
@@ -550,8 +551,6 @@
 {
     XImage *img = NULL;
     XShmSegmentInfo *shminfo;
-    JNIEnv* env;
-    jboolean xShmAttachResult;
 
     shminfo = malloc(sizeof(XShmSegmentInfo));
     if (shminfo == NULL) {
@@ -591,8 +590,9 @@
 
     shminfo->readOnly = False;
 
-    env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    xShmAttachResult = TryXShmAttach(env, awt_display, shminfo);
+    resetXShmAttachFailed();
+    EXEC_WITH_XERROR_HANDLER(XShmAttachXErrHandler,
+                             XShmAttach(awt_display, shminfo));
 
     /*
      * Once the XSync round trip has finished then we
@@ -601,7 +601,7 @@
      */
     shmctl(shminfo->shmid, IPC_RMID, 0);
 
-    if (xShmAttachResult == JNI_FALSE) {
+    if (isXShmAttachFailed() == JNI_TRUE) {
         J2dRlsTraceLn1(J2D_TRACE_ERROR,
                        "X11SD_SetupSharedSegment XShmAttach has failed: %s",
                        strerror(errno));
--- a/src/solaris/native/sun/xawt/XlibWrapper.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/solaris/native/sun/xawt/XlibWrapper.c	Thu Dec 26 14:39:02 2013 -0800
@@ -41,6 +41,7 @@
 #include <sizecalc.h>
 
 #include <awt.h>
+#include <awt_util.h>
 #include <jvm.h>
 
 #include <Region.h>
@@ -1262,6 +1263,10 @@
 JavaVM* jvm = NULL;
 static int ToolkitErrorHandler(Display * dpy, XErrorEvent * event) {
     JNIEnv * env;
+    // First call the native synthetic error handler declared in "awt_util.h" file.
+    if (current_native_xerror_handler != NULL) {
+        current_native_xerror_handler(dpy, event);
+    }
     if (jvm != NULL) {
         env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
         if (env) {
--- a/src/windows/classes/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/windows/classes/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java	Thu Dec 26 14:39:02 2013 -0800
@@ -230,6 +230,7 @@
         @Override
         public void run() {
             long overlapped = 0L;
+            boolean pending = false;
             try {
                 begin();
 
@@ -243,6 +244,7 @@
                                      overlapped);
                     if (n == IOStatus.UNAVAILABLE) {
                         // I/O is pending
+                        pending = true;
                         return;
                     }
                     // acquired lock immediately
@@ -252,10 +254,10 @@
             } catch (Throwable x) {
                 // lock failed or channel closed
                 removeFromFileLockTable(fli);
-                if (overlapped != 0L)
-                    ioCache.remove(overlapped);
                 result.setFailure(toIOException(x));
             } finally {
+                if (!pending && overlapped != 0L)
+                    ioCache.remove(overlapped);
                 end();
             }
 
--- a/src/windows/native/sun/security/krb5/NativeCreds.c	Wed Dec 18 15:56:58 2013 -0800
+++ b/src/windows/native/sun/security/krb5/NativeCreds.c	Thu Dec 26 14:39:02 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, 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
@@ -380,7 +380,8 @@
  */
 JNIEXPORT jobject JNICALL Java_sun_security_krb5_Credentials_acquireDefaultNativeCreds(
         JNIEnv *env,
-        jclass krbcredsClass) {
+        jclass krbcredsClass,
+        jintArray jetypes) {
 
     KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
     PKERB_RETRIEVE_TKT_RESPONSE TktCacheResponse = NULL;
@@ -396,9 +397,12 @@
     jobject ticketFlags, startTime, endTime, krbCreds = NULL;
     jobject authTime, renewTillTime, hostAddresses = NULL;
     KERB_EXTERNAL_TICKET *msticket;
-    int ignore_cache = 0;
+    int found_in_cache = 0;
     FILETIME Now, EndTime, LocalEndTime;
 
+    int i, netypes;
+    jint *etypes = NULL;
+
     while (TRUE) {
 
         if (krbcredsConstructor == 0) {
@@ -465,31 +469,33 @@
         // got the native MS TGT
         msticket = &(TktCacheResponse->Ticket);
 
+        netypes = (*env)->GetArrayLength(env, jetypes);
+        etypes = (jint *) (*env)->GetIntArrayElements(env, jetypes, NULL);
+
         // check TGT validity
-        switch (msticket->SessionKey.KeyType) {
-            case KERB_ETYPE_DES_CBC_CRC:
-            case KERB_ETYPE_DES_CBC_MD5:
-            case KERB_ETYPE_NULL:
-            case KERB_ETYPE_RC4_HMAC_NT:
-                GetSystemTimeAsFileTime(&Now);
-                EndTime.dwLowDateTime = msticket->EndTime.LowPart;
-                EndTime.dwHighDateTime = msticket->EndTime.HighPart;
-                FileTimeToLocalFileTime(&EndTime, &LocalEndTime);
-                if (CompareFileTime(&Now, &LocalEndTime) >= 0) {
-                    ignore_cache = 1;
-                }
-                if (msticket->TicketFlags & KERB_TICKET_FLAGS_invalid) {
-                    ignore_cache = 1;
-                }
-                break;
-            case KERB_ETYPE_RC4_MD4:
-            default:
-                // not supported
-                ignore_cache = 1;
-                break;
+        if (native_debug) {
+            printf("LSA: TICKET SessionKey KeyType is %d\n", msticket->SessionKey.KeyType);
         }
 
-        if (ignore_cache) {
+        if ((msticket->TicketFlags & KERB_TICKET_FLAGS_invalid) == 0) {
+            GetSystemTimeAsFileTime(&Now);
+            EndTime.dwLowDateTime = msticket->EndTime.LowPart;
+            EndTime.dwHighDateTime = msticket->EndTime.HighPart;
+            FileTimeToLocalFileTime(&EndTime, &LocalEndTime);
+            if (CompareFileTime(&Now, &LocalEndTime) < 0) {
+                for (i=0; i<netypes; i++) {
+                    if (etypes[i] == msticket->SessionKey.KeyType) {
+                        found_in_cache = 1;
+                        if (native_debug) {
+                            printf("LSA: Valid etype found: %d\n", etypes[i]);
+                        }
+                        break;
+                    }
+                }
+            }
+        }
+
+        if (!found_in_cache) {
             if (native_debug) {
                 printf("LSA: MS TGT in cache is invalid/not supported; request new ticket\n");
             }
@@ -503,34 +509,40 @@
             }
 
             pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
-            pTicketRequest->EncryptionType = KERB_ETYPE_DES_CBC_MD5;
             pTicketRequest->CacheOptions = KERB_RETRIEVE_TICKET_DONT_USE_CACHE;
 
-            Status = LsaCallAuthenticationPackage(
-                        LogonHandle,
-                        PackageId,
-                        pTicketRequest,
-                        requestSize,
-                        &pTicketResponse,
-                        &responseSize,
-                        &SubStatus
-                        );
+            for (i=0; i<netypes; i++) {
+                pTicketRequest->EncryptionType = etypes[i];
+                Status = LsaCallAuthenticationPackage(
+                            LogonHandle,
+                            PackageId,
+                            pTicketRequest,
+                            requestSize,
+                            &pTicketResponse,
+                            &responseSize,
+                            &SubStatus
+                            );
 
-            if (native_debug) {
-                printf("LSA: Response size is %d\n", responseSize);
-            }
+                if (native_debug) {
+                    printf("LSA: Response size is %d for %d\n", responseSize, etypes[i]);
+                }
 
-            if (!LSA_SUCCESS(Status) || !LSA_SUCCESS(SubStatus)) {
-                if (!LSA_SUCCESS(Status)) {
-                    ShowNTError("LsaCallAuthenticationPackage", Status);
-                } else {
-                    ShowNTError("Protocol status", SubStatus);
+                if (!LSA_SUCCESS(Status) || !LSA_SUCCESS(SubStatus)) {
+                    if (!LSA_SUCCESS(Status)) {
+                        ShowNTError("LsaCallAuthenticationPackage", Status);
+                    } else {
+                        ShowNTError("Protocol status", SubStatus);
+                    }
+                    continue;
                 }
+
+                // got the native MS Kerberos TGT
+                msticket = &(pTicketResponse->Ticket);
                 break;
             }
-
-            // got the native MS Kerberos TGT
-            msticket = &(pTicketResponse->Ticket);
+        }
+        if (etypes != NULL) {
+            (*env)->ReleaseIntArrayElements(env, jetypes, etypes, 0);
         }
 
         /*
@@ -653,7 +665,7 @@
                 hostAddresses);
 
         break;
-    } // end of WHILE
+    } // end of WHILE. This WHILE will never loop.
 
     // clean up resources
     if (TktCacheResponse != NULL) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/Class/checkMemberAccess/CheckMemberAccess.java	Thu Dec 26 14:39:02 2013 -0800
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/*
+ * @test
+ * @bug 8021368
+ * @summary SecurityManager.checkMemberAccess call should not resolve
+ *          and load other classes
+ * @run main/othervm/policy=test.policy CheckMemberAccess
+ */
+
+public class CheckMemberAccess {
+    private static int count = 0;
+    public static void main(String[] args) throws Exception {
+        String testClasses = System.getProperty("test.classes", ".");
+        // remove Foo class
+        // the test will verify SecurityManager.checkMemberAccess should not
+        // cause any class loading of implementation classes
+        Path p = Paths.get(testClasses, "CheckMemberAccess$Foo.class");
+        if (Files.exists(p)) {
+            // Foo already deleted in rerun
+            Files.delete(p);
+        }
+        // patch the checkMemberAcces_ method name
+        patch(Paths.get(testClasses, "CheckMemberAccess$PrivateCheckMemberAccess.class"));
+        patch(Paths.get(testClasses, "CheckMemberAccess$StaticCheckMemberAccess.class"));
+
+        test(new OverriddedCheckMemberAccess(), count+1);
+        test(new NoOverriddedCheckMemberAccess(), count+1);
+        test(new PrivateCheckMemberAccess(), count);
+        test(new StaticCheckMemberAccess(), count);
+    }
+
+    private static void patch(Path p) throws IOException {
+        // s/checkMemberAcces_/checkMemberAccess
+        byte[] bytes = Files.readAllBytes(p);
+        int len = "Acces_".length();
+        for (int i=0; i < bytes.length-len; i++) {
+            if (bytes[i] == 'A' &&
+                bytes[i+1] == 'c' &&
+                bytes[i+2] == 'c' &&
+                bytes[i+3] == 'e' &&
+                bytes[i+4] == 's' &&
+                bytes[i+5] == '_') {
+                bytes[i+5] = 's';
+                break;
+            }
+        }
+        Files.write(p, bytes);
+    }
+
+    public void findMe() {};
+    public static void test(SecurityManager smgr, int expected) throws Exception {
+        System.setSecurityManager(smgr);
+        // this will trigger SecurityManager.checkMemberAccess to be called
+        Method m = CheckMemberAccess.class.getMethod("findMe", new Class<?>[0]);
+        if (count != expected) {
+            throw new RuntimeException(smgr.getClass() + ": " + count + " != " + expected);
+        }
+    }
+
+    static class OverriddedCheckMemberAccess extends SecurityManager {
+        @Override
+        public void checkMemberAccess(Class<?> clazz, int which) {
+            System.out.println("OverriddedCheckMemberAccess.checkMemberAccess called");
+            count++;
+        }
+        // implementation-specific class should not be loaded when
+        // this.checkMemberAccess is called
+        public Foo foo() {
+            return null;
+        }
+    }
+    static class NoOverriddedCheckMemberAccess extends OverriddedCheckMemberAccess {
+    }
+    static class PrivateCheckMemberAccess extends SecurityManager {
+        private void checkMemberAcces_(Class<?> clazz, int which) {
+            throw new RuntimeException("should not reach here");
+        }
+        // implementation-specific class should not be loaded when
+        // this.checkMemberAccess is called
+        public Foo foo() {
+            return null;
+        }
+    }
+    static class StaticCheckMemberAccess extends SecurityManager {
+        public static void checkMemberAcces_(Class<?> clazz, int which) {
+            throw new RuntimeException("should not reach here");
+        }
+        // implementation-specific class should not be loaded when
+        // this.checkMemberAccess is called
+        public Foo foo() {
+            return null;
+        }
+    }
+    static class Foo {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/Class/checkMemberAccess/test.policy	Thu Dec 26 14:39:02 2013 -0800
@@ -0,0 +1,6 @@
+grant {
+    permission java.lang.RuntimePermission "createSecurityManager";
+    permission java.lang.RuntimePermission "setSecurityManager";
+    permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
+    permission java.util.PropertyPermission "*", "read";
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/ref/FinalizeOverride.java	Thu Dec 26 14:39:02 2013 -0800
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/* @test
+ * @bug 8027351
+ * @summary Basic test of the finalize method
+ */
+
+public class FinalizeOverride {
+    // finalizedCount is incremented when the finalize method is invoked
+    private static AtomicInteger finalizedCount = new AtomicInteger();
+
+    // finalizedSum and privateFinalizedInvoke are used to verify
+    // the right overrided finalize method is invoked
+    private static AtomicInteger finalizedSum = new AtomicInteger();
+    private static volatile boolean privateFinalizeInvoked = false;
+
+    public static void main(String[] argvs) throws IOException {
+        patchPrivateFinalize();
+
+        test(new Base(10), 10);
+        test(new Subclass(20), 0);
+        test(new SubSubclass(30), 30);
+        test(new PublicFinalize(40), 40*100+40);
+        test(new PrivateFinalize(50), 50);
+        test(new NoOverride(60), 60);
+    }
+
+    static void test(Object o, int expected) {
+        int count = finalizedCount.get();
+        int sum = finalizedSum.get();
+        privateFinalizeInvoked = false;
+
+        // force GC and finalization
+        o = null;
+        while (finalizedCount.get() != (count+1)) {
+            System.gc();
+            System.runFinalization();
+        }
+
+        if (privateFinalizeInvoked) {
+            throw new RuntimeException("private finalize method invoked");
+        }
+        if (finalizedCount.get() != (count+1)) {
+            throw new RuntimeException("Unexpected count=" + finalizedCount +
+                " expected=" + (count+1));
+        }
+        if (finalizedSum.get() != (sum+expected)) {
+            throw new RuntimeException("Unexpected sum=" + finalizedSum +
+                " prev=" + sum + " value=" + expected);
+        }
+    }
+
+    static void patchPrivateFinalize() throws IOException {
+        // patch the private f_nal_ze method name to "finalize"
+        String testClasses = System.getProperty("test.classes", ".");
+        Path p = Paths.get(testClasses, "FinalizeOverride$PrivateFinalize.class");
+        byte[] bytes = Files.readAllBytes(p);
+        int len = "f_nal_ze".length();
+        for (int i=0; i < bytes.length-len; i++) {
+            if (bytes[i] == 'f' &&
+                bytes[i+1] == '_' &&
+                bytes[i+2] == 'n' &&
+                bytes[i+3] == 'a' &&
+                bytes[i+4] == 'l' &&
+                bytes[i+5] == '_' &&
+                bytes[i+6] == 'z' &&
+                bytes[i+7] == 'e')
+            {
+                // s%_%i%
+                bytes[i+1] = 'i';
+                bytes[i+5] = 'i';
+                break;
+            }
+        }
+        Files.write(p, bytes);
+    }
+
+    static class Base {
+        protected int value;
+        Base(int v) {
+            this.value = v;
+        }
+        int called() {
+            finalizedSum.addAndGet(value);
+            return value;
+        }
+        protected void finalize() {
+            System.out.println("Base.finalize() sum += " + called());
+            finalizedCount.incrementAndGet();
+        }
+    }
+    static class PublicFinalize extends Base {
+        PublicFinalize(int v) {
+            super(v);
+        }
+        public void finalize() {
+            finalizedSum.addAndGet(value * 100);
+            System.out.println("PublicFinalize.finalize() sum += " + called() +
+                "+"+value+"*100");
+            finalizedCount.incrementAndGet();
+        }
+    }
+    static class Subclass extends Base {
+        Subclass(int v) {
+            super(v);
+        }
+        protected void finalize() {
+            // no value added to sum
+            System.out.println("Subclass.finalize() sum += 0");
+            finalizedCount.incrementAndGet();
+        }
+    }
+    static class SubSubclass extends Subclass {
+        SubSubclass(int v) {
+            super(v);
+        }
+        protected final void finalize() {
+            finalizedSum.addAndGet(value);
+            System.out.println("SubSubclass.finalize() sum +=" +value);
+            finalizedCount.incrementAndGet();
+        }
+    }
+    static class PrivateFinalize extends Base {
+        PrivateFinalize(int v) {
+            super(v);
+        }
+        private void f_nal_ze() {
+            // finalization catches any exception
+            System.out.println("Error: private finalize invoked!!");
+            privateFinalizeInvoked = true;
+            finalizedCount.incrementAndGet();
+        }
+    }
+    static class NoOverride extends PrivateFinalize {
+        NoOverride(int v) {
+            super(v);
+        }
+    }
+}
--- a/test/java/net/URLClassLoader/closetest/CloseTest.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/test/java/net/URLClassLoader/closetest/CloseTest.java	Thu Dec 26 14:39:02 2013 -0800
@@ -25,7 +25,8 @@
  * @test
  * @bug 4167874
  * @library ../../../../com/sun/net/httpserver
- * @build FileServerHandler
+ * @library /lib/testlibrary
+ * @build FileServerHandler jdk.testlibrary.FileUtils
  * @run shell build.sh
  * @run main/othervm CloseTest
  * @summary URL-downloaded jar files can consume all available file descriptors
--- a/test/java/net/URLClassLoader/closetest/Common.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/test/java/net/URLClassLoader/closetest/Common.java	Thu Dec 26 14:39:02 2013 -0800
@@ -23,6 +23,9 @@
 
 import java.io.*;
 import java.net.*;
+import java.nio.file.Files;
+import jdk.testlibrary.FileUtils;
+import static java.nio.file.StandardCopyOption.*;
 
 public class Common {
 
@@ -39,42 +42,16 @@
             if (!src.isFile()) {
                 throw new RuntimeException ("File not found: " + src.toString());
             }
-            dst.delete();
-            dst.createNewFile();
-            FileInputStream i = new FileInputStream (src);
-            FileOutputStream o = new FileOutputStream (dst);
-            byte[] buf = new byte [1024];
-            int count;
-            while ((count=i.read(buf)) >= 0) {
-                o.write (buf, 0, count);
-            }
-            i.close();
-            o.close();
+            Files.copy(src.toPath(), dst.toPath(), REPLACE_EXISTING);
         } catch (IOException e) {
             throw new RuntimeException (e);
         }
     }
 
-    static void rm_minus_rf (File path) {
-        if (!path.exists()) {
+    static void rm_minus_rf (File path) throws IOException, InterruptedException {
+        if (!path.exists())
             return;
-        }
-        if (path.isFile()) {
-            if (!path.delete()) {
-                throw new RuntimeException ("Could not delete " + path);
-            }
-        } else if (path.isDirectory ()) {
-            String[] names = path.list();
-            File[] files = path.listFiles();
-            for (int i=0; i<files.length; i++) {
-                rm_minus_rf (new File(path, names[i]));
-            }
-            if (!path.delete()) {
-                throw new RuntimeException ("Could not delete " + path);
-            }
-        } else {
-            throw new RuntimeException ("Trying to delete something that isn't a file or a directory");
-        }
+        FileUtils.deleteFileTreeWithRetry(path.toPath());
     }
 
     static void copyDir (File src, File dst) {
--- a/test/java/net/URLClassLoader/closetest/GetResourceAsStream.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/test/java/net/URLClassLoader/closetest/GetResourceAsStream.java	Thu Dec 26 14:39:02 2013 -0800
@@ -24,6 +24,8 @@
 /**
  * @test
  * @bug 6899919
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.FileUtils
  * @run shell build2.sh
  * @run main/othervm GetResourceAsStream
  */
--- a/test/java/rmi/testlibrary/TestLibrary.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/test/java/rmi/testlibrary/TestLibrary.java	Thu Dec 26 14:39:02 2013 -0800
@@ -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
@@ -127,6 +127,33 @@
         bomb(null, e);
     }
 
+    /**
+     * Helper method to determine if registry has started
+     *
+     * @param port The port number to check
+     * @param msTimeout The amount of milliseconds to spend checking
+     */
+
+    public static boolean checkIfRegistryRunning(int port, int msTimeout) {
+        long stopTime = System.currentTimeMillis() + msTimeout;
+        do {
+            try {
+                Registry r = LocateRegistry.getRegistry(port);
+                String[] s = r.list();
+                // no exception. We're now happy that registry is running
+                return true;
+            } catch (RemoteException e) {
+                // problem - not ready ? Try again
+                try {
+                    Thread.sleep(500);
+                } catch (InterruptedException ie) {
+                    // not expected
+                }
+            }
+        } while (stopTime > System.currentTimeMillis());
+        return false;
+    }
+
     public static String getProperty(String property, String defaultVal) {
         final String prop = property;
         final String def = defaultVal;
--- a/test/javax/xml/ws/clientjar/TestWsImport.java	Wed Dec 18 15:56:58 2013 -0800
+++ b/test/javax/xml/ws/clientjar/TestWsImport.java	Thu Dec 26 14:39:02 2013 -0800
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8016271
+ * @bug 8016271 8026405
  * @summary wsimport -clientjar does not create portable jar on windows due to hardcoded '\'
  * @run main/othervm TestWsImport
  */
@@ -77,14 +77,14 @@
             String address = "http://localhost:" + port + "/hello";
 
             Service service = Service.create(new URL(address + "?wsdl"),
-                new QName("http://test/jaxws/sample/",
-                "TestService"));
+                new QName("http://test/jaxws/sample/", "TestService"));
 
             String[] wsargs = {
                 wsimport,
                 "-p",
                 "wstest",
                 "-J-Djavax.xml.accessExternalSchema=all",
+                "-J-Dcom.sun.tools.internal.ws.Invoker.noSystemProxies=true",
                 address + "?wsdl",
                 "-clientjar",
                 "wsjar.jar"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/lib/testlibrary/jdk/testlibrary/FileUtils.java	Thu Dec 26 14:39:02 2013 -0800
@@ -0,0 +1,194 @@
+/*
+ * 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 jdk.testlibrary;
+
+import java.io.IOException;
+import java.nio.file.DirectoryNotEmptyException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.List;
+
+
+/**
+ * Common library for various test file utility functions.
+ */
+public final class FileUtils {
+
+    private static final boolean isWindows =
+                            System.getProperty("os.name").startsWith("Windows");
+    private static final int RETRY_DELETE_MILLIS = isWindows ? 500 : 0;
+    private static final int MAX_RETRY_DELETE_TIMES = isWindows ? 15 : 0;
+
+    /**
+     * Deletes a file, retrying if necessary.
+     *
+     * @param path  the file to delete
+     *
+     * @throws NoSuchFileException
+     *         if the file does not exist (optional specific exception)
+     * @throws DirectoryNotEmptyException
+     *         if the file is a directory and could not otherwise be deleted
+     *         because the directory is not empty (optional specific exception)
+     * @throws IOException
+     *         if an I/O error occurs
+     */
+    public static void deleteFileWithRetry(Path path)
+        throws IOException
+    {
+        try {
+            deleteFileWithRetry0(path);
+        } catch (InterruptedException x) {
+            throw new IOException("Interrupted while deleting.", x);
+        }
+    }
+
+    /**
+     * Deletes a file, retrying if necessary.
+     * No exception thrown if file doesn't exist.
+     *
+     * @param path  the file to delete
+     *
+     * @throws NoSuchFileException
+     *         if the file does not exist (optional specific exception)
+     * @throws DirectoryNotEmptyException
+     *         if the file is a directory and could not otherwise be deleted
+     *         because the directory is not empty (optional specific exception)
+     * @throws IOException
+     *         if an I/O error occurs
+     */
+    public static void deleteFileIfExistsWithRetry(Path path)
+        throws IOException
+    {
+        try {
+            if(Files.exists(path))
+                deleteFileWithRetry0(path);
+        } catch (InterruptedException x) {
+            throw new IOException("Interrupted while deleting.", x);
+        }
+    }
+
+    private static void deleteFileWithRetry0(Path path)
+        throws IOException, InterruptedException
+    {
+        int times = 0;
+        IOException ioe = null;
+        while (true) {
+            try {
+                Files.delete(path);
+                while (Files.exists(path)) {
+                    times++;
+                    if (times > MAX_RETRY_DELETE_TIMES)
+                        throw new IOException("File still exists after " + times + " waits.");
+                    Thread.sleep(RETRY_DELETE_MILLIS);
+                }
+                break;
+            } catch (NoSuchFileException | DirectoryNotEmptyException x) {
+                throw x;
+            } catch (IOException x) {
+                // Backoff/retry in case another process is accessing the file
+                times++;
+                if (ioe == null)
+                    ioe = x;
+                else
+                    ioe.addSuppressed(x);
+
+                if (times > MAX_RETRY_DELETE_TIMES)
+                    throw ioe;
+                Thread.sleep(RETRY_DELETE_MILLIS);
+            }
+        }
+    }
+
+    /**
+     * Deletes a directory and its subdirectories, retrying if necessary.
+     *
+     * @param dir  the directory to delete
+     *
+     * @throws  IOException
+     *          If an I/O error occurs. Any such exceptions are caught
+     *          internally. If only one is caught, then it is re-thrown.
+     *          If more than one exception is caught, then the second and
+     *          following exceptions are added as suppressed exceptions of the
+     *          first one caught, which is then re-thrown.
+     */
+    public static void deleteFileTreeWithRetry(Path dir)
+         throws IOException
+    {
+        IOException ioe = null;
+        final List<IOException> excs = deleteFileTreeUnchecked(dir);
+        if (!excs.isEmpty()) {
+            ioe = excs.remove(0);
+            for (IOException x : excs)
+                ioe.addSuppressed(x);
+        }
+        if (ioe != null)
+            throw ioe;
+    }
+
+    public static List<IOException> deleteFileTreeUnchecked(Path dir) {
+        final List<IOException> excs = new ArrayList<>();
+        try {
+            java.nio.file.Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
+                @Override
+                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
+                    try {
+                        deleteFileWithRetry0(file);
+                    } catch (IOException x) {
+                        excs.add(x);
+                    } catch (InterruptedException x) {
+                        excs.add(new IOException("Interrupted while deleting.", x));
+                        return FileVisitResult.TERMINATE;
+                    }
+                    return FileVisitResult.CONTINUE;
+                }
+                @Override
+                public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
+                    try {
+                        deleteFileWithRetry0(dir);
+                    } catch (IOException x) {
+                        excs.add(x);
+                    } catch (InterruptedException x) {
+                        excs.add(new IOException("Interrupted while deleting.", x));
+                        return FileVisitResult.TERMINATE;
+                    }
+                    return FileVisitResult.CONTINUE;
+                }
+                @Override
+                public FileVisitResult visitFileFailed(Path file, IOException exc) {
+                    excs.add(exc);
+                    return FileVisitResult.CONTINUE;
+                }
+            });
+        } catch (IOException x) {
+            excs.add(x);
+        }
+        return excs;
+    }
+}
+