--- old/jaxws/.hgtags 2013-02-07 17:06:39.000000000 +0100 +++ new/jaxws/.hgtags 2013-02-07 17:06:39.000000000 +0100 @@ -225,6 +225,14 @@ df3e4c85e26c651d098cddd546916a625fd777cd jdk7u10-b30 846f4e01218ffe37b2dbceaf89c222c0aea43180 jdk7u11-b20 1f06394ca182cb392e472ba7b63b28a40725629d jdk7u11-b21 +ed609545e38c2e499437292c1541e4d1c2b8b992 jdk7u11-b03 +4e1dd1192649575e80d893bcab411077b77c9a0c jdk7u11-b04 +0e1eefefc2d0c8f0d0cd9e7fb7d78ae026aa8ba0 jdk7u11-b05 +7365410bb417d6a40996920bb4dbb44bdb1225a9 jdk7u11-b06 +66786f9d73c479ce70a306e14dd7f653f5b3a4f9 jdk7u11-b07 +a3cadd00459f1146fdcfa8702bbb29efdcd58960 jdk7u11-b08 +c7ea4220ad61b125bd7c4b7f112dd9ff18e9be33 jdk7u13-b09 +1d2eb88cadaf29bf577a71c69b04afe2468d8ff6 jdk7u13-b20 55dcda93e8c8b5c3170def946de35dd0407eab59 jdk7u8-b01 c025e953f655b375f27f8f94493ceeb43ef1d979 jdk7u8-b02 705b60b56ead99d64d1b7302cba3a200ab048ff7 jdk7u8-b03 --- old/jdk/.hgtags 2013-02-07 17:06:39.000000000 +0100 +++ new/jdk/.hgtags 2013-02-07 17:06:39.000000000 +0100 @@ -225,6 +225,14 @@ 84218dff5e4c7bc00fd9266769c0d12bdde866f5 jdk7u10-b30 ecc14534318c80dc7612c8b1d328a67849c5b07f jdk7u11-b20 d9969a953f693f5760b1d2759f11a2cb222e4f20 jdk7u11-b21 +84da14fbd3ac12a3c6734fa4b6a366cfde1426af jdk7u11-b03 +932ef74edbf984299a68c126c70bbe04ffbde9b5 jdk7u11-b04 +fb35fb91f6478f8076993bcc4112746bcd9a2985 jdk7u11-b05 +f26def552d2c4873aeaee00241f60efc462a11a7 jdk7u11-b06 +1d14a3d7bac870423e52a889d2f5f60ee76ddc6a jdk7u11-b07 +ee61b528b3f866b20095f5e9593896d4ea4be468 jdk7u11-b08 +0b9564dab118d40bc5edc60269f736f97ab6f385 jdk7u13-b09 +8eb180a284b0911b2645d5cbdff5be499a75d6b2 jdk7u13-b20 df945ef30444adf08f3ef14b0c49c8bda6dda587 jdk7u8-b01 dd1e513c05b8b8c8402e9ecf9c0d5bdbebb1a089 jdk7u8-b02 355cf1937d0824b54ac38ee5a5496197647840f9 jdk7u8-b03 --- old/jdk/src/share/bin/jli_util.h 2013-02-07 17:06:40.000000000 +0100 +++ new/jdk/src/share/bin/jli_util.h 2013-02-07 17:06:40.000000000 +0100 @@ -66,7 +66,7 @@ #include #define JLI_StrCaseCmp(p1, p2) stricmp((p1), (p2)) #define JLI_StrNCaseCmp(p1, p2, p3) strnicmp((p1), (p2), (p3)) -#define JLI_Snprintf _snprintf +int JLI_Snprintf(char *buffer, size_t size, const char *format, ...); void JLI_CmdToArgs(char *cmdline); #else #include --- old/jdk/src/share/bin/parse_manifest.c 2013-02-07 17:06:41.000000000 +0100 +++ new/jdk/src/share/bin/parse_manifest.c 2013-02-07 17:06:41.000000000 +0100 @@ -490,9 +490,9 @@ #ifdef O_BINARY | O_BINARY /* use binary mode on windows */ #endif - )) == -1) + )) == -1) { return (-1); - + } info->manifest_version = NULL; info->main_class = NULL; info->jre_version = NULL; @@ -539,12 +539,14 @@ zentry entry; void *data = NULL; - fd = open(jarfile, O_RDONLY + if ((fd = open(jarfile, O_RDONLY #ifdef O_BINARY | O_BINARY /* use binary mode on windows */ #endif - ); - if (fd != -1 && find_file(fd, &entry, filename) == 0) { + )) == -1) { + return NULL; + } + if (find_file(fd, &entry, filename) == 0) { data = inflate_file(fd, &entry, size); } close(fd); @@ -586,8 +588,9 @@ #ifdef O_BINARY | O_BINARY /* use binary mode on windows */ #endif - )) == -1) + )) == -1) { return (-1); + } if (rc = find_file(fd, &entry, manifest_name) != 0) { close(fd); --- old/jdk/src/share/classes/com/sun/beans/finder/MethodFinder.java 2013-02-07 17:06:42.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/beans/finder/MethodFinder.java 2013-02-07 17:06:42.000000000 +0100 @@ -66,11 +66,14 @@ Signature signature = new Signature(type, name, args); Method method = CACHE.get(signature); - if (method != null) { + boolean cached = method != null; + if (cached && isPackageAccessible(method.getDeclaringClass())) { return method; } method = findAccessibleMethod(new MethodFinder(name, args).find(type.getMethods())); - CACHE.put(signature, method); + if (!cached) { + CACHE.put(signature, method); + } return method; } --- old/jdk/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java 2013-02-07 17:06:43.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java 2013-02-07 17:06:42.000000000 +0100 @@ -41,6 +41,8 @@ import javax.crypto.SecretKey; import javax.crypto.spec.*; +import sun.security.util.KeyUtil; + /** * This class implements the Diffie-Hellman key agreement protocol between * any number of parties. @@ -200,6 +202,9 @@ throw new InvalidKeyException("Incompatible parameters"); } + // validate the Diffie-Hellman public key + KeyUtil.validate(dhPubKey); + // store the y value this.y = dhPubKey.getY(); --- old/jdk/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java 2013-02-07 17:06:43.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java 2013-02-07 17:06:43.000000000 +0100 @@ -1003,7 +1003,6 @@ /** Write a constant pool reference. */ public void putRef(Entry e) { - assert(index != null); addValue(encodeRefOrNull(e, index)); } public void putRef(Entry e, Index index) { @@ -1055,6 +1054,8 @@ int encodeRef(Entry e, Index ix) { + if (ix == null) + throw new RuntimeException("null index for " + e.stringValue()); int coding = ix.indexOf(e); if (verbose > 2) Utils.log.fine("putRef "+coding+" => "+e); --- old/jdk/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java 2013-02-07 17:06:44.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java 2013-02-07 17:06:44.000000000 +0100 @@ -1053,6 +1053,8 @@ /** Index of all CP entries of a given tag and class. */ public Index getMemberIndex(byte tag, ClassEntry classRef) { + if (classRef == null) + throw new RuntimeException("missing class reference for " + tagName(tag)); if (indexByTagAndClass == null) indexByTagAndClass = new Index[CONSTANT_Limit][]; Index allClasses = getIndexByTag(CONSTANT_Class); --- old/jdk/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java 2013-02-07 17:06:45.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java 2013-02-07 17:06:45.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2012, 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 @@ -104,6 +104,10 @@ return (p200 == null)? null: p200._nunp; } + private synchronized long getUnpackerPtr() { + return unpackerPtr; + } + // Callback from the unpacker engine to get more data. private long readInputFn(ByteBuffer pbuf, long minlen) throws IOException { if (in == null) return 0; // nothing is readable --- old/jdk/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java 2013-02-07 17:06:46.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java 2013-02-07 17:06:46.000000000 +0100 @@ -84,7 +84,7 @@ * @param out an OutputStream * @exception IOException if an error is encountered. */ - public void pack(JarFile in, OutputStream out) throws IOException { + public synchronized void pack(JarFile in, OutputStream out) throws IOException { assert(Utils.currentInstance.get() == null); TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null @@ -119,7 +119,7 @@ * @param out an OutputStream * @exception IOException if an error is encountered. */ - public void pack(JarInputStream in, OutputStream out) throws IOException { + public synchronized void pack(JarInputStream in, OutputStream out) throws IOException { assert(Utils.currentInstance.get() == null); TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null : TimeZone.getDefault(); --- old/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java 2013-02-07 17:06:47.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java 2013-02-07 17:06:46.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2012, 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 @@ -107,7 +107,7 @@ * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ - public void unpack(InputStream in, JarOutputStream out) throws IOException { + public synchronized void unpack(InputStream in, JarOutputStream out) throws IOException { if (in == null) { throw new NullPointerException("null input"); } @@ -152,7 +152,7 @@ * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ - public void unpack(File in, JarOutputStream out) throws IOException { + public synchronized void unpack(File in, JarOutputStream out) throws IOException { if (in == null) { throw new NullPointerException("null input"); } --- old/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java 2013-02-07 17:06:47.000000000 +0100 +++ new/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java 2013-02-07 17:06:47.000000000 +0100 @@ -56,6 +56,8 @@ import java.lang.reflect.InvocationTargetException; import javax.management.AttributeNotFoundException; import javax.management.openmbean.CompositeData; +import sun.reflect.misc.MethodUtil; +import sun.reflect.misc.ReflectUtil; /** * This class contains the methods for performing all the tests needed to verify @@ -528,8 +530,10 @@ // to locate method readMethod = SimpleIntrospector.getReadMethod(clazz, element); } - if (readMethod != null) - return readMethod.invoke(complex); + if (readMethod != null) { + ReflectUtil.checkPackageAccess(readMethod.getDeclaringClass()); + return MethodUtil.invoke(readMethod, complex, new Class[0]); + } throw new AttributeNotFoundException( "Could not find the getter method for the property " + --- old/jdk/src/share/classes/java/awt/Dialog.java 2013-02-07 17:06:48.000000000 +0100 +++ new/jdk/src/share/classes/java/awt/Dialog.java 2013-02-07 17:06:48.000000000 +0100 @@ -39,6 +39,7 @@ import sun.awt.util.IdentityArrayList; import sun.awt.util.IdentityLinkedList; import sun.security.util.SecurityConstants; +import java.security.AccessControlException; /** * A Dialog is a top-level window with a title and a border @@ -128,6 +129,8 @@ */ boolean undecorated = false; + private transient boolean initialized = false; + /** * Modal dialogs block all input to some top-level windows. * Whether a particular window is blocked depends on dialog's type @@ -671,6 +674,7 @@ this.title = title; setModalityType(modalityType); SunToolkit.checkAndSetPolicy(this); + initialized = true; } /** @@ -722,6 +726,7 @@ this.title = title; setModalityType(modalityType); SunToolkit.checkAndSetPolicy(this); + initialized = true; } /** @@ -851,12 +856,9 @@ if (modalityType == type) { return; } - if (type == ModalityType.TOOLKIT_MODAL) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.AWT.TOOLKIT_MODALITY_PERMISSION); - } - } + + checkModalityPermission(type); + modalityType = type; modal = (modalityType != ModalityType.MODELESS); } @@ -1025,6 +1027,9 @@ */ @Deprecated public void show() { + if (!initialized) throw new IllegalStateException( + "The dialog component has not been initialized properly"); + beforeFirstShow = false; if (!isModal()) { conditionalShow(null, null); @@ -1600,18 +1605,51 @@ } } + private void checkModalityPermission(ModalityType mt) { + if (mt == ModalityType.TOOLKIT_MODAL) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission( + SecurityConstants.AWT.TOOLKIT_MODALITY_PERMISSION + ); + } + } + } + private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException, HeadlessException { GraphicsEnvironment.checkHeadless(); - s.defaultReadObject(); + + java.io.ObjectInputStream.GetField fields = + s.readFields(); + + ModalityType localModalityType = (ModalityType)fields.get("modalityType", null); + + try { + checkModalityPermission(localModalityType); + } catch (AccessControlException ace) { + localModalityType = DEFAULT_MODALITY_TYPE; + } // in 1.5 or earlier modalityType was absent, so use "modal" instead - if (modalityType == null) { + if (localModalityType == null) { + this.modal = fields.get("modal", false); setModal(modal); + } else { + this.modalityType = localModalityType; } + this.resizable = fields.get("resizable", true); + this.undecorated = fields.get("undecorated", false); + this.title = (String)fields.get("title", ""); + blockedWindows = new IdentityArrayList(); + + SunToolkit.checkAndSetPolicy(this); + + initialized = true; + } /* --- old/jdk/src/share/classes/java/awt/EventQueue.java 2013-02-07 17:06:49.000000000 +0100 +++ new/jdk/src/share/classes/java/awt/EventQueue.java 2013-02-07 17:06:49.000000000 +0100 @@ -189,7 +189,8 @@ } public void removeSourceEvents(EventQueue eventQueue, Object source, - boolean removeAllEvents) { + boolean removeAllEvents) + { eventQueue.removeSourceEvents(source, removeAllEvents); } public boolean noEvents(EventQueue eventQueue) { @@ -198,6 +199,11 @@ public void wakeup(EventQueue eventQueue, boolean isShutdown) { eventQueue.wakeup(isShutdown); } + public void invokeAndWait(Object source, Runnable r) + throws InterruptedException, InvocationTargetException + { + EventQueue.invokeAndWait(source, r); + } }); } @@ -1233,8 +1239,14 @@ * @since 1.2 */ public static void invokeAndWait(Runnable runnable) - throws InterruptedException, InvocationTargetException { + throws InterruptedException, InvocationTargetException + { + invokeAndWait(Toolkit.getDefaultToolkit(), runnable); + } + static void invokeAndWait(Object source, Runnable runnable) + throws InterruptedException, InvocationTargetException + { if (EventQueue.isDispatchThread()) { throw new Error("Cannot call invokeAndWait from the event dispatcher thread"); } @@ -1243,8 +1255,7 @@ Object lock = new AWTInvocationLock(); InvocationEvent event = - new InvocationEvent(Toolkit.getDefaultToolkit(), runnable, lock, - true); + new InvocationEvent(source, runnable, lock, true); synchronized (lock) { Toolkit.getEventQueue().postEvent(event); --- old/jdk/src/share/classes/java/awt/TextComponent.java 2013-02-07 17:06:50.000000000 +0100 +++ new/jdk/src/share/classes/java/awt/TextComponent.java 2013-02-07 17:06:50.000000000 +0100 @@ -107,12 +107,6 @@ // the background color of non-editable TextComponents. boolean backgroundSetByClientCode = false; - /** - * True if this TextComponent has access - * to the System clipboard. - */ - transient private boolean canAccessClipboard; - transient protected TextListener textListener; /* @@ -137,7 +131,6 @@ GraphicsEnvironment.checkHeadless(); this.text = (text != null) ? text : ""; setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); - checkSystemClipboardAccess(); } private void enableInputMethodsIfNecessary() { @@ -732,17 +725,14 @@ /** * Assigns a valid value to the canAccessClipboard instance variable. */ - private void checkSystemClipboardAccess() { - canAccessClipboard = true; + private boolean canAccessClipboard() { SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - sm.checkSystemClipboardAccess(); - } - catch (SecurityException e) { - canAccessClipboard = false; - } - } + if (sm == null) return true; + try { + sm.checkSystemClipboardAccess(); + return true; + } catch (SecurityException e) {} + return false; } /* @@ -825,7 +815,6 @@ } } enableInputMethodsIfNecessary(); - checkSystemClipboardAccess(); } --- old/jdk/src/share/classes/java/awt/Window.java 2013-02-07 17:06:51.000000000 +0100 +++ new/jdk/src/share/classes/java/awt/Window.java 2013-02-07 17:06:51.000000000 +0100 @@ -1206,7 +1206,7 @@ } else { try { - EventQueue.invokeAndWait(action); + EventQueue.invokeAndWait(this, action); } catch (InterruptedException e) { System.err.println("Disposal was interrupted:"); --- old/jdk/src/share/classes/java/io/ObjectInputStream.java 2013-02-07 17:06:52.000000000 +0100 +++ new/jdk/src/share/classes/java/io/ObjectInputStream.java 2013-02-07 17:06:51.000000000 +0100 @@ -1750,6 +1750,12 @@ ObjectStreamClass desc = readClassDesc(false); desc.checkDeserialize(); + Class cl = desc.forClass(); + if (cl == String.class || cl == Class.class + || cl == ObjectStreamClass.class) { + throw new InvalidClassException("invalid class descriptor"); + } + Object obj; try { obj = desc.isInstantiable() ? desc.newInstance() : null; --- old/jdk/src/share/classes/java/lang/Class.java 2013-02-07 17:06:52.000000000 +0100 +++ new/jdk/src/share/classes/java/lang/Class.java 2013-02-07 17:06:52.000000000 +0100 @@ -65,7 +65,9 @@ import sun.reflect.generics.scope.ClassScope; import sun.security.util.SecurityConstants; import java.lang.annotation.Annotation; +import java.lang.reflect.Proxy; import sun.reflect.annotation.*; +import sun.reflect.misc.ReflectUtil; /** * Instances of the class {@code Class} represent classes and @@ -320,7 +322,7 @@ throws InstantiationException, IllegalAccessException { if (System.getSecurityManager() != null) { - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), false); } return newInstance0(); } @@ -1297,7 +1299,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), false); // Privileged so this implementation can look at DECLARED classes, // something the caller might not have privilege to do. The code here @@ -1372,7 +1374,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true); return copyFields(privateGetPublicFields(null)); } @@ -1423,7 +1425,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true); return copyMethods(privateGetPublicMethods()); } @@ -1472,7 +1474,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true); return copyConstructors(privateGetDeclaredConstructors(true)); } @@ -1531,7 +1533,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true); Field field = getField0(name); if (field == null) { throw new NoSuchFieldException(name); @@ -1616,7 +1618,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true); Method method = getMethod0(name, parameterTypes); if (method == null) { throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); @@ -1670,7 +1672,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true); return getConstructor0(parameterTypes, Member.PUBLIC); } @@ -1712,7 +1714,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), false); return getDeclaredClasses0(); } @@ -1756,7 +1758,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true); return copyFields(privateGetDeclaredFields(false)); } @@ -1804,7 +1806,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true); return copyMethods(privateGetDeclaredMethods(false)); } @@ -1849,7 +1851,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true); return copyConstructors(privateGetDeclaredConstructors(false)); } @@ -1893,7 +1895,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true); Field field = searchFields(privateGetDeclaredFields(false), name); if (field == null) { throw new NoSuchFieldException(name); @@ -1948,7 +1950,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true); Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes); if (method == null) { throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); @@ -1998,7 +2000,7 @@ // be very careful not to change the stack depth of this // checkMemberAccess call for security reasons // see java.lang.SecurityManager.checkMemberAccess - checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader()); + checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true); return getConstructor0(parameterTypes, Member.DECLARED); } @@ -2168,19 +2170,26 @@ *

Default policy: allow all clients access with normal Java access * control. */ - private void checkMemberAccess(int which, ClassLoader ccl) { + private void checkMemberAccess(int which, ClassLoader ccl, boolean checkProxyInterfaces) { SecurityManager s = System.getSecurityManager(); if (s != null) { s.checkMemberAccess(this, which); ClassLoader cl = getClassLoader0(); - if ((ccl != null) && (ccl != cl) && - ((cl == null) || !cl.isAncestor(ccl))) { + if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { String name = this.getName(); int i = name.lastIndexOf('.'); if (i != -1) { - s.checkPackageAccess(name.substring(0, i)); + // skip the package access check on a proxy class in default proxy package + String pkg = name.substring(0, i); + if (!Proxy.isProxyClass(this) || !pkg.equals(ReflectUtil.PROXY_PACKAGE)) { + s.checkPackageAccess(pkg); + } } } + // check package access on the proxy interfaces + if (checkProxyInterfaces && Proxy.isProxyClass(this)) { + ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); + } } } --- old/jdk/src/share/classes/java/lang/invoke/MethodHandleProxies.java 2013-02-07 17:06:53.000000000 +0100 +++ new/jdk/src/share/classes/java/lang/invoke/MethodHandleProxies.java 2013-02-07 17:06:53.000000000 +0100 @@ -26,8 +26,12 @@ package java.lang.invoke; import java.lang.reflect.*; +import java.security.AccessController; +import java.security.PrivilegedAction; import sun.invoke.WrapperInstance; import java.util.ArrayList; +import sun.reflect.Reflection; +import sun.reflect.misc.ReflectUtil; /** * This class consists exclusively of static methods that help adapt @@ -137,6 +141,18 @@ T asInterfaceInstance(final Class intfc, final MethodHandle target) { if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers())) throw new IllegalArgumentException("not a public interface: "+intfc.getName()); + SecurityManager smgr = System.getSecurityManager(); + if (smgr != null) { + final int CALLER_FRAME = 2; // 0: Reflection, 1: asInterfaceInstance, 2: caller + final Class caller = Reflection.getCallerClass(CALLER_FRAME); + final ClassLoader ccl = caller.getClassLoader(); + ReflectUtil.checkProxyPackageAccess(ccl, intfc); + } + ClassLoader proxyLoader = intfc.getClassLoader(); + if (proxyLoader == null) { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); // avoid use of BCP + proxyLoader = cl != null ? cl : ClassLoader.getSystemClassLoader(); + } final Method[] methods = getSingleNameMethods(intfc); if (methods == null) throw new IllegalArgumentException("not a single-method interface: "+intfc.getName()); @@ -148,27 +164,44 @@ checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class)); vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount()); } - return intfc.cast(Proxy.newProxyInstance( - intfc.getClassLoader(), - new Class[]{ intfc, WrapperInstance.class }, - new InvocationHandler() { - private Object getArg(String name) { - if ((Object)name == "getWrapperInstanceTarget") return target; - if ((Object)name == "getWrapperInstanceType") return intfc; - throw new AssertionError(); - } - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - for (int i = 0; i < methods.length; i++) { - if (method.equals(methods[i])) - return vaTargets[i].invokeExact(args); - } - if (method.getDeclaringClass() == WrapperInstance.class) - return getArg(method.getName()); - if (isObjectMethod(method)) - return callObjectMethod(proxy, method, args); - throw new InternalError("bad proxy method: "+method); + final InvocationHandler ih = new InvocationHandler() { + private Object getArg(String name) { + if ((Object)name == "getWrapperInstanceTarget") return target; + if ((Object)name == "getWrapperInstanceType") return intfc; + throw new AssertionError(); + } + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + for (int i = 0; i < methods.length; i++) { + if (method.equals(methods[i])) + return vaTargets[i].invokeExact(args); } - })); + if (method.getDeclaringClass() == WrapperInstance.class) + return getArg(method.getName()); + if (isObjectMethod(method)) + return callObjectMethod(proxy, method, args); + throw new InternalError("bad proxy method: "+method); + } + }; + + Object proxy; + if (smgr != null) { + // sun.invoke.WrapperInstance is a restricted interface not accessible + // by any non-null class loader. + final ClassLoader loader = proxyLoader; + proxy = AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + return Proxy.newProxyInstance( + loader, + new Class[]{ intfc, WrapperInstance.class }, + ih); + } + }); + } else { + proxy = Proxy.newProxyInstance(proxyLoader, + new Class[]{ intfc, WrapperInstance.class }, + ih); + } + return intfc.cast(proxy); } /** --- old/jdk/src/share/classes/java/lang/reflect/Proxy.java 2013-02-07 17:06:54.000000000 +0100 +++ new/jdk/src/share/classes/java/lang/reflect/Proxy.java 2013-02-07 17:06:54.000000000 +0100 @@ -27,6 +27,9 @@ import java.lang.ref.Reference; import java.lang.ref.WeakReference; +import java.security.AccessController; +import java.security.Permission; +import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -36,6 +39,9 @@ import java.util.List; import java.util.WeakHashMap; import sun.misc.ProxyGenerator; +import sun.reflect.Reflection; +import sun.reflect.misc.ReflectUtil; +import sun.security.util.SecurityConstants; /** * {@code Proxy} provides static methods for creating dynamic proxy @@ -265,9 +271,69 @@ * @param h the invocation handler for this proxy instance */ protected Proxy(InvocationHandler h) { + doNewInstanceCheck(); this.h = h; } + private static class ProxyAccessHelper { + // The permission is implementation specific. + static final Permission PROXY_PERMISSION = + new ReflectPermission("proxyConstructorNewInstance"); + // These system properties are defined to provide a short-term + // workaround if customers need to disable the new security checks. + static final boolean allowNewInstance; + static final boolean allowNullLoader; + static { + allowNewInstance = getBooleanProperty("sun.reflect.proxy.allowsNewInstance"); + allowNullLoader = getBooleanProperty("sun.reflect.proxy.allowsNullLoader"); + } + + private static boolean getBooleanProperty(final String key) { + String s = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty(key); + } + }); + return Boolean.valueOf(s); + } + + static boolean needsNewInstanceCheck(Class proxyClass) { + if (!Proxy.isProxyClass(proxyClass) || allowNewInstance) { + return false; + } + + if (proxyClass.getName().startsWith(ReflectUtil.PROXY_PACKAGE + ".")) { + // all proxy interfaces are public + return false; + } + for (Class intf : proxyClass.getInterfaces()) { + if (!Modifier.isPublic(intf.getModifiers())) { + return true; + } + } + return false; + } + } + + /* + * Access check on a proxy class that implements any non-public interface. + * + * @throws SecurityException if a security manager exists, and + * the caller does not have the permission. + */ + private void doNewInstanceCheck() { + SecurityManager sm = System.getSecurityManager(); + Class proxyClass = this.getClass(); + if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(proxyClass)) { + try { + sm.checkPermission(ProxyAccessHelper.PROXY_PERMISSION); + } catch (SecurityException e) { + throw new SecurityException("Not allowed to construct a Proxy " + + "instance that implements a non-public interface", e); + } + } + } + /** * Returns the {@code java.lang.Class} object for a proxy class * given a class loader and an array of interfaces. The proxy class @@ -346,6 +412,51 @@ Class... interfaces) throws IllegalArgumentException { + return getProxyClass0(loader, interfaces); // stack walk magic: do not refactor + } + + private static void checkProxyLoader(ClassLoader ccl, + ClassLoader loader) + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + if (loader == null && ccl != null) { + if (!ProxyAccessHelper.allowNullLoader) { + sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); + } + } + } + } + + /* + * Generate a proxy class (caller-sensitive). + * + * To define a proxy class, it performs the access checks as in + * Class.forName (VM will invoke ClassLoader.checkPackageAccess): + * 1. "getClassLoader" permission check if loader == null + * 2. checkPackageAccess on the interfaces it implements + * + * To get a constructor and new instance of a proxy class, it performs + * the package access check on the interfaces it implements + * as in Class.getConstructor. + * + * If an interface is non-public, the proxy class must be defined by + * the defining loader of the interface. If the caller's class loader + * is not the same as the defining loader of the interface, the VM + * will throw IllegalAccessError when the generated proxy class is + * being defined via the defineClass0 method. + */ + private static Class getProxyClass0(ClassLoader loader, + Class... interfaces) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + final int CALLER_FRAME = 3; // 0: Reflection, 1: getProxyClass0 2: Proxy 3: caller + final Class caller = Reflection.getCallerClass(CALLER_FRAME); + final ClassLoader ccl = caller.getClassLoader(); + checkProxyLoader(ccl, loader); + ReflectUtil.checkProxyPackageAccess(ccl, interfaces); + } + if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } @@ -497,8 +608,9 @@ } } - if (proxyPkg == null) { // if no non-public proxy interfaces, - proxyPkg = ""; // use the unnamed package + if (proxyPkg == null) { + // if no non-public proxy interfaces, use sun.proxy package + proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; } { @@ -598,22 +710,43 @@ /* * Look up or generate the designated proxy class. */ - Class cl = getProxyClass(loader, interfaces); + Class cl = getProxyClass0(loader, interfaces); // stack walk magic: do not refactor /* * Invoke its constructor with the designated invocation handler. */ try { - Constructor cons = cl.getConstructor(constructorParams); - return cons.newInstance(new Object[] { h }); + final Constructor cons = cl.getConstructor(constructorParams); + final InvocationHandler ih = h; + SecurityManager sm = System.getSecurityManager(); + if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) { + // create proxy instance with doPrivilege as the proxy class may + // implement non-public interfaces that requires a special permission + return AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + return newInstance(cons, ih); + } + }); + } else { + return newInstance(cons, ih); + } } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); - } catch (IllegalAccessException e) { - throw new InternalError(e.toString()); - } catch (InstantiationException e) { + } + } + + private static Object newInstance(Constructor cons, InvocationHandler h) { + try { + return cons.newInstance(new Object[] {h} ); + } catch (IllegalAccessException | InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { - throw new InternalError(e.toString()); + Throwable t = e.getCause(); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else { + throw new InternalError(t.toString()); + } } } --- old/jdk/src/share/classes/java/net/InetSocketAddress.java 2013-02-07 17:06:55.000000000 +0100 +++ new/jdk/src/share/classes/java/net/InetSocketAddress.java 2013-02-07 17:06:55.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2012, 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 @@ -24,9 +24,12 @@ */ package java.net; -import java.io.ObjectInputStream; import java.io.IOException; import java.io.InvalidObjectException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.ObjectStreamField; /** * @@ -46,23 +49,105 @@ * @see java.net.ServerSocket * @since 1.4 */ -public class InetSocketAddress extends SocketAddress { - /* The hostname of the Socket Address - * @serial - */ - private String hostname = null; - /* The IP address of the Socket Address - * @serial - */ - private InetAddress addr = null; - /* The port number of the Socket Address - * @serial - */ - private int port; +public class InetSocketAddress + extends SocketAddress +{ + // Private implementation class pointed to by all public methods. + private static class InetSocketAddressHolder { + // The hostname of the Socket Address + private String hostname; + // The IP address of the Socket Address + private InetAddress addr; + // The port number of the Socket Address + private int port; + + private InetSocketAddressHolder(String hostname, InetAddress addr, int port) { + this.hostname = hostname; + this.addr = addr; + this.port = port; + } + + private int getPort() { + return port; + } + + private InetAddress getAddress() { + return addr; + } + + private String getHostName() { + if (hostname != null) + return hostname; + if (addr != null) + return addr.getHostName(); + return null; + } + + private String getHostString() { + if (hostname != null) + return hostname; + if (addr != null) { + if (addr.hostName != null) + return addr.hostName; + else + return addr.getHostAddress(); + } + return null; + } + + private boolean isUnresolved() { + return addr == null; + } + + @Override + public String toString() { + if (isUnresolved()) { + return hostname + ":" + port; + } else { + return addr.toString() + ":" + port; + } + } + + @Override + public final boolean equals(Object obj) { + if (obj == null || !(obj instanceof InetSocketAddressHolder)) + return false; + InetSocketAddressHolder that = (InetSocketAddressHolder)obj; + boolean sameIP; + if (addr != null) + sameIP = addr.equals(that.addr); + else if (hostname != null) + sameIP = (that.addr == null) && + hostname.equalsIgnoreCase(that.hostname); + else + sameIP = (that.addr == null) && (that.hostname == null); + return sameIP && (port == that.port); + } + + @Override + public final int hashCode() { + if (addr != null) + return addr.hashCode() + port; + if (hostname != null) + return hostname.toLowerCase().hashCode() + port; + return port; + } + } + + private final transient InetSocketAddressHolder holder; private static final long serialVersionUID = 5076001401234631237L; - private InetSocketAddress() { + private static int checkPort(int port) { + if (port < 0 || port > 0xFFFF) + throw new IllegalArgumentException("port out of range:" + port); + return port; + } + + private static String checkHost(String hostname) { + if (hostname == null) + throw new IllegalArgumentException("hostname can't be null"); + return hostname; } /** @@ -97,14 +182,10 @@ * range of valid port values. */ public InetSocketAddress(InetAddress addr, int port) { - if (port < 0 || port > 0xFFFF) { - throw new IllegalArgumentException("port out of range:" + port); - } - this.port = port; - if (addr == null) - this.addr = InetAddress.anyLocalAddress(); - else - this.addr = addr; + holder = new InetSocketAddressHolder( + null, + addr == null ? InetAddress.anyLocalAddress() : addr, + checkPort(port)); } /** @@ -132,19 +213,20 @@ * @see #isUnresolved() */ public InetSocketAddress(String hostname, int port) { - if (port < 0 || port > 0xFFFF) { - throw new IllegalArgumentException("port out of range:" + port); - } - if (hostname == null) { - throw new IllegalArgumentException("hostname can't be null"); - } + checkHost(hostname); + InetAddress addr = null; + String host = null; try { addr = InetAddress.getByName(hostname); } catch(UnknownHostException e) { - this.hostname = hostname; - addr = null; + host = hostname; } - this.port = port; + holder = new InetSocketAddressHolder(host, addr, checkPort(port)); + } + + // private constructor for creating unresolved instances + private InetSocketAddress(int port, String hostname) { + holder = new InetSocketAddressHolder(hostname, null, port); } /** @@ -169,31 +251,67 @@ * @since 1.5 */ public static InetSocketAddress createUnresolved(String host, int port) { - if (port < 0 || port > 0xFFFF) { - throw new IllegalArgumentException("port out of range:" + port); - } - if (host == null) { - throw new IllegalArgumentException("hostname can't be null"); - } - InetSocketAddress s = new InetSocketAddress(); - s.port = port; - s.hostname = host; - s.addr = null; - return s; + return new InetSocketAddress(checkPort(port), checkHost(host)); } - private void readObject(ObjectInputStream s) - throws IOException, ClassNotFoundException { - s.defaultReadObject(); + /** + * @serialField hostname String + * @serialField addr InetAddress + * @serialField port int + */ + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("hostname", String.class), + new ObjectStreamField("addr", InetAddress.class), + new ObjectStreamField("port", int.class)}; + + private void writeObject(ObjectOutputStream out) + throws IOException + { + // Don't call defaultWriteObject() + ObjectOutputStream.PutField pfields = out.putFields(); + pfields.put("hostname", holder.hostname); + pfields.put("addr", holder.addr); + pfields.put("port", holder.port); + out.writeFields(); + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + // Don't call defaultReadObject() + ObjectInputStream.GetField oisFields = in.readFields(); + final String oisHostname = (String)oisFields.get("hostname", null); + final InetAddress oisAddr = (InetAddress)oisFields.get("addr", null); + final int oisPort = oisFields.get("port", -1); // Check that our invariants are satisfied - if (port < 0 || port > 0xFFFF) { - throw new InvalidObjectException("port out of range:" + port); - } - - if (hostname == null && addr == null) { + checkPort(oisPort); + if (oisHostname == null && oisAddr == null) throw new InvalidObjectException("hostname and addr " + "can't both be null"); + + InetSocketAddressHolder h = new InetSocketAddressHolder(oisHostname, + oisAddr, + oisPort); + UNSAFE.putObject(this, FIELDS_OFFSET, h); + } + + private void readObjectNoData() + throws ObjectStreamException + { + throw new InvalidObjectException("Stream data required"); + } + + 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( + InetSocketAddress.class.getDeclaredField("holder")); + UNSAFE = unsafe; + } catch (ReflectiveOperationException e) { + throw new Error(e); } } @@ -203,7 +321,7 @@ * @return the port number. */ public final int getPort() { - return port; + return holder.getPort(); } /** @@ -213,7 +331,7 @@ * @return the InetAdress or null if it is unresolved. */ public final InetAddress getAddress() { - return addr; + return holder.getAddress(); } /** @@ -224,31 +342,19 @@ * @return the hostname part of the address. */ public final String getHostName() { - if (hostname != null) - return hostname; - if (addr != null) - return addr.getHostName(); - return null; + return holder.getHostName(); } /** * Returns the hostname, or the String form of the address if it * doesn't have a hostname (it was created using a literal). - * This has the benefit of not attemptimg a reverse lookup. + * This has the benefit of not attempting a reverse lookup. * * @return the hostname, or String representation of the address. * @since 1.7 */ public final String getHostString() { - if (hostname != null) - return hostname; - if (addr != null) { - if (addr.hostName != null) - return addr.hostName; - else - return addr.getHostAddress(); - } - return null; + return holder.getHostString(); } /** @@ -258,7 +364,7 @@ * an InetAddress. */ public final boolean isUnresolved() { - return addr == null; + return holder.isUnresolved(); } /** @@ -269,12 +375,9 @@ * * @return a string representation of this object. */ + @Override public String toString() { - if (isUnresolved()) { - return hostname + ":" + port; - } else { - return addr.toString() + ":" + port; - } + return holder.toString(); } /** @@ -297,19 +400,11 @@ * false otherwise. * @see java.net.InetAddress#equals(java.lang.Object) */ + @Override public final boolean equals(Object obj) { if (obj == null || !(obj instanceof InetSocketAddress)) return false; - InetSocketAddress sockAddr = (InetSocketAddress) obj; - boolean sameIP = false; - if (this.addr != null) - sameIP = this.addr.equals(sockAddr.addr); - else if (this.hostname != null) - sameIP = (sockAddr.addr == null) && - this.hostname.equalsIgnoreCase(sockAddr.hostname); - else - sameIP = (sockAddr.addr == null) && (sockAddr.hostname == null); - return sameIP && (this.port == sockAddr.port); + return holder.equals(((InetSocketAddress) obj).holder); } /** @@ -317,11 +412,8 @@ * * @return a hash code value for this socket address. */ + @Override public final int hashCode() { - if (addr != null) - return addr.hashCode() + port; - if (hostname != null) - return hostname.toLowerCase().hashCode() + port; - return port; + return holder.hashCode(); } } --- old/jdk/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java 2013-02-07 17:06:56.000000000 +0100 +++ new/jdk/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java 2013-02-07 17:06:56.000000000 +0100 @@ -34,8 +34,10 @@ */ package java.util.concurrent; -import java.util.concurrent.locks.*; -import java.util.concurrent.atomic.*; +import java.util.concurrent.locks.AbstractQueuedSynchronizer; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.atomic.AtomicInteger; import java.util.*; /** @@ -491,10 +493,15 @@ * policy limiting the number of threads. Even though it is not * treated as an error, failure to create threads may result in * new tasks being rejected or existing ones remaining stuck in - * the queue. On the other hand, no special precautions exist to - * handle OutOfMemoryErrors that might be thrown while trying to - * create threads, since there is generally no recourse from - * within this class. + * the queue. + * + * We go further and preserve pool invariants even in the face of + * errors such as OutOfMemoryError, that might be thrown while + * trying to create threads. Such errors are rather common due to + * the need to allocate a native stack in Thread#start, and users + * will want to perform clean pool shutdown to clean up. There + * will likely be enough memory available for the cleanup code to + * complete without encountering yet another OutOfMemoryError. */ private volatile ThreadFactory threadFactory; @@ -568,9 +575,13 @@ * task execution. This protects against interrupts that are * intended to wake up a worker thread waiting for a task from * instead interrupting a task being run. We implement a simple - * non-reentrant mutual exclusion lock rather than use ReentrantLock - * because we do not want worker tasks to be able to reacquire the - * lock when they invoke pool control methods like setCorePoolSize. + * non-reentrant mutual exclusion lock rather than use + * ReentrantLock because we do not want worker tasks to be able to + * reacquire the lock when they invoke pool control methods like + * setCorePoolSize. Additionally, to suppress interrupts until + * the thread actually starts running tasks, we initialize lock + * state to a negative value, and clear it upon start (in + * runWorker). */ private final class Worker extends AbstractQueuedSynchronizer @@ -594,6 +605,7 @@ * @param firstTask the first task (null if none) */ Worker(Runnable firstTask) { + setState(-1); // inhibit interrupts until runWorker this.firstTask = firstTask; this.thread = getThreadFactory().newThread(this); } @@ -609,7 +621,7 @@ // The value 1 represents the locked state. protected boolean isHeldExclusively() { - return getState() == 1; + return getState() != 0; } protected boolean tryAcquire(int unused) { @@ -630,6 +642,16 @@ public boolean tryLock() { return tryAcquire(1); } public void unlock() { release(1); } public boolean isLocked() { return isHeldExclusively(); } + + void interruptIfStarted() { + Thread t; + if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) { + try { + t.interrupt(); + } catch (SecurityException ignore) { + } + } + } } /* @@ -728,12 +750,8 @@ final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { - for (Worker w : workers) { - try { - w.thread.interrupt(); - } catch (SecurityException ignore) { - } - } + for (Worker w : workers) + w.interruptIfStarted(); } finally { mainLock.unlock(); } @@ -790,19 +808,6 @@ private static final boolean ONLY_ONE = true; - /** - * Ensures that unless the pool is stopping, the current thread - * does not have its interrupt set. This requires a double-check - * of state in case the interrupt was cleared concurrently with a - * shutdownNow -- if so, the interrupt is re-enabled. - */ - private void clearInterruptsForTaskRun() { - if (runStateLessThan(ctl.get(), STOP) && - Thread.interrupted() && - runStateAtLeast(ctl.get(), STOP)) - Thread.currentThread().interrupt(); - } - /* * Misc utilities, most of which are also exported to * ScheduledThreadPoolExecutor @@ -862,12 +867,13 @@ * Checks if a new worker can be added with respect to current * pool state and the given bound (either core or maximum). If so, * the worker count is adjusted accordingly, and, if possible, a - * new worker is created and started running firstTask as its + * new worker is created and started, running firstTask as its * first task. This method returns false if the pool is stopped or * eligible to shut down. It also returns false if the thread - * factory fails to create a thread when asked, which requires a - * backout of workerCount, and a recheck for termination, in case - * the existence of this worker was holding up termination. + * factory fails to create a thread when asked. If the thread + * creation fails, either due to the thread factory returning + * null, or due to an exception (typically OutOfMemoryError in + * Thread#start), we roll back cleanly. * * @param firstTask the task the new thread should run first (or * null if none). Workers are created with an initial first task @@ -910,46 +916,65 @@ } } - Worker w = new Worker(firstTask); - Thread t = w.thread; + boolean workerStarted = false; + boolean workerAdded = false; + Worker w = null; + try { + final ReentrantLock mainLock = this.mainLock; + w = new Worker(firstTask); + final Thread t = w.thread; + if (t != null) { + mainLock.lock(); + try { + // Recheck while holding lock. + // Back out on ThreadFactory failure or if + // shut down before lock acquired. + int c = ctl.get(); + int rs = runStateOf(c); + + if (rs < SHUTDOWN || + (rs == SHUTDOWN && firstTask == null)) { + if (t.isAlive()) // precheck that t is startable + throw new IllegalThreadStateException(); + workers.add(w); + int s = workers.size(); + if (s > largestPoolSize) + largestPoolSize = s; + workerAdded = true; + } + } finally { + mainLock.unlock(); + } + if (workerAdded) { + t.start(); + workerStarted = true; + } + } + } finally { + if (! workerStarted) + addWorkerFailed(w); + } + return workerStarted; + } + /** + * Rolls back the worker thread creation. + * - removes worker from workers, if present + * - decrements worker count + * - rechecks for termination, in case the existence of this + * worker was holding up termination + */ + private void addWorkerFailed(Worker w) { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { - // Recheck while holding lock. - // Back out on ThreadFactory failure or if - // shut down before lock acquired. - int c = ctl.get(); - int rs = runStateOf(c); - - if (t == null || - (rs >= SHUTDOWN && - ! (rs == SHUTDOWN && - firstTask == null))) { - decrementWorkerCount(); - tryTerminate(); - return false; - } - - workers.add(w); - - int s = workers.size(); - if (s > largestPoolSize) - largestPoolSize = s; + if (w != null) + workers.remove(w); + decrementWorkerCount(); + tryTerminate(); } finally { mainLock.unlock(); } - - t.start(); - // It is possible (but unlikely) for a thread to have been - // added to workers, but not yet started, during transition to - // STOP, which could result in a rare missed interrupt, - // because Thread.interrupt is not guaranteed to have any effect - // on a non-yet-started Thread (see Thread#interrupt). - if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted()) - t.interrupt(); - - return true; } /** @@ -1096,15 +1121,25 @@ * @param w the worker */ final void runWorker(Worker w) { + Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; + w.unlock(); // allow interrupts boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { w.lock(); - clearInterruptsForTaskRun(); + // If pool is stopping, ensure thread is interrupted; + // if not, ensure thread is not interrupted. This + // requires a recheck in second case to deal with + // shutdownNow race while clearing interrupt + if ((runStateAtLeast(ctl.get(), STOP) || + (Thread.interrupted() && + runStateAtLeast(ctl.get(), STOP))) && + !wt.isInterrupted()) + wt.interrupt(); try { - beforeExecute(w.thread, task); + beforeExecute(wt, task); Throwable thrown = null; try { task.run(); @@ -2064,3 +2099,4 @@ } } } + --- old/jdk/src/share/classes/java/util/jar/JarFile.java 2013-02-07 17:06:57.000000000 +0100 +++ new/jdk/src/share/classes/java/util/jar/JarFile.java 2013-02-07 17:06:56.000000000 +0100 @@ -34,6 +34,7 @@ import java.security.cert.Certificate; import java.security.AccessController; import java.security.CodeSource; +import sun.misc.IOUtils; import sun.security.action.GetPropertyAction; import sun.security.util.ManifestEntryVerifier; import sun.misc.SharedSecrets; @@ -329,6 +330,9 @@ if (names != null) { for (int i = 0; i < names.length; i++) { JarEntry e = getJarEntry(names[i]); + if (e == null) { + throw new JarException("corrupted jar file"); + } if (!e.isDirectory()) { if (mev == null) { mev = new ManifestEntryVerifier @@ -348,6 +352,10 @@ // treat the jar file as being unsigned jv = null; verify = false; + if (JarVerifier.debug != null) { + JarVerifier.debug.println("jarfile parsing error!"); + ex.printStackTrace(); + } } // if after initializing the verifier we have nothing @@ -375,11 +383,9 @@ * META-INF files. */ private byte[] getBytes(ZipEntry ze) throws IOException { - byte[] b = new byte[(int)ze.getSize()]; - try (DataInputStream is = new DataInputStream(super.getInputStream(ze))) { - is.readFully(b, 0, b.length); + try (InputStream is = super.getInputStream(ze)) { + return IOUtils.readFully(is, (int)ze.getSize(), true); } - return b; } /** @@ -479,12 +485,7 @@ if (!isKnownToNotHaveClassPathAttribute()) { JarEntry manEntry = getManEntry(); if (manEntry != null) { - byte[] b = new byte[(int)manEntry.getSize()]; - try (DataInputStream dis = new DataInputStream( - super.getInputStream(manEntry))) { - dis.readFully(b, 0, b.length); - } - + byte[] b = getBytes(manEntry); int last = b.length - src.length; int i = 0; next: --- old/jdk/src/share/classes/java/util/logging/Level.java 2013-02-07 17:06:57.000000000 +0100 +++ new/jdk/src/share/classes/java/util/logging/Level.java 2013-02-07 17:06:57.000000000 +0100 @@ -24,6 +24,10 @@ */ package java.util.logging; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.ResourceBundle; /** @@ -59,7 +63,6 @@ */ public class Level implements java.io.Serializable { - private static java.util.ArrayList known = new java.util.ArrayList<>(); private static String defaultBundle = "sun.util.logging.resources.logging"; /** @@ -77,6 +80,9 @@ */ private final String resourceBundleName; + // localized level name + private String localizedLevelName; + /** * OFF is a special level that can be used to turn off logging. * This level is initialized to Integer.MAX_VALUE. @@ -202,9 +208,8 @@ this.name = name; this.value = value; this.resourceBundleName = resourceBundleName; - synchronized (Level.class) { - known.add(this); - } + this.localizedLevelName = resourceBundleName == null ? name : null; + KnownLevel.add(this); } /** @@ -236,12 +241,76 @@ * @return localized name */ public String getLocalizedName() { + return getLocalizedLevelName(); + } + + // package-private getLevelName() is used by the implementation + // instead of getName() to avoid calling the subclass's version + final String getLevelName() { + return this.name; + } + + final synchronized String getLocalizedLevelName() { + if (localizedLevelName != null) { + return localizedLevelName; + } + try { ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName); - return rb.getString(name); + localizedLevelName = rb.getString(name); } catch (Exception ex) { - return name; + localizedLevelName = name; + } + return localizedLevelName; + } + + // Returns a mirrored Level object that matches the given name as + // specified in the Level.parse method. Returns null if not found. + // + // It returns the same Level object as the one returned by Level.parse + // method if the given name is a non-localized name or integer. + // + // If the name is a localized name, findLevel and parse method may + // return a different level value if there is a custom Level subclass + // that overrides Level.getLocalizedName() to return a different string + // than what's returned by the default implementation. + // + static Level findLevel(String name) { + if (name == null) { + throw new NullPointerException(); + } + + KnownLevel level; + + // Look for a known Level with the given non-localized name. + level = KnownLevel.findByName(name); + if (level != null) { + return level.mirroredLevel; } + + // Now, check if the given name is an integer. If so, + // first look for a Level with the given value and then + // if necessary create one. + try { + int x = Integer.parseInt(name); + level = KnownLevel.findByValue(x); + if (level == null) { + // add new Level + Level levelObject = new Level(name, x); + level = KnownLevel.findByValue(x); + } + return level.mirroredLevel; + } catch (NumberFormatException ex) { + // Not an integer. + // Drop through. + } + + level = KnownLevel.findByLocalizedLevelName(name); + if (level != null) { + return level.mirroredLevel; + } + + return null; } /** @@ -268,21 +337,15 @@ // Serialization magic to prevent "doppelgangers". // This is a performance optimization. private Object readResolve() { - synchronized (Level.class) { - for (int i = 0; i < known.size(); i++) { - Level other = known.get(i); - if (this.name.equals(other.name) && this.value == other.value - && (this.resourceBundleName == other.resourceBundleName || - (this.resourceBundleName != null && - this.resourceBundleName.equals(other.resourceBundleName)))) { - return other; - } - } - // Woops. Whoever sent us this object knows - // about a new log level. Add it to our list. - known.add(this); - return this; + KnownLevel o = KnownLevel.matches(this); + if (o != null) { + return o.levelObject; } + + // Woops. Whoever sent us this object knows + // about a new log level. Add it to our list. + Level level = new Level(this.name, this.value, this.resourceBundleName); + return level; } /** @@ -296,6 +359,7 @@ *
  • "SEVERE" *
  • "1000" * + * * @param name string to be parsed * @throws NullPointerException if the name is null * @throws IllegalArgumentException if the value is not valid. @@ -315,12 +379,12 @@ // Check that name is not null. name.length(); + KnownLevel level; + // Look for a known Level with the given non-localized name. - for (int i = 0; i < known.size(); i++) { - Level l = known.get(i); - if (name.equals(l.name)) { - return l; - } + level = KnownLevel.findByName(name); + if (level != null) { + return level.levelObject; } // Now, check if the given name is an integer. If so, @@ -328,14 +392,13 @@ // if necessary create one. try { int x = Integer.parseInt(name); - for (int i = 0; i < known.size(); i++) { - Level l = known.get(i); - if (l.value == x) { - return l; - } + level = KnownLevel.findByValue(x); + if (level == null) { + // add new Level + Level levelObject = new Level(name, x); + level = KnownLevel.findByValue(x); } - // Create a new Level. - return new Level(name, x); + return level.levelObject; } catch (NumberFormatException ex) { // Not an integer. // Drop through. @@ -344,11 +407,9 @@ // Finally, look for a known level with the given localized name, // in the current default locale. // This is relatively expensive, but not excessively so. - for (int i = 0; i < known.size(); i++) { - Level l = known.get(i); - if (name.equals(l.getLocalizedName())) { - return l; - } + level = KnownLevel.findByLocalizedName(name); + if (level != null) { + return level.levelObject; } // OK, we've tried everything and failed @@ -375,4 +436,124 @@ public int hashCode() { return this.value; } + + // KnownLevel class maintains the global list of all known levels. + // The API allows multiple custom Level instances of the same name/value + // be created. This class provides convenient methods to find a level + // by a given name, by a given value, or by a given localized name. + // + // KnownLevel wraps the following Level objects: + // 1. levelObject: standard Level object or custom Level object + // 2. mirroredLevel: Level object representing the level specified in the + // logging configuration. + // + // Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods + // are non-final but the name and resource bundle name are parameters to + // the Level constructor. Use the mirroredLevel object instead of the + // levelObject to prevent the logging framework to execute foreign code + // implemented by untrusted Level subclass. + // + // Implementation Notes: + // If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods + // were final, the following KnownLevel implementation can be removed. + // Future API change should take this into consideration. + static final class KnownLevel { + private static Map> nameToLevels = new HashMap<>(); + private static Map> intToLevels = new HashMap<>(); + final Level levelObject; // instance of Level class or Level subclass + final Level mirroredLevel; // instance of Level class + KnownLevel(Level l) { + this.levelObject = l; + if (l.getClass() == Level.class) { + this.mirroredLevel = l; + } else { + this.mirroredLevel = new Level(l.name, l.value, l.resourceBundleName); + } + } + + static synchronized void add(Level l) { + // the mirroredLevel object is always added to the list + // before the custom Level instance + KnownLevel o = new KnownLevel(l); + List list = nameToLevels.get(l.name); + if (list == null) { + list = new ArrayList<>(); + nameToLevels.put(l.name, list); + } + list.add(o); + + list = intToLevels.get(l.value); + if (list == null) { + list = new ArrayList<>(); + intToLevels.put(l.value, list); + } + list.add(o); + } + + // Returns a KnownLevel with the given non-localized name. + static synchronized KnownLevel findByName(String name) { + List list = nameToLevels.get(name); + if (list != null) { + return list.get(0); + } + return null; + } + + // Returns a KnownLevel with the given value. + static synchronized KnownLevel findByValue(int value) { + List list = intToLevels.get(value); + if (list != null) { + return list.get(0); + } + return null; + } + + // Returns a KnownLevel with the given localized name matching + // by calling the Level.getLocalizedLevelName() method (i.e. found + // from the resourceBundle associated with the Level object). + // This method does not call Level.getLocalizedName() that may + // be overridden in a subclass implementation + static synchronized KnownLevel findByLocalizedLevelName(String name) { + for (List levels : nameToLevels.values()) { + for (KnownLevel l : levels) { + String lname = l.levelObject.getLocalizedLevelName(); + if (name.equals(lname)) { + return l; + } + } + } + return null; + } + + // Returns a KnownLevel with the given localized name matching + // by calling the Level.getLocalizedName() method + static synchronized KnownLevel findByLocalizedName(String name) { + for (List levels : nameToLevels.values()) { + for (KnownLevel l : levels) { + String lname = l.levelObject.getLocalizedName(); + if (name.equals(lname)) { + return l; + } + } + } + return null; + } + + static synchronized KnownLevel matches(Level l) { + List list = nameToLevels.get(l.name); + if (list != null) { + for (KnownLevel level : list) { + Level other = level.mirroredLevel; + if (l.value == other.value && + (l.resourceBundleName == other.resourceBundleName || + (l.resourceBundleName != null && + l.resourceBundleName.equals(other.resourceBundleName)))) { + return level; + } + } + } + return null; + } + } + } --- old/jdk/src/share/classes/java/util/logging/LogManager.java 2013-02-07 17:06:58.000000000 +0100 +++ new/jdk/src/share/classes/java/util/logging/LogManager.java 2013-02-07 17:06:58.000000000 +0100 @@ -34,6 +34,8 @@ import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.net.URL; +import sun.misc.JavaAWTAccess; +import sun.misc.SharedSecrets; import sun.security.action.GetPropertyAction; /** @@ -155,10 +157,9 @@ = new PropertyChangeSupport(LogManager.class); private final static Level defaultLevel = Level.INFO; - // Table of named Loggers that maps names to Loggers. - private Hashtable namedLoggers = new Hashtable<>(); - // Tree of named Loggers - private LogNode root = new LogNode(null); + // LoggerContext for system loggers and user loggers + private final LoggerContext systemContext = new SystemLoggerContext(); + private final LoggerContext userContext = new LoggerContext(); private Logger rootLogger; // Have we done the primordial reading of the configuration file? @@ -197,6 +198,7 @@ // Create and retain Logger for the root of the namespace. manager.rootLogger = manager.new RootLogger(); manager.addLogger(manager.rootLogger); + manager.systemContext.addLocalLogger(manager.rootLogger); // Adding the global Logger. Doing so in the Logger. // would deadlock with the LogManager.. @@ -279,14 +281,14 @@ return; } readPrimordialConfiguration = true; + try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws Exception { + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Void run() throws Exception { readConfiguration(); // Platform loggers begin to delegate to java.util.logging.Logger sun.util.logging.PlatformLogger.redirectPlatformLoggers(); - return null; } }); @@ -337,20 +339,65 @@ changes.removePropertyChangeListener(l); } - // Package-level method. + // Returns the LoggerContext for the user code (i.e. application or AppContext). + // Loggers are isolated from each AppContext. + private LoggerContext getUserContext() { + LoggerContext context = null; + + SecurityManager sm = System.getSecurityManager(); + JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess(); + if (sm != null && javaAwtAccess != null) { + synchronized (javaAwtAccess) { + // AppContext.getAppContext() returns the system AppContext if called + // from a system thread but Logger.getLogger might be called from + // an applet code. Instead, find the AppContext of the applet code + // from the execution stack. + Object ecx = javaAwtAccess.getExecutionContext(); + if (ecx == null) { + // fall back to AppContext.getAppContext() + ecx = javaAwtAccess.getContext(); + } + context = (LoggerContext)javaAwtAccess.get(ecx, LoggerContext.class); + if (context == null) { + if (javaAwtAccess.isMainAppContext()) { + context = userContext; + } else { + context = new LoggerContext(); + context.addLocalLogger(manager.rootLogger); + } + javaAwtAccess.put(ecx, LoggerContext.class, context); + } + } + } else { + context = userContext; + } + return context; + } + + private List contexts() { + List cxs = new ArrayList<>(); + cxs.add(systemContext); + cxs.add(getUserContext()); + return cxs; + } + // Find or create a specified logger instance. If a logger has // already been created with the given name it is returned. // Otherwise a new logger instance is created and registered // in the LogManager global namespace. - // This method will always return a non-null Logger object. // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by addLogger(). - Logger demandLogger(String name) { + // + // This method must delegate to the LogManager implementation to + // add a new Logger or return the one that has been added previously + // as a LogManager subclass may override the addLogger, getLogger, + // readConfiguration, and other methods. + Logger demandLogger(String name, String resourceBundleName) { Logger result = getLogger(name); if (result == null) { // only allocate the new logger once - Logger newLogger = new Logger(name, null); + Logger newLogger = new Logger(name, resourceBundleName); do { if (addLogger(newLogger)) { // We successfully added the new Logger that we @@ -375,24 +422,228 @@ return result; } - // If logger.getUseParentHandlers() returns 'true' and any of the logger's - // parents have levels or handlers defined, make sure they are instantiated. - private void processParentHandlers(Logger logger, String name) { - int ix = 1; - for (;;) { - int ix2 = name.indexOf(".", ix); - if (ix2 < 0) { - break; + Logger demandSystemLogger(String name, String resourceBundleName) { + return systemContext.demandLogger(name, resourceBundleName); + } + + // LoggerContext maintains the logger namespace per context. + // The default LogManager implementation has one system context and user + // context. The system context is used to maintain the namespace for + // all system loggers and is queried by the system code. If a system logger + // doesn't exist in the user context, it'll also be added to the user context. + // The user context is queried by the user code and all other loggers are + // added in the user context. + static class LoggerContext { + // Table of named Loggers that maps names to Loggers. + private final Hashtable namedLoggers = new Hashtable<>(); + // Tree of named Loggers + private final LogNode root; + + private LoggerContext() { + this.root = new LogNode(null, this); + } + + Logger demandLogger(String name, String resourceBundleName) { + // a LogManager subclass may have its own implementation to add and + // get a Logger. So delegate to the LogManager to do the work. + return manager.demandLogger(name, resourceBundleName); + } + + synchronized Logger findLogger(String name) { + LoggerWeakRef ref = namedLoggers.get(name); + if (ref == null) { + return null; + } + Logger logger = ref.get(); + if (logger == null) { + // Hashtable holds stale weak reference + // to a logger which has been GC-ed. + removeLogger(name); + } + return logger; + } + + // Add a logger to this context. This method will only set its level + // and process parent loggers. It doesn't set its handlers. + synchronized boolean addLocalLogger(Logger logger) { + final String name = logger.getName(); + if (name == null) { + throw new NullPointerException(); + } + + // cleanup some Loggers that have been GC'ed + manager.drainLoggerRefQueueBounded(); + + LoggerWeakRef ref = namedLoggers.get(name); + if (ref != null) { + if (ref.get() == null) { + // It's possible that the Logger was GC'ed after the + // drainLoggerRefQueueBounded() call above so allow + // a new one to be registered. + removeLogger(name); + } else { + // We already have a registered logger with the given name. + return false; + } + } + + // We're adding a new logger. + // Note that we are creating a weak reference here. + ref = manager.new LoggerWeakRef(logger); + namedLoggers.put(name, ref); + + // Apply any initial level defined for the new logger. + Level level = manager.getLevelProperty(name + ".level", null); + if (level != null) { + doSetLevel(logger, level); + } + + processParentHandlers(logger, name); + + // Find the new node and its parent. + LogNode node = getNode(name); + node.loggerRef = ref; + Logger parent = null; + LogNode nodep = node.parent; + while (nodep != null) { + LoggerWeakRef nodeRef = nodep.loggerRef; + if (nodeRef != null) { + parent = nodeRef.get(); + if (parent != null) { + break; + } + } + nodep = nodep.parent; + } + + if (parent != null) { + doSetParent(logger, parent); + } + // Walk over the children and tell them we are their new parent. + node.walkAndSetParent(logger); + // new LogNode is ready so tell the LoggerWeakRef about it + ref.setNode(node); + return true; + } + + void removeLogger(String name) { + namedLoggers.remove(name); + } + + synchronized Enumeration getLoggerNames() { + return namedLoggers.keys(); + } + + // If logger.getUseParentHandlers() returns 'true' and any of the logger's + // parents have levels or handlers defined, make sure they are instantiated. + private void processParentHandlers(final Logger logger, final String name) { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + if (logger != manager.rootLogger) { + boolean useParent = manager.getBooleanProperty(name + ".useParentHandlers", true); + if (!useParent) { + logger.setUseParentHandlers(false); + } + } + return null; + } + }); + + int ix = 1; + for (;;) { + int ix2 = name.indexOf(".", ix); + if (ix2 < 0) { + break; + } + String pname = name.substring(0, ix2); + if (manager.getProperty(pname + ".level") != null || + manager.getProperty(pname + ".handlers") != null) { + // This pname has a level/handlers definition. + // Make sure it exists. + demandLogger(pname, null); + } + ix = ix2+1; + } + } + + // Gets a node in our tree of logger nodes. + // If necessary, create it. + LogNode getNode(String name) { + if (name == null || name.equals("")) { + return root; + } + LogNode node = root; + while (name.length() > 0) { + int ix = name.indexOf("."); + String head; + if (ix > 0) { + head = name.substring(0, ix); + name = name.substring(ix + 1); + } else { + head = name; + name = ""; + } + if (node.children == null) { + node.children = new HashMap<>(); + } + LogNode child = node.children.get(head); + if (child == null) { + child = new LogNode(node, this); + node.children.put(head, child); + } + node = child; } - String pname = name.substring(0,ix2); + return node; + } + } - if (getProperty(pname+".level") != null || - getProperty(pname+".handlers") != null) { - // This pname has a level/handlers definition. - // Make sure it exists. - demandLogger(pname); + static class SystemLoggerContext extends LoggerContext { + // Add a system logger in the system context's namespace as well as + // in the LogManager's namespace if not exist so that there is only + // one single logger of the given name. System loggers are visible + // to applications unless a logger of the same name has been added. + Logger demandLogger(String name, String resourceBundleName) { + Logger result = findLogger(name); + if (result == null) { + // only allocate the new system logger once + Logger newLogger = new Logger(name, resourceBundleName); + do { + if (addLocalLogger(newLogger)) { + // We successfully added the new Logger that we + // created above so return it without refetching. + result = newLogger; + } else { + // We didn't add the new Logger that we created above + // because another thread added a Logger with the same + // name after our null check above and before our call + // to addLogger(). We have to refetch the Logger because + // addLogger() returns a boolean instead of the Logger + // reference itself. However, if the thread that created + // the other Logger is not holding a strong reference to + // the other Logger, then it is possible for the other + // Logger to be GC'ed after we saw it in addLogger() and + // before we can refetch it. If it has been GC'ed then + // we'll just loop around and try again. + result = findLogger(name); + } + } while (result == null); } - ix = ix2+1; + // Add the system logger to the LogManager's namespace if not exists + // The LogManager will set its handlers via the LogManager.addLogger method. + if (!manager.addLogger(result) && result.getHandlers().length == 0) { + // if logger already exists but handlers not set + final Logger l = manager.getLogger(name); + final Logger logger = result; + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + for (Handler hdl : l.getHandlers()) { + logger.addHandler(hdl); + } + return null; + } + }); + } + return result; } } @@ -401,32 +652,27 @@ // be made based on the logging configuration, which can // only be modified by trusted code. private void loadLoggerHandlers(final Logger logger, final String name, - final String handlersPropertyName) { + final String handlersPropertyName) + { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { - if (logger != rootLogger) { - boolean useParent = getBooleanProperty(name + ".useParentHandlers", true); - if (!useParent) { - logger.setUseParentHandlers(false); - } - } - String names[] = parseClassNames(handlersPropertyName); for (int i = 0; i < names.length; i++) { String word = names[i]; try { - Class clz = ClassLoader.getSystemClassLoader().loadClass(word); + Class clz = ClassLoader.getSystemClassLoader().loadClass(word); Handler hdl = (Handler) clz.newInstance(); - try { - // Check if there is a property defining the - // this handler's level. - String levs = getProperty(word + ".level"); - if (levs != null) { - hdl.setLevel(Level.parse(levs)); + // Check if there is a property defining the + // this handler's level. + String levs = getProperty(word + ".level"); + if (levs != null) { + Level l = Level.findLevel(levs); + if (l != null) { + hdl.setLevel(l); + } else { + // Probably a bad level. Drop through. + System.err.println("Can't set level for " + word); } - } catch (Exception ex) { - System.err.println("Can't set level for " + word); - // Probably a bad level. Drop through. } // Add this Handler to the logger logger.addHandler(hdl); @@ -437,7 +683,8 @@ } } return null; - }}); + } + }); } @@ -482,7 +729,7 @@ if (node != null) { // if we have a LogNode, then we were a named Logger // so clear namedLoggers weak ref to us - manager.namedLoggers.remove(name); + node.context.removeLogger(name); name = null; // clear our ref to the Logger's name node.loggerRef = null; // clear LogNode's weak ref to us @@ -571,73 +818,22 @@ * false if a logger of that name already exists. * @exception NullPointerException if the logger name is null. */ - public synchronized boolean addLogger(Logger logger) { + public boolean addLogger(Logger logger) { final String name = logger.getName(); if (name == null) { throw new NullPointerException(); } - - // cleanup some Loggers that have been GC'ed - drainLoggerRefQueueBounded(); - - LoggerWeakRef ref = namedLoggers.get(name); - if (ref != null) { - if (ref.get() == null) { - // It's possible that the Logger was GC'ed after the - // drainLoggerRefQueueBounded() call above so allow - // a new one to be registered. - namedLoggers.remove(name); - } else { - // We already have a registered logger with the given name. - return false; - } - } - - // We're adding a new logger. - // Note that we are creating a weak reference here. - ref = new LoggerWeakRef(logger); - namedLoggers.put(name, ref); - - // Apply any initial level defined for the new logger. - Level level = getLevelProperty(name+".level", null); - if (level != null) { - doSetLevel(logger, level); - } - - // Do we have a per logger handler too? - // Note: this will add a 200ms penalty - loadLoggerHandlers(logger, name, name+".handlers"); - processParentHandlers(logger, name); - - // Find the new node and its parent. - LogNode node = findNode(name); - node.loggerRef = ref; - Logger parent = null; - LogNode nodep = node.parent; - while (nodep != null) { - LoggerWeakRef nodeRef = nodep.loggerRef; - if (nodeRef != null) { - parent = nodeRef.get(); - if (parent != null) { - break; - } - } - nodep = nodep.parent; - } - - if (parent != null) { - doSetParent(logger, parent); + LoggerContext cx = getUserContext(); + if (cx.addLocalLogger(logger)) { + // Do we have a per logger handler too? + // Note: this will add a 200ms penalty + loadLoggerHandlers(logger, name, name + ".handlers"); + return true; + } else { + return false; } - // Walk over the children and tell them we are their new parent. - node.walkAndSetParent(logger); - - // new LogNode is ready so tell the LoggerWeakRef about it - ref.setNode(node); - - return true; } - // Private method to set a level on a logger. // If necessary, we raise privilege before doing the call. private static void doSetLevel(final Logger logger, final Level level) { @@ -656,8 +852,6 @@ }}); } - - // Private method to set a parent on a logger. // If necessary, we raise privilege before doing the setParent call. private static void doSetParent(final Logger logger, final Logger parent) { @@ -676,36 +870,6 @@ }}); } - // Find a node in our tree of logger nodes. - // If necessary, create it. - private LogNode findNode(String name) { - if (name == null || name.equals("")) { - return root; - } - LogNode node = root; - while (name.length() > 0) { - int ix = name.indexOf("."); - String head; - if (ix > 0) { - head = name.substring(0,ix); - name = name.substring(ix+1); - } else { - head = name; - name = ""; - } - if (node.children == null) { - node.children = new HashMap<>(); - } - LogNode child = node.children.get(head); - if (child == null) { - child = new LogNode(node); - node.children.put(head, child); - } - node = child; - } - return node; - } - /** * Method to find a named logger. *

    @@ -721,18 +885,8 @@ * @param name name of the logger * @return matching logger or null if none is found */ - public synchronized Logger getLogger(String name) { - LoggerWeakRef ref = namedLoggers.get(name); - if (ref == null) { - return null; - } - Logger logger = ref.get(); - if (logger == null) { - // Hashtable holds stale weak reference - // to a logger which has been GC-ed. - namedLoggers.remove(name); - } - return logger; + public Logger getLogger(String name) { + return getUserContext().findLogger(name); } /** @@ -751,8 +905,8 @@ *

    * @return enumeration of logger name strings */ - public synchronized Enumeration getLoggerNames() { - return namedLoggers.keys(); + public Enumeration getLoggerNames() { + return getUserContext().getLoggerNames(); } /** @@ -837,20 +991,20 @@ // the global handlers, if they haven't been initialized yet. initializedGlobalHandlers = true; } - Enumeration enum_ = getLoggerNames(); - while (enum_.hasMoreElements()) { - String name = (String)enum_.nextElement(); - resetLogger(name); + for (LoggerContext cx : contexts()) { + Enumeration enum_ = cx.getLoggerNames(); + while (enum_.hasMoreElements()) { + String name = enum_.nextElement(); + Logger logger = cx.findLogger(name); + if (logger != null) { + resetLogger(logger); + } + } } } - // Private method to reset an individual target logger. - private void resetLogger(String name) { - Logger logger = getLogger(name); - if (logger == null) { - return; - } + private void resetLogger(Logger logger) { // Close all the Logger's handlers. Handler[] targets = logger.getHandlers(); for (int i = 0; i < targets.length; i++) { @@ -862,6 +1016,7 @@ // Problems closing a handler? Keep going... } } + String name = logger.getName(); if (name != null && name.equals("")) { // This is the root logger. logger.setLevel(defaultLevel); @@ -1009,11 +1164,8 @@ if (val == null) { return defaultValue; } - try { - return Level.parse(val.trim()); - } catch (Exception ex) { - return defaultValue; - } + Level l = Level.findLevel(val.trim()); + return l != null ? l : defaultValue; } // Package private method to get a filter property. @@ -1076,7 +1228,6 @@ loadLoggerHandlers(rootLogger, null, "handlers"); } - private final Permission controlPermission = new LoggingPermission("control", null); void checkPermission() { @@ -1104,9 +1255,11 @@ HashMap children; LoggerWeakRef loggerRef; LogNode parent; + final LoggerContext context; - LogNode(LogNode parent) { + LogNode(LogNode parent, LoggerContext context) { this.parent = parent; + this.context = context; } // Recursive method to walk the tree below a node and set @@ -1133,7 +1286,6 @@ // that we only instantiate the global handlers when they // are first needed. private class RootLogger extends Logger { - private RootLogger() { super("", null); setLevel(defaultLevel); @@ -1165,7 +1317,7 @@ // Private method to be called when the configuration has // changed to apply any level settings to any pre-existing loggers. synchronized private void setLevelsOnExistingLoggers() { - Enumeration enum_ = props.propertyNames(); + Enumeration enum_ = props.propertyNames(); while (enum_.hasMoreElements()) { String key = (String)enum_.nextElement(); if (!key.endsWith(".level")) { @@ -1179,11 +1331,13 @@ System.err.println("Bad level value for property: " + key); continue; } - Logger l = getLogger(name); - if (l == null) { - continue; + for (LoggerContext cx : contexts()) { + Logger l = cx.findLogger(name); + if (l == null) { + continue; + } + l.setLevel(level); } - l.setLevel(level); } } --- old/jdk/src/share/classes/java/util/logging/Logger.java 2013-02-07 17:06:59.000000000 +0100 +++ new/jdk/src/share/classes/java/util/logging/Logger.java 2013-02-07 17:06:59.000000000 +0100 @@ -283,6 +283,40 @@ } } + // Until all JDK code converted to call sun.util.logging.PlatformLogger + // (see 7054233), we need to determine if Logger.getLogger is to add + // a system logger or user logger. + // + // As an interim solution, if the immediate caller whose caller loader is + // null, we assume it's a system logger and add it to the system context. + // These system loggers only set the resource bundle to the given + // resource bundle name (rather than the default system resource bundle). + private static class SystemLoggerHelper { + static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); + private static boolean getBooleanProperty(final String key) { + String s = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty(key); + } + }); + return Boolean.valueOf(s); + } + } + + private static Logger demandLogger(String name, String resourceBundleName) { + LogManager manager = LogManager.getLogManager(); + SecurityManager sm = System.getSecurityManager(); + if (sm != null && !SystemLoggerHelper.disableCallerCheck) { + // 0: Reflection 1: Logger.demandLogger 2: Logger.getLogger 3: caller + final int SKIP_FRAMES = 3; + Class caller = sun.reflect.Reflection.getCallerClass(SKIP_FRAMES); + if (caller.getClassLoader() == null) { + return manager.demandSystemLogger(name, resourceBundleName); + } + } + return manager.demandLogger(name, resourceBundleName); + } + /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise @@ -324,8 +358,7 @@ // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. - LogManager manager = LogManager.getLogManager(); - return manager.demandLogger(name); + return demandLogger(name, null); } /** @@ -372,8 +405,7 @@ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). public static Logger getLogger(String name, String resourceBundleName) { - LogManager manager = LogManager.getLogManager(); - Logger result = manager.demandLogger(name); + Logger result = demandLogger(name, resourceBundleName); if (result.resourceBundleName == null) { // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName); @@ -384,6 +416,17 @@ return result; } + // package-private + // Add a platform logger to the system context. + // i.e. caller of sun.util.logging.PlatformLogger.getLogger + static Logger getPlatformLogger(String name) { + LogManager manager = LogManager.getLogManager(); + + // all loggers in the system context will default to + // the system logger's resource bundle + Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); + return result; + } /** * Create an anonymous Logger. The newly created Logger is not @@ -536,7 +579,7 @@ private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); - if (ebname != null) { + if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname)); } @@ -1285,6 +1328,23 @@ // May also return null if we can't find the resource bundle and // there is no suitable previous cached value. + static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; + + private static ResourceBundle findSystemResourceBundle(final Locale locale) { + // the resource bundle is in a restricted package + return AccessController.doPrivileged(new PrivilegedAction() { + public ResourceBundle run() { + try { + return ResourceBundle.getBundle(SYSTEM_LOGGER_RB_NAME, + locale, + ClassLoader.getSystemClassLoader()); + } catch (MissingResourceException e) { + throw new InternalError(e.toString()); + } + } + }); + } + private synchronized ResourceBundle findResourceBundle(String name) { // Return a null bundle for a null name. if (name == null) { @@ -1299,6 +1359,13 @@ return catalog; } + if (name.equals(SYSTEM_LOGGER_RB_NAME)) { + catalog = findSystemResourceBundle(currentLocale); + catalogName = name; + catalogLocale = currentLocale; + return catalog; + } + // Use the thread's context ClassLoader. If there isn't one, // use the SystemClassloader. ClassLoader cl = Thread.currentThread().getContextClassLoader(); @@ -1315,7 +1382,6 @@ // ClassLoader. Drop through. } - // Fall back to searching up the call stack and trying each // calling ClassLoader. for (int ix = 0; ; ix++) { --- old/jdk/src/share/classes/java/util/logging/Logging.java 2013-02-07 17:07:00.000000000 +0100 +++ new/jdk/src/share/classes/java/util/logging/Logging.java 2013-02-07 17:07:00.000000000 +0100 @@ -34,15 +34,15 @@ * * The LoggingMXBean interface provides a standard * method for management access to the individual - * java.util.Logger objects available at runtime. + * {@code Logger} objects available at runtime. * * @author Ron Mann * @author Mandy Chung * @since 1.5 * * @see javax.management - * @see java.util.Logger - * @see java.util.LogManager + * @see Logger + * @see LogManager */ class Logging implements LoggingMXBean { @@ -75,7 +75,7 @@ if (level == null) { return EMPTY_STRING; } else { - return level.getName(); + return level.getLevelName(); } } @@ -85,7 +85,6 @@ } Logger logger = logManager.getLogger(loggerName); - if (logger == null) { throw new IllegalArgumentException("Logger " + loggerName + "does not exist"); @@ -94,7 +93,10 @@ Level level = null; if (levelName != null) { // parse will throw IAE if logLevel is invalid - level = Level.parse(levelName); + level = Level.findLevel(levelName); + if (level == null) { + throw new IllegalArgumentException("Unknown level \"" + levelName + "\""); + } } logger.setLevel(level); --- old/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java 2013-02-07 17:07:01.000000000 +0100 +++ new/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java 2013-02-07 17:07:00.000000000 +0100 @@ -37,7 +37,8 @@ @Override public Object getLogger(String name) { - return Logger.getLogger(name); + // always create a platform logger with the resource bundle name + return Logger.getPlatformLogger(name); } @Override @@ -92,12 +93,16 @@ @Override public Object parseLevel(String levelName) { - return Level.parse(levelName); + Level level = Level.findLevel(levelName); + if (level == null) { + throw new IllegalArgumentException("Unknown level \"" + levelName + "\""); + } + return level; } @Override public String getLevelName(Object level) { - return ((Level) level).getName(); + return ((Level) level).getLevelName(); } @Override --- old/jdk/src/share/classes/java/util/logging/SimpleFormatter.java 2013-02-07 17:07:01.000000000 +0100 +++ new/jdk/src/share/classes/java/util/logging/SimpleFormatter.java 2013-02-07 17:07:01.000000000 +0100 @@ -162,7 +162,7 @@ dat, source, record.getLoggerName(), - record.getLevel().getLocalizedName(), + record.getLevel().getLocalizedLevelName(), message, throwable); } --- old/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java 2013-02-07 17:07:02.000000000 +0100 +++ new/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java 2013-02-07 17:07:02.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,11 +39,13 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.logging.Level; import java.util.Map; import java.util.Set; @@ -78,6 +80,8 @@ import javax.management.RuntimeOperationsException; import javax.management.ServiceNotFoundException; import javax.management.loading.ClassLoaderRepository; +import sun.misc.JavaSecurityAccess; +import sun.misc.SharedSecrets; import sun.reflect.misc.MethodUtil; import sun.reflect.misc.ReflectUtil; @@ -138,6 +142,9 @@ private boolean registered = false; private transient MBeanServer server = null; + private final static JavaSecurityAccess javaSecurityAccess = SharedSecrets.getJavaSecurityAccess(); + final private AccessControlContext acc = AccessController.getContext(); + /*************************************/ /* constructors */ /*************************************/ @@ -1025,10 +1032,31 @@ if (opClassName != null) { try { - final ClassLoader targetClassLoader = - targetObject.getClass().getClassLoader(); - targetClass = Class.forName(opClassName, false, - targetClassLoader); + AccessControlContext stack = AccessController.getContext(); + final Object obj = targetObject; + final String className = opClassName; + final ClassNotFoundException[] caughtException = new ClassNotFoundException[1]; + + targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction>() { + + @Override + public Class run() { + try { + ReflectUtil.checkPackageAccess(className); + final ClassLoader targetClassLoader = + obj.getClass().getClassLoader(); + return Class.forName(className, false, + targetClassLoader); + } catch (ClassNotFoundException e) { + caughtException[0] = e; + } + return null; + } + }, stack, acc); + + if (caughtException[0] != null) { + throw caughtException[0]; + } } catch (ClassNotFoundException e) { final String msg = "class for invoke " + opName + " not found"; @@ -1061,9 +1089,9 @@ return result; } - private static Method resolveMethod(Class targetClass, + private Method resolveMethod(Class targetClass, String opMethodName, - String[] sig) + final String[] sig) throws ReflectionException { final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); @@ -1078,30 +1106,45 @@ if (sig == null) argClasses = null; else { + final AccessControlContext stack = AccessController.getContext(); + final ReflectionException[] caughtException = new ReflectionException[1]; final ClassLoader targetClassLoader = targetClass.getClassLoader(); argClasses = new Class[sig.length]; - for (int i = 0; i < sig.length; i++) { - if (tracing) { - MODELMBEAN_LOGGER.logp(Level.FINER, - RequiredModelMBean.class.getName(),"resolveMethod", - "resolve type " + sig[i]); - } - argClasses[i] = (Class) primitiveClassMap.get(sig[i]); - if (argClasses[i] == null) { - try { - argClasses[i] = - Class.forName(sig[i], false, targetClassLoader); - } catch (ClassNotFoundException e) { + + javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction() { + + @Override + public Void run() { + for (int i = 0; i < sig.length; i++) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, - RequiredModelMBean.class.getName(), - "resolveMethod", - "class not found"); + RequiredModelMBean.class.getName(),"resolveMethod", + "resolve type " + sig[i]); + } + argClasses[i] = (Class) primitiveClassMap.get(sig[i]); + if (argClasses[i] == null) { + try { + ReflectUtil.checkPackageAccess(sig[i]); + argClasses[i] = + Class.forName(sig[i], false, targetClassLoader); + } catch (ClassNotFoundException e) { + if (tracing) { + MODELMBEAN_LOGGER.logp(Level.FINER, + RequiredModelMBean.class.getName(), + "resolveMethod", + "class not found"); + } + final String msg = "Parameter class not found"; + caughtException[0] = new ReflectionException(e, msg); + } } - final String msg = "Parameter class not found"; - throw new ReflectionException(e, msg); } + return null; } + }, stack, acc); + + if (caughtException[0] != null) { + throw caughtException[0]; } } @@ -1133,7 +1176,7 @@ /* Find a method in RequiredModelMBean as determined by the given parameters. Return null if there is none, or if the parameters exclude using it. Called from invoke. */ - private static Method findRMMBMethod(String opMethodName, + private Method findRMMBMethod(String opMethodName, Object targetObjectField, String opClassName, String[] sig) { @@ -1155,19 +1198,29 @@ if (opClassName == null) targetClass = rmmbClass; else { - try { - final ClassLoader targetClassLoader = - rmmbClass.getClassLoader(); - targetClass = Class.forName(opClassName, false, - targetClassLoader); - if (!rmmbClass.isAssignableFrom(targetClass)) - return null; - } catch (ClassNotFoundException e) { - return null; - } + AccessControlContext stack = AccessController.getContext(); + final String className = opClassName; + targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction>() { + + @Override + public Class run() { + try { + ReflectUtil.checkPackageAccess(className); + final ClassLoader targetClassLoader = + rmmbClass.getClassLoader(); + Class clz = Class.forName(className, false, + targetClassLoader); + if (!rmmbClass.isAssignableFrom(clz)) + return null; + return clz; + } catch (ClassNotFoundException e) { + return null; + } + } + }, stack, acc); } try { - return resolveMethod(targetClass, opMethodName, sig); + return targetClass != null ? resolveMethod(targetClass, opMethodName, sig) : null; } catch (ReflectionException e) { return null; } @@ -1177,12 +1230,35 @@ * Invoke the given method, and throw the somewhat unpredictable * appropriate exception if the method itself gets an exception. */ - private Object invokeMethod(String opName, Method method, - Object targetObject, Object[] opArgs) + private Object invokeMethod(String opName, final Method method, + final Object targetObject, final Object[] opArgs) throws MBeanException, ReflectionException { try { - ReflectUtil.checkPackageAccess(method.getDeclaringClass()); - return MethodUtil.invoke(method, targetObject, opArgs); + final Throwable[] caughtException = new Throwable[1]; + AccessControlContext stack = AccessController.getContext(); + Object rslt = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction() { + + @Override + public Object run() { + try { + ReflectUtil.checkPackageAccess(method.getDeclaringClass()); + return MethodUtil.invoke(method, targetObject, opArgs); + } catch (InvocationTargetException e) { + caughtException[0] = e; + } catch (IllegalAccessException e) { + caughtException[0] = e; + } + return null; + } + }, stack, acc); + if (caughtException[0] != null) { + if (caughtException[0] instanceof Exception) { + throw (Exception)caughtException[0]; + } else if(caughtException[0] instanceof Error) { + throw (Error)caughtException[0]; + } + } + return rslt; } catch (RuntimeErrorException ree) { throw new RuntimeOperationsException(ree, "RuntimeException occurred in RequiredModelMBean "+ @@ -1567,7 +1643,7 @@ } // make sure response class matches type field - String respType = attrInfo.getType(); + final String respType = attrInfo.getType(); if (response != null) { String responseClass = response.getClass().getName(); if (!respType.equals(responseClass)) { @@ -1590,9 +1666,31 @@ // inequality may come from type subclassing boolean subtype; try { - ClassLoader cl = - response.getClass().getClassLoader(); - Class c = Class.forName(respType, true, cl); + final Class respClass = response.getClass(); + final Exception[] caughException = new Exception[1]; + + AccessControlContext stack = AccessController.getContext(); + + Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction>() { + + @Override + public Class run() { + try { + ReflectUtil.checkPackageAccess(respType); + ClassLoader cl = + respClass.getClassLoader(); + return Class.forName(respType, true, cl); + } catch (Exception e) { + caughException[0] = e; + } + return null; + } + }, stack, acc); + + if (caughException[0] != null) { + throw caughException[0]; + } + subtype = c.isInstance(response); } catch (Exception e) { subtype = false; @@ -2745,16 +2843,37 @@ return MBeanServerFactory.getClassLoaderRepository(server); } - private Class loadClass(String className) + private Class loadClass(final String className) throws ClassNotFoundException { - try { - return Class.forName(className); - } catch (ClassNotFoundException e) { - final ClassLoaderRepository clr = - getClassLoaderRepository(); - if (clr == null) throw new ClassNotFoundException(className); - return clr.loadClass(className); + AccessControlContext stack = AccessController.getContext(); + final ClassNotFoundException[] caughtException = new ClassNotFoundException[1]; + + Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction>() { + + @Override + public Class run() { + try { + ReflectUtil.checkPackageAccess(className); + return Class.forName(className); + } catch (ClassNotFoundException e) { + final ClassLoaderRepository clr = + getClassLoaderRepository(); + try { + if (clr == null) throw new ClassNotFoundException(className); + return clr.loadClass(className); + } catch (ClassNotFoundException ex) { + caughtException[0] = ex; + } + } + return null; + } + }, stack, acc); + + if (caughtException[0] != null) { + throw caughtException[0]; } + + return c; } @@ -2878,4 +2997,4 @@ Void.class.getName() }; } -} +} \ No newline at end of file --- old/jdk/src/share/classes/javax/swing/JTable.java 2013-02-07 17:07:03.000000000 +0100 +++ new/jdk/src/share/classes/javax/swing/JTable.java 2013-02-07 17:07:03.000000000 +0100 @@ -781,15 +781,11 @@ scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER); if (corner == null || corner instanceof UIResource){ corner = null; - Object componentClass = UIManager.get( - "Table.scrollPaneCornerComponent"); - if (componentClass instanceof Class){ - try { - corner = (Component) - ((Class)componentClass).newInstance(); - } catch (Exception e) { - // just ignore and don't set corner - } + try { + corner = (Component) UIManager.get( + "Table.scrollPaneCornerComponent"); + } catch (Exception e) { + // just ignore and don't set corner } scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, corner); --- old/jdk/src/share/classes/javax/swing/RepaintManager.java 2013-02-07 17:07:04.000000000 +0100 +++ new/jdk/src/share/classes/javax/swing/RepaintManager.java 2013-02-07 17:07:04.000000000 +0100 @@ -27,11 +27,12 @@ import java.awt.*; import java.awt.event.*; -import java.awt.peer.ComponentPeer; -import java.awt.peer.ContainerPeer; import java.awt.image.VolatileImage; +import java.security.AccessControlContext; import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; import java.applet.*; import sun.awt.AWTAccessor; @@ -39,6 +40,8 @@ import sun.awt.DisplayChangedListener; import sun.awt.SunToolkit; import sun.java2d.SunGraphicsEnvironment; +import sun.misc.JavaSecurityAccess; +import sun.misc.SharedSecrets; import sun.security.action.GetPropertyAction; import com.sun.java.swing.SwingUtilities3; @@ -176,6 +179,9 @@ */ private final ProcessingRunnable processingRunnable; + private final static JavaSecurityAccess javaSecurityAccess = + SharedSecrets.getJavaSecurityAccess(); + static { volatileImageBufferEnabled = "true".equals(AccessController. @@ -548,13 +554,26 @@ // This is called from the toolkit thread when awt needs to run a // Runnable before we paint. // - void nativeQueueSurfaceDataRunnable(AppContext appContext, Component c, - Runnable r) { + void nativeQueueSurfaceDataRunnable(AppContext appContext, + final Component c, final Runnable r) + { synchronized(this) { if (runnableList == null) { runnableList = new LinkedList(); } - runnableList.add(r); + runnableList.add(new Runnable() { + public void run() { + AccessControlContext stack = AccessController.getContext(); + AccessControlContext acc = + AWTAccessor.getComponentAccessor().getAccessControlContext(c); + javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction() { + public Void run() { + r.run(); + return null; + } + }, stack, acc); + } + }); } scheduleProcessingRunnable(appContext); } @@ -652,9 +671,9 @@ * @see #addInvalidComponent */ public void validateInvalidComponents() { - java.util.List ic; + final java.util.List ic; synchronized(this) { - if(invalidComponents == null) { + if (invalidComponents == null) { return; } ic = invalidComponents; @@ -662,7 +681,17 @@ } int n = ic.size(); for(int i = 0; i < n; i++) { - ic.get(i).validate(); + final Component c = ic.get(i); + AccessControlContext stack = AccessController.getContext(); + AccessControlContext acc = + AWTAccessor.getComponentAccessor().getAccessControlContext(c); + javaSecurityAccess.doIntersectionPrivilege( + new PrivilegedAction() { + public Void run() { + c.validate(); + return null; + } + }, stack, acc); } } @@ -740,74 +769,75 @@ paintDirtyRegions(tmpDirtyComponents); } - private void paintDirtyRegions(Map - tmpDirtyComponents){ - int i, count; - java.util.List roots; - Component dirtyComponent; - - count = tmpDirtyComponents.size(); - if (count == 0) { + private void paintDirtyRegions( + final Map tmpDirtyComponents) + { + if (tmpDirtyComponents.isEmpty()) { return; } - Rectangle rect; - int localBoundsX = 0; - int localBoundsY = 0; - int localBoundsH; - int localBoundsW; - Enumeration keys; - - roots = new ArrayList(count); + final java.util.List roots = + new ArrayList(tmpDirtyComponents.size()); for (Component dirty : tmpDirtyComponents.keySet()) { collectDirtyComponents(tmpDirtyComponents, dirty, roots); } - count = roots.size(); + final AtomicInteger count = new AtomicInteger(roots.size()); painting = true; try { - for(i=0 ; i < count ; i++) { - dirtyComponent = roots.get(i); - rect = tmpDirtyComponents.get(dirtyComponent); - localBoundsH = dirtyComponent.getHeight(); - localBoundsW = dirtyComponent.getWidth(); - - SwingUtilities.computeIntersection(localBoundsX, - localBoundsY, - localBoundsW, - localBoundsH, - rect); - if (dirtyComponent instanceof JComponent) { - ((JComponent)dirtyComponent).paintImmediately( - rect.x,rect.y,rect.width, rect.height); - } - else if (dirtyComponent.isShowing()) { - Graphics g = JComponent.safelyGetGraphics( - dirtyComponent, dirtyComponent); - // If the Graphics goes away, it means someone disposed of - // the window, don't do anything. - if (g != null) { - g.setClip(rect.x, rect.y, rect.width, rect.height); - try { - dirtyComponent.paint(g); - } finally { - g.dispose(); + for(int j = 0; j < count.get(); j++) { + final int i = j; + final Component dirtyComponent = roots.get(j); + + AccessControlContext stack = AccessController.getContext(); + AccessControlContext acc = + AWTAccessor.getComponentAccessor().getAccessControlContext(dirtyComponent); + javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction() { + public Void run() { + Rectangle rect = tmpDirtyComponents.get(dirtyComponent); + + int localBoundsH = dirtyComponent.getHeight(); + int localBoundsW = dirtyComponent.getWidth(); + SwingUtilities.computeIntersection(0, + 0, + localBoundsW, + localBoundsH, + rect); + if (dirtyComponent instanceof JComponent) { + ((JComponent)dirtyComponent).paintImmediately( + rect.x,rect.y,rect.width, rect.height); + } + else if (dirtyComponent.isShowing()) { + Graphics g = JComponent.safelyGetGraphics( + dirtyComponent, dirtyComponent); + // If the Graphics goes away, it means someone disposed of + // the window, don't do anything. + if (g != null) { + g.setClip(rect.x, rect.y, rect.width, rect.height); + try { + dirtyComponent.paint(g); + } finally { + g.dispose(); + } + } + } + // If the repaintRoot has been set, service it now and + // remove any components that are children of repaintRoot. + if (repaintRoot != null) { + adjustRoots(repaintRoot, roots, i + 1); + count.set(roots.size()); + paintManager.isRepaintingRoot = true; + repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(), + repaintRoot.getHeight()); + paintManager.isRepaintingRoot = false; + // Only service repaintRoot once. + repaintRoot = null; } + + return null; } - } - // If the repaintRoot has been set, service it now and - // remove any components that are children of repaintRoot. - if (repaintRoot != null) { - adjustRoots(repaintRoot, roots, i + 1); - count = roots.size(); - paintManager.isRepaintingRoot = true; - repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(), - repaintRoot.getHeight()); - paintManager.isRepaintingRoot = false; - // Only service repaintRoot once. - repaintRoot = null; - } + }, stack, acc); } } finally { painting = false; --- old/jdk/src/share/classes/javax/swing/UIDefaults.java 2013-02-07 17:07:05.000000000 +0100 +++ new/jdk/src/share/classes/javax/swing/UIDefaults.java 2013-02-07 17:07:05.000000000 +0100 @@ -677,6 +677,8 @@ try { String className = (String)get(uiClassID); if (className != null) { + ReflectUtil.checkPackageAccess(className); + Class cls = (Class)get(className); if (cls == null) { if (uiClassLoader == null) { --- old/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java 2013-02-07 17:07:06.000000000 +0100 +++ new/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java 2013-02-07 17:07:05.000000000 +0100 @@ -159,7 +159,12 @@ // Store Table ScrollPane Corner Component uiDefaults.put("Table.scrollPaneCornerComponent", - TableScrollPaneCorner.class); + new UIDefaults.ActiveValue() { + @Override + public Object createValue(UIDefaults table) { + return new TableScrollPaneCorner(); + } + }); // Setup the settings for ToolBarSeparator which is custom // installed for Nimbus --- old/jdk/src/share/classes/sun/applet/AppletPanel.java 2013-02-07 17:07:06.000000000 +0100 +++ new/jdk/src/share/classes/sun/applet/AppletPanel.java 2013-02-07 17:07:06.000000000 +0100 @@ -45,6 +45,7 @@ import java.util.Collections; import java.util.Locale; import java.util.WeakHashMap; +import sun.awt.AWTAccessor; import sun.awt.AppContext; import sun.awt.EmbeddedFrame; import sun.awt.SunToolkit; @@ -448,12 +449,12 @@ // to avoid deadlock. try { final AppletPanel p = this; - - EventQueue.invokeAndWait(new Runnable() { - public void run() { - p.validate(); - } - }); + Runnable r = new Runnable() { + public void run() { + p.validate(); + } + }; + AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r); } catch(InterruptedException ie) { } @@ -478,18 +479,19 @@ try { final AppletPanel p = this; final Applet a = applet; - - EventQueue.invokeAndWait(new Runnable() { - public void run() { - p.validate(); - a.setVisible(true); - - // Fix for BugTraq ID 4041703. - // Set the default focus for an applet. - if (hasInitialFocus()) - setDefaultFocus(); + Runnable r = new Runnable() { + public void run() { + p.validate(); + a.setVisible(true); + + // Fix for BugTraq ID 4041703. + // Set the default focus for an applet. + if (hasInitialFocus()) { + setDefaultFocus(); } - }); + } + }; + AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r); } catch(InterruptedException ie) { } @@ -512,13 +514,12 @@ // to avoid deadlock. try { final Applet a = applet; - - EventQueue.invokeAndWait(new Runnable() { - public void run() - { - a.setVisible(false); - } - }); + Runnable r = new Runnable() { + public void run() { + a.setVisible(false); + } + }; + AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r); } catch(InterruptedException ie) { } @@ -570,17 +571,14 @@ } status = APPLET_DISPOSE; - try - { + try { final Applet a = applet; - - EventQueue.invokeAndWait(new Runnable() - { - public void run() - { + Runnable r = new Runnable() { + public void run() { remove(a); } - }); + }; + AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r); } catch(InterruptedException ie) { --- old/jdk/src/share/classes/sun/awt/AWTAccessor.java 2013-02-07 17:07:07.000000000 +0100 +++ new/jdk/src/share/classes/sun/awt/AWTAccessor.java 2013-02-07 17:07:07.000000000 +0100 @@ -35,6 +35,7 @@ import sun.misc.Unsafe; import java.awt.peer.ComponentPeer; +import java.lang.reflect.InvocationTargetException; import java.security.AccessControlContext; import java.io.File; @@ -477,6 +478,12 @@ * appeared. */ void wakeup(EventQueue eventQueue, boolean isShutdown); + + /** + * Static in EventQueue + */ + void invokeAndWait(Object source, Runnable r) + throws InterruptedException, InvocationTargetException; } /* --- old/jdk/src/share/classes/sun/awt/AppContext.java 2013-02-07 17:07:08.000000000 +0100 +++ new/jdk/src/share/classes/sun/awt/AppContext.java 2013-02-07 17:07:08.000000000 +0100 @@ -327,21 +327,27 @@ // Before we return the main "system" AppContext, check to // see if there's an AWTSecurityManager installed. If so, // allow it to choose the AppContext to return. - SecurityManager securityManager = System.getSecurityManager(); - if ((securityManager != null) && - (securityManager instanceof AWTSecurityManager)) - { - AWTSecurityManager awtSecMgr = (AWTSecurityManager)securityManager; - AppContext secAppContext = awtSecMgr.getAppContext(); - if (secAppContext != null) { - appContext = secAppContext; // Return what we're told - } + AppContext secAppContext = getExecutionAppContext(); + if (secAppContext != null) { + appContext = secAppContext; // Return what we're told } } return appContext; } + private final static AppContext getExecutionAppContext() { + SecurityManager securityManager = System.getSecurityManager(); + if ((securityManager != null) && + (securityManager instanceof AWTSecurityManager)) + { + AWTSecurityManager awtSecMgr = (AWTSecurityManager) securityManager; + AppContext secAppContext = awtSecMgr.getAppContext(); + return secAppContext; // Return what we're told + } + return null; + } + /** * Returns the main ("system") AppContext. * @@ -806,6 +812,21 @@ public boolean isMainAppContext() { return (numAppContexts == 1); } + public Object getContext() { + return getAppContext(); + } + public Object getExecutionContext() { + return getExecutionAppContext(); + } + public Object get(Object context, Object key) { + return ((AppContext)context).get(key); + } + public void put(Object context, Object key, Object value) { + ((AppContext)context).put(key, value); + } + public void remove(Object context, Object key) { + ((AppContext)context).remove(key); + } }); } } --- old/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java 2013-02-07 17:07:09.000000000 +0100 +++ new/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java 2013-02-07 17:07:09.000000000 +0100 @@ -198,7 +198,7 @@ } this.bandOffset = this.dataOffsets[0]; - verify(false); + verify(); } /** @@ -857,38 +857,68 @@ } /** - * Verify that the layout parameters are consistent with - * the data. If strictCheck - * is false, this method will check for ArrayIndexOutOfBounds conditions. If - * strictCheck is true, this method will check for additional error - * conditions such as line wraparound (width of a line greater than - * the scanline stride). - * @return String Error string, if the layout is incompatible with - * the data. Otherwise returns null. - */ - private void verify (boolean strictCheck) { - // Make sure data for Raster is in a legal range - for (int i=0; i < dataOffsets.length; i++) { + * Verify that the layout parameters are consistent with the data. + * + * The method verifies whether scanline stride and pixel stride do not + * cause an integer overflow during calculation of a position of the pixel + * in data buffer. It also verifies whether the data buffer has enough data + * to correspond the raster layout attributes. + * + * @throws RasterFormatException if an integer overflow is detected, + * or if data buffer has not enough capacity. + */ + protected final void verify() { + for (int i = 0; i < dataOffsets.length; i++) { if (dataOffsets[i] < 0) { - throw new RasterFormatException("Data offsets for band "+i+ - "("+dataOffsets[i]+ - ") must be >= 0"); + throw new RasterFormatException("Data offsets for band " + i + + "(" + dataOffsets[i] + + ") must be >= 0"); } } int maxSize = 0; int size; - for (int i=0; i < numDataElements; i++) { - size = (height-1)*scanlineStride + (width-1)*pixelStride + - dataOffsets[i]; + // we can be sure that width and height are greater than 0 + if (scanlineStride < 0 || + scanlineStride > (Integer.MAX_VALUE / height)) + { + // integer overflow + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } + int lastScanOffset = (height - 1) * scanlineStride; + + if (pixelStride < 0 || + pixelStride > (Integer.MAX_VALUE / width)) + { + // integer overflow + throw new RasterFormatException("Incorrect pixel stride: " + + pixelStride); + } + int lastPixelOffset = (width - 1) * pixelStride; + + if (lastPixelOffset > (Integer.MAX_VALUE - lastScanOffset)) { + // integer overflow + throw new RasterFormatException("Incorrect raster attributes"); + } + lastPixelOffset += lastScanOffset; + + for (int i = 0; i < numDataElements; i++) { + size = lastPixelOffset + dataOffsets[i]; + if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) { + throw new RasterFormatException("Incorrect band offset: " + + dataOffsets[i]); + + } + if (size > maxSize) { maxSize = size; } } if (data.length < maxSize) { - throw new RasterFormatException("Data array too small (should be "+ - maxSize+" )"); + throw new RasterFormatException("Data array too small (should be " + + maxSize + " )"); } } --- old/jdk/src/share/classes/sun/awt/image/ByteInterleavedRaster.java 2013-02-07 17:07:10.000000000 +0100 +++ new/jdk/src/share/classes/sun/awt/image/ByteInterleavedRaster.java 2013-02-07 17:07:09.000000000 +0100 @@ -250,7 +250,7 @@ } } - verify(false); + verify(); } /** @@ -1292,33 +1292,6 @@ return createCompatibleWritableRaster(width,height); } - /** - * Verify that the layout parameters are consistent with - * the data. If strictCheck - * is false, this method will check for ArrayIndexOutOfBounds conditions. If - * strictCheck is true, this method will check for additional error - * conditions such as line wraparound (width of a line greater than - * the scanline stride). - * @return String Error string, if the layout is incompatible with - * the data. Otherwise returns null. - */ - private void verify (boolean strictCheck) { - int maxSize = 0; - int size; - - for (int i=0; i < numDataElements; i++) { - size = (height-1)*scanlineStride + (width-1)*pixelStride + - dataOffsets[i]; - if (size > maxSize) { - maxSize = size; - } - } - if (data.length < maxSize) { - throw new RasterFormatException("Data array too small (should be "+ - maxSize+" )"); - } - } - public String toString() { return new String ("ByteInterleavedRaster: width = "+width+" height = " + height --- old/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java 2013-02-07 17:07:11.000000000 +0100 +++ new/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java 2013-02-07 17:07:10.000000000 +0100 @@ -198,7 +198,7 @@ } this.bandOffset = this.dataOffsets[0]; - verify(false); + verify(); } /** @@ -791,38 +791,67 @@ } /** - * Verify that the layout parameters are consistent with - * the data. If strictCheck - * is false, this method will check for ArrayIndexOutOfBounds conditions. If - * strictCheck is true, this method will check for additional error - * conditions such as line wraparound (width of a line greater than - * the scanline stride). - * @return String Error string, if the layout is incompatible with - * the data. Otherwise returns null. - */ - private void verify (boolean strictCheck) { - // Make sure data for Raster is in a legal range - for (int i=0; i < dataOffsets.length; i++) { + * Verify that the layout parameters are consistent with the data. + * + * The method verifies whether scanline stride and pixel stride do not + * cause an integer overflow during calculation of a position of the pixel + * in data buffer. It also verifies whether the data buffer has enough data + * to correspond the raster layout attributes. + * + * @throws RasterFormatException if an integer overflow is detected, + * or if data buffer has not enough capacity. + */ + protected final void verify() { + for (int i = 0; i < dataOffsets.length; i++) { if (dataOffsets[i] < 0) { - throw new RasterFormatException("Data offsets for band "+i+ - "("+dataOffsets[i]+ - ") must be >= 0"); + throw new RasterFormatException("Data offsets for band " + i + + "(" + dataOffsets[i] + + ") must be >= 0"); } } int maxSize = 0; int size; - for (int i=0; i < numDataElements; i++) { - size = (height-1)*scanlineStride + (width-1)*pixelStride + - dataOffsets[i]; + // we can be sure that width and height are greater than 0 + if (scanlineStride < 0 || + scanlineStride > (Integer.MAX_VALUE / height)) + { + // integer overflow + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } + int lastScanOffset = (height - 1) * scanlineStride; + + if (pixelStride < 0 || + pixelStride > (Integer.MAX_VALUE / width)) + { + // integer overflow + throw new RasterFormatException("Incorrect pixel stride: " + + pixelStride); + } + int lastPixelOffset = (width - 1) * pixelStride; + + if (lastPixelOffset > (Integer.MAX_VALUE - lastScanOffset)) { + // integer overflow + throw new RasterFormatException("Incorrect raster attributes"); + } + lastPixelOffset += lastScanOffset; + + for (int i = 0; i < numDataElements; i++) { + size = lastPixelOffset + dataOffsets[i]; + if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) { + throw new RasterFormatException("Incorrect band offset: " + + dataOffsets[i]); + } + if (size > maxSize) { maxSize = size; } } if (data.length < maxSize) { - throw new RasterFormatException("Data array too small (should be "+ - maxSize+" )"); + throw new RasterFormatException("Data array too small (should be " + + maxSize + " )"); } } --- old/jdk/src/share/classes/sun/awt/image/ShortInterleavedRaster.java 2013-02-07 17:07:11.000000000 +0100 +++ new/jdk/src/share/classes/sun/awt/image/ShortInterleavedRaster.java 2013-02-07 17:07:11.000000000 +0100 @@ -171,7 +171,7 @@ sampleModel); } this.bandOffset = this.dataOffsets[0]; - verify(false); + verify(); } /** @@ -762,33 +762,6 @@ return createCompatibleWritableRaster(width,height); } - /** - * Verify that the layout parameters are consistent with - * the data. If strictCheck - * is false, this method will check for ArrayIndexOutOfBounds conditions. If - * strictCheck is true, this method will check for additional error - * conditions such as line wraparound (width of a line greater than - * the scanline stride). - * @return String Error string, if the layout is incompatible with - * the data. Otherwise returns null. - */ - private void verify (boolean strictCheck) { - int maxSize = 0; - int size; - - for (int i=0; i < numDataElements; i++) { - size = (height-1)*scanlineStride + (width-1)*pixelStride + - dataOffsets[i]; - if (size > maxSize) { - maxSize = size; - } - } - if (data.length < maxSize) { - throw new RasterFormatException("Data array too small (should be "+ - maxSize+" )"); - } - } - public String toString() { return new String ("ShortInterleavedRaster: width = "+width +" height = " + height --- old/jdk/src/share/classes/sun/misc/JavaAWTAccess.java 2013-02-07 17:07:12.000000000 +0100 +++ new/jdk/src/share/classes/sun/misc/JavaAWTAccess.java 2013-02-07 17:07:12.000000000 +0100 @@ -26,6 +26,14 @@ package sun.misc; public interface JavaAWTAccess { + public Object getContext(); + public Object getExecutionContext(); + + public Object get(Object context, Object key); + public void put(Object context, Object key, Object value); + public void remove(Object context, Object key); + + // convenience methods whose context is the object returned by getContext() public Object get(Object key); public void put(Object key, Object value); public void remove(Object key); --- old/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java 2013-02-07 17:07:13.000000000 +0100 +++ new/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java 2013-02-07 17:07:13.000000000 +0100 @@ -41,8 +41,12 @@ private boolean needToReadHeader = true; - static char CR = '\r'; - static char LF = '\n'; + final static char CR = '\r'; + final static char LF = '\n'; + /* + * Maximum chunk header size of 2KB + 2 bytes for CRLF + */ + private final static int MAX_CHUNK_HEADER_SIZE = 2050; private int numeric (char[] arr, int nchars) throws IOException { assert arr.length >= nchars; @@ -73,10 +77,14 @@ char[] len_arr = new char [16]; int len_size = 0; boolean end_of_len = false; + int read = 0; while ((c=in.read())!= -1) { char ch = (char) c; - if (len_size == len_arr.length -1) { + read++; + if ((len_size == len_arr.length -1) || + (read > MAX_CHUNK_HEADER_SIZE)) + { throw new IOException ("invalid chunk header"); } if (gotCR) { --- old/jdk/src/share/classes/sun/net/www/http/ChunkedInputStream.java 2013-02-07 17:07:14.000000000 +0100 +++ new/jdk/src/share/classes/sun/net/www/http/ChunkedInputStream.java 2013-02-07 17:07:14.000000000 +0100 @@ -125,6 +125,11 @@ */ private boolean closed; + /* + * Maximum chunk header size of 2KB + 2 bytes for CRLF + */ + private final static int MAX_CHUNK_HEADER_SIZE = 2050; + /** * State to indicate that next field should be :- * chunk-size [ chunk-extension ] CRLF @@ -290,6 +295,10 @@ break; } pos++; + if ((pos - rawPos) >= MAX_CHUNK_HEADER_SIZE) { + error = true; + throw new IOException("Chunk header too long"); + } } if (pos >= rawCount) { return; --- old/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java 2013-02-07 17:07:15.000000000 +0100 +++ new/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java 2013-02-07 17:07:14.000000000 +0100 @@ -419,7 +419,7 @@ synchronized (writeLock) { ensureOpen(); - InetSocketAddress isa = (InetSocketAddress)target; + InetSocketAddress isa = Net.checkAddress(target); InetAddress ia = isa.getAddress(); if (ia == null) throw new IOException("Target address not resolved"); @@ -430,9 +430,9 @@ SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (ia.isMulticastAddress()) { - sm.checkMulticast(isa.getAddress()); + sm.checkMulticast(ia); } else { - sm.checkConnect(isa.getAddress().getHostAddress(), + sm.checkConnect(ia.getHostAddress(), isa.getPort()); } } @@ -452,7 +452,7 @@ return 0; writerThread = NativeThread.current(); do { - n = send(fd, src, target); + n = send(fd, src, isa); } while ((n == IOStatus.INTERRUPTED) && isOpen()); synchronized (stateLock) { @@ -469,7 +469,7 @@ } } - private int send(FileDescriptor fd, ByteBuffer src, SocketAddress target) + private int send(FileDescriptor fd, ByteBuffer src, InetSocketAddress target) throws IOException { if (src instanceof DirectBuffer) @@ -500,7 +500,7 @@ } private int sendFromNativeBuffer(FileDescriptor fd, ByteBuffer bb, - SocketAddress target) + InetSocketAddress target) throws IOException { int pos = bb.position(); @@ -512,7 +512,7 @@ int written; try { written = send0(preferIPv6, fd, ((DirectBuffer)bb).address() + pos, - rem, target); + rem, target.getAddress(), target.getPort()); } catch (PortUnreachableException pue) { if (isConnected()) throw pue; @@ -1092,8 +1092,8 @@ boolean connected) throws IOException; - private native int send0(boolean preferIPv6, FileDescriptor fd, long address, int len, - SocketAddress sa) + private native int send0(boolean preferIPv6, FileDescriptor fd, long address, + int len, InetAddress addr, int port) throws IOException; static { --- old/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java 2013-02-07 17:07:15.000000000 +0100 +++ new/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java 2013-02-07 17:07:15.000000000 +0100 @@ -144,4 +144,63 @@ } return true; } + + // Returns true if p is an ancestor of cl i.e. class loader 'p' can + // be found in the cl's delegation chain + private static boolean isAncestor(ClassLoader p, ClassLoader cl) { + ClassLoader acl = cl; + do { + acl = acl.getParent(); + if (p == acl) { + return true; + } + } while (acl != null); + return false; + } + + /** + * Returns true if package access check is needed for reflective + * access from a class loader 'from' to classes or members in + * a class defined by class loader 'to'. This method returns true + * if 'from' is not the same as or an ancestor of 'to'. All code + * in a system domain are granted with all permission and so this + * method returns false if 'from' class loader is a class loader + * loading system classes. On the other hand, if a class loader + * attempts to access system domain classes, it requires package + * access check and this method will return true. + */ + public static boolean needsPackageAccessCheck(ClassLoader from, ClassLoader to) { + if (from == null || from == to) + return false; + + if (to == null) + return true; + + return !isAncestor(from, to); + } + + /** + * Access check on the interfaces that a proxy class implements and throw + * {@code SecurityException} if it accesses a restricted package. + * + * @param ccl the caller's class loader + * @param interfaces the list of interfaces that a proxy class implements + * + * @see Proxy#checkProxyAccess + */ + public static void checkProxyPackageAccess(ClassLoader ccl, + Class... interfaces) + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + for (Class intf : interfaces) { + ClassLoader cl = intf.getClassLoader(); + if (needsPackageAccessCheck(ccl, cl)) { + checkPackageAccess(intf); + } + } + } + } + + public static final String PROXY_PACKAGE = "sun.proxy"; } --- old/jdk/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java 2013-02-07 17:07:17.000000000 +0100 +++ new/jdk/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java 2013-02-07 17:07:17.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2012, 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,7 +153,7 @@ returnServerError(e.getMessage()); } else - returnClientError("invalid command: " + command); + returnClientError("invalid command."); } catch (Exception e) { returnServerError("internal error: " + e.getMessage()); } @@ -225,7 +225,7 @@ try { port = Integer.parseInt(param); } catch (NumberFormatException e) { - throw new CGIClientException("invalid port number: " + param); + throw new CGIClientException("invalid port number."); } if (port <= 0 || port > 0xFFFF) throw new CGIClientException("invalid port: " + port); @@ -293,11 +293,14 @@ "unexpected EOF reading server response"); if (line.toLowerCase().startsWith(key)) { - // if contentLengthFound is true - // we should probably do something here - responseContentLength = - Integer.parseInt(line.substring(key.length()).trim()); - contentLengthFound = true; + if (contentLengthFound) { + throw new CGIServerException( + "Multiple Content-length entries found."); + } else { + responseContentLength = + Integer.parseInt(line.substring(key.length()).trim()); + contentLengthFound = true; + } } } while ((line.length() != 0) && (line.charAt(0) != '\r') && (line.charAt(0) != '\n')); --- old/jdk/src/share/classes/sun/rmi/transport/proxy/HttpInputStream.java 2013-02-07 17:07:18.000000000 +0100 +++ new/jdk/src/share/classes/sun/rmi/transport/proxy/HttpInputStream.java 2013-02-07 17:07:17.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2012, 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 @@ -70,11 +70,14 @@ throw new EOFException(); if (line.toLowerCase().startsWith(key)) { - // if contentLengthFound is true - // we should probably do something here - bytesLeft = - Integer.parseInt(line.substring(key.length()).trim()); - contentLengthFound = true; + if (contentLengthFound) { + throw new IOException( + "Multiple Content-length entries found."); + } else { + bytesLeft = + Integer.parseInt(line.substring(key.length()).trim()); + contentLengthFound = true; + } } // The idea here is to go past the first blank line. --- old/jdk/src/share/classes/sun/security/pkcs11/P11KeyAgreement.java 2013-02-07 17:07:18.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/pkcs11/P11KeyAgreement.java 2013-02-07 17:07:18.000000000 +0100 @@ -37,6 +37,7 @@ import static sun.security.pkcs11.TemplateManager.*; import sun.security.pkcs11.wrapper.*; import static sun.security.pkcs11.wrapper.PKCS11Constants.*; +import sun.security.util.KeyUtil; /** * KeyAgreement implementation class. This class currently supports @@ -134,6 +135,10 @@ BigInteger p, g, y; if (key instanceof DHPublicKey) { DHPublicKey dhKey = (DHPublicKey)key; + + // validate the Diffie-Hellman public key + KeyUtil.validate(dhKey); + y = dhKey.getY(); DHParameterSpec params = dhKey.getParams(); p = params.getP(); @@ -145,6 +150,10 @@ try { DHPublicKeySpec spec = (DHPublicKeySpec)kf.engineGetKeySpec (key, DHPublicKeySpec.class); + + // validate the Diffie-Hellman public key + KeyUtil.validate(spec); + y = spec.getY(); p = spec.getP(); g = spec.getG(); --- old/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java 2013-02-07 17:07:19.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java 2013-02-07 17:07:19.000000000 +0100 @@ -128,9 +128,8 @@ * in the constructor. */ void processMessage(byte type, int messageLen) throws IOException { - if (state > type - && (type != HandshakeMessage.ht_hello_request - && state != HandshakeMessage.ht_client_hello)) { + if (state >= type + && (type != HandshakeMessage.ht_hello_request)) { throw new SSLProtocolException( "Handshake message sequence violation, " + type); } @@ -193,8 +192,12 @@ } break; case K_DH_ANON: - this.serverKeyExchange(new DH_ServerKeyExchange( + try { + this.serverKeyExchange(new DH_ServerKeyExchange( input, protocolVersion)); + } catch (GeneralSecurityException e) { + throwSSLException("Server key", e); + } break; case K_DHE_DSS: case K_DHE_RSA: @@ -922,7 +925,7 @@ case K_DHE_RSA: case K_DHE_DSS: case K_DH_ANON: - preMasterSecret = dh.getAgreedSecret(serverDH); + preMasterSecret = dh.getAgreedSecret(serverDH, true); break; case K_ECDHE_RSA: case K_ECDHE_ECDSA: --- old/jdk/src/share/classes/sun/security/ssl/DHClientKeyExchange.java 2013-02-07 17:07:20.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/DHClientKeyExchange.java 2013-02-07 17:07:20.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,7 @@ import java.io.IOException; import java.io.PrintStream; import java.math.BigInteger; - +import javax.net.ssl.SSLHandshakeException; /* * Message used by clients to send their Diffie-Hellman public @@ -50,7 +50,7 @@ private byte dh_Yc[]; // 1 to 2^16 -1 bytes BigInteger getClientPublicKey() { - return new BigInteger(1, dh_Yc); + return dh_Yc == null ? null : new BigInteger(1, dh_Yc); } /* @@ -72,7 +72,14 @@ * but that's what the protocol spec requires.) */ DHClientKeyExchange(HandshakeInStream input) throws IOException { - dh_Yc = input.getBytes16(); + if (input.available() >= 2) { + dh_Yc = input.getBytes16(); + } else { + // currently, we don't support cipher suites that requires + // implicit public key of client. + throw new SSLHandshakeException( + "Unsupported implicit client DiffieHellman public key"); + } } int messageLength() { @@ -84,7 +91,9 @@ } void send(HandshakeOutStream s) throws IOException { - s.putBytes16(dh_Yc); + if (dh_Yc != null && dh_Yc.length != 0) { + s.putBytes16(dh_Yc); + } } void print(PrintStream s) throws IOException { --- old/jdk/src/share/classes/sun/security/ssl/DHCrypt.java 2013-02-07 17:07:21.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/DHCrypt.java 2013-02-07 17:07:21.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2012, 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,12 +28,15 @@ import java.math.BigInteger; import java.security.*; - +import java.io.IOException; +import javax.net.ssl.SSLHandshakeException; import javax.crypto.SecretKey; import javax.crypto.KeyAgreement; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.*; +import sun.security.util.KeyUtil; + /** * This class implements the Diffie-Hellman key exchange algorithm. * D-H means combining your private key with your partners public key to @@ -54,7 +57,8 @@ * . if we are server, call DHCrypt(keyLength,random). This generates * an ephemeral keypair of the request length. * . if we are client, call DHCrypt(modulus, base, random). This - * generates an ephemeral keypair using the parameters specified by the server. + * generates an ephemeral keypair using the parameters specified by + * the server. * . send parameters and public value to remote peer * . receive peers ephemeral public key * . call getAgreedSecret() to calculate the shared secret @@ -83,6 +87,9 @@ // public component of our key, X = (g ^ x) mod p private BigInteger publicValue; // X (aka y) + // the times to recove from failure if public key validation + private static int MAX_FAILOVER_TIMES = 2; + /** * Generate a Diffie-Hellman keypair of the specified size. */ @@ -90,9 +97,12 @@ try { KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman"); kpg.initialize(keyLength, random); - KeyPair kp = kpg.generateKeyPair(); - privateKey = kp.getPrivate(); - DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic()); + + DHPublicKeySpec spec = generateDHPublicKeySpec(kpg); + if (spec == null) { + throw new RuntimeException("Could not generate DH keypair"); + } + publicValue = spec.getY(); modulus = spec.getP(); base = spec.getG(); @@ -115,20 +125,25 @@ KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman"); DHParameterSpec params = new DHParameterSpec(modulus, base); kpg.initialize(params, random); - KeyPair kp = kpg.generateKeyPair(); - privateKey = kp.getPrivate(); - DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic()); + + DHPublicKeySpec spec = generateDHPublicKeySpec(kpg); + if (spec == null) { + throw new RuntimeException("Could not generate DH keypair"); + } + publicValue = spec.getY(); } catch (GeneralSecurityException e) { throw new RuntimeException("Could not generate DH keypair", e); } } + static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) { if (key instanceof DHPublicKey) { DHPublicKey dhKey = (DHPublicKey)key; DHParameterSpec params = dhKey.getParams(); - return new DHPublicKeySpec(dhKey.getY(), params.getP(), params.getG()); + return new DHPublicKeySpec(dhKey.getY(), + params.getP(), params.getG()); } try { KeyFactory factory = JsseJce.getKeyFactory("DH"); @@ -166,17 +181,32 @@ *

    It is illegal to call this member function if the private key * has not been set (or generated). * - * @param peerPublicKey the peer's public key. - * @returns the secret, which is an unsigned big-endian integer - * the same size as the Diffie-Hellman modulus. + * @param peerPublicKey the peer's public key. + * @param keyIsValidated whether the {@code peerPublicKey} has beed + * validated + * @return the secret, which is an unsigned big-endian integer + * the same size as the Diffie-Hellman modulus. */ - SecretKey getAgreedSecret(BigInteger peerPublicValue) { + SecretKey getAgreedSecret(BigInteger peerPublicValue, + boolean keyIsValidated) throws IOException { try { KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman"); DHPublicKeySpec spec = new DHPublicKeySpec(peerPublicValue, modulus, base); PublicKey publicKey = kf.generatePublic(spec); KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman"); + + // validate the Diffie-Hellman public key + if (!keyIsValidated && + !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) { + try { + KeyUtil.validate(spec); + } catch (InvalidKeyException ike) { + // prefer handshake_failure alert to internal_error alert + throw new SSLHandshakeException(ike.getMessage()); + } + } + ka.init(privateKey); ka.doPhase(publicKey, true); return ka.generateSecret("TlsPremasterSecret"); @@ -185,4 +215,33 @@ } } + // Generate and validate DHPublicKeySpec + private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg) + throws GeneralSecurityException { + + boolean doExtraValiadtion = + (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName())); + for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) { + KeyPair kp = kpg.generateKeyPair(); + privateKey = kp.getPrivate(); + DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic()); + + // validate the Diffie-Hellman public key + if (doExtraValiadtion) { + try { + KeyUtil.validate(spec); + } catch (InvalidKeyException ivke) { + if (i == MAX_FAILOVER_TIMES) { + throw ivke; + } + // otherwise, ignore the exception and try the next one + continue; + } + } + + return spec; + } + + return null; + } } --- old/jdk/src/share/classes/sun/security/ssl/HandshakeMessage.java 2013-02-07 17:07:22.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/HandshakeMessage.java 2013-02-07 17:07:21.000000000 +0100 @@ -41,12 +41,14 @@ import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; +import javax.crypto.spec.DHPublicKeySpec; import javax.net.ssl.*; import sun.security.internal.spec.TlsPrfParameterSpec; import sun.security.ssl.CipherSuite.*; import static sun.security.ssl.CipherSuite.PRF.*; +import sun.security.util.KeyUtil; /** * Many data structures are involved in the handshake messages. These @@ -702,6 +704,7 @@ this.protocolVersion = protocolVersion; this.preferableSignatureAlgorithm = null; + // The DH key has been validated in the constructor of DHCrypt. setValues(obj); signature = null; } @@ -718,6 +721,7 @@ this.protocolVersion = protocolVersion; + // The DH key has been validated in the constructor of DHCrypt. setValues(obj); Signature sig; @@ -744,7 +748,8 @@ * DH_anon key exchange */ DH_ServerKeyExchange(HandshakeInStream input, - ProtocolVersion protocolVersion) throws IOException { + ProtocolVersion protocolVersion) + throws IOException, GeneralSecurityException { this.protocolVersion = protocolVersion; this.preferableSignatureAlgorithm = null; @@ -752,6 +757,10 @@ dh_p = input.getBytes16(); dh_g = input.getBytes16(); dh_Ys = input.getBytes16(); + KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys), + new BigInteger(1, dh_p), + new BigInteger(1, dh_g))); + signature = null; } @@ -772,6 +781,9 @@ dh_p = input.getBytes16(); dh_g = input.getBytes16(); dh_Ys = input.getBytes16(); + KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys), + new BigInteger(1, dh_p), + new BigInteger(1, dh_g))); // read the signature and hash algorithm if (protocolVersion.v >= ProtocolVersion.TLS12.v) { --- old/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java 2013-02-07 17:07:22.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java 2013-02-07 17:07:22.000000000 +0100 @@ -36,7 +36,7 @@ import javax.net.ssl.*; import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec; -import sun.security.util.KeyLength; +import sun.security.util.KeyUtil; /** * This is the client key exchange message (CLIENT --> SERVER) used with @@ -193,7 +193,7 @@ "unable to get the plaintext of the premaster secret"); } - int keySize = KeyLength.getKeySize(secretKey); + int keySize = KeyUtil.getKeySize(secretKey); if (keySize > 0 && keySize != 384) { // 384 = 48 * 8 if (debug != null && Debug.isOn("handshake")) { System.out.println( --- old/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java 2013-02-07 17:07:23.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java 2013-02-07 17:07:23.000000000 +0100 @@ -150,7 +150,7 @@ // In SSLv3 and TLS, messages follow strictly increasing // numerical order _except_ for one annoying special case. // - if ((state > type) + if ((state >= type) && (state != HandshakeMessage.ht_client_key_exchange && type != HandshakeMessage.ht_certificate_verify)) { throw new SSLProtocolException( @@ -250,13 +250,15 @@ } // - // Move the state machine forward except for that annoying - // special case. This means that clients could send extra - // cert verify messages; not a problem so long as all of - // them actually check out. + // Move state machine forward if the message handling + // code didn't already do so // - if (state < type && type != HandshakeMessage.ht_certificate_verify) { - state = type; + if (state < type) { + if(type == HandshakeMessage.ht_certificate_verify) { + state = type + 2; // an annoying special case + } else { + state = type; + } } } @@ -1363,7 +1365,7 @@ if (debug != null && Debug.isOn("handshake")) { mesg.print(System.out); } - return dh.getAgreedSecret(mesg.getClientPublicKey()); + return dh.getAgreedSecret(mesg.getClientPublicKey(), false); } private SecretKey clientKeyExchange(ECDHClientKeyExchange mesg) --- old/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java 2013-02-07 17:07:24.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java 2013-02-07 17:07:24.000000000 +0100 @@ -38,7 +38,7 @@ import java.util.Collections; import java.util.ArrayList; -import sun.security.util.KeyLength; +import sun.security.util.KeyUtil; /** * Signature and hash algorithm. @@ -279,7 +279,7 @@ * If key size is less than 512, the digest length should be * less than or equal to 20 bytes. */ - int keySize = KeyLength.getKeySize(signingKey); + int keySize = KeyUtil.getKeySize(signingKey); if (keySize >= 768) { maxDigestLength = HashAlgorithm.SHA512.length; } else if ((keySize >= 512) && (keySize < 768)) { --- old/jdk/src/share/classes/sun/security/util/DerIndefLenConverter.java 2013-02-07 17:07:25.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/util/DerIndefLenConverter.java 2013-02-07 17:07:25.000000000 +0100 @@ -325,6 +325,10 @@ } } + if (unresolved != 0) { + throw new IOException("not all indef len BER resolved"); + } + newData = new byte[dataSize + numOfTotalLenBytes + unused]; dataPos=0; newDataPos=0; index=0; --- old/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java 2013-02-07 17:07:26.000000000 +0100 +++ new/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java 2013-02-07 17:07:25.000000000 +0100 @@ -438,7 +438,7 @@ // Does this key constraint disable the specified key? public boolean disables(Key key) { - int size = KeyLength.getKeySize(key); + int size = KeyUtil.getKeySize(key); if (size == 0) { return true; // we don't allow any key of size 0. --- old/jdk/src/share/lib/security/java.security-linux 2013-02-07 17:07:26.000000000 +0100 +++ new/jdk/src/share/lib/security/java.security-linux 2013-02-07 17:07:26.000000000 +0100 @@ -123,7 +123,19 @@ # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,oracle.jrockit.jfr. +package.access=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr. # # List of comma-separated packages that start with or equal this string @@ -135,7 +147,19 @@ # by default, none of the class loaders supplied with the JDK call # checkPackageDefinition. # -package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,oracle.jrockit.jfr. +package.definition=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr. # # Determines whether this properties file can be appended to --- old/jdk/src/share/lib/security/java.security-macosx 2013-02-07 17:07:27.000000000 +0100 +++ new/jdk/src/share/lib/security/java.security-macosx 2013-02-07 17:07:27.000000000 +0100 @@ -124,7 +124,20 @@ # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,apple.,oracle.jrockit.jfr. +package.access=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr.,\ + apple. # # List of comma-separated packages that start with or equal this string @@ -136,7 +149,20 @@ # by default, none of the class loaders supplied with the JDK call # checkPackageDefinition. # -package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,apple.,oracle.jrockit.jfr. +package.definition=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr.,\ + apple. # # Determines whether this properties file can be appended to --- old/jdk/src/share/lib/security/java.security-solaris 2013-02-07 17:07:28.000000000 +0100 +++ new/jdk/src/share/lib/security/java.security-solaris 2013-02-07 17:07:28.000000000 +0100 @@ -125,7 +125,19 @@ # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,oracle.jrockit.jfr. +package.access=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr. # # List of comma-separated packages that start with or equal this string @@ -137,7 +149,19 @@ # by default, none of the class loaders supplied with the JDK call # checkPackageDefinition. # -package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,oracle.jrockit.jfr. +package.definition=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr. # # Determines whether this properties file can be appended to --- old/jdk/src/share/lib/security/java.security-windows 2013-02-07 17:07:29.000000000 +0100 +++ new/jdk/src/share/lib/security/java.security-windows 2013-02-07 17:07:29.000000000 +0100 @@ -124,7 +124,19 @@ # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,oracle.jrockit.jfr. +package.access=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr. # # List of comma-separated packages that start with or equal this string @@ -136,7 +148,19 @@ # by default, none of the class loaders supplied with the JDK call # checkPackageDefinition. # -package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,oracle.jrockit.jfr. +package.definition=sun.,\ + com.sun.xml.internal.bind.,\ + com.sun.xml.internal.org.jvnet.staxex.,\ + com.sun.xml.internal.ws.,\ + com.sun.imageio.,\ + com.sun.istack.internal.,\ + com.sun.jmx.defaults.,\ + com.sun.jmx.remote.util.,\ + com.sun.org.apache.xerces.internal.utils.,\ + com.sun.org.apache.xalan.internal.utils.,\ + com.sun.org.glassfish.external.,\ + com.sun.org.glassfish.gmbal.,\ + oracle.jrockit.jfr. # # Determines whether this properties file can be appended to --- old/jdk/src/share/native/com/sun/java/util/jar/pack/bands.cpp 2013-02-07 17:07:30.000000000 +0100 +++ new/jdk/src/share/native/com/sun/java/util/jar/pack/bands.cpp 2013-02-07 17:07:29.000000000 +0100 @@ -187,6 +187,10 @@ entry* band::getRefCommon(cpindex* ix_, bool nullOKwithCaller) { CHECK_0; + if (ix_ == NULL) { + abort("no index"); + return NULL; + } assert(ix_->ixTag == ixTag || (ixTag == CONSTANT_Literal && ix_->ixTag >= CONSTANT_Integer --- old/jdk/src/share/native/com/sun/java/util/jar/pack/bands.h 2013-02-07 17:07:30.000000000 +0100 +++ new/jdk/src/share/native/com/sun/java/util/jar/pack/bands.h 2013-02-07 17:07:30.000000000 +0100 @@ -101,8 +101,8 @@ int getByte() { assert(ix == null); return vs[0].getByte(); } int getInt() { assert(ix == null); return vs[0].getInt(); } - entry* getRefN() { assert(ix != null); return getRefCommon(ix, true); } - entry* getRef() { assert(ix != null); return getRefCommon(ix, false); } + entry* getRefN() { return getRefCommon(ix, true); } + entry* getRef() { return getRefCommon(ix, false); } entry* getRefUsing(cpindex* ix2) { assert(ix == null); return getRefCommon(ix2, true); } entry* getRefCommon(cpindex* ix, bool nullOK); --- old/jdk/src/share/native/com/sun/java/util/jar/pack/jni.cpp 2013-02-07 17:07:31.000000000 +0100 +++ new/jdk/src/share/native/com/sun/java/util/jar/pack/jni.cpp 2013-02-07 17:07:31.000000000 +0100 @@ -50,6 +50,7 @@ static jmethodID currentInstMID; static jmethodID readInputMID; static jclass NIclazz; +static jmethodID getUnpackerPtrMID; static char* dbg = null; @@ -60,8 +61,8 @@ static unpacker* get_unpacker(JNIEnv *env, jobject pObj, bool noCreate=false) { unpacker* uPtr; - uPtr = (unpacker*)jlong2ptr(env->GetLongField(pObj, unpackerPtrFID)); - //fprintf(stderr, "get_unpacker(%p) uPtr=%p\n", pObj, uPtr); + jlong p = env->CallLongMethod(pObj, getUnpackerPtrMID); + uPtr = (unpacker*)jlong2ptr(p); if (uPtr == null) { if (noCreate) return null; uPtr = new unpacker(); @@ -94,11 +95,15 @@ if (env == null) return null; jobject pObj = env->CallStaticObjectMethod(NIclazz, currentInstMID); - //fprintf(stderr, "get_unpacker() pObj=%p\n", pObj); - if (pObj == null) - return null; - // Got pObj and env; now do it the easy way. - return get_unpacker(env, pObj); + //fprintf(stderr, "get_unpacker0() pObj=%p\n", pObj); + if (pObj != null) { + // Got pObj and env; now do it the easy way. + return get_unpacker(env, pObj); + } + // this should really not happen, if it does something is seriously + // wrong throw an exception + THROW_IOE(ERROR_INTERNAL); + return null; } static void free_unpacker(JNIEnv *env, jobject pObj, unpacker* uPtr) { @@ -127,18 +132,23 @@ JNIEXPORT void JNICALL Java_com_sun_java_util_jar_pack_NativeUnpack_initIDs(JNIEnv *env, jclass clazz) { +#ifndef PRODUCT dbg = getenv("DEBUG_ATTACH"); while( dbg != null) { sleep(10); } +#endif NIclazz = (jclass) env->NewGlobalRef(clazz); unpackerPtrFID = env->GetFieldID(clazz, "unpackerPtr", "J"); currentInstMID = env->GetStaticMethodID(clazz, "currentInstance", "()Ljava/lang/Object;"); readInputMID = env->GetMethodID(clazz, "readInputFn", "(Ljava/nio/ByteBuffer;J)J"); + getUnpackerPtrMID = env->GetMethodID(clazz, "getUnpackerPtr", "()J"); + if (unpackerPtrFID == null || currentInstMID == null || readInputMID == null || - NIclazz == null) { + NIclazz == null || + getUnpackerPtrMID == null) { THROW_IOE("cannot init class members"); } } @@ -146,8 +156,13 @@ JNIEXPORT jlong JNICALL Java_com_sun_java_util_jar_pack_NativeUnpack_start(JNIEnv *env, jobject pObj, jobject pBuf, jlong offset) { - unpacker* uPtr = get_unpacker(env, pObj); - + // try to get the unpacker pointer the hard way first, we do this to ensure + // valid object pointers and env is intact, if not now is good time to bail. + unpacker* uPtr = get_unpacker(); + //fprintf(stderr, "start(%p) uPtr=%p initializing\n", pObj, uPtr); + if (uPtr == null) { + return -1; + } // redirect our io to the default log file or whatever. uPtr->redirect_stdio(); @@ -163,7 +178,12 @@ else { buf = (char*)buf + (size_t)offset; buflen -= (size_t)offset; } } - + // before we start off we make sure there is no other error by the time we + // get here + if (uPtr->aborting()) { + THROW_IOE(uPtr->get_abort_message()); + return 0; + } uPtr->start(buf, buflen); if (uPtr->aborting()) { THROW_IOE(uPtr->get_abort_message()); @@ -230,11 +250,14 @@ // We have fetched all the files. // Now swallow up any remaining input. - if (uPtr->input_remaining() == 0) + if (uPtr->input_remaining() == 0) { return null; - else - return env->NewDirectByteBuffer(uPtr->input_scan(), - uPtr->input_remaining()); + } else { + bytes remaining_bytes; + remaining_bytes.malloc(uPtr->input_remaining()); + remaining_bytes.copyFrom(uPtr->input_scan(), uPtr->input_remaining()); + return env->NewDirectByteBuffer(remaining_bytes.ptr, remaining_bytes.len); + } } JNIEXPORT jlong JNICALL --- old/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp 2013-02-07 17:07:32.000000000 +0100 +++ new/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp 2013-02-07 17:07:32.000000000 +0100 @@ -267,11 +267,13 @@ } inline cpindex* cpool::getFieldIndex(entry* classRef) { + if (classRef == NULL) { abort("missing class reference"); return NULL; } assert(classRef->tagMatches(CONSTANT_Class)); assert((uint)classRef->inord < (uint)tag_count[CONSTANT_Class]); return &member_indexes[classRef->inord*2+0]; } inline cpindex* cpool::getMethodIndex(entry* classRef) { + if (classRef == NULL) { abort("missing class reference"); return NULL; } assert(classRef->tagMatches(CONSTANT_Class)); assert((uint)classRef->inord < (uint)tag_count[CONSTANT_Class]); return &member_indexes[classRef->inord*2+1]; @@ -1238,6 +1240,7 @@ entry& e = cpMap[i]; e.refs = U_NEW(entry*, e.nrefs = 2); e.refs[0] = cp_band1.getRef(); + CHECK; e.refs[1] = cp_band2.getRef(); CHECK; } @@ -1963,6 +1966,7 @@ int attrc = ADH_BYTE_CONTEXT(header); int idx = ADH_BYTE_INDEX(header); entry* name = attr_definition_name.getRef(); + CHECK; entry* layout = attr_definition_layout.getRef(); CHECK; attr_defs[attrc].defineLayout(idx, name, layout->value.b.strval()); @@ -2067,7 +2071,9 @@ if (ics[i].name == NO_ENTRY_YET) { // Long form. ics[i].outer = ic_outer_class.getRefN(); + CHECK; ics[i].name = ic_name.getRefN(); + CHECK; } else { // Fill in outer and name based on inner. bytes& n = ics[i].inner->value.b; @@ -2583,6 +2589,7 @@ e = b.getRefUsing(cp.getKQIndex()); else e = b.getRefN(); + CHECK; switch (b.le_len) { case 0: break; case 1: putu1ref(e); break; @@ -2964,7 +2971,7 @@ void unpacker::read_bands() { byte* rp0 = rp; - + CHECK; read_file_header(); CHECK; @@ -3632,10 +3639,12 @@ // packed file and len is the length of the buffer. // If null, the callback is used to fill an internal buffer. void unpacker::start(void* packptr, size_t len) { + CHECK; NOT_PRODUCT(debug_u = this); if (packptr != null && len != 0) { inbytes.set((byte*) packptr, len); } + CHECK; read_bands(); } @@ -3766,6 +3775,7 @@ NOT_PRODUCT(bc_superfield.setIndex(null)); NOT_PRODUCT(bc_supermethod.setIndex(null)); } + CHECK; for (int curIP = 0; ; curIP++) { int curPC = (int)(wpoffset() - codeBase); @@ -3879,7 +3889,8 @@ int coding = bc_initref.getInt(); // Find the nth overloading of in classRef. entry* ref = null; - cpindex* ix = (classRef == null)? null: cp.getMethodIndex(classRef); + cpindex* ix = cp.getMethodIndex(classRef); + CHECK; for (int j = 0, which_init = 0; ; j++) { ref = (ix == null)? null: ix->get(j); if (ref == null) break; // oops, bad input @@ -4150,6 +4161,7 @@ case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_EnclosingMethod): aname = cp.sym[cpool::s_EnclosingMethod]; putref(class_EnclosingMethod_RC.getRefN()); + CHECK_0; putref(class_EnclosingMethod_RDN.getRefN()); break; @@ -4168,6 +4180,7 @@ putu2(count = method_Exceptions_N.getInt()); for (j = 0; j < count; j++) { putref(method_Exceptions_RC.getRefN()); + CHECK_0; } break; @@ -4191,16 +4204,18 @@ // (253) [(1)(2)(2)] // (254) [(1)(2)(2)(2)] putu2(code_StackMapTable_offset.getInt()); + CHECK_0; for (int k = (tag - 251); k > 0; k--) { put_stackmap_type(); + CHECK_0; } } else { // (255) [(1)NH[(2)]NH[(2)]] putu2(code_StackMapTable_offset.getInt()); putu2(j2 = code_StackMapTable_local_N.getInt()); - while (j2-- > 0) put_stackmap_type(); + while (j2-- > 0) {put_stackmap_type(); CHECK_0;} putu2(j2 = code_StackMapTable_stack_N.getInt()); - while (j2-- > 0) put_stackmap_type(); + while (j2-- > 0) {put_stackmap_type(); CHECK_0;} } } break; @@ -4224,7 +4239,9 @@ bii += code_LocalVariableTable_span_O.getInt(); putu2(to_bci(bii) - bci); putref(code_LocalVariableTable_name_RU.getRefN()); + CHECK_0; putref(code_LocalVariableTable_type_RS.getRefN()); + CHECK_0; putu2(code_LocalVariableTable_slot.getInt()); } break; @@ -4239,7 +4256,9 @@ bii += code_LocalVariableTypeTable_span_O.getInt(); putu2(to_bci(bii) - bci); putref(code_LocalVariableTypeTable_name_RU.getRefN()); + CHECK_0; putref(code_LocalVariableTypeTable_type_RS.getRefN()); + CHECK_0; putu2(code_LocalVariableTypeTable_slot.getInt()); } break; @@ -4267,7 +4286,7 @@ break; } } - + CHECK_0; if (aname == null) { // Unparse a compressor-defined attribute. layout_definition* lo = ad.getLayout(idx); @@ -4366,6 +4385,7 @@ julong indexMask = ad.flagIndexMask(); cur_class = class_this.getRef(); + CHECK; cur_super = class_super.getRef(); CHECK; @@ -4380,6 +4400,7 @@ putu2(num = class_interface_count.getInt()); for (i = 0; i < num; i++) { putref(class_interface.getRef()); + CHECK; } write_members(class_field_count.getInt(), ATTR_CONTEXT_FIELD); @@ -4460,7 +4481,9 @@ flags &= ~ACC_IC_LONG_FORM; // clear high bit if set to get clean zero extra_ic.flags = flags; extra_ic.outer = class_InnerClasses_outer_RCN.getRefN(); + CHECK; extra_ic.name = class_InnerClasses_name_RUN.getRefN(); + CHECK; // Detect if this is an exact copy of the global tuple. if (global_ic != null) { if (global_ic->flags != extra_ic.flags || --- old/jdk/src/share/native/sun/awt/image/awt_parseImage.c 2013-02-07 17:07:33.000000000 +0100 +++ new/jdk/src/share/native/sun/awt/image/awt_parseImage.c 2013-02-07 17:07:33.000000000 +0100 @@ -114,6 +114,62 @@ return status; } +/* Verifies whether the channel offsets are sane and correspond to the type of + * the raster. + * + * Return value: + * 0: Failure: channel offsets are invalid + * 1: Success + */ +static int checkChannelOffsets(RasterS_t *rasterP, int dataArrayLength) { + int i, lastPixelOffset, lastScanOffset; + switch (rasterP->rasterType) { + case COMPONENT_RASTER_TYPE: + if (!SAFE_TO_MULT(rasterP->height, rasterP->scanlineStride)) { + return 0; + } + if (!SAFE_TO_MULT(rasterP->width, rasterP->pixelStride)) { + return 0; + } + + lastScanOffset = (rasterP->height - 1) * rasterP->scanlineStride; + lastPixelOffset = (rasterP->width - 1) * rasterP->pixelStride; + + + if (!SAFE_TO_ADD(lastPixelOffset, lastScanOffset)) { + return 0; + } + + lastPixelOffset += lastScanOffset; + + for (i = 0; i < rasterP->numDataElements; i++) { + int off = rasterP->chanOffsets[i]; + int size = lastPixelOffset + off; + + if (off < 0 || !SAFE_TO_ADD(lastPixelOffset, off)) { + return 0; + } + + if (size < lastPixelOffset || size >= dataArrayLength) { + // an overflow, or insufficient buffer capacity + return 0; + } + } + return 1; + case BANDED_RASTER_TYPE: + // NB:caller does not support the banded rasters yet, + // so this branch of the code must be re-defined in + // order to provide valid criteria for the data offsets + // verification, when/if banded rasters will be supported. + // At the moment, we prohibit banded rasters as well. + return 0; + default: + // PACKED_RASTER_TYPE: does not support channel offsets + // UNKNOWN_RASTER_TYPE: should not be used, likely indicates an error + return 0; + } +} + /* Parse the raster. All of the raster information is returned in the * rasterP structure. * @@ -125,7 +181,6 @@ int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) { jobject joffs = NULL; /* int status;*/ - int isDiscrete = TRUE; if (JNU_IsNull(env, jraster)) { JNU_ThrowNullPointerException(env, "null Raster object"); @@ -155,6 +210,9 @@ return -1; } + // make sure that the raster type is initialized + rasterP->rasterType = UNKNOWN_RASTER_TYPE; + if (rasterP->numBands <= 0 || rasterP->numBands > MAX_NUMBANDS) { @@ -165,9 +223,14 @@ return 0; } + rasterP->sppsm.isUsed = 0; + if ((*env)->IsInstanceOf(env, rasterP->jsampleModel, (*env)->FindClass(env,"java/awt/image/SinglePixelPackedSampleModel"))) { jobject jmask, joffs, jnbits; + + rasterP->sppsm.isUsed = 1; + rasterP->sppsm.maxBitSize = (*env)->GetIntField(env, rasterP->jsampleModel, g_SPPSMmaxBitID); @@ -254,7 +317,6 @@ } rasterP->chanOffsets[0] = (*env)->GetIntField(env, jraster, g_BPRdataBitOffsetID); rasterP->dataType = BYTE_DATA_TYPE; - isDiscrete = FALSE; } else { rasterP->type = sun_awt_image_IntegerComponentRaster_TYPE_CUSTOM; @@ -265,7 +327,19 @@ return 0; } - if (isDiscrete) { + // do basic validation of the raster structure + if (rasterP->width <= 0 || rasterP->height <= 0 || + rasterP->pixelStride <= 0 || rasterP->scanlineStride <= 0) + { + // invalid raster + return -1; + } + + // channel (data) offsets + switch (rasterP->rasterType) { + case COMPONENT_RASTER_TYPE: + case BANDED_RASTER_TYPE: // note that this routine does not support banded rasters at the moment + // get channel (data) offsets rasterP->chanOffsets = NULL; if (SAFE_TO_ALLOC_2(rasterP->numDataElements, sizeof(jint))) { rasterP->chanOffsets = @@ -278,10 +352,21 @@ } (*env)->GetIntArrayRegion(env, joffs, 0, rasterP->numDataElements, rasterP->chanOffsets); + if (rasterP->jdata == NULL) { + // unable to verify the raster + return -1; + } + // verify whether channel offsets look sane + if (!checkChannelOffsets(rasterP, (*env)->GetArrayLength(env, rasterP->jdata))) { + return -1; + } + break; + default: + ; // PACKED_RASTER_TYPE does not use the channel offsets. } - /* additioanl check for sppsm fields validity: make sure that - * size of raster samples doesn't exceed the data type cpacity. + /* additional check for sppsm fields validity: make sure that + * size of raster samples doesn't exceed the data type capacity. */ if (rasterP->dataType > UNKNOWN_DATA_TYPE && /* data type has been recognized */ rasterP->sppsm.maxBitSize > 0 && /* raster has SPP sample model */ @@ -631,6 +716,21 @@ } else if (cmodelP->cmType == DIRECT_CM_TYPE || cmodelP->cmType == PACKED_CM_TYPE) { int i; + + /* do some sanity check first: make sure that + * - sample model is SinglePixelPackedSampleModel + * - number of bands in the raster corresponds to the number + * of color components in the color model + */ + if (!rasterP->sppsm.isUsed || + rasterP->numBands != cmodelP->numComponents) + { + /* given raster is not compatible with the color model, + * so the operation has to be aborted. + */ + return -1; + } + if (cmodelP->maxNbits > 8) { hintP->needToExpand = TRUE; hintP->expandToNbits = cmodelP->maxNbits; --- old/jdk/src/share/native/sun/awt/image/awt_parseImage.h 2013-02-07 17:07:34.000000000 +0100 +++ new/jdk/src/share/native/sun/awt/image/awt_parseImage.h 2013-02-07 17:07:34.000000000 +0100 @@ -95,6 +95,7 @@ jint offsets[MAX_NUMBANDS]; jint nBits[MAX_NUMBANDS]; jint maxBitSize; + jint isUsed; // flag to indicate whether the raster sample model is SPPSM } SPPSampleModelS_t; /* Struct that holds information for the Raster object */ --- old/jdk/src/share/native/sun/awt/medialib/safe_alloc.h 2013-02-07 17:07:35.000000000 +0100 +++ new/jdk/src/share/native/sun/awt/medialib/safe_alloc.h 2013-02-07 17:07:34.000000000 +0100 @@ -41,5 +41,10 @@ (((w) > 0) && ((h) > 0) && ((sz) > 0) && \ (((0xffffffffu / ((juint)(w))) / ((juint)(h))) > ((juint)(sz)))) +#define SAFE_TO_MULT(a, b) \ + (((a) > 0) && ((b) >= 0) && ((0x7fffffff / (a)) > (b))) + +#define SAFE_TO_ADD(a, b) \ + (((a) >= 0) && ((b) >= 0) && ((0x7fffffff - (a)) > (b))) #endif // __SAFE_ALLOC_H__ --- old/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c 2013-02-07 17:07:35.000000000 +0100 +++ new/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c 2013-02-07 17:07:35.000000000 +0100 @@ -133,6 +133,10 @@ ImageFormat srcFormat; jpeg_read_header(cinfo, TRUE); + + // SplashScreen jpeg converter expects data in RGB format only + cinfo->out_color_space = JCS_RGB; + jpeg_start_decompress(cinfo); SplashCleanup(splash); --- old/jdk/src/solaris/classes/sun/nio/ch/SctpChannelImpl.java 2013-02-07 17:07:36.000000000 +0100 +++ new/jdk/src/solaris/classes/sun/nio/ch/SctpChannelImpl.java 2013-02-07 17:07:36.000000000 +0100 @@ -1019,13 +1019,21 @@ boolean unordered, int ppid) throws IOException { + InetAddress addr = null; // no preferred address + int port = 0; + if (target != null) { + InetSocketAddress isa = Net.checkAddress(target); + addr = isa.getAddress(); + port = isa.getPort(); + } + int pos = bb.position(); int lim = bb.limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); - int written = send0(fd, ((DirectBuffer)bb).address() + pos, - rem, target, -1 /*121*/, streamNumber, unordered, ppid); + int written = send0(fd, ((DirectBuffer)bb).address() + pos, rem, addr, + port, -1 /*121*/, streamNumber, unordered, ppid); if (written > 0) bb.position(pos + written); return written; @@ -1084,7 +1092,7 @@ long address, int length, boolean peek) throws IOException; static native int send0(int fd, long address, int length, - SocketAddress target, int assocId, int streamNumber, + InetAddress addr, int port, int assocId, int streamNumber, boolean unordered, int ppid) throws IOException; private static native int checkConnect(FileDescriptor fd, boolean block, --- old/jdk/src/solaris/classes/sun/nio/ch/SctpMultiChannelImpl.java 2013-02-07 17:07:37.000000000 +0100 +++ new/jdk/src/solaris/classes/sun/nio/ch/SctpMultiChannelImpl.java 2013-02-07 17:07:37.000000000 +0100 @@ -880,13 +880,20 @@ boolean unordered, int ppid) throws IOException { + InetAddress addr = null; // no preferred address + int port = 0; + if (target != null) { + InetSocketAddress isa = Net.checkAddress(target); + addr = isa.getAddress(); + port = isa.getPort(); + } int pos = bb.position(); int lim = bb.limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); - int written = send0(fd, ((DirectBuffer)bb).address() + pos, - rem, target, assocId, streamNumber, unordered, ppid); + int written = send0(fd, ((DirectBuffer)bb).address() + pos, rem, addr, + port, assocId, streamNumber, unordered, ppid); if (written > 0) bb.position(pos + written); return written; @@ -967,13 +974,14 @@ private static int send0(int fd, long address, int length, - SocketAddress target, + InetAddress addr, + int port, int assocId, int streamNumber, boolean unordered, int ppid) throws IOException { - return SctpChannelImpl.send0(fd, address, length, target, assocId, + return SctpChannelImpl.send0(fd, address, length, addr, port, assocId, streamNumber, unordered, ppid); } --- old/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c 2013-02-07 17:07:38.000000000 +0100 +++ new/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c 2013-02-07 17:07:38.000000000 +0100 @@ -46,8 +46,6 @@ #include "sun_nio_ch_DatagramChannelImpl.h" -static jfieldID isa_addrID; /* address in java.net.InetSocketAddress */ -static jfieldID isa_portID; /* port in java.net.InetSocketAddress */ static jfieldID dci_senderID; /* sender in sun.nio.ch.DatagramChannelImpl */ static jfieldID dci_senderAddrID; /* sender InetAddress in sun.nio.ch.DatagramChannelImpl */ static jfieldID dci_senderPortID; /* sender port in sun.nio.ch.DatagramChannelImpl */ @@ -61,9 +59,6 @@ isa_class = (*env)->NewGlobalRef(env, clazz); isa_ctorID = (*env)->GetMethodID(env, clazz, "", "(Ljava/net/InetAddress;I)V"); - isa_addrID = (*env)->GetFieldID(env, clazz, "addr", - "Ljava/net/InetAddress;"); - isa_portID = (*env)->GetFieldID(env, clazz, "port", "I"); clazz = (*env)->FindClass(env, "sun/nio/ch/DatagramChannelImpl"); dci_senderID = (*env)->GetFieldID(env, clazz, "sender", @@ -212,15 +207,13 @@ JNIEXPORT jint JNICALL Java_sun_nio_ch_DatagramChannelImpl_send0(JNIEnv *env, jobject this, jboolean preferIPv6, jobject fdo, jlong address, - jint len, jobject dest) + jint len, jobject destAddress, jint destPort) { jint fd = fdval(env, fdo); void *buf = (void *)jlong_to_ptr(address); SOCKADDR sa; int sa_len = SOCKADDR_LEN; jint n = 0; - jobject destAddress = (*env)->GetObjectField(env, dest, isa_addrID); - jint destPort = (*env)->GetIntField(env, dest, isa_portID); if (len > MAX_PACKET_LEN) { len = MAX_PACKET_LEN; --- old/jdk/src/solaris/native/sun/nio/ch/SctpChannelImpl.c 2013-02-07 17:07:39.000000000 +0100 +++ new/jdk/src/solaris/native/sun/nio/ch/SctpChannelImpl.c 2013-02-07 17:07:38.000000000 +0100 @@ -67,8 +67,6 @@ static jmethodID spc_ctrID; /* sun.nio.ch.SctpPeerAddressChanged. */ static jclass ss_class; /* sun.nio.ch.SctpShutdown */ static jmethodID ss_ctrID; /* sun.nio.ch.SctpShutdown. */ -static jfieldID isa_addrID; /* java.net.InetSocketAddress.addr */ -static jfieldID isa_portID; /* java.net.InetSocketAddress.port */ /* defined in SctpNet.c */ jobject SockAddrToInetSocketAddress(JNIEnv* env, struct sockaddr* addr); @@ -136,13 +134,6 @@ CHECK_NULL(ss_class); ss_ctrID = (*env)->GetMethodID(env, cls, "", "(I)V"); CHECK_NULL(ss_ctrID); - - /* InetSocketAddress */ - cls = (*env)->FindClass(env, "java/net/InetSocketAddress"); - CHECK_NULL(cls); - isa_addrID = (*env)->GetFieldID(env, cls, "addr", "Ljava/net/InetAddress;"); - CHECK_NULL(isa_addrID); - isa_portID = (*env)->GetFieldID(env, cls, "port", "I"); } void getControlData @@ -507,12 +498,12 @@ /* * Class: sun_nio_ch_SctpChannelImpl * Method: send0 - * Signature: (IJILjava/net/SocketAddress;IIZI)I + * Signature: (IJILjava/net/InetAddress;IIIZI)I */ JNIEXPORT jint JNICALL Java_sun_nio_ch_SctpChannelImpl_send0 (JNIEnv *env, jclass klass, jint fd, jlong address, jint length, - jobject saTarget, jint assocId, jint streamNumber, jboolean unordered, - jint ppid) { + jobject targetAddress, jint targetPort, jint assocId, jint streamNumber, + jboolean unordered, jint ppid) { SOCKADDR sa; int sa_len = sizeof(sa); ssize_t rv = 0; @@ -524,17 +515,13 @@ struct controlData cdata[1]; /* SctpChannel: - * saTarget may contain the preferred address or NULL to use primary, + * targetAddress may contain the preferred address or NULL to use primary, * assocId will always be -1 * SctpMultiChannell: - * Setup new association, saTarget will contain address, assocId = -1 - * Association already existing, assocId != -1, saTarget = preferred addr + * Setup new association, targetAddress will contain address, assocId = -1 + * Association already existing, assocId != -1, targetAddress = preferred addr */ - if (saTarget != NULL /*&& assocId <= 0*/) { - - jobject targetAddress = (*env)->GetObjectField(env, saTarget, isa_addrID); - jint targetPort = (*env)->GetIntField(env, saTarget, isa_portID); - + if (targetAddress != NULL /*&& assocId <= 0*/) { if (NET_InetAddressToSockaddr(env, targetAddress, targetPort, (struct sockaddr *)&sa, &sa_len, JNI_TRUE) != 0) { --- old/jdk/src/windows/bin/java_md.c 2013-02-07 17:07:39.000000000 +0100 +++ new/jdk/src/windows/bin/java_md.c 2013-02-07 17:07:39.000000000 +0100 @@ -101,7 +101,6 @@ /* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */ #define D3D_PRELOAD_FUNC "preloadD3D" - /* Extracts value of a parameter with the specified name * from command line argument (returns pointer in the argument). * Returns NULL if the argument does not contains the parameter. @@ -202,7 +201,7 @@ } JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg", - jrepath, FILESEP, FILESEP, (char*)GetArch(), FILESEP); + jrepath, FILESEP, FILESEP, (char*)GetArch(), FILESEP); /* Find the specified JVM type */ if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) { @@ -276,7 +275,8 @@ #endif #ifdef CRT_DLL if (GetJREPath(crtpath, MAXPATHLEN)) { - if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") + JLI_StrLen(CRT_DLL) >= MAXPATHLEN) { + if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") + + JLI_StrLen(CRT_DLL) >= MAXPATHLEN) { JLI_ReportErrorMessage(JRE_ERROR11); return JNI_FALSE; } @@ -347,7 +347,8 @@ if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) { JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype); } else { - JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL, jrepath, jvmtype); + JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL, + jrepath, jvmtype); } if (stat(jvmpath, &s) == 0) { return JNI_TRUE; @@ -525,6 +526,37 @@ } return (counts * 1000 * 1000)/counterFrequency.QuadPart; } +/* + * windows snprintf does not guarantee a null terminator in the buffer, + * if the computed size is equal to or greater than the buffer size, + * as well as error conditions. This function guarantees a null terminator + * under all these conditions. An unreasonable buffer or size will return + * an error value. Under all other conditions this function will return the + * size of the bytes actually written minus the null terminator, similar + * to ansi snprintf api. Thus when calling this function the caller must + * ensure storage for the null terminator. + */ +int +JLI_Snprintf(char* buffer, size_t size, const char* format, ...) { + int rc; + va_list vl; + if (size == 0 || buffer == NULL) + return -1; + buffer[0] = '\0'; + va_start(vl, format); + rc = vsnprintf(buffer, size, format, vl); + va_end(vl); + /* force a null terminator, if something is amiss */ + if (rc < 0) { + /* apply ansi semantics */ + buffer[size - 1] = '\0'; + return size; + } else if (rc == size) { + /* force a null terminator */ + buffer[size - 1] = '\0'; + } + return rc; +} void JLI_ReportErrorMessage(const char* fmt, ...) { @@ -880,7 +912,7 @@ */ void ExecJRE(char *jre, char **argv) { - int len; + jint len; char path[MAXPATHLEN + 1]; const char *progname = GetProgramName(); @@ -1417,7 +1449,10 @@ // we add the indicator tlen = 1 + JLI_StrLen(strv[i]) + 1; nargv[i] = (char *) JLI_MemAlloc(tlen); - JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F', strv[i]); + if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F', + strv[i]) < 0) { + return NULL; + } JLI_TraceLauncher("%s\n", nargv[i]); } --- old/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java 2013-02-07 17:07:40.000000000 +0100 +++ new/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java 2013-02-07 17:07:40.000000000 +0100 @@ -491,14 +491,15 @@ try { replaceSurfaceData(); } catch (InvalidPipeException e) { - // REMIND : what do we do if our surface creation failed? + // REMIND : what do we do if our surface creation failed? } } } }; + Component c = (Component)target; // Fix 6255371. - if (!PaintEventDispatcher.getPaintEventDispatcher().queueSurfaceDataReplacing((Component)target, r)) { - postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), r)); + if (!PaintEventDispatcher.getPaintEventDispatcher().queueSurfaceDataReplacing(c, r)) { + postEvent(new InvocationEvent(c, r)); } } @@ -620,7 +621,7 @@ } public void disposeLater() { - postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), new Runnable() { + postEvent(new InvocationEvent(target, new Runnable() { public void run() { dispose(); } --- old/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java 2013-02-07 17:07:41.000000000 +0100 +++ new/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java 2013-02-07 17:07:41.000000000 +0100 @@ -29,12 +29,9 @@ import java.awt.*; import java.awt.event.*; import java.awt.peer.ComponentPeer; -import java.util.*; -import java.awt.color.*; import java.awt.image.*; import sun.awt.image.ByteInterleavedRaster; import sun.security.action.GetPropertyAction; -import java.lang.reflect.*; public class WEmbeddedFrame extends EmbeddedFrame { @@ -232,11 +229,13 @@ } else { // To avoid focus concurrence b/w IE and EmbeddedFrame // activation is postponed by means of posting it to EDT. - EventQueue.invokeLater(new Runnable() { - public void run() { - ((WEmbeddedFramePeer)getPeer()).synthesizeWmActivate(true); - } - }); + Runnable r = new Runnable() { + public void run() { + ((WEmbeddedFramePeer)getPeer()).synthesizeWmActivate(true); + } + }; + WToolkit.postEvent(WToolkit.targetToAppContext(this), + new InvocationEvent(this, r)); } } --- old/jdk/src/windows/native/sun/nio/ch/DatagramChannelImpl.c 2013-02-07 17:07:42.000000000 +0100 +++ new/jdk/src/windows/native/sun/nio/ch/DatagramChannelImpl.c 2013-02-07 17:07:42.000000000 +0100 @@ -34,8 +34,6 @@ #include "net_util.h" #include -static jfieldID isa_addrID; /* address in java.net.InetSocketAddress */ -static jfieldID isa_portID; /* port in java.net.InetSocketAddress */ static jfieldID dci_senderID; /* sender in sun.nio.ch.DatagramChannelImpl */ static jfieldID dci_senderAddrID; /* sender InetAddress in sun.nio.ch.DatagramChannelImpl */ static jfieldID dci_senderPortID; /* sender port in sun.nio.ch.DatagramChannelImpl */ @@ -50,9 +48,6 @@ isa_class = (*env)->NewGlobalRef(env, clazz); isa_ctorID = (*env)->GetMethodID(env, clazz, "", "(Ljava/net/InetAddress;I)V"); - isa_addrID = (*env)->GetFieldID(env, clazz, "addr", - "Ljava/net/InetAddress;"); - isa_portID = (*env)->GetFieldID(env, clazz, "port", "I"); clazz = (*env)->FindClass(env, "sun/nio/ch/DatagramChannelImpl"); dci_senderID = (*env)->GetFieldID(env, clazz, "sender", @@ -214,15 +209,14 @@ JNIEXPORT jint JNICALL Java_sun_nio_ch_DatagramChannelImpl_send0(JNIEnv *env, jobject this, jboolean preferIPv6, jobject fdo, - jlong address, jint len, jobject dest) + jlong address, jint len, + jobject destAddress, jint destPort) { jint fd = fdval(env, fdo); void *buf = (void *)jlong_to_ptr(address); SOCKETADDRESS sa; int sa_len; jint rv = 0; - jobject destAddress = (*env)->GetObjectField(env, dest, isa_addrID); - jint destPort = (*env)->GetIntField(env, dest, isa_portID); if (NET_InetAddressToSockaddr(env, destAddress, destPort, (struct sockaddr *)&sa, --- old/jdk/src/windows/native/sun/windows/awt_TextComponent.cpp 2013-02-07 17:07:43.000000000 +0100 +++ new/jdk/src/windows/native/sun/windows/awt_TextComponent.cpp 2013-02-07 17:07:42.000000000 +0100 @@ -53,14 +53,12 @@ * AwtTextComponent fields */ -/* java.awt.TextComponent fields */ -jfieldID AwtTextComponent::canAccessClipboardID; - - /************************************************************************ * AwtTextComponent methods */ +jmethodID AwtTextComponent::canAccessClipboardMID; + AwtTextComponent::AwtTextComponent() { m_synthetic = FALSE; m_lStartPos = -1; @@ -367,8 +365,7 @@ } jobject target = GetTarget(env); jboolean canAccessClipboard = - env->GetBooleanField(target, - AwtTextComponent::canAccessClipboardID); + env->CallBooleanMethod (target, AwtTextComponent::canAccessClipboardMID); env->DeleteLocalRef(target); return (canAccessClipboard) ? mrDoDefault : mrConsume; } @@ -854,12 +851,13 @@ { TRY; - cls = env->FindClass("java/awt/TextComponent"); - if (cls != NULL) { - AwtTextComponent::canAccessClipboardID = - env->GetFieldID(cls, "canAccessClipboard", "Z"); - DASSERT(AwtTextComponent::canAccessClipboardID != NULL); - } + jclass textComponentClassID = env->FindClass("java/awt/TextComponent"); + AwtTextComponent::canAccessClipboardMID = + env->GetMethodID(textComponentClassID, + "canAccessClipboard", "()Z"); + env->DeleteLocalRef(textComponentClassID); + + DASSERT(AwtTextComponent::canAccessClipboardMID != NULL) CATCH_BAD_ALLOC; } --- old/jdk/src/windows/native/sun/windows/awt_TextComponent.h 2013-02-07 17:07:43.000000000 +0100 +++ new/jdk/src/windows/native/sun/windows/awt_TextComponent.h 2013-02-07 17:07:43.000000000 +0100 @@ -42,8 +42,7 @@ class AwtTextComponent : public AwtComponent { public: - /* java.awt.TextComponent canAccessClipboard field ID */ - static jfieldID canAccessClipboardID; + static jmethodID canAccessClipboardMID; AwtTextComponent(); --- old/jdk/test/Makefile 2013-02-07 17:07:44.000000000 +0100 +++ new/jdk/test/Makefile 2013-02-07 17:07:44.000000000 +0100 @@ -512,6 +512,7 @@ javax/script \ java/sql javax/sql \ javax/smartcardio \ + javax/xml/soap \ com/sun/xml \ javax/xml/ws com/sun/internal/ws \ com/sun/org/apache/xerces \ --- old/jdk/test/java/nio/channels/DatagramChannel/SendToUnresolved.java 2013-02-07 17:07:45.000000000 +0100 +++ new/jdk/test/java/nio/channels/DatagramChannel/SendToUnresolved.java 2013-02-07 17:07:45.000000000 +0100 @@ -42,7 +42,7 @@ try { dc.send(bb, sa); throw new RuntimeException("Expected exception not thrown"); - } catch (IOException e) { + } catch (IOException | UnresolvedAddressException e) { // Correct result } dc.close(); --- old/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy 2013-02-07 17:07:46.000000000 +0100 +++ new/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy 2013-02-07 17:07:46.000000000 +0100 @@ -13,6 +13,7 @@ permission java.io.FilePermission ".${/}-", "read,write,delete"; permission java.lang.RuntimePermission "createClassLoader"; + permission java.lang.RuntimePermission "getClassLoader"; permission java.lang.RuntimePermission "setContextClassLoader"; // used by TestLibrary to determine test environment --- old/jdk/test/java/rmi/testlibrary/JavaVM.java 2013-02-07 17:07:47.000000000 +0100 +++ new/jdk/test/java/rmi/testlibrary/JavaVM.java 2013-02-07 17:07:46.000000000 +0100 @@ -133,6 +133,14 @@ return TestLibrary.getExtraProperty("jcov.options",""); } + public void start(Runnable runnable) throws IOException { + if (runnable == null) { + throw new NullPointerException("Runnable cannot be null."); + } + + start(); + new JavaVMCallbackHandler(runnable).start(); + } /** * Exec the VM as specified in this object's constructor. @@ -235,4 +243,35 @@ protected Process getVM() { return vm; } + + /** + * Handles calling the callback. + */ + private class JavaVMCallbackHandler extends Thread { + Runnable runnable; + + JavaVMCallbackHandler(Runnable runnable) { + this.runnable = runnable; + } + + + /** + * Wait for the Process to terminate and notify the callback. + */ + @Override + public void run() { + if (vm != null) { + try { + vm.waitFor(); + } catch(InterruptedException ie) { + // Restore the interrupted status + Thread.currentThread().interrupt(); + } + } + + if (runnable != null) { + runnable.run(); + } + } + } } --- old/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java 2013-02-07 17:07:47.000000000 +0100 +++ new/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java 2013-02-07 17:07:47.000000000 +0100 @@ -29,7 +29,7 @@ import javax.net.ssl.*; import java.lang.reflect.*; -import sun.security.util.KeyLength; +import sun.security.util.KeyUtil; public class ShortRSAKeyWithinTLS { @@ -175,13 +175,13 @@ privateKey = (PrivateKey)ks.getKey(keyAlias, null); publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey(); - int privateKeySize = KeyLength.getKeySize(privateKey); + int privateKeySize = KeyUtil.getKeySize(privateKey); if (privateKeySize != keySize) { throw new Exception("Expected key size is " + keySize + ", but the private key size is " + privateKeySize); } - int publicKeySize = KeyLength.getKeySize(publicKey); + int publicKeySize = KeyUtil.getKeySize(publicKey); if (publicKeySize != keySize) { throw new Exception("Expected key size is " + keySize + ", but the public key size is " + publicKeySize); --- old/jdk/test/tools/launcher/ToolsOpts.java 2013-02-07 17:07:48.000000000 +0100 +++ new/jdk/test/tools/launcher/ToolsOpts.java 2013-02-07 17:07:48.000000000 +0100 @@ -23,6 +23,7 @@ /* * @test + * @bug 8002091 * @summary Test options patterns for javac,javah,javap and javadoc using * javac as a test launcher. Create a dummy javac and intercept options to check * reception of options as passed through the launcher without having to launch --- /dev/null 2013-02-05 10:56:25.513074029 +0100 +++ new/jdk/src/share/classes/sun/security/util/KeyUtil.java 2013-02-07 17:07:49.000000000 +0100 @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2012, 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 sun.security.util; + +import java.security.Key; +import java.security.PrivilegedAction; +import java.security.AccessController; +import java.security.InvalidKeyException; +import java.security.interfaces.ECKey; +import java.security.interfaces.RSAKey; +import java.security.interfaces.DSAKey; +import java.security.spec.KeySpec; +import javax.crypto.SecretKey; +import javax.crypto.interfaces.DHKey; +import javax.crypto.interfaces.DHPublicKey; +import javax.crypto.spec.DHParameterSpec; +import javax.crypto.spec.DHPublicKeySpec; +import java.math.BigInteger; + +/** + * A utility class to get key length, valiate keys, etc. + */ +public final class KeyUtil { + + /** + * Returns the key size of the given key object in bits. + * + * @param key the key object, cannot be null + * @return the key size of the given key object in bits, or -1 if the + * key size is not accessible + */ + public static final int getKeySize(Key key) { + int size = -1; + + if (key instanceof Length) { + try { + Length ruler = (Length)key; + size = ruler.length(); + } catch (UnsupportedOperationException usoe) { + // ignore the exception + } + + if (size >= 0) { + return size; + } + } + + // try to parse the length from key specification + if (key instanceof SecretKey) { + SecretKey sk = (SecretKey)key; + String format = sk.getFormat(); + if ("RAW".equals(format) && sk.getEncoded() != null) { + size = (sk.getEncoded().length * 8); + } // Otherwise, it may be a unextractable key of PKCS#11, or + // a key we are not able to handle. + } else if (key instanceof RSAKey) { + RSAKey pubk = (RSAKey)key; + size = pubk.getModulus().bitLength(); + } else if (key instanceof ECKey) { + ECKey pubk = (ECKey)key; + size = pubk.getParams().getOrder().bitLength(); + } else if (key instanceof DSAKey) { + DSAKey pubk = (DSAKey)key; + size = pubk.getParams().getP().bitLength(); + } else if (key instanceof DHKey) { + DHKey pubk = (DHKey)key; + size = pubk.getParams().getP().bitLength(); + } // Otherwise, it may be a unextractable key of PKCS#11, or + // a key we are not able to handle. + + return size; + } + + /** + * Returns whether the key is valid or not. + *

    + * Note that this method is only apply to DHPublicKey at present. + * + * @param publicKey + * the key object, cannot be null + * + * @throws NullPointerException if {@code publicKey} is null + * @throws InvalidKeyException if {@code publicKey} is invalid + */ + public static final void validate(Key key) + throws InvalidKeyException { + if (key == null) { + throw new NullPointerException( + "The key to be validated cannot be null"); + } + + if (key instanceof DHPublicKey) { + validateDHPublicKey((DHPublicKey)key); + } + } + + + /** + * Returns whether the key spec is valid or not. + *

    + * Note that this method is only apply to DHPublicKeySpec at present. + * + * @param keySpec + * the key spec object, cannot be null + * + * @throws NullPointerException if {@code keySpec} is null + * @throws InvalidKeyException if {@code keySpec} is invalid + */ + public static final void validate(KeySpec keySpec) + throws InvalidKeyException { + if (keySpec == null) { + throw new NullPointerException( + "The key spec to be validated cannot be null"); + } + + if (keySpec instanceof DHPublicKeySpec) { + validateDHPublicKey((DHPublicKeySpec)keySpec); + } + } + + /** + * Returns whether the specified provider is Oracle provider or not. + *

    + * Note that this method is only apply to SunJCE and SunPKCS11 at present. + * + * @param providerName + * the provider name + * @return true if, and only if, the provider of the specified + * {@code providerName} is Oracle provider + */ + public static final boolean isOracleJCEProvider(String providerName) { + return providerName != null && (providerName.equals("SunJCE") || + providerName.startsWith("SunPKCS11")); + } + + /** + * Returns whether the Diffie-Hellman public key is valid or not. + * + * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to + * validate Diffie-Hellman public keys: + * 1. Verify that y lies within the interval [2,p-1]. If it does not, + * the key is invalid. + * 2. Compute y^q mod p. If the result == 1, the key is valid. + * Otherwise the key is invalid. + */ + private static void validateDHPublicKey(DHPublicKey publicKey) + throws InvalidKeyException { + DHParameterSpec paramSpec = publicKey.getParams(); + + BigInteger p = paramSpec.getP(); + BigInteger g = paramSpec.getG(); + BigInteger y = publicKey.getY(); + + validateDHPublicKey(p, g, y); + } + + private static void validateDHPublicKey(DHPublicKeySpec publicKeySpec) + throws InvalidKeyException { + validateDHPublicKey(publicKeySpec.getP(), + publicKeySpec.getG(), publicKeySpec.getY()); + } + + private static void validateDHPublicKey(BigInteger p, + BigInteger g, BigInteger y) throws InvalidKeyException { + + // For better interoperability, the interval is limited to [2, p-2]. + BigInteger leftOpen = BigInteger.ONE; + BigInteger rightOpen = p.subtract(BigInteger.ONE); + if (y.compareTo(leftOpen) <= 0) { + throw new InvalidKeyException( + "Diffie-Hellman public key is too small"); + } + if (y.compareTo(rightOpen) >= 0) { + throw new InvalidKeyException( + "Diffie-Hellman public key is too large"); + } + + // Don't bother to check against the y^q mod p if safe primes are used. + } +} + --- /dev/null 2013-02-05 10:56:25.513074029 +0100 +++ new/jdk/test/java/util/logging/CustomLogManager.java 2013-02-07 17:07:50.000000000 +0100 @@ -0,0 +1,177 @@ +/* + * 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.*; +import java.util.*; +import java.util.logging.*; + +/* + * Custom LogManager implementation to verify that the implementation delegates + * to the LogManager subclass to register both system logger and user logger. + * + * The LogManager implementation is the one configuring the logger's property + * such as level, handler, etc. + */ +public class CustomLogManager extends LogManager { + static LogManager INSTANCE; + Map namedLoggers = new HashMap<>(); + Properties props = initConfig(); + public CustomLogManager() { + if (INSTANCE != null) { + throw new RuntimeException("CustomLogManager already created"); + } + INSTANCE = this; + } + + public synchronized boolean addLogger(Logger logger) { + String name = logger.getName(); + if (namedLoggers.containsKey(name)) { + return false; + } + namedLoggers.put(name, logger); + // set level + if (props.get(name + ".level") != null) { + logger.setLevel(Level.parse(props.getProperty(name + ".level"))); + } + // add handlers + if (props.get(name + ".handlers") != null && logger.getHandlers().length == 0) { + logger.addHandler(new CustomHandler()); + } + // add parent loggers + int ix = 1; + for (;;) { + int ix2 = name.indexOf(".", ix); + if (ix2 < 0) { + break; + } + String pname = name.substring(0, ix2); + if (props.get(pname + ".level") != null || + props.get(pname + ".handlers") != null) { + // This pname has a level/handlers definition. + // Make sure it exists. + // + // The test doesn't set the parent for simplicity. + if (!namedLoggers.containsKey(pname)) { + Logger.getLogger(pname); + } + } + ix = ix2 + 1; + } + return true; + } + + public synchronized Logger getLogger(String name) { + return namedLoggers.get(name); + } + + public synchronized Enumeration getLoggerNames() { + return Collections.enumeration(namedLoggers.keySet()); + } + + public String getProperty(String name) { + return props.getProperty(name); + } + + public void readConfiguration() { + // do nothing + } + + public void readConfiguration(InputStream ins) { + // do nothing + } + + private Properties initConfig() { + Properties props = new Properties(); + props.put(".level", "CONFIG"); + props.put("CustomLogManagerTest.level", "WARNING"); + props.put("CustomLogManagerTest.handlers", "CustomLogManager$CustomHandler"); + props.put("SimpleLogManager.level", "INFO"); + props.put("SimpleLogManager.handlers", "CustomLogManager$CustomHandler"); + props.put("CustomLogManager$CustomHandler.level", "WARNING"); + props.put(".handlers", "CustomLogManager$CustomHandler"); + props.put("org.foo.bar.level", "SEVERE"); + props.put("org.foo.handlers", "CustomLogManager$CustomHandler"); + props.put("org.openjdk.level", "SEVERE"); + props.put("org.openjdk.handlers", "CustomLogManager$CustomHandler"); + props.put("org.openjdk.core.level", "INFO"); + + return props; + } + + public static void checkLogger(String name) { + checkLogger(name, null); + } + + public static void checkLogger(String name, String resourceBundleName) { + Logger logger = INSTANCE.getLogger(name); + if (logger == null) { + throw new RuntimeException("Logger \"" + name + "\" not exist"); + } + System.out.format("Logger \"%s\" level=%s handlers=%s resourcebundle=%s%n", + name, logger.getLevel(), + Arrays.toString(logger.getHandlers()), + logger.getResourceBundleName()); + String rb = logger.getResourceBundleName(); + if (rb != resourceBundleName && (rb == null || rb.equals(resourceBundleName))) { + throw new RuntimeException("Logger \"" + name + + "\" unexpected resource bundle: " + rb); + } + + String value = INSTANCE.getProperty(name + ".level"); + String level = logger.getLevel() != null ? logger.getLevel().getName() : null; + if (level != value && (level == null || level.equals(value))) { + throw new RuntimeException("Logger \"" + name + "\" unexpected level: " + level); + } + + Handler[] handlers = logger.getHandlers(); + String hdl = INSTANCE.getProperty(name + ".handlers"); + if ((hdl == null && handlers.length != 0) || + (hdl != null && handlers.length != 1)) { + throw new RuntimeException("Logger \"" + name + "\" unexpected handler: " + + Arrays.toString(handlers)); + } + checkParents(name); + } + + private static void checkParents(String name) { + int ix = 1; + for (;;) { + int ix2 = name.indexOf(".", ix); + if (ix2 < 0) { + break; + } + String pname = name.substring(0, ix2); + if (INSTANCE.getProperty(pname + ".level") != null || + INSTANCE.getProperty(pname + ".handlers") != null) { + // This pname has a level/handlers definition. + // Make sure it exists. + checkLogger(pname); + } + ix = ix2 + 1; + } + } + + // only CustomLogManager can create an instance of CustomHandler + private class CustomHandler extends StreamHandler { + } +} --- /dev/null 2013-02-05 10:56:25.513074029 +0100 +++ new/jdk/test/java/util/logging/CustomLogManagerTest.java 2013-02-07 17:07:51.000000000 +0100 @@ -0,0 +1,63 @@ +/* + * 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.*; +import java.util.*; + +import java.util.logging.*; +import sun.util.logging.PlatformLogger; + +/* + * @test + * @bug 8005615 + * @summary Add loggers to custom log manager + * + * @compile -XDignore.symbol.file CustomLogManagerTest.java CustomLogManager.java + * @run main/othervm -Djava.util.logging.manager=CustomLogManager CustomLogManagerTest + */ +public class CustomLogManagerTest { + private static final String RESOURCE_BUNDLE = "sun.util.logging.resources.logging"; + public static void main(String[] args) { + String mgr = System.getProperty("java.util.logging.manager"); + if (!mgr.equals("CustomLogManager")) { + throw new RuntimeException("java.util.logging.manager not set"); + } + + Logger.getLogger(CustomLogManagerTest.class.getName()); + Logger.getLogger("org.foo.Foo"); + Logger.getLogger("org.foo.bar.Foo", RESOURCE_BUNDLE); + // platform logger will be set with the default system resource bundle + PlatformLogger.getLogger("org.openjdk.core.logger"); + + if (LogManager.getLogManager() != CustomLogManager.INSTANCE) { + throw new RuntimeException(LogManager.getLogManager() + " not CustomLogManager"); + } + + CustomLogManager.checkLogger(CustomLogManagerTest.class.getName()); + CustomLogManager.checkLogger("org.foo.Foo"); + CustomLogManager.checkLogger("org.foo.bar.Foo", RESOURCE_BUNDLE); + CustomLogManager.checkLogger(Logger.GLOBAL_LOGGER_NAME); + CustomLogManager.checkLogger(""); + CustomLogManager.checkLogger("org.openjdk.core.logger", RESOURCE_BUNDLE); + } +} --- /dev/null 2013-02-05 10:56:25.513074029 +0100 +++ new/jdk/test/java/util/logging/SimpleLogManager.java 2013-02-07 17:07:52.000000000 +0100 @@ -0,0 +1,113 @@ +/* + * 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.util.*; +import java.util.logging.*; +import sun.util.logging.PlatformLogger; + +/* + * @test + * @bug 8005615 + * @summary A LogManager subclass overrides its own implementation of named + * logger (see the subclassing information in the Logger class specification) + * + * @compile -XDignore.symbol.file CustomLogManager.java SimpleLogManager.java + * @run main/othervm -Djava.util.logging.manager=SimpleLogManager SimpleLogManager + */ +public class SimpleLogManager extends CustomLogManager { + public static void main(String[] args) { + String classname = System.getProperty("java.util.logging.manager"); + if (!classname.equals("SimpleLogManager")) { + throw new RuntimeException("java.util.logging.manager not set"); + } + + Logger logger = Logger.getLogger(SimpleLogManager.class.getName()); + Logger.getLogger("org.foo.bar.Foo"); + + // a platform logger used by the system code is just a Logger instance. + PlatformLogger.getLogger("org.openjdk.core.logger"); + + LogManager mgr = LogManager.getLogManager(); + if (mgr != CustomLogManager.INSTANCE || !(mgr instanceof SimpleLogManager)) { + throw new RuntimeException(LogManager.getLogManager() + " not SimpleLogManager"); + } + + checkCustomLogger(SimpleLogManager.class.getName(), null); + checkCustomLogger("org.foo.bar.Foo", null); + checkCustomLogger("org.openjdk.core.logger", "sun.util.logging.resources.logging"); + + // ## The LogManager.demandLogger method does not handle custom log manager + // ## that overrides the getLogger method to return a custom logger + // ## (see the test case in 8005640). Logger.getLogger may return + // ## a Logger instance but LogManager overrides it with a custom Logger + // ## instance like this case. + // + // However, the specification of LogManager and Logger subclassing is + // not clear whether this is supported or not. The following check + // just captures the current behavior. + if (logger instanceof CustomLogger) { + throw new RuntimeException(logger + " not CustomLogger"); + } + } + + private static void checkCustomLogger(String name, String resourceBundleName) { + CustomLogManager.checkLogger(name, resourceBundleName); + Logger logger1 = Logger.getLogger(name); + Logger logger2 = LogManager.getLogManager().getLogger(name); + if (logger1 != logger2) { + throw new RuntimeException(logger1 + " != " + logger2); + } + if (!(logger1 instanceof CustomLogger)) { + throw new RuntimeException(logger1 + " not CustomLogger"); + } + } + + /* + * This SimpleLogManager overrides the addLogger method to replace + * the given logger with a custom logger. + * + * It's unclear what the recommended way to use custom logger is. + * A LogManager subclass might override the getLogger method to return + * a custom Logger and create a new custom logger if not exist so that + * Logger.getLogger() can return a custom Logger instance but that violates + * the LogManager.getLogger() spec which should return null if not found. + */ + public synchronized boolean addLogger(Logger logger) { + String name = logger.getName(); + if (namedLoggers.containsKey(name)) { + return false; + } + CustomLogger newLogger = new CustomLogger(logger); + super.addLogger(newLogger); + return true; + } + + public class CustomLogger extends Logger { + CustomLogger(Logger logger) { + super(logger.getName(), logger.getResourceBundleName()); + } + CustomLogger(String name) { + super(name, null); + } + } +} --- old/jdk/src/share/classes/sun/security/util/KeyLength.java 2013-02-07 17:07:53.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2012, 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 sun.security.util; - -import java.security.Key; -import java.security.PrivilegedAction; -import java.security.AccessController; -import java.security.interfaces.ECKey; -import java.security.interfaces.RSAKey; -import java.security.interfaces.DSAKey; -import javax.crypto.SecretKey; -import javax.crypto.interfaces.DHKey; - -/** - * A utility class to get key length - */ -public final class KeyLength { - - /** - * Returns the key size of the given key object in bits. - * - * @param key the key object, cannot be null - * @return the key size of the given key object in bits, or -1 if the - * key size is not accessible - */ - final public static int getKeySize(Key key) { - int size = -1; - - if (key instanceof Length) { - try { - Length ruler = (Length)key; - size = ruler.length(); - } catch (UnsupportedOperationException usoe) { - // ignore the exception - } - - if (size >= 0) { - return size; - } - } - - // try to parse the length from key specification - if (key instanceof SecretKey) { - SecretKey sk = (SecretKey)key; - String format = sk.getFormat(); - if ("RAW".equals(format) && sk.getEncoded() != null) { - size = (sk.getEncoded().length * 8); - } // Otherwise, it may be a unextractable key of PKCS#11, or - // a key we are not able to handle. - } else if (key instanceof RSAKey) { - RSAKey pubk = (RSAKey)key; - size = pubk.getModulus().bitLength(); - } else if (key instanceof ECKey) { - ECKey pubk = (ECKey)key; - size = pubk.getParams().getOrder().bitLength(); - } else if (key instanceof DSAKey) { - DSAKey pubk = (DSAKey)key; - size = pubk.getParams().getP().bitLength(); - } else if (key instanceof DHKey) { - DHKey pubk = (DHKey)key; - size = pubk.getParams().getP().bitLength(); - } // Otherwise, it may be a unextractable key of PKCS#11, or - // a key we are not able to handle. - - return size; - } -} - --- old/langtools/.hgtags 2013-02-07 17:07:53.000000000 +0100 +++ new/langtools/.hgtags 2013-02-07 17:07:53.000000000 +0100 @@ -225,6 +225,14 @@ 87683444edad33cc9f4bbcd9008d98ba34350ded jdk7u12-b01 b01338429ab6821f44d19601de433b538942b53d jdk7u11-b20 aeef1c7e43bc2d4a0960ebf42b642f7a34ec8afc jdk7u11-b21 +eaa8a0141c35edc382d7ce0b1148912db8422b16 jdk7u11-b03 +e8071ede35dc5948f5ed127941be192a4a8c1ebd jdk7u11-b04 +17b9bb22f3fd6a624879a29a3fc4b252327c113d jdk7u11-b05 +96c8b3b817aa3e672f78f1d5006616104378ff29 jdk7u11-b06 +c5d3dabddff76c92425cbf6a99ed4e066d16b4fd jdk7u11-b07 +a0d9abc405580d6fa0ae217fab96608285a38c41 jdk7u11-b08 +a778aaf53c52f78c92f29a1220d9f46de94c9247 jdk7u13-b09 +761b933e269693fd689c2af5d8317201b2172dbb jdk7u13-b20 12996c33d506d741ae7c3cc8e2aa2f650a36b839 jdk7u12-b02 3fe61a8a2cfb02ee2b1cd4cd257b76c5b8668cd3 jdk7u12-b03 e2adb6f53caaa618521bdf965bc484c7ffae190f jdk7u12-b04 --- old/./.hgtags 2013-02-07 17:07:54.000000000 +0100 +++ new/./.hgtags 2013-02-07 17:07:54.000000000 +0100 @@ -225,6 +225,14 @@ b5fb925394331313dbe3859fdc408bfd37193476 jdk7u10-b30 c2d5141baeda6c9b5bbc83c21eff9c3940fefae4 jdk7u11-b20 168aa0f1417b3651a955ae66068dc148b660f829 jdk7u11-b21 +c8a37a49fc90ae31b864544d6d4a9f6137d4995d jdk7u11-b03 +0b418e2ccf9093718609144689d1a8b316ad951f jdk7u11-b04 +e127e6c94b56f7348df67d9672c16a7dc9c5ec5e jdk7u11-b05 +f6abff072aabfee866342d9f7f4aac7d13450ddf jdk7u11-b06 +80a3d0bcd3d4c9e83b75416178bdd60a2d23ebbc jdk7u11-b07 +e7c55def6796d3c426631b5717084ef122908847 jdk7u11-b08 +2412f7b8551ede5296cb6e1d6189f40aad9eeffe jdk7u13-b09 +3b7815df113f8044039739276237b964ee8fa015 jdk7u13-b20 1ab3edf5061fdde3a6f6510373a92444445af710 jdk7u8-b01 d7a94c8cbbbfadbd9e2f3e4737eb7deb572dedc9 jdk7u8-b02 e7c504c99ab60e3b21cdc9460afaa3926d53cff1 jdk7u8-b03 --- old/corba/.hgtags 2013-02-07 17:07:54.000000000 +0100 +++ new/corba/.hgtags 2013-02-07 17:07:54.000000000 +0100 @@ -225,6 +225,14 @@ 22cf8bc2ec47498fe548b308a81be0486dd7e3d0 jdk7u10-b30 e7952daece16b27d69cb78f6912407c3bbaf8e83 jdk7u11-b20 dff0f0272891b1d53497d9525567959b73476ff9 jdk7u11-b21 +96a3c68e5741dc9ab5cb0da426511eb15fd29ede jdk7u11-b03 +1413b173730f4796fca42c89eeb804a5935b0264 jdk7u11-b04 +5c49a17bc15f4fd4722746788f5130df132cd038 jdk7u11-b05 +30057c20fbb3caa61857656d05421e56731184f2 jdk7u11-b06 +9d9440d1fa2dd872c2a2b564fc5fa4d3555afab6 jdk7u11-b07 +983fac5b27376839142ac5a8770461e4e48c2dc8 jdk7u11-b08 +b192d148731916e4b1b47b7a3e6b0a1d7ddf3f14 jdk7u13-b09 +b9ab9b203a41469a274419d26be2c04558b57ce8 jdk7u13-b20 353c15c4bc371f2f8258344c988d1403477cc140 jdk7u8-b01 d17ca8d088f7cc0dd42230472f534c8d1e415bcb jdk7u8-b02 7c62cfa17e9613bf69d4f9b2ae74f3724d7a2955 jdk7u8-b03 --- old/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_orbutil.jmk 2013-02-07 17:07:55.000000000 +0100 +++ new/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_orbutil.jmk 2013-02-07 17:07:55.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2000, 2012, 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,10 +29,6 @@ com/sun/corba/se/impl/orbutil/DenseIntMapImpl.java \ com/sun/corba/se/impl/orbutil/GetPropertyAction.java \ com/sun/corba/se/impl/orbutil/HexOutputStream.java \ - com/sun/corba/se/impl/orbutil/IIOPInputStream_1_3.java \ - com/sun/corba/se/impl/orbutil/IIOPInputStream_1_3_1.java \ - com/sun/corba/se/impl/orbutil/IIOPOutputStream_1_3.java \ - com/sun/corba/se/impl/orbutil/IIOPOutputStream_1_3_1.java \ com/sun/corba/se/impl/orbutil/LegacyHookGetFields.java \ com/sun/corba/se/impl/orbutil/LegacyHookPutFields.java \ com/sun/corba/se/impl/orbutil/LogKeywords.java \ @@ -45,19 +41,11 @@ com/sun/corba/se/impl/orbutil/ORBUtility.java \ com/sun/corba/se/impl/orbutil/ORBClassLoader.java \ com/sun/corba/se/impl/orbutil/RepIdDelegator.java \ - com/sun/corba/se/impl/orbutil/RepIdDelegator_1_3.java \ - com/sun/corba/se/impl/orbutil/RepIdDelegator_1_3_1.java \ - com/sun/corba/se/impl/orbutil/RepositoryIdCache_1_3.java \ - com/sun/corba/se/impl/orbutil/RepositoryId_1_3.java \ com/sun/corba/se/impl/orbutil/RepositoryIdFactory.java \ com/sun/corba/se/impl/orbutil/RepositoryIdStrings.java \ com/sun/corba/se/impl/orbutil/RepositoryIdUtility.java \ com/sun/corba/se/impl/orbutil/RepositoryIdInterface.java \ - com/sun/corba/se/impl/orbutil/RepositoryIdCache_1_3_1.java \ - com/sun/corba/se/impl/orbutil/RepositoryId_1_3_1.java \ com/sun/corba/se/impl/orbutil/StackImpl.java \ - com/sun/corba/se/impl/orbutil/ValueHandlerImpl_1_3_1.java \ - com/sun/corba/se/impl/orbutil/ValueHandlerImpl_1_3.java \ com/sun/corba/se/impl/orbutil/closure/Future.java \ com/sun/corba/se/impl/orbutil/closure/Constant.java \ com/sun/corba/se/impl/orbutil/concurrent/Sync.java \ --- old/corba/src/share/classes/com/sun/corba/se/impl/activation/ServerMain.java 2013-02-07 17:07:56.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/activation/ServerMain.java 2013-02-07 17:07:55.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2012, 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 @@ -322,9 +322,9 @@ com.sun.corba.se.spi.activation._ServerImplBase { private ORB orb; - private Method installMethod ; - private Method uninstallMethod ; - private Method shutdownMethod ; + private transient Method installMethod ; + private transient Method uninstallMethod ; + private transient Method shutdownMethod ; private Object methodArgs[] ; ServerCallback(ORB orb, Method installMethod, Method uninstallMethod, --- old/corba/src/share/classes/com/sun/corba/se/impl/corba/AnyImpl.java 2013-02-07 17:07:56.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/corba/AnyImpl.java 2013-02-07 17:07:56.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2012, 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 @@ -1218,7 +1218,7 @@ // See bug 4391648 for more info about the tcORB in this // case. RepositoryIdStrings repStrs - = RepositoryIdFactory.getRepIdStringsFactory(tcORB); + = RepositoryIdFactory.getRepIdStringsFactory(); // Assertion: c instanceof Serializable? @@ -1251,7 +1251,7 @@ // Anything else // We know that this is a TypeCodeImpl since it is our ORB classTC = (TypeCodeImpl)ValueUtility.createTypeCodeForClass( - tcORB, c, ORBUtility.createValueHandler(tcORB)); + tcORB, c, ORBUtility.createValueHandler()); // Intruct classTC to store its buffer classTC.setCaching(true); // Update the cache --- old/corba/src/share/classes/com/sun/corba/se/impl/encoding/CDRInputStream_1_0.java 2013-02-07 17:07:57.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/encoding/CDRInputStream_1_0.java 2013-02-07 17:07:57.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2012, 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 @@ -269,8 +269,8 @@ private final void createRepositoryIdHandlers() { - repIdUtil = RepositoryIdFactory.getRepIdUtility(orb); - repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(orb); + repIdUtil = RepositoryIdFactory.getRepIdUtility(); + repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); } public GIOPVersion getGIOPVersion() { @@ -564,10 +564,7 @@ checkForNegativeLength(len); - if (orb != null && ORBUtility.isLegacyORB((ORB)orb)) - return legacyReadString(len); - else - return internalReadString(len); + return internalReadString(len); } private final String internalReadString(int len) { @@ -588,54 +585,6 @@ return new String(result, 0, getCharConverter().getNumChars()); } - private final String legacyReadString(int len) { - - // - // Workaround for ORBs which send string lengths of - // zero to mean empty string. - // - // - // IMPORTANT: Do not replace 'new String("")' with "", it may result - // in a Serialization bug (See serialization.zerolengthstring) and - // bug id: 4728756 for details - if (len == 0) - return new String(""); - - len--; - char[] c = new char[len]; - - int n = 0; - while (n < len) { - int avail; - int bytes; - int wanted; - - avail = bbwi.buflen - bbwi.position(); - if (avail <= 0) { - grow(1, 1); - avail = bbwi.buflen - bbwi.position(); - } - wanted = len - n; - bytes = (wanted < avail) ? wanted : avail; - // Microbenchmarks are showing a loop of ByteBuffer.get(int) being - // faster than ByteBuffer.get(byte[], int, int). - for (int i=0; i bbwi.buflen) - alignAndCheck(1, 1); - bbwi.position(bbwi.position() + 1); - - return new String(c); - } - public final String read_string() { return readStringOrIndirection(false); } @@ -1045,7 +994,7 @@ try { if (valueHandler == null) - valueHandler = ORBUtility.createValueHandler(orb); + valueHandler = ORBUtility.createValueHandler(); value = valueHandler.readValue(parent, indirection, --- old/corba/src/share/classes/com/sun/corba/se/impl/encoding/CDROutputStream_1_0.java 2013-02-07 17:07:57.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/encoding/CDROutputStream_1_0.java 2013-02-07 17:07:57.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2012, 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 @@ -189,18 +189,8 @@ private final void createRepositoryIdHandlers() { - if (orb != null) { - // Get the appropriate versions based on the ORB version. The - // ORB versioning info is only in the core ORB. - repIdUtil - = RepositoryIdFactory.getRepIdUtility(orb); - repIdStrs - = RepositoryIdFactory.getRepIdStringsFactory(orb); - } else { - // Get the latest versions - repIdUtil = RepositoryIdFactory.getRepIdUtility(); - repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); - } + repIdUtil = RepositoryIdFactory.getRepIdUtility(); + repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); } public BufferManagerWrite getBufferManager() @@ -705,7 +695,7 @@ private void writeArray(Serializable array, Class clazz) { if (valueHandler == null) - valueHandler = ORBUtility.createValueHandler(orb); //d11638 + valueHandler = ORBUtility.createValueHandler(); //d11638 // Write value_tag int indirection = writeValueTag(mustChunk, true, @@ -768,7 +758,7 @@ private void writeRMIIIOPValueType(Serializable object, Class clazz) { if (valueHandler == null) - valueHandler = ORBUtility.createValueHandler(orb); //d11638 + valueHandler = ORBUtility.createValueHandler(); //d11638 Serializable key = object; --- old/corba/src/share/classes/com/sun/corba/se/impl/io/FVDCodeBaseImpl.java 2013-02-07 17:07:58.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/io/FVDCodeBaseImpl.java 2013-02-07 17:07:58.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -86,7 +86,7 @@ // default to using the current ORB version in case the // vhandler is not set if (vhandler == null) { - vhandler = new ValueHandlerImpl(false); + vhandler = ValueHandlerImpl.getInstance(false); } // Util.getCodebase may return null which would @@ -120,7 +120,7 @@ // default to using the current ORB version in case the // vhandler is not set if (vhandler == null) { - vhandler = new ValueHandlerImpl(false); + vhandler = ValueHandlerImpl.getInstance(false); } try{ @@ -161,7 +161,7 @@ // default to using the current ORB version in case the // vhandler is not set if (vhandler == null) { - vhandler = new ValueHandlerImpl(false); + vhandler = ValueHandlerImpl.getInstance(false); } Stack repIds = new Stack(); --- old/corba/src/share/classes/com/sun/corba/se/impl/io/ObjectStreamClass.java 2013-02-07 17:07:59.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/io/ObjectStreamClass.java 2013-02-07 17:07:59.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ /* * Licensed Materials - Property of IBM * RMI-IIOP v1.0 - * Copyright IBM Corp. 1998 1999 All Rights Reserved + * Copyright IBM Corp. 1998 2012 All Rights Reserved * */ @@ -56,7 +56,8 @@ import java.util.Arrays; import java.util.Comparator; -import java.util.Hashtable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import com.sun.corba.se.impl.util.RepositoryId; @@ -83,8 +84,6 @@ private static Object noArgsList[] = {}; private static Class noTypesList[] = {}; - private static Hashtable translatedFields; - /** true if represents enum type */ private boolean isEnum; @@ -384,6 +383,55 @@ */ } + private static final class PersistentFieldsValue { + private final ConcurrentMap map = new ConcurrentHashMap(); + private static final Object NULL_VALUE = + (PersistentFieldsValue.class.getName() + ".NULL_VALUE"); + + PersistentFieldsValue() { } + + ObjectStreamField[] get(Class type) { + Object value = map.get(type); + if (value == null) { + value = computeValue(type); + map.putIfAbsent(type, value); + } + return ((value == NULL_VALUE) ? null : (ObjectStreamField[])value); + } + + private static Object computeValue(Class type) { + try { + Field pf = type.getDeclaredField("serialPersistentFields"); + int mods = pf.getModifiers(); + if (Modifier.isPrivate(mods) && Modifier.isStatic(mods) && + Modifier.isFinal(mods)) { + pf.setAccessible(true); + java.io.ObjectStreamField[] fields = + (java.io.ObjectStreamField[])pf.get(type); + return translateFields(fields); + } + } catch (NoSuchFieldException e1) { + } catch (IllegalAccessException e2) { + } catch (IllegalArgumentException e3) { + } catch (ClassCastException e4) { } + return NULL_VALUE; + } + + private static ObjectStreamField[] translateFields( + java.io.ObjectStreamField[] fields) { + ObjectStreamField[] translation = + new ObjectStreamField[fields.length]; + for (int i = 0; i < fields.length; i++) { + translation[i] = new ObjectStreamField(fields[i].getName(), + fields[i].getType()); + } + return translation; + } + } + + private static final PersistentFieldsValue persistentFieldsValue = + new PersistentFieldsValue(); + /* * Initialize class descriptor. This method is only invoked on class * descriptors created via calls to lookupInternal(). This method is kept @@ -416,35 +464,7 @@ * If it is declared, use the declared serialPersistentFields. * Otherwise, extract the fields from the class itself. */ - try { - Field pf = cl.getDeclaredField("serialPersistentFields"); - // serial bug 7; the serialPersistentFields were not - // being read and stored as Accessible bit was not set - pf.setAccessible(true); - // serial bug 7; need to find if the field is of type - // java.io.ObjectStreamField - java.io.ObjectStreamField[] f = - (java.io.ObjectStreamField[])pf.get(cl); - int mods = pf.getModifiers(); - if ((Modifier.isPrivate(mods)) && - (Modifier.isStatic(mods)) && - (Modifier.isFinal(mods))) - { - fields = (ObjectStreamField[])translateFields((Object[])pf.get(cl)); - } - } catch (NoSuchFieldException e) { - fields = null; - } catch (IllegalAccessException e) { - fields = null; - } catch (IllegalArgumentException e) { - fields = null; - } catch (ClassCastException e) { - /* Thrown if a field serialPersistentField exists - * but it is not of type ObjectStreamField. - */ - fields = null; - } - + fields = persistentFieldsValue.get(cl); if (fields == null) { /* Get all of the declared fields for this @@ -641,44 +661,6 @@ superclass = null; } - private static Object[] translateFields(Object objs[]) - throws NoSuchFieldException { - try{ - java.io.ObjectStreamField fields[] = (java.io.ObjectStreamField[])objs; - Object translation[] = null; - - if (translatedFields == null) - translatedFields = new Hashtable(); - - translation = (Object[])translatedFields.get(fields); - - if (translation != null) - return translation; - else { - Class osfClass = Class.forName("com.sun.corba.se.impl.io.ObjectStreamField"); - translation = (Object[])java.lang.reflect.Array.newInstance(osfClass, objs.length); - Object arg[] = new Object[2]; - Class types[] = {String.class, Class.class}; - Constructor constructor = osfClass.getDeclaredConstructor(types); - for (int i = fields.length -1; i >= 0; i--){ - arg[0] = fields[i].getName(); - arg[1] = fields[i].getType(); - - translation[i] = constructor.newInstance(arg); - } - translatedFields.put(fields, translation); - - } - - return (Object[])translation; - } - catch(Throwable t){ - NoSuchFieldException nsfe = new NoSuchFieldException(); - nsfe.initCause( t ) ; - throw nsfe ; - } - } - /* * Set the class this version descriptor matches. * The base class name and serializable hash must match. @@ -1555,8 +1537,8 @@ private boolean hasExternalizableBlockData; Method writeObjectMethod; Method readObjectMethod; - private Method writeReplaceObjectMethod; - private Method readResolveObjectMethod; + private transient Method writeReplaceObjectMethod; + private transient Method readResolveObjectMethod; private Constructor cons ; /** --- old/corba/src/share/classes/com/sun/corba/se/impl/io/ValueHandlerImpl.java 2013-02-07 17:07:59.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/io/ValueHandlerImpl.java 2013-02-07 17:07:59.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2012, 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 @@ -53,7 +53,7 @@ import com.sun.corba.se.impl.logging.OMGSystemException; import com.sun.corba.se.impl.logging.UtilSystemException; -public class ValueHandlerImpl implements javax.rmi.CORBA.ValueHandlerMultiFormat { +public final class ValueHandlerImpl implements javax.rmi.CORBA.ValueHandlerMultiFormat { // Property to override our maximum stream format version public static final String FORMAT_VERSION_PROPERTY @@ -150,14 +150,22 @@ writeValueWithVersion(out, value, streamFormatVersion); } - public ValueHandlerImpl(){} + private ValueHandlerImpl(){} - public ValueHandlerImpl(boolean isInputStream) { + private ValueHandlerImpl(boolean isInputStream) { this(); useHashtables = false; this.isInputStream = isInputStream; } + static ValueHandlerImpl getInstance() { + return new ValueHandlerImpl(); + } + + static ValueHandlerImpl getInstance(boolean isInputStream) { + return new ValueHandlerImpl(isInputStream); + } + /** * Writes the value to the stream using java semantics. * @param out The stream to write the value to @@ -458,12 +466,7 @@ return ObjectStreamClass.lookup(value.getClass()).writeReplace(value); } - /** - * Encapsulates writing of Java char arrays so that the 1.3 subclass - * can override it without exposing internals across packages. This - * is a fix for bug 4367783. - */ - protected void writeCharArray(org.omg.CORBA_2_3.portable.OutputStream out, + private void writeCharArray(org.omg.CORBA_2_3.portable.OutputStream out, char[] array, int offset, int length) @@ -576,12 +579,7 @@ } } - /** - * Encapsulates reading of Java char arrays so that the 1.3 subclass - * can override it without exposing internals across packages. This - * is a fix for bug 4367783. - */ - protected void readCharArray(org.omg.CORBA_2_3.portable.InputStream in, + private void readCharArray(org.omg.CORBA_2_3.portable.InputStream in, char[] array, int offset, int length) @@ -795,7 +793,7 @@ return RepositoryId.cache.getId(repId).isSequence(); } - protected String getOutputStreamClassName() { + private String getOutputStreamClassName() { return "com.sun.corba.se.impl.io.IIOPOutputStream"; } @@ -843,29 +841,11 @@ private IIOPOutputStream createOutputStreamBuiltInNoPriv( final String name ) throws IOException { - return - name.equals( - IIOPOutputStream - .class.getName() - ) ? - new IIOPOutputStream() : - - name.equals( - com.sun.corba.se.impl.orbutil.IIOPOutputStream_1_3 - .class.getName() - ) ? - new com.sun.corba.se.impl.orbutil.IIOPOutputStream_1_3() : - - name.equals( - com.sun.corba.se.impl.orbutil.IIOPOutputStream_1_3_1 - .class.getName() - ) ? - new com.sun.corba.se.impl.orbutil.IIOPOutputStream_1_3_1() : - - null; + return name.equals(IIOPOutputStream.class.getName()) ? + new IIOPOutputStream() : null; } - protected String getInputStreamClassName() { + private String getInputStreamClassName() { return "com.sun.corba.se.impl.io.IIOPInputStream"; } @@ -913,26 +893,8 @@ private IIOPInputStream createInputStreamBuiltInNoPriv( final String name ) throws IOException { - return - name.equals( - IIOPInputStream - .class.getName() - ) ? - new IIOPInputStream() : - - name.equals( - com.sun.corba.se.impl.orbutil.IIOPInputStream_1_3 - .class.getName() - ) ? - new com.sun.corba.se.impl.orbutil.IIOPInputStream_1_3() : - - name.equals( - com.sun.corba.se.impl.orbutil.IIOPInputStream_1_3_1 - .class.getName() - ) ? - new com.sun.corba.se.impl.orbutil.IIOPInputStream_1_3_1() : - - null; + return name.equals(IIOPInputStream.class.getName()) ? + new IIOPInputStream() : null; } /** @@ -958,12 +920,7 @@ } - /** - * Our JDK 1.3 and JDK 1.3.1 behavior subclasses override this. - * The correct behavior is for a Java char to map to a CORBA wchar, - * but our older code mapped it to a CORBA char. - */ - protected TCKind getJavaCharTCKind() { + TCKind getJavaCharTCKind() { return TCKind.tk_wchar; } } --- old/corba/src/share/classes/com/sun/corba/se/impl/io/ValueUtility.java 2013-02-07 17:08:00.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/io/ValueUtility.java 2013-02-07 17:08:00.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2012, 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 @@ -93,6 +93,14 @@ null, // tk_abstract_interface 32 }; + static { + sun.corba.SharedSecrets.setJavaCorbaAccess(new sun.corba.JavaCorbaAccess() { + public ValueHandlerImpl newValueHandlerImpl() { + return ValueHandlerImpl.getInstance(); + } + }); + } + public static String getSignature(ValueMember member) throws ClassNotFoundException { --- old/corba/src/share/classes/com/sun/corba/se/impl/javax/rmi/CORBA/Util.java 2013-02-07 17:08:01.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/javax/rmi/CORBA/Util.java 2013-02-07 17:08:00.000000000 +0100 @@ -112,6 +112,9 @@ import com.sun.corba.se.impl.orbutil.ORBClassLoader; import com.sun.corba.se.impl.logging.UtilSystemException; import com.sun.corba.se.spi.logging.CORBALogDomains; +import sun.corba.SharedSecrets; +import sun.corba.JavaCorbaAccess; + /** * Provides utility methods that can be used by stubs and ties to @@ -125,7 +128,8 @@ // Maps targets to ties. private static IdentityHashtable exportedServants = new IdentityHashtable(); - private static ValueHandlerImpl valueHandlerSingleton = new ValueHandlerImpl(); + private static final ValueHandlerImpl valueHandlerSingleton = + SharedSecrets.getJavaCorbaAccess().newValueHandlerImpl(); private UtilSystemException utilWrapper = UtilSystemException.get( CORBALogDomains.RPC_ENCODING); --- old/corba/src/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java 2013-02-07 17:08:01.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java 2013-02-07 17:08:01.000000000 +0100 @@ -840,7 +840,7 @@ // backward compatability 4365188 CodeBase cb; - ValueHandler vh = ORBUtility.createValueHandler(this); + ValueHandler vh = ORBUtility.createValueHandler(); cb = (CodeBase)vh.getRunTimeCodeBase(); return ORBUtility.connectAndGetIOR( this, cb ) ; --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ORBUtility.java 2013-02-07 17:08:02.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ORBUtility.java 2013-02-07 17:08:02.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2012, 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 @@ -160,45 +160,13 @@ } /** - * Creates the correct ValueHandler for the given ORB, - * querying ORBVersion information. If the ORB or - * ORBVersion is null, gets the ValueHandler from - * Util.createValueHandler. + * Return default ValueHandler */ - public static ValueHandler createValueHandler(ORB orb) { - - if (orb == null) - return Util.createValueHandler(); - - ORBVersion version = orb.getORBVersion(); - - if (version == null) - return Util.createValueHandler(); - - if (version.equals(ORBVersionFactory.getOLD())) - return new ValueHandlerImpl_1_3(); - if (version.equals(ORBVersionFactory.getNEW())) - return new ValueHandlerImpl_1_3_1(); - + public static ValueHandler createValueHandler() { return Util.createValueHandler(); } /** - * Returns true if the given ORB could accurately be determined to be a - * Kestrel or earlier ORB. Note: If passed the ORBSingleton, this will return - * false. - */ - public static boolean isLegacyORB(ORB orb) - { - try { - ORBVersion currentORB = orb.getORBVersion(); - return currentORB.equals( ORBVersionFactory.getOLD() ) ; - } catch (SecurityException se) { - return false; - } - } - - /** * Returns true if it was accurately determined that the remote ORB is * a foreign (non-JavaSoft) ORB. Note: If passed the ORBSingleton, this * will return false. --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClass_1_3_1.java 2013-02-07 17:08:02.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClass_1_3_1.java 2013-02-07 17:08:02.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2012, 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 @@ -1119,8 +1119,8 @@ private boolean hasExternalizableBlockData; Method writeObjectMethod; Method readObjectMethod; - private Method writeReplaceObjectMethod; - private Method readResolveObjectMethod; + private transient Method writeReplaceObjectMethod; + private transient Method readResolveObjectMethod; /* * ObjectStreamClass_1_3_1 that this one was built from. --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepositoryIdFactory.java 2013-02-07 17:08:03.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepositoryIdFactory.java 2013-02-07 17:08:03.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,12 +30,6 @@ public abstract class RepositoryIdFactory { - private static final RepIdDelegator_1_3 legacyDelegator - = new RepIdDelegator_1_3(); - - private static final RepIdDelegator_1_3_1 ladybirdDelegator - = new RepIdDelegator_1_3_1(); - private static final RepIdDelegator currentDelegator = new RepIdDelegator(); @@ -48,29 +42,6 @@ } /** - * Checks the version of the ORB and returns the appropriate - * RepositoryIdStrings instance. - */ - public static RepositoryIdStrings getRepIdStringsFactory(ORB orb) - { - if (orb != null) { - switch (orb.getORBVersion().getORBType()) { - case ORBVersion.NEWER: - case ORBVersion.FOREIGN: - case ORBVersion.JDK1_3_1_01: - return currentDelegator; - case ORBVersion.OLD: - return legacyDelegator; - case ORBVersion.NEW: - return ladybirdDelegator; - default: - return currentDelegator; - } - } else - return currentDelegator; - } - - /** * Returns the latest version RepositoryIdUtility instance */ public static RepositoryIdUtility getRepIdUtility() @@ -78,26 +49,4 @@ return currentDelegator; } - /** - * Checks the version of the ORB and returns the appropriate - * RepositoryIdUtility instance. - */ - public static RepositoryIdUtility getRepIdUtility(ORB orb) - { - if (orb != null) { - switch (orb.getORBVersion().getORBType()) { - case ORBVersion.NEWER: - case ORBVersion.FOREIGN: - case ORBVersion.JDK1_3_1_01: - return currentDelegator; - case ORBVersion.OLD: - return legacyDelegator; - case ORBVersion.NEW: - return ladybirdDelegator; - default: - return currentDelegator; - } - } else - return currentDelegator; - } } --- old/corba/src/share/classes/com/sun/corba/se/spi/orb/ORB.java 2013-02-07 17:08:04.000000000 +0100 +++ new/corba/src/share/classes/com/sun/corba/se/spi/orb/ORB.java 2013-02-07 17:08:03.000000000 +0100 @@ -98,6 +98,7 @@ import com.sun.corba.se.impl.presentation.rmi.PresentationManagerImpl ; import com.sun.corba.se.impl.orbutil.ORBClassLoader ; +import sun.awt.AppContext; public abstract class ORB extends com.sun.corba.se.org.omg.CORBA.ORB implements Broker, TypeCodeFactory @@ -173,14 +174,7 @@ protected MonitoringManager monitoringManager; - // There is only one instance of the PresentationManager - // that is shared between all ORBs. This is necessary - // because RMI-IIOP requires the PresentationManager in - // places where no ORB is available, so the PresentationManager - // must be global. It is initialized here as well. - protected static PresentationManager globalPM = null ; - - static { + private static PresentationManager setupPresentationManager() { staticWrapper = ORBUtilSystemException.get( CORBALogDomains.RPC_PRESENTATION ) ; @@ -218,12 +212,13 @@ return sff ; } } - ) ; + ); - globalPM = new PresentationManagerImpl( useDynamicStub ) ; - globalPM.setStubFactoryFactory( false, + PresentationManager pm = new PresentationManagerImpl( useDynamicStub ) ; + pm.setStubFactoryFactory( false, PresentationDefaults.getStaticStubFactoryFactory() ) ; - globalPM.setStubFactoryFactory( true, dynamicStubFactoryFactory ) ; + pm.setStubFactoryFactory( true, dynamicStubFactoryFactory ) ; + return pm; } public void destroy() { @@ -234,11 +229,19 @@ byteBufferPool = null; } - /** Get the single instance of the PresentationManager + /** + * Returns the Presentation Manager for the current thread group, using the ThreadGroup-specific + * AppContext to hold it. Creates and records one if needed. */ public static PresentationManager getPresentationManager() { - return globalPM ; + AppContext ac = AppContext.getAppContext(); + PresentationManager pm = (PresentationManager) ac.get(PresentationManager.class); + if (pm == null) { + pm = setupPresentationManager(); + ac.put(PresentationManager.class, pm); + } + return pm; } /** Get the appropriate StubFactoryFactory. This @@ -248,8 +251,9 @@ public static PresentationManager.StubFactoryFactory getStubFactoryFactory() { - boolean useDynamicStubs = globalPM.useDynamicStubs() ; - return globalPM.getStubFactoryFactory( useDynamicStubs ) ; + PresentationManager gPM = getPresentationManager(); + boolean useDynamicStubs = gPM.useDynamicStubs() ; + return gPM.getStubFactoryFactory( useDynamicStubs ) ; } protected ORB() @@ -543,6 +547,7 @@ public abstract ThreadPoolManager getThreadPoolManager(); public abstract CopierManager getCopierManager() ; + } // End of file. --- /dev/null 2013-02-05 10:56:25.513074029 +0100 +++ new/corba/src/share/classes/sun/corba/JavaCorbaAccess.java 2013-02-07 17:08:04.000000000 +0100 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2012, 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 sun.corba; + +import com.sun.corba.se.impl.io.ValueHandlerImpl; + +public interface JavaCorbaAccess { + public ValueHandlerImpl newValueHandlerImpl(); +} --- /dev/null 2013-02-05 10:56:25.513074029 +0100 +++ new/corba/src/share/classes/sun/corba/SharedSecrets.java 2013-02-07 17:08:05.000000000 +0100 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2012, 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 sun.corba; + +import com.sun.corba.se.impl.io.ValueUtility; +import sun.misc.Unsafe; + +import java.security.AccessController; + +/** A repository of "shared secrets", which are a mechanism for + calling implementation-private methods in another package without + using reflection. A package-private class implements a public + interface and provides the ability to call package-private methods + within that package; the object implementing that interface is + provided through a third package to which access is restricted. + This framework avoids the primary disadvantage of using reflection + for this purpose, namely the loss of compile-time checking. */ + +// SharedSecrets cloned in corba repo to avoid build issues +public class SharedSecrets { + private static final Unsafe unsafe = Unsafe.getUnsafe(); + private static JavaCorbaAccess javaCorbaAccess; + + public static JavaCorbaAccess getJavaCorbaAccess() { + if (javaCorbaAccess == null) { + // Ensure ValueUtility is initialized; we know that that class + // provides the shared secret + unsafe.ensureClassInitialized(ValueUtility.class); + } + return javaCorbaAccess; + } + + public static void setJavaCorbaAccess(JavaCorbaAccess access) { + javaCorbaAccess = access; + } + +} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/IIOPInputStream_1_3.java 2013-02-07 17:08:05.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2000, 2002, 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.corba.se.impl.orbutil; - -import java.io.*; -import java.util.Hashtable; - -/** - * Implements legacy behavior from before Ladybird to maintain - * backwards compatibility. - */ -public class IIOPInputStream_1_3 extends com.sun.corba.se.impl.io.IIOPInputStream -{ - // The newer version in the io package correctly reads a wstring instead. - // This concerns bug 4379597. - protected String internalReadUTF(org.omg.CORBA.portable.InputStream stream) - { - return stream.read_string(); - } - - /** - * Before JDK 1.3.1_01, the PutField/GetField implementation - * actually sent a Hashtable. - */ - public ObjectInputStream.GetField readFields() - throws IOException, ClassNotFoundException, NotActiveException { - Hashtable fields = (Hashtable)readObject(); - return new LegacyHookGetFields(fields); - } - - public IIOPInputStream_1_3() - throws java.io.IOException { - super(); - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/IIOPInputStream_1_3_1.java 2013-02-07 17:08:06.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2001, 2002, 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.corba.se.impl.orbutil; - -import java.io.*; -import java.util.Hashtable; - -/** - * Implements legacy behavior from Ladybird to maintain - * backwards compatibility. - */ -public class IIOPInputStream_1_3_1 extends com.sun.corba.se.impl.io.IIOPInputStream -{ - public IIOPInputStream_1_3_1() - throws java.io.IOException { - super(); - } - - /** - * Before JDK 1.3.1_01, the PutField/GetField implementation - * actually sent a Hashtable. - */ - public ObjectInputStream.GetField readFields() - throws IOException, ClassNotFoundException, NotActiveException { - - Hashtable fields = (Hashtable)readObject(); - return new LegacyHookGetFields(fields); - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/IIOPOutputStream_1_3.java 2013-02-07 17:08:06.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2000, 2002, 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.corba.se.impl.orbutil; - -import java.io.*; - -/** - * Implements legacy behavior from before Ladybird to maintain - * backwards compatibility. - */ -public class IIOPOutputStream_1_3 extends com.sun.corba.se.impl.io.IIOPOutputStream -{ - // We can't assume that the superclass's putFields - // member will be non-private. We must allow - // the RI to run on JDK 1.3.1 FCS as well as - // the JDK 1.3.1_01 patch. - private ObjectOutputStream.PutField putFields_1_3; - - // The newer version in the io package correctly writes a wstring instead. - // This concerns bug 4379597. - protected void internalWriteUTF(org.omg.CORBA.portable.OutputStream stream, - String data) - { - stream.write_string(data); - } - - public IIOPOutputStream_1_3() - throws java.io.IOException { - super(); - } - - /** - * Before JDK 1.3.1_01, the PutField/GetField implementation - * actually sent a Hashtable. - */ - public ObjectOutputStream.PutField putFields() - throws IOException { - putFields_1_3 = new LegacyHookPutFields(); - return putFields_1_3; - } - - public void writeFields() - throws IOException { - putFields_1_3.write(this); - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/IIOPOutputStream_1_3_1.java 2013-02-07 17:08:06.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2001, 2002, 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.corba.se.impl.orbutil; - -import java.io.*; -import java.util.Hashtable; - -/** - * Implements legacy behavior from Ladybird to maintain - * backwards compatibility. - */ -public class IIOPOutputStream_1_3_1 extends com.sun.corba.se.impl.io.IIOPOutputStream -{ - // We can't assume that the superclass's putFields - // member will be non-private. We must allow - // the RI to run on JDK 1.3.1 FCS as well as - // the JDK 1.3.1_01 patch. - private ObjectOutputStream.PutField putFields_1_3_1; - - public IIOPOutputStream_1_3_1() - throws java.io.IOException { - super(); - } - - /** - * Before JDK 1.3.1_01, the PutField/GetField implementation - * actually sent a Hashtable. - */ - public ObjectOutputStream.PutField putFields() - throws IOException { - - putFields_1_3_1 = new LegacyHookPutFields(); - return putFields_1_3_1; - } - - public void writeFields() - throws IOException { - - putFields_1_3_1.write(this); - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepIdDelegator_1_3.java 2013-02-07 17:08:07.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2000, 2004, 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.corba.se.impl.orbutil; - -import org.omg.CORBA.ORB; -import java.io.Serializable; -import java.util.Hashtable; -import java.net.MalformedURLException; -import com.sun.corba.se.impl.io.TypeMismatchException; -import com.sun.corba.se.impl.util.RepositoryId; - -/** - * Delegates to the RepositoryId_1_3 implementation in - * com.sun.corba.se.impl.orbutil. This is necessary to - * overcome the fact that many of RepositoryId's methods - * are static. - */ -public final class RepIdDelegator_1_3 - implements RepositoryIdStrings, - RepositoryIdUtility, - RepositoryIdInterface -{ - // RepositoryIdFactory methods - - public String createForAnyType(Class type) { - return RepositoryId_1_3.createForAnyType(type); - } - - public String createForJavaType(Serializable ser) - throws TypeMismatchException - { - return RepositoryId_1_3.createForJavaType(ser); - } - - public String createForJavaType(Class clz) - throws TypeMismatchException - { - return RepositoryId_1_3.createForJavaType(clz); - } - - public String createSequenceRepID(java.lang.Object ser) { - return RepositoryId_1_3.createSequenceRepID(ser); - } - - public String createSequenceRepID(Class clazz) { - return RepositoryId_1_3.createSequenceRepID(clazz); - } - - public RepositoryIdInterface getFromString(String repIdString) { - return new RepIdDelegator_1_3(RepositoryId_1_3.cache.getId(repIdString)); - } - - // RepositoryIdUtility methods - - public boolean isChunkedEncoding(int valueTag) { - return RepositoryId.isChunkedEncoding(valueTag); - } - - public boolean isCodeBasePresent(int valueTag) { - return RepositoryId.isCodeBasePresent(valueTag); - } - - public String getClassDescValueRepId() { - return RepositoryId_1_3.kClassDescValueRepID; - } - - public String getWStringValueRepId() { - return RepositoryId_1_3.kWStringValueRepID; - } - - public int getTypeInfo(int valueTag) { - return RepositoryId.getTypeInfo(valueTag); - } - - public int getStandardRMIChunkedNoRepStrId() { - return RepositoryId.kPreComputed_StandardRMIChunked_NoRep; - } - - public int getCodeBaseRMIChunkedNoRepStrId() { - return RepositoryId.kPreComputed_CodeBaseRMIChunked_NoRep; - } - - public int getStandardRMIChunkedId() { - return RepositoryId.kPreComputed_StandardRMIChunked; - } - - public int getCodeBaseRMIChunkedId() { - return RepositoryId.kPreComputed_CodeBaseRMIChunked; - } - - public int getStandardRMIUnchunkedId() { - return RepositoryId.kPreComputed_StandardRMIUnchunked; - } - - public int getCodeBaseRMIUnchunkedId() { - return RepositoryId.kPreComputed_CodeBaseRMIUnchunked; - } - - public int getStandardRMIUnchunkedNoRepStrId() { - return RepositoryId.kPreComputed_StandardRMIUnchunked_NoRep; - } - - public int getCodeBaseRMIUnchunkedNoRepStrId() { - return RepositoryId.kPreComputed_CodeBaseRMIUnchunked_NoRep; - } - - // RepositoryIdInterface methods - - public Class getClassFromType() throws ClassNotFoundException { - return delegate.getClassFromType(); - } - - public Class getClassFromType(String codebaseURL) - throws ClassNotFoundException, MalformedURLException - { - return delegate.getClassFromType(codebaseURL); - } - - public Class getClassFromType(Class expectedType, - String codebaseURL) - throws ClassNotFoundException, MalformedURLException - { - return delegate.getClassFromType(expectedType, codebaseURL); - } - - public String getClassName() { - return delegate.getClassName(); - } - - // Constructor used for factory/utility cases - public RepIdDelegator_1_3() {} - - // Constructor used by getIdFromString. All non-static - // RepositoryId methods will use the provided delegate. - private RepIdDelegator_1_3(RepositoryId_1_3 _delegate) { - this.delegate = _delegate; - } - - private RepositoryId_1_3 delegate = null; - - public String toString() { - if (delegate != null) - return delegate.toString(); - else - return this.getClass().getName(); - } - - public boolean equals(Object obj) { - if (delegate != null) - return delegate.equals(obj); - else - return super.equals(obj); - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepIdDelegator_1_3_1.java 2013-02-07 17:08:07.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2001, 2004, 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.corba.se.impl.orbutil; - -import org.omg.CORBA.ORB; -import java.io.Serializable; -import java.util.Hashtable; -import java.net.MalformedURLException; -import com.sun.corba.se.impl.io.TypeMismatchException; -import com.sun.corba.se.impl.util.RepositoryId; - -/** - * Delegates to the RepositoryId_1_3_1 implementation in - * com.sun.corba.se.impl.orbutil. This is necessary to - * overcome the fact that many of RepositoryId's methods - * are static. - */ -public final class RepIdDelegator_1_3_1 - implements RepositoryIdStrings, - RepositoryIdUtility, - RepositoryIdInterface -{ - // RepositoryIdFactory methods - - public String createForAnyType(Class type) { - return RepositoryId_1_3_1.createForAnyType(type); - } - - public String createForJavaType(Serializable ser) - throws TypeMismatchException - { - return RepositoryId_1_3_1.createForJavaType(ser); - } - - public String createForJavaType(Class clz) - throws TypeMismatchException - { - return RepositoryId_1_3_1.createForJavaType(clz); - } - - public String createSequenceRepID(java.lang.Object ser) { - return RepositoryId_1_3_1.createSequenceRepID(ser); - } - - public String createSequenceRepID(Class clazz) { - return RepositoryId_1_3_1.createSequenceRepID(clazz); - } - - public RepositoryIdInterface getFromString(String repIdString) { - return new RepIdDelegator_1_3_1(RepositoryId_1_3_1.cache.getId(repIdString)); - } - - // RepositoryIdUtility methods - - public boolean isChunkedEncoding(int valueTag) { - return RepositoryId.isChunkedEncoding(valueTag); - } - - public boolean isCodeBasePresent(int valueTag) { - return RepositoryId.isCodeBasePresent(valueTag); - } - - public String getClassDescValueRepId() { - return RepositoryId_1_3_1.kClassDescValueRepID; - } - - public String getWStringValueRepId() { - return RepositoryId_1_3_1.kWStringValueRepID; - } - - public int getTypeInfo(int valueTag) { - return RepositoryId.getTypeInfo(valueTag); - } - - public int getStandardRMIChunkedNoRepStrId() { - return RepositoryId.kPreComputed_StandardRMIChunked_NoRep; - } - - public int getCodeBaseRMIChunkedNoRepStrId() { - return RepositoryId.kPreComputed_CodeBaseRMIChunked_NoRep; - } - - public int getStandardRMIChunkedId() { - return RepositoryId.kPreComputed_StandardRMIChunked; - } - - public int getCodeBaseRMIChunkedId() { - return RepositoryId.kPreComputed_CodeBaseRMIChunked; - } - - public int getStandardRMIUnchunkedId() { - return RepositoryId.kPreComputed_StandardRMIUnchunked; - } - - public int getCodeBaseRMIUnchunkedId() { - return RepositoryId.kPreComputed_CodeBaseRMIUnchunked; - } - - public int getStandardRMIUnchunkedNoRepStrId() { - return RepositoryId.kPreComputed_StandardRMIUnchunked_NoRep; - } - - public int getCodeBaseRMIUnchunkedNoRepStrId() { - return RepositoryId.kPreComputed_CodeBaseRMIUnchunked_NoRep; - } - - // RepositoryIdInterface methods - - public Class getClassFromType() throws ClassNotFoundException { - return delegate.getClassFromType(); - } - - public Class getClassFromType(String codebaseURL) - throws ClassNotFoundException, MalformedURLException - { - return delegate.getClassFromType(codebaseURL); - } - - public Class getClassFromType(Class expectedType, - String codebaseURL) - throws ClassNotFoundException, MalformedURLException - { - return delegate.getClassFromType(expectedType, codebaseURL); - } - - public String getClassName() { - return delegate.getClassName(); - } - - // Constructor used for factory/utility cases - public RepIdDelegator_1_3_1() {} - - // Constructor used by getIdFromString. All non-static - // RepositoryId methods will use the provided delegate. - private RepIdDelegator_1_3_1(RepositoryId_1_3_1 _delegate) { - this.delegate = _delegate; - } - - private RepositoryId_1_3_1 delegate = null; - - public String toString() { - if (delegate != null) - return delegate.toString(); - else - return this.getClass().getName(); - } - - public boolean equals(Object obj) { - if (delegate != null) - return delegate.equals(obj); - else - return super.equals(obj); - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepositoryIdCache_1_3.java 2013-02-07 17:08:07.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2000, 2002, 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. - */ -/* - * Licensed Materials - Property of IBM - * RMI-IIOP v1.0 - * Copyright IBM Corp. 1998 1999 All Rights Reserved - * - */ - -package com.sun.corba.se.impl.orbutil; - -import java.util.Stack; -import java.util.Hashtable; -import java.util.EmptyStackException; -import java.util.Enumeration; - -// Really limited pool - in this case just creating several at a time... -class RepositoryIdPool_1_3 extends Stack { - - private static int MAX_CACHE_SIZE = 4; - private RepositoryIdCache_1_3 cache; - - public final synchronized RepositoryId_1_3 popId() { - - try { - return (RepositoryId_1_3)super.pop(); - } - catch(EmptyStackException e) { - increasePool(5); - return (RepositoryId_1_3)super.pop(); - } - - } - - // Pool management - final void increasePool(int size) { - //if (cache.size() <= MAX_CACHE_SIZE) - for (int i = size; i > 0; i--) - push(new RepositoryId_1_3()); - /* - // _REVISIT_ This will not work w/out either thread tracing or weak references. I am - // betting that thread tracing almost completely negates benefit of reuse. Until either - // 1.2 only inclusion or proof to the contrary, I'll leave it this way... - else { - int numToReclaim = cache.size() / 2; - Enumeration keys = cache.keys(); - Enumeration elements = cache.elements(); - for (int i = numToReclaim; i > 0; i--) { - Object key = keys.nextElement(); - Object element = elements.nextElement(); - - push(element); - cache.remove(key); - } - } - */ - } - - final void setCaches(RepositoryIdCache_1_3 cache) { - this.cache = cache; - } - -} - -public class RepositoryIdCache_1_3 extends Hashtable { - - private RepositoryIdPool_1_3 pool = new RepositoryIdPool_1_3(); - - public RepositoryIdCache_1_3() { - pool.setCaches(this); - } - - public final synchronized RepositoryId_1_3 getId(String key) { - RepositoryId_1_3 repId = (RepositoryId_1_3)super.get(key); - - if (repId != null) - return repId; - else { - //repId = pool.popId().init(key); - repId = new RepositoryId_1_3(key); - put(key, repId); - return repId; - } - - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepositoryIdCache_1_3_1.java 2013-02-07 17:08:08.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2001, 2002, 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.corba.se.impl.orbutil; - -import java.util.Stack; -import java.util.Hashtable; -import java.util.EmptyStackException; -import java.util.Enumeration; - -// Really limited pool - in this case just creating several at a time... -class RepositoryIdPool_1_3_1 extends Stack { - - private static int MAX_CACHE_SIZE = 4; - private RepositoryIdCache_1_3_1 cache; - - public final synchronized RepositoryId_1_3_1 popId() { - - try { - return (RepositoryId_1_3_1)super.pop(); - } - catch(EmptyStackException e) { - increasePool(5); - return (RepositoryId_1_3_1)super.pop(); - } - - } - - // Pool management - final void increasePool(int size) { - //if (cache.size() <= MAX_CACHE_SIZE) - for (int i = size; i > 0; i--) - push(new RepositoryId_1_3_1()); - /* - // _REVISIT_ This will not work w/out either thread tracing or weak references. I am - // betting that thread tracing almost completely negates benefit of reuse. Until either - // 1.2 only inclusion or proof to the contrary, I'll leave it this way... - else { - int numToReclaim = cache.size() / 2; - Enumeration keys = cache.keys(); - Enumeration elements = cache.elements(); - for (int i = numToReclaim; i > 0; i--) { - Object key = keys.nextElement(); - Object element = elements.nextElement(); - - push(element); - cache.remove(key); - } - } - */ - } - - final void setCaches(RepositoryIdCache_1_3_1 cache) { - this.cache = cache; - } - -} - -public class RepositoryIdCache_1_3_1 extends Hashtable { - - private RepositoryIdPool_1_3_1 pool = new RepositoryIdPool_1_3_1(); - - public RepositoryIdCache_1_3_1() { - pool.setCaches(this); - } - - public final synchronized RepositoryId_1_3_1 getId(String key) { - RepositoryId_1_3_1 repId = (RepositoryId_1_3_1)super.get(key); - - if (repId != null) - return repId; - else { - //repId = pool.popId().init(key); - repId = new RepositoryId_1_3_1(key); - put(key, repId); - return repId; - } - - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepositoryId_1_3.java 2013-02-07 17:08:08.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,990 +0,0 @@ -/* - * Copyright (c) 2000, 2012, 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. - */ -/* - * Licensed Materials - Property of IBM - * RMI-IIOP v1.0 - * Copyright IBM Corp. 1998 1999 All Rights Reserved - * - */ - -package com.sun.corba.se.impl.orbutil; - -import java.util.StringTokenizer; -import java.util.Hashtable; -import java.io.IOException; -import java.lang.reflect.Method; - -// Imports for using codebase URL to load class -import java.net.MalformedURLException; -import org.omg.CORBA.portable.ValueBase; -import org.omg.CORBA.portable.IDLEntity; - -import com.sun.corba.se.impl.util.JDKBridge; -import com.sun.corba.se.impl.util.Utility; -import com.sun.corba.se.impl.util.PackagePrefixChecker; -import com.sun.corba.se.impl.util.IdentityHashtable; -import com.sun.corba.se.impl.io.ObjectStreamClass; - -import javax.rmi.CORBA.Util; - -// keeping the original RepositoryId class that was shipped in -// JDK 1.3. It has interoperability bugs - -public class RepositoryId_1_3 { - - // Legal IDL Identifier characters (1 = legal). Note - // that '.' (2E) is marked as legal even though it is - // not legal in IDL. This allows us to treat a fully - // qualified Java name with '.' package separators - // uniformly, and is safe because that is the only - // legal use of '.' in a Java name. - - public static final RepositoryIdCache_1_3 cache = new RepositoryIdCache_1_3(); - private static final byte[] IDL_IDENTIFIER_CHARS = { - - // 0 1 2 3 4 5 6 7 8 9 a b c d e f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 00-0f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 10-1f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,1,0, // 20-2f - 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, // 30-3f - 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 40-4f - 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,1, // 50-5f - 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 60-6f - 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0, // 70-7f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 80-8f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 90-9f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // a0-af - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // b0-bf - 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // c0-cf - 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // d0-df - 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // e0-ef - 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // f0-ff - }; - - private static String defaultServerURL = null; - private static boolean useCodebaseOnly = false; - - static { - if (defaultServerURL == null) - defaultServerURL = (String)JDKBridge.getLocalCodebase(); - useCodebaseOnly = JDKBridge.useCodebaseOnly(); - - } - - private static IdentityHashtable classToRepStr = new IdentityHashtable(); - private static IdentityHashtable classIDLToRepStr = new IdentityHashtable(); - private static IdentityHashtable classSeqToRepStr = new IdentityHashtable(); - - private static IdentityHashtable repStrToByteArray = new IdentityHashtable(); - private static Hashtable repStrToClass = new Hashtable(); - - private String repId = null; - private boolean isSupportedFormat = true; - private String typeString = null; - private String versionString = null; - private boolean isSequence = false; - private boolean isRMIValueType = false; - private boolean isIDLType = false; - private String completeClassName = null; - private String unqualifiedName = null; - private String definedInId = null; - private Class clazz = null; - private String suid = null, actualSuid = null; - private long suidLong = ObjectStreamClass.kDefaultUID, actualSuidLong = ObjectStreamClass.kDefaultUID; - - // Repository ID fragments - private static final String kValuePrefix = "RMI:"; - private static final String kIDLPrefix = "IDL:"; - private static final String kIDLNamePrefix = "omg.org/"; - private static final String kIDLClassnamePrefix = "org.omg."; - private static final String kSequencePrefix = "["; - private static final String kCORBAPrefix = "CORBA/"; - private static final String kArrayPrefix = kValuePrefix + kSequencePrefix + kCORBAPrefix; - private static final int kValuePrefixLength = kValuePrefix.length(); - private static final int kIDLPrefixLength = kIDLPrefix.length(); - private static final int kSequencePrefixLength = kSequencePrefix.length(); - private static final String kInterfaceHashCode = ":0000000000000000"; - private static final String kInterfaceOnlyHashStr = "0000000000000000"; - private static final String kExternalizableHashStr = "0000000000000001"; - - // Value tag utility methods and constants - public static final int kInitialValueTag= 0x7fffff00; - public static final int kNoTypeInfo = 0; - public static final int kSingleRepTypeInfo = 0x02; - public static final int kPartialListTypeInfo = 0x06; - public static final int kChunkedMask = 0x08; - - // Public, well known repository IDs - - // _REVISIT_ : A table structure with a good search routine for all of this - // would be more efficient and easier to maintain... - - // String - public static final String kWStringValueVersion = "1.0"; - public static final String kWStringValueHash = ":"+kWStringValueVersion; - public static final String kWStringStubValue = "WStringValue"; - public static final String kWStringTypeStr = "omg.org/CORBA/"+kWStringStubValue; - public static final String kWStringValueRepID = kIDLPrefix + kWStringTypeStr + kWStringValueHash; - - // Any - public static final String kAnyRepID = kIDLPrefix + "omg.org/CORBA/Any"; - - // Class - public static final String kClassDescValueHash = ":" + Long.toHexString( - ObjectStreamClass.getSerialVersionUID(javax.rmi.CORBA.ClassDesc.class)); - public static final String kClassDescStubValue = "ClassDesc"; - public static final String kClassDescTypeStr = "javax.rmi.CORBA."+kClassDescStubValue; - public static final String kClassDescValueRepID = kValuePrefix + kClassDescTypeStr + kClassDescValueHash; - - // Object - public static final String kObjectValueHash = ":1.0"; - public static final String kObjectStubValue = "Object"; - - // Sequence - public static final String kSequenceValueHash = ":1.0"; - public static final String kPrimitiveSequenceValueHash = ":0000000000000000"; - - // Serializable - public static final String kSerializableValueHash = ":1.0"; - public static final String kSerializableStubValue = "Serializable"; - - // Externalizable - public static final String kExternalizableValueHash = ":1.0"; - public static final String kExternalizableStubValue = "Externalizable"; - - // Remote (The empty string is used for java.rmi.Remote) - public static final String kRemoteValueHash = ""; - public static final String kRemoteStubValue = ""; - public static final String kRemoteTypeStr = ""; - public static final String kRemoteValueRepID = ""; - - private static final Hashtable kSpecialArrayTypeStrings = new Hashtable(); - - static { - kSpecialArrayTypeStrings.put("CORBA.WStringValue", new StringBuffer(java.lang.String.class.getName())); - kSpecialArrayTypeStrings.put("javax.rmi.CORBA.ClassDesc", new StringBuffer(java.lang.Class.class.getName())); - kSpecialArrayTypeStrings.put("CORBA.Object", new StringBuffer(java.rmi.Remote.class.getName())); - - } - - private static final Hashtable kSpecialCasesRepIDs = new Hashtable(); - - static { - kSpecialCasesRepIDs.put(java.lang.String.class, kWStringValueRepID); - kSpecialCasesRepIDs.put(java.lang.Class.class, kClassDescValueRepID); - kSpecialCasesRepIDs.put(java.rmi.Remote.class, kRemoteValueRepID); - } - - private static final Hashtable kSpecialCasesStubValues = new Hashtable(); - - static { - kSpecialCasesStubValues.put(java.lang.String.class, kWStringStubValue); - kSpecialCasesStubValues.put(java.lang.Class.class, kClassDescStubValue); - kSpecialCasesStubValues.put(java.lang.Object.class, kObjectStubValue); - kSpecialCasesStubValues.put(java.io.Serializable.class, kSerializableStubValue); - kSpecialCasesStubValues.put(java.io.Externalizable.class, kExternalizableStubValue); - kSpecialCasesStubValues.put(java.rmi.Remote.class, kRemoteStubValue); - } - - - private static final Hashtable kSpecialCasesVersions = new Hashtable(); - - static { - kSpecialCasesVersions.put(java.lang.String.class, kWStringValueHash); - kSpecialCasesVersions.put(java.lang.Class.class, kClassDescValueHash); - kSpecialCasesVersions.put(java.lang.Object.class, kObjectValueHash); - kSpecialCasesVersions.put(java.io.Serializable.class, kSerializableValueHash); - kSpecialCasesVersions.put(java.io.Externalizable.class, kExternalizableValueHash); - kSpecialCasesVersions.put(java.rmi.Remote.class, kRemoteValueHash); - } - - private static final Hashtable kSpecialCasesClasses = new Hashtable(); - - static { - kSpecialCasesClasses.put(kWStringTypeStr, java.lang.String.class); - kSpecialCasesClasses.put(kClassDescTypeStr, java.lang.Class.class); - kSpecialCasesClasses.put(kRemoteTypeStr, java.rmi.Remote.class); - - kSpecialCasesClasses.put("org.omg.CORBA.WStringValue", java.lang.String.class); - kSpecialCasesClasses.put("javax.rmi.CORBA.ClassDesc", java.lang.Class.class); - //kSpecialCasesClasses.put(kRemoteTypeStr, java.rmi.Remote.class); - } - - private static final Hashtable kSpecialCasesArrayPrefix = new Hashtable(); - - static { - kSpecialCasesArrayPrefix.put(java.lang.String.class, kValuePrefix + kSequencePrefix + kCORBAPrefix); - kSpecialCasesArrayPrefix.put(java.lang.Class.class, kValuePrefix + kSequencePrefix + "javax/rmi/CORBA/"); - kSpecialCasesArrayPrefix.put(java.lang.Object.class, kValuePrefix + kSequencePrefix + "java/lang/"); - kSpecialCasesArrayPrefix.put(java.io.Serializable.class, kValuePrefix + kSequencePrefix + "java/io/"); - kSpecialCasesArrayPrefix.put(java.io.Externalizable.class, kValuePrefix + kSequencePrefix + "java/io/"); - kSpecialCasesArrayPrefix.put(java.rmi.Remote.class, kValuePrefix + kSequencePrefix + kCORBAPrefix); - } - - private static final Hashtable kSpecialPrimitives = new Hashtable(); - - static { - kSpecialPrimitives.put("int","long"); - kSpecialPrimitives.put("long","longlong"); - kSpecialPrimitives.put("byte","octet"); - } - - /** - * Used to convert ascii to hex. - */ - private static final byte ASCII_HEX[] = { - (byte)'0', - (byte)'1', - (byte)'2', - (byte)'3', - (byte)'4', - (byte)'5', - (byte)'6', - (byte)'7', - (byte)'8', - (byte)'9', - (byte)'A', - (byte)'B', - (byte)'C', - (byte)'D', - (byte)'E', - (byte)'F', - }; - - - // Interface Rep ID Strings - public static final String kjava_rmi_Remote = createForAnyType(java.rmi.Remote.class); - public static final String korg_omg_CORBA_Object = createForAnyType(org.omg.CORBA.Object.class); - - // Dummy arguments for getIdFromHelper method - public static final Class kNoParamTypes[] ={}; - public static final Object kNoArgs[] = {}; - - - RepositoryId_1_3(){} - - RepositoryId_1_3(String aRepId){ - init(aRepId); - } - - RepositoryId_1_3 init(String aRepId){ - - this.repId = aRepId; - - // Special case for remote - if (aRepId.length() == 0) { - clazz = java.rmi.Remote.class; - typeString = ""; - isRMIValueType = true; - suid = kInterfaceOnlyHashStr; - return this; - } - else if (aRepId.equals(kWStringValueRepID)) { - clazz = java.lang.String.class; - typeString = kWStringTypeStr; - isIDLType = true; - versionString = kWStringValueVersion; - return this; - } - else { - - String repId = convertFromISOLatin1(aRepId); - - versionString = repId.substring(repId.indexOf(':', repId.indexOf(':')+1)); - if (repId.startsWith(kIDLPrefix)) { - typeString = - repId.substring(kIDLPrefixLength, repId.indexOf(':', kIDLPrefixLength)); - isIDLType = true; - if (typeString.startsWith(kIDLNamePrefix)) - completeClassName = kIDLClassnamePrefix + - typeString.substring(kIDLNamePrefix.length()).replace('/','.'); - else completeClassName = typeString.replace('/','.'); - - } - else if (repId.startsWith(kValuePrefix)) { - typeString = - repId.substring(kValuePrefixLength, repId.indexOf(':', kValuePrefixLength)); - isRMIValueType = true; - - if (versionString.indexOf('.') == -1) { - actualSuid = versionString.substring(1); - suid = actualSuid; // default if not explicitly specified - - if (actualSuid.indexOf(':') != -1){ - // we have a declared hash also - int pos = actualSuid.indexOf(':')+1; - // actualSuid = suid.substring(pos); - // suid = suid.substring(0, pos-1); - suid = actualSuid.substring(pos); - actualSuid = actualSuid.substring(0, pos-1); - } - - } - else { - // _REVISIT_ : Special case version failure ? - } - } - else isSupportedFormat = false; - - if (typeString.startsWith(kSequencePrefix)) { - isSequence = true; - } - - - return this; - } - } - - public final String getUnqualifiedName() { - if (unqualifiedName == null){ - String className = getClassName(); - int index = (className != null) ? className.lastIndexOf('.') : -1; - if (index == -1){ - unqualifiedName = className; - definedInId = "IDL::1.0"; - } - else { - unqualifiedName = className.substring(index); - definedInId = "IDL:" + className.substring(0, index).replace('.','/') + ":1.0"; - } - } - - return unqualifiedName; - } - - public final String getDefinedInId() { - if (definedInId == null){ - getUnqualifiedName(); - } - - return definedInId; - } - - public final String getTypeString() { - return typeString; - } - - public final String getVersionString() { - return versionString; - } - - public final String getSerialVersionUID() { - return suid; - } - - public final String getActualSerialVersionUID() { - return actualSuid; - } - public final long getSerialVersionUIDAsLong() { - return suidLong; - } - - public final long getActualSerialVersionUIDAsLong() { - return actualSuidLong; - } - - public final boolean isRMIValueType() { - return isRMIValueType; - } - - public final boolean isIDLType() { - return isIDLType; - } - - public final String getRepositoryId() { - return repId; - } - - public static byte[] getByteArray(String repStr) { - synchronized (repStrToByteArray){ - return (byte[]) repStrToByteArray.get(repStr); - } - } - - public static void setByteArray(String repStr, byte[] repStrBytes) { - synchronized (repStrToByteArray){ - repStrToByteArray.put(repStr, repStrBytes); - } - } - - public final boolean isSequence() { - return isSequence; - } - - public final boolean isSupportedFormat() { - return isSupportedFormat; - } - - - // This method will return the classname from the typestring OR if the classname turns out to be - // a special class "pseudo" name, then the matching real classname is returned. - public final String getClassName() { - - if (isRMIValueType) - return typeString; - else if (isIDLType) - return completeClassName; - else return null; - - } - - // This method calls getClazzFromType() and falls back to the repStrToClass - // cache if no class was found. It's used where any class matching the - // given repid is an acceptable result. - public final Class getAnyClassFromType() throws ClassNotFoundException { - try { - return getClassFromType(); - } catch (ClassNotFoundException cnfe) { - Class clz = (Class)repStrToClass.get(repId); - if (clz != null) - return clz; - else - throw cnfe; - } - } - - public final Class getClassFromType() - throws ClassNotFoundException { - if (clazz != null) - return clazz; - - Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); - - if (specialCase != null){ - clazz = specialCase; - return specialCase; - } - else - { - try{ - return Util.loadClass(getClassName(), null, null); - } - catch(ClassNotFoundException cnfe){ - if (defaultServerURL != null) { - try{ - return getClassFromType(defaultServerURL); - } - catch(MalformedURLException mue){ - throw cnfe; - } - } - else throw cnfe; - } - } - - } - - public final Class getClassFromType(Class expectedType, String codebase) - throws ClassNotFoundException { - if (clazz != null) - return clazz; - - Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); - - if (specialCase != null){ - clazz = specialCase; - return specialCase; - } else { - ClassLoader expectedTypeClassLoader = (expectedType == null ? null : expectedType.getClassLoader()); - return loadClassOfType(getClassName(), - codebase, - expectedTypeClassLoader, - expectedType, - expectedTypeClassLoader); - } - - } - - public final Class getClassFromType(String url) - throws ClassNotFoundException, MalformedURLException { - return Util.loadClass(getClassName(), url, null); - } - - public final String toString() { - return repId; - } - - private static String createHashString(java.io.Serializable ser) { - - return createHashString(ser.getClass()); - } - - private static String createHashString(java.lang.Class clazz) { - - if (clazz.isInterface() || !java.io.Serializable.class.isAssignableFrom(clazz)) - return kInterfaceHashCode; - - - long actualLong = ObjectStreamClassUtil_1_3.computeStructuralUID(false, clazz); - String hash = null; - if (actualLong == 0) - hash = kInterfaceOnlyHashStr; - else if (actualLong == 1) - hash = kExternalizableHashStr; - else - hash = Long.toHexString(actualLong).toUpperCase(); - while(hash.length() < 16){ - hash = "0" + hash; - } - - long declaredLong = ObjectStreamClassUtil_1_3.computeSerialVersionUID(clazz); - String declared = null; - if (declaredLong == 0) - declared = kInterfaceOnlyHashStr; - else if (declaredLong == 1) - declared = kExternalizableHashStr; - else - declared = Long.toHexString(declaredLong).toUpperCase(); - while (declared.length() < 16){ - declared = "0" + declared; - } - hash = hash + ":" + declared; - - return ":" + hash; - } - - /** - * Creates a repository ID for a sequence. This is for expert users only as - * this method assumes the object passed is an array. If passed an object - * that is not an array, it will produce a rep id for a sequence of zero - * length. This would be an error. - * @param ser The Java object to create a repository ID for - **/ - public static String createSequenceRepID(java.lang.Object ser){ - return createSequenceRepID(ser.getClass()); - } - - /** - * Creates a repository ID for a sequence. This is for expert users only as - * this method assumes the object passed is an array. If passed an object - * that is not an array, it will produce a malformed rep id. - * @param clazz The Java class to create a repository ID for - **/ - public static String createSequenceRepID(java.lang.Class clazz){ - synchronized (classSeqToRepStr){ - - String repid = (String)classSeqToRepStr.get(clazz); - if (repid != null) - return repid; - - Class originalClazz = clazz; - - Class type = null; - int numOfDims = 0; - - while ((type = clazz.getComponentType()) != null) { - numOfDims++; - clazz = type; - } - - if (clazz.isPrimitive()) - repid = kValuePrefix + originalClazz.getName() + kPrimitiveSequenceValueHash; - else { - StringBuffer buf = new StringBuffer(); - buf.append(kValuePrefix); - while(numOfDims-- > 0) { - buf.append("["); - } - buf.append("L"); - buf.append(convertToISOLatin1(clazz.getName())); - buf.append(";"); - buf.append(createHashString(clazz)); - repid = buf.toString(); - } - classSeqToRepStr.put(originalClazz,repid); - return repid; - } - - } - - - public static String createForSpecialCase(java.lang.Class clazz){ - if (clazz.isArray()){ - return createSequenceRepID(clazz); - } - else { - return (String)kSpecialCasesRepIDs.get(clazz); - } - } - - public static String createForSpecialCase(java.io.Serializable ser){ - Class clazz = ser.getClass(); - if (clazz.isArray()){ - return createSequenceRepID(ser); - } - else - return createForSpecialCase(clazz); - } - - /** - * Creates a repository ID for a normal Java Type. - * @param ser The Java object to create a repository ID for - * @exception com.sun.corba.se.impl.io.TypeMismatchException if ser implements the - * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. - **/ - public static String createForJavaType(java.io.Serializable ser) - throws com.sun.corba.se.impl.io.TypeMismatchException - { - synchronized (classToRepStr) { - String repid = createForSpecialCase(ser); - if (repid != null) - return repid; - Class clazz = ser.getClass(); - repid = (String)classToRepStr.get(clazz); - - if (repid != null) - return repid; - - repid = kValuePrefix + convertToISOLatin1(clazz.getName()) + - createHashString(clazz); - - classToRepStr.put(clazz, repid); - repStrToClass.put(repid, clazz); - return repid; - } - } - - /** - * Creates a repository ID for a normal Java Type. - * @param clz The Java class to create a repository ID for - * @exception com.sun.corba.se.impl.io.TypeMismatchException if ser implements the - * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. - **/ - public static String createForJavaType(Class clz) - throws com.sun.corba.se.impl.io.TypeMismatchException - { - synchronized (classToRepStr){ - String repid = createForSpecialCase(clz); - if (repid != null) - return repid; - - repid = (String)classToRepStr.get(clz); - if (repid != null) - return repid; - - repid = kValuePrefix + convertToISOLatin1(clz.getName()) + - createHashString(clz); - - classToRepStr.put(clz, repid); - repStrToClass.put(repid, clz); - return repid; - } - } - - /** - * Creates a repository ID for an IDL Java Type. - * @param ser The IDL Value object to create a repository ID for - * @param major The major version number - * @param minor The minor version number - * @exception com.sun.corba.se.impl.io.TypeMismatchException if ser does not implement the - * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. - **/ - public static String createForIDLType(Class ser, int major, int minor) - throws com.sun.corba.se.impl.io.TypeMismatchException - { - synchronized (classIDLToRepStr){ - String repid = (String)classIDLToRepStr.get(ser); - if (repid != null) - return repid; - - repid = kIDLPrefix + convertToISOLatin1(ser.getName()).replace('.','/') + - ":" + major + "." + minor; - classIDLToRepStr.put(ser, repid); - return repid; - } - } - - private static String getIdFromHelper(Class clazz){ - try { - Class helperClazz = Utility.loadClassForClass(clazz.getName()+"Helper", null, - clazz.getClassLoader(), clazz, clazz.getClassLoader()); - Method idMethod = helperClazz.getDeclaredMethod("id", kNoParamTypes); - return (String)idMethod.invoke(null, kNoArgs); - } - catch(java.lang.ClassNotFoundException cnfe) - { - throw new org.omg.CORBA.MARSHAL(cnfe.toString()); - } - catch(java.lang.NoSuchMethodException nsme) - { - throw new org.omg.CORBA.MARSHAL(nsme.toString()); - } - catch(java.lang.reflect.InvocationTargetException ite) - { - throw new org.omg.CORBA.MARSHAL(ite.toString()); - } - catch(java.lang.IllegalAccessException iae) - { - throw new org.omg.CORBA.MARSHAL(iae.toString()); - } - } - - /** - * Createa a repository ID for the type if it is either a java type - * or an IDL type. - * @param type The type to create rep. id for - * @return The rep. id. - **/ - public static String createForAnyType(Class type) { - try{ - if (type.isArray()) - return createSequenceRepID(type); - else if (IDLEntity.class.isAssignableFrom(type)) - { - try{ - return getIdFromHelper(type); - } - catch(Throwable t) { - return createForIDLType(type, 1, 0); - } - } - else return createForJavaType(type); - } - catch(com.sun.corba.se.impl.io.TypeMismatchException e){ - return null; - } - - } - - public static boolean isAbstractBase(Class clazz) { - return (clazz.isInterface() && - IDLEntity.class.isAssignableFrom(clazz) && - (!ValueBase.class.isAssignableFrom(clazz)) && - (!org.omg.CORBA.Object.class.isAssignableFrom(clazz))); - - } - - /** - * Convert strings with illegal IDL identifier characters. - *

    - * Section 5.5.7 of OBV spec. - */ - private static String convertToISOLatin1 (String name) { - - int length = name.length(); - if (length == 0) { - return name; - } - StringBuffer buffer = null; - - for (int i = 0; i < length; i++) { - - char c = name.charAt(i); - - if (c > 255 || IDL_IDENTIFIER_CHARS[c] == 0) { - - // We gotta convert. Have we already started? - - if (buffer == null) { - - // No, so get set up... - - buffer = new StringBuffer(name.substring(0,i)); - } - - // Convert the character into the IDL escape syntax... - buffer.append( - "\\U" + - (char)ASCII_HEX[(c & 0xF000) >>> 12] + - (char)ASCII_HEX[(c & 0x0F00) >>> 8] + - (char)ASCII_HEX[(c & 0x00F0) >>> 4] + - (char)ASCII_HEX[(c & 0x000F)]); - - } else { - if (buffer != null) { - buffer.append(c); - } - } - } - - if (buffer != null) { - name = buffer.toString(); - } - - return name; - } - - /** - * Convert strings with ISO Latin 1 escape sequences back to original strings. - *

    - * Section 5.5.7 of OBV spec. - */ - private static String convertFromISOLatin1 (String name) { - - int index = -1; - StringBuffer buf = new StringBuffer(name); - - while ((index = buf.toString().indexOf("\\U")) != -1){ - String str = "0000" + buf.toString().substring(index+2, index+6); - - // Convert Hexadecimal - byte[] buffer = new byte[(str.length() - 4) / 2]; - for (int i=4, j=0; i < str.length(); i +=2, j++) { - buffer[j] = (byte)((ORBUtility.hexOf(str.charAt(i)) << 4) & 0xF0); - buffer[j] |= (byte)((ORBUtility.hexOf(str.charAt(i+1)) << 0) & 0x0F); - } - buf = new StringBuffer(delete(buf.toString(), index, index+6)); - buf.insert(index, (char)buffer[1]); - } - - return buf.toString(); - - - } - - private static String delete(String str, int from, int to) - { - return str.substring(0, from) + str.substring(to, str.length()); - } - - private static String replace(String target, String arg, String source) - { - int i = 0; - i = target.indexOf(arg); - - while(i != -1) - { - String left = target.substring(0, i); - String right = target.substring(i+arg.length()); - target = new String(left+source+right); - i = target.indexOf(arg); - } - return target; - } - - /* - * Load a class and check that it is assignable to a given type. - * @param className the class name. - * @param remoteCodebase the codebase to use. May be null. - * @param loader the class loader of last resort. May be null. - * @param expectedType the expected type. May be null. - * @return the loaded class. - */ - private Class loadClassOfType (String className, - String remoteCodebase, - ClassLoader loader, - Class expectedType, - ClassLoader expectedTypeClassLoader) - throws ClassNotFoundException { - - Class loadedClass = null; - - try { - //Sequence finding of the stubs according to spec - try{ - //If-else is put here for speed up of J2EE. - //According to the OMG spec, the if clause is not dead code. - //It can occur if some compiler has allowed generation - //into org.omg.stub hierarchy for non-offending - //classes. This will encourage people to - //produce non-offending class stubs in their own hierarchy. - if(!PackagePrefixChecker - .hasOffendingPrefix(PackagePrefixChecker - .withoutPackagePrefix(className))){ - loadedClass = Util.loadClass - (PackagePrefixChecker.withoutPackagePrefix(className), - remoteCodebase, - loader); - } else { - loadedClass = Util.loadClass - (className, - remoteCodebase, - loader); - } - } catch (ClassNotFoundException cnfe) { - loadedClass = Util.loadClass - (className, - remoteCodebase, - loader); - } - if (expectedType == null) - return loadedClass; - } catch (ClassNotFoundException cnfe) { - if (expectedType == null) - throw cnfe; - } - - // If no class was not loaded, or if the loaded class is not of the - // correct type, make a further attempt to load the correct class - // using the classloader of the expected type. - // _REVISIT_ Is this step necessary, or should the Util,loadClass - // algorithm always produce a valid class if the setup is correct? - // Does the OMG standard algorithm need to be changed to include - // this step? - if (loadedClass == null || !expectedType.isAssignableFrom(loadedClass)) { - if (expectedType.getClassLoader() != expectedTypeClassLoader) - throw new IllegalArgumentException("expectedTypeClassLoader not class loader of expectedType."); - - if (expectedTypeClassLoader != null) - loadedClass = expectedTypeClassLoader.loadClass(className); - else - loadedClass = ORBClassLoader.loadClass(className); - } - - return loadedClass; - } - - /** - * Checks to see if the FullValueDescription should be retrieved. - * @exception Throws IOException if suids do not match or if the repositoryID - * is not an RMIValueType - */ - public static boolean useFullValueDescription(Class clazz, String repositoryID) - throws IOException{ - - String clazzRepIDStr = createForAnyType(clazz); - - if (clazzRepIDStr.equals(repositoryID)) - return false; - - RepositoryId_1_3 targetRepid; - RepositoryId_1_3 clazzRepid; - - synchronized(cache) { - // to avoid race condition where multiple threads could be - // accessing this method, and their access to the cache may - // be interleaved giving unexpected results - - targetRepid = cache.getId(repositoryID); - clazzRepid = cache.getId(clazzRepIDStr); - } - - if ((targetRepid.isRMIValueType()) && (clazzRepid.isRMIValueType())){ - if (!targetRepid.getSerialVersionUID().equals(clazzRepid.getSerialVersionUID())) { - - String mssg = "Mismatched serialization UIDs : Source (Rep. ID" + - clazzRepid + ") = " + - clazzRepid.getSerialVersionUID() + " whereas Target (Rep. ID " + repositoryID + - ") = " + targetRepid.getSerialVersionUID(); - throw new IOException(mssg); - } else { - return true; - } - } else { - - throw new IOException("The repository ID is not of an RMI value type (Expected ID = " + clazzRepIDStr + "; Received ID = " + repositoryID +")"); - } - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/RepositoryId_1_3_1.java 2013-02-07 17:08:09.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,1065 +0,0 @@ -/* - * Copyright (c) 2001, 2012, 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.corba.se.impl.orbutil; - -import java.util.StringTokenizer; -import java.util.Hashtable; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import org.omg.CORBA.portable.ValueBase; -import org.omg.CORBA.portable.IDLEntity; - -//d11638 files in the same package, therefore remove their reference -//import com.sun.corba.se.impl.util.JDKBridge; -//import com.sun.corba.se.impl.util.IdentityHashtable; -import com.sun.corba.se.impl.util.JDKBridge; -import com.sun.corba.se.impl.util.Utility; -import com.sun.corba.se.impl.util.PackagePrefixChecker; -import com.sun.corba.se.impl.util.IdentityHashtable; - -import javax.rmi.CORBA.Util; - -/** - * Because all methods in RepositoryId are static, we have - * to duplicate all of this code, freezing it in its 1.3.1 - * form for backwards compatibility. - * - * For security reasons, we can't expose enough of - * io/ObjectStreamClass, so it has to be duplicated in - * orbutil. - */ -public class RepositoryId_1_3_1 { - - // Legal IDL Identifier characters (1 = legal). Note - // that '.' (2E) is marked as legal even though it is - // not legal in IDL. This allows us to treat a fully - // qualified Java name with '.' package separators - // uniformly, and is safe because that is the only - // legal use of '.' in a Java name. - - private static final byte[] IDL_IDENTIFIER_CHARS = { - - // 0 1 2 3 4 5 6 7 8 9 a b c d e f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 00-0f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 10-1f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,1,0, // 20-2f - 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, // 30-3f - 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 40-4f - 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,1, // 50-5f - 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 60-6f - 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0, // 70-7f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 80-8f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 90-9f - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // a0-af - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // b0-bf - 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // c0-cf - 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // d0-df - 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // e0-ef - 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // f0-ff - }; - - - private static final long serialVersionUID = 123456789L; - - private static String defaultServerURL = null; - private static boolean useCodebaseOnly = false; - - static { - if (defaultServerURL == null) - defaultServerURL = (String)JDKBridge.getLocalCodebase(); - useCodebaseOnly = JDKBridge.useCodebaseOnly(); - - } - - private static IdentityHashtable classToRepStr = new IdentityHashtable(); - private static IdentityHashtable classIDLToRepStr = new IdentityHashtable(); - private static IdentityHashtable classSeqToRepStr = new IdentityHashtable(); - - private static IdentityHashtable repStrToByteArray = new IdentityHashtable(); - private static Hashtable repStrToClass = new Hashtable(); - - private String repId = null; - private boolean isSupportedFormat = true; - private String typeString = null; - private String versionString = null; - private boolean isSequence = false; - private boolean isRMIValueType = false; - private boolean isIDLType = false; - private String completeClassName = null; - private String unqualifiedName = null; - private String definedInId = null; - private Class clazz = null; - private String suid = null, actualSuid = null; - private long suidLong = ObjectStreamClass_1_3_1.kDefaultUID, actualSuidLong = ObjectStreamClass_1_3_1.kDefaultUID; - - // Repository ID fragments - private static final String kSequenceKeyword = "seq"; - private static final String kValuePrefix = "RMI:"; - private static final String kIDLPrefix = "IDL:"; - private static final String kIDLNamePrefix = "omg.org/"; - private static final String kIDLClassnamePrefix = "org.omg."; - private static final String kSequencePrefix = "["; - private static final String kCORBAPrefix = "CORBA/"; - private static final String kArrayPrefix = kValuePrefix + kSequencePrefix + kCORBAPrefix; - private static final int kValuePrefixLength = kValuePrefix.length(); - private static final int kIDLPrefixLength = kIDLPrefix.length(); - private static final int kSequencePrefixLength = kSequencePrefix.length(); - private static final String kInterfaceHashCode = ":0000000000000000"; - private static final String kInterfaceOnlyHashStr = "0000000000000000"; - private static final String kExternalizableHashStr = "0000000000000001"; - - // Value tag utility methods and constants - public static final int kInitialValueTag= 0x7fffff00; - public static final int kNoTypeInfo = 0; - public static final int kSingleRepTypeInfo = 0x02; - public static final int kPartialListTypeInfo = 0x06; - public static final int kChunkedMask = 0x08; - public static final int kPreComputed_StandardRMIUnchunked = RepositoryId_1_3_1.computeValueTag(false, RepositoryId_1_3_1.kSingleRepTypeInfo, false); - public static final int kPreComputed_CodeBaseRMIUnchunked = RepositoryId_1_3_1.computeValueTag(true, RepositoryId_1_3_1.kSingleRepTypeInfo, false); - public static final int kPreComputed_StandardRMIChunked = RepositoryId_1_3_1.computeValueTag(false, RepositoryId_1_3_1.kSingleRepTypeInfo, true); - public static final int kPreComputed_CodeBaseRMIChunked = RepositoryId_1_3_1.computeValueTag(true, RepositoryId_1_3_1.kSingleRepTypeInfo, true); - - public static final int kPreComputed_StandardRMIUnchunked_NoRep = RepositoryId_1_3_1.computeValueTag(false, RepositoryId_1_3_1.kNoTypeInfo, false); - public static final int kPreComputed_CodeBaseRMIUnchunked_NoRep = RepositoryId_1_3_1.computeValueTag(true, RepositoryId_1_3_1.kNoTypeInfo, false); - public static final int kPreComputed_StandardRMIChunked_NoRep = RepositoryId_1_3_1.computeValueTag(false, RepositoryId_1_3_1.kNoTypeInfo, true); - public static final int kPreComputed_CodeBaseRMIChunked_NoRep = RepositoryId_1_3_1.computeValueTag(true, RepositoryId_1_3_1.kNoTypeInfo, true); - - // Public, well known repository IDs - - // _REVISIT_ : A table structure with a good search routine for all of this - // would be more efficient and easier to maintain... - - // String - public static final String kWStringValueVersion = "1.0"; - public static final String kWStringValueHash = ":"+kWStringValueVersion; - public static final String kWStringStubValue = "WStringValue"; - public static final String kWStringTypeStr = "omg.org/CORBA/"+kWStringStubValue; - public static final String kWStringValueRepID = kIDLPrefix + kWStringTypeStr + kWStringValueHash; - - // Any - public static final String kAnyRepID = kIDLPrefix + "omg.org/CORBA/Any"; - - // Class - // Anita4: convert to uppercase - public static final String kClassDescValueHash = ":" + - Long.toHexString( - ObjectStreamClass_1_3_1.getActualSerialVersionUID(javax.rmi.CORBA.ClassDesc.class)).toUpperCase() + ":" + - Long.toHexString( - ObjectStreamClass_1_3_1.getSerialVersionUID(javax.rmi.CORBA.ClassDesc.class)).toUpperCase(); - public static final String kClassDescStubValue = "ClassDesc"; - public static final String kClassDescTypeStr = "javax.rmi.CORBA."+kClassDescStubValue; - public static final String kClassDescValueRepID = kValuePrefix + kClassDescTypeStr + kClassDescValueHash; - - // Object - public static final String kObjectValueHash = ":1.0"; - public static final String kObjectStubValue = "Object"; - - // Sequence - public static final String kSequenceValueHash = ":1.0"; - public static final String kPrimitiveSequenceValueHash = ":0000000000000000"; - - // Serializable - public static final String kSerializableValueHash = ":1.0"; - public static final String kSerializableStubValue = "Serializable"; - - // Externalizable - public static final String kExternalizableValueHash = ":1.0"; - public static final String kExternalizableStubValue = "Externalizable"; - - // Remote (The empty string is used for java.rmi.Remote) - public static final String kRemoteValueHash = ""; - public static final String kRemoteStubValue = ""; - public static final String kRemoteTypeStr = ""; - public static final String kRemoteValueRepID = ""; - - private static final Hashtable kSpecialArrayTypeStrings = new Hashtable(); - - static { - kSpecialArrayTypeStrings.put("CORBA.WStringValue", new StringBuffer(java.lang.String.class.getName())); - kSpecialArrayTypeStrings.put("javax.rmi.CORBA.ClassDesc", new StringBuffer(java.lang.Class.class.getName())); - kSpecialArrayTypeStrings.put("CORBA.Object", new StringBuffer(java.rmi.Remote.class.getName())); - - } - - private static final Hashtable kSpecialCasesRepIDs = new Hashtable(); - - static { - kSpecialCasesRepIDs.put(java.lang.String.class, kWStringValueRepID); - kSpecialCasesRepIDs.put(java.lang.Class.class, kClassDescValueRepID); - kSpecialCasesRepIDs.put(java.rmi.Remote.class, kRemoteValueRepID); - } - - private static final Hashtable kSpecialCasesStubValues = new Hashtable(); - - static { - kSpecialCasesStubValues.put(java.lang.String.class, kWStringStubValue); - kSpecialCasesStubValues.put(java.lang.Class.class, kClassDescStubValue); - kSpecialCasesStubValues.put(java.lang.Object.class, kObjectStubValue); - kSpecialCasesStubValues.put(java.io.Serializable.class, kSerializableStubValue); - kSpecialCasesStubValues.put(java.io.Externalizable.class, kExternalizableStubValue); - kSpecialCasesStubValues.put(java.rmi.Remote.class, kRemoteStubValue); - } - - - private static final Hashtable kSpecialCasesVersions = new Hashtable(); - - static { - kSpecialCasesVersions.put(java.lang.String.class, kWStringValueHash); - kSpecialCasesVersions.put(java.lang.Class.class, kClassDescValueHash); - kSpecialCasesVersions.put(java.lang.Object.class, kObjectValueHash); - kSpecialCasesVersions.put(java.io.Serializable.class, kSerializableValueHash); - kSpecialCasesVersions.put(java.io.Externalizable.class, kExternalizableValueHash); - kSpecialCasesVersions.put(java.rmi.Remote.class, kRemoteValueHash); - } - - private static final Hashtable kSpecialCasesClasses = new Hashtable(); - - static { - kSpecialCasesClasses.put(kWStringTypeStr, java.lang.String.class); - kSpecialCasesClasses.put(kClassDescTypeStr, java.lang.Class.class); - kSpecialCasesClasses.put(kRemoteTypeStr, java.rmi.Remote.class); - - kSpecialCasesClasses.put("org.omg.CORBA.WStringValue", java.lang.String.class); - kSpecialCasesClasses.put("javax.rmi.CORBA.ClassDesc", java.lang.Class.class); - //kSpecialCasesClasses.put(kRemoteTypeStr, java.rmi.Remote.class); - } - - private static final Hashtable kSpecialCasesArrayPrefix = new Hashtable(); - - static { - kSpecialCasesArrayPrefix.put(java.lang.String.class, kValuePrefix + kSequencePrefix + kCORBAPrefix); - kSpecialCasesArrayPrefix.put(java.lang.Class.class, kValuePrefix + kSequencePrefix + "javax/rmi/CORBA/"); - kSpecialCasesArrayPrefix.put(java.lang.Object.class, kValuePrefix + kSequencePrefix + "java/lang/"); - kSpecialCasesArrayPrefix.put(java.io.Serializable.class, kValuePrefix + kSequencePrefix + "java/io/"); - kSpecialCasesArrayPrefix.put(java.io.Externalizable.class, kValuePrefix + kSequencePrefix + "java/io/"); - kSpecialCasesArrayPrefix.put(java.rmi.Remote.class, kValuePrefix + kSequencePrefix + kCORBAPrefix); - } - - private static final Hashtable kSpecialPrimitives = new Hashtable(); - - static { - kSpecialPrimitives.put("int","long"); - kSpecialPrimitives.put("long","longlong"); - kSpecialPrimitives.put("byte","octet"); - } - - /** - * Used to convert ascii to hex. - */ - private static final byte ASCII_HEX[] = { - (byte)'0', - (byte)'1', - (byte)'2', - (byte)'3', - (byte)'4', - (byte)'5', - (byte)'6', - (byte)'7', - (byte)'8', - (byte)'9', - (byte)'A', - (byte)'B', - (byte)'C', - (byte)'D', - (byte)'E', - (byte)'F', - }; - - - // bug fix for 4328952; to eliminate possibility of overriding this - // in a subclass. - public static final RepositoryIdCache_1_3_1 cache = new RepositoryIdCache_1_3_1(); - - // Interface Rep ID Strings - public static final String kjava_rmi_Remote = createForAnyType(java.rmi.Remote.class); - public static final String korg_omg_CORBA_Object = createForAnyType(org.omg.CORBA.Object.class); - - // Dummy arguments for getIdFromHelper method - public static final Class kNoParamTypes[] ={}; - public static final Object kNoArgs[] = {}; - - - // To create a RepositoryID, use code similar to the following: - // RepositoryId.cache.getId( id ); - - RepositoryId_1_3_1(){} - - RepositoryId_1_3_1(String aRepId){ - init(aRepId); - } - - RepositoryId_1_3_1 init(String aRepId){ - - this.repId = aRepId; - - // Special case for remote - if (aRepId.length() == 0) { - clazz = java.rmi.Remote.class; - typeString = ""; - isRMIValueType = true; - suid = kInterfaceOnlyHashStr; - return this; - } - else if (aRepId.equals(kWStringValueRepID)) { - clazz = java.lang.String.class; - typeString = kWStringTypeStr; - isIDLType = true; - // fix where Attempting to obtain a FullValueDescription - // for an RMI value type with a String field causes an exception. - completeClassName = "java.lang.String"; - versionString = kWStringValueVersion; - return this; - } - else { - - String repId = convertFromISOLatin1(aRepId); - - versionString = repId.substring(repId.indexOf(':', repId.indexOf(':')+1)); - if (repId.startsWith(kIDLPrefix)) { - typeString = - repId.substring(kIDLPrefixLength, repId.indexOf(':', kIDLPrefixLength)); - isIDLType = true; - if (typeString.startsWith(kIDLNamePrefix)) - completeClassName = kIDLClassnamePrefix + - typeString.substring(kIDLNamePrefix.length()).replace('/','.'); - else completeClassName = typeString.replace('/','.'); - - } - else if (repId.startsWith(kValuePrefix)) { - typeString = - repId.substring(kValuePrefixLength, repId.indexOf(':', kValuePrefixLength)); - isRMIValueType = true; - - if (versionString.indexOf('.') == -1) { - actualSuid = versionString.substring(1); - suid = actualSuid; // default if not explicitly specified - - if (actualSuid.indexOf(':') != -1){ - // we have a declared hash also - int pos = actualSuid.indexOf(':')+1; - // actualSuid = suid.substring(pos); - // suid = suid.substring(0, pos-1); - suid = actualSuid.substring(pos); - actualSuid = actualSuid.substring(0, pos-1); - } - - } - else { - // _REVISIT_ : Special case version failure ? - } - } - else isSupportedFormat = false; - - if (typeString.startsWith(kSequencePrefix)) { - isSequence = true; - } - - - return this; - } - } - - public final String getUnqualifiedName() { - if (unqualifiedName == null){ - String className = getClassName(); - int index = className.lastIndexOf('.'); - if (index == -1){ - unqualifiedName = className; - definedInId = "IDL::1.0"; - } - else { - unqualifiedName = className.substring(index); - definedInId = "IDL:" + className.substring(0, index).replace('.','/') + ":1.0"; - } - } - - return unqualifiedName; - } - - public final String getDefinedInId() { - if (definedInId == null){ - getUnqualifiedName(); - } - - return definedInId; - } - - public final String getTypeString() { - return typeString; - } - - public final String getVersionString() { - return versionString; - } - - public final String getSerialVersionUID() { - return suid; - } - - public final String getActualSerialVersionUID() { - return actualSuid; - } - public final long getSerialVersionUIDAsLong() { - return suidLong; - } - - public final long getActualSerialVersionUIDAsLong() { - return actualSuidLong; - } - - public final boolean isRMIValueType() { - return isRMIValueType; - } - - public final boolean isIDLType() { - return isIDLType; - } - - public final String getRepositoryId() { - return repId; - } - - public static byte[] getByteArray(String repStr) { - synchronized (repStrToByteArray){ - return (byte[]) repStrToByteArray.get(repStr); - } - } - - public static void setByteArray(String repStr, byte[] repStrBytes) { - synchronized (repStrToByteArray){ - repStrToByteArray.put(repStr, repStrBytes); - } - } - - public final boolean isSequence() { - return isSequence; - } - - public final boolean isSupportedFormat() { - return isSupportedFormat; - } - - - // This method will return the classname from the typestring OR if the classname turns out to be - // a special class "pseudo" name, then the matching real classname is returned. - public final String getClassName() { - - if (isRMIValueType) - return typeString; - else if (isIDLType) - return completeClassName; - else return null; - - } - - // This method calls getClazzFromType() and falls back to the repStrToClass - // cache if no class was found. It's used where any class matching the - // given repid is an acceptable result. - public final Class getAnyClassFromType() throws ClassNotFoundException { - try { - return getClassFromType(); - } catch (ClassNotFoundException cnfe) { - Class clz = (Class)repStrToClass.get(repId); - if (clz != null) - return clz; - else - throw cnfe; - } - } - - public final Class getClassFromType() - throws ClassNotFoundException { - if (clazz != null) - return clazz; - - Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); - - if (specialCase != null){ - clazz = specialCase; - return specialCase; - } - else - { - try{ - return Util.loadClass(getClassName(), null, null); - } - catch(ClassNotFoundException cnfe){ - if (defaultServerURL != null) { - try{ - return getClassFromType(defaultServerURL); - } - catch(MalformedURLException mue){ - throw cnfe; - } - } - else throw cnfe; - } - } - - } - - public final Class getClassFromType(Class expectedType, String codebase) - throws ClassNotFoundException { - if (clazz != null) - return clazz; - - Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); - - if (specialCase != null){ - clazz = specialCase; - return specialCase; - } else { - ClassLoader expectedTypeClassLoader = (expectedType == null ? null : expectedType.getClassLoader()); - return loadClassOfType(getClassName(), - codebase, - expectedTypeClassLoader, - expectedType, - expectedTypeClassLoader); - } - - } - - public final Class getClassFromType(String url) - throws ClassNotFoundException, MalformedURLException { - return Util.loadClass(getClassName(), url, null); - } - - public final String toString() { - return repId; - } - - /** - * Checks to see if the FullValueDescription should be retrieved. - * @exception Throws IOException if suids do not match or if the repositoryID - * is not an RMIValueType - */ - public static boolean useFullValueDescription(Class clazz, String repositoryID) - throws IOException{ - - String clazzRepIDStr = createForAnyType(clazz); - - if (clazzRepIDStr.equals(repositoryID)) - return false; - - RepositoryId_1_3_1 targetRepid; - RepositoryId_1_3_1 clazzRepid; - - synchronized(cache) { - // to avoid race condition where multiple threads could be - // accessing this method, and their access to the cache may - // be interleaved giving unexpected results - - targetRepid = cache.getId(repositoryID); - clazzRepid = cache.getId(clazzRepIDStr); - } - //ObjectStreamClass osc = ObjectStreamClass.lookup(clazz); - - if ((targetRepid.isRMIValueType()) && (clazzRepid.isRMIValueType())){ - if (!targetRepid.getSerialVersionUID().equals(clazzRepid.getSerialVersionUID())) { - - String mssg = "Mismatched serialization UIDs : Source (Rep. ID" + - clazzRepid + ") = " + - clazzRepid.getSerialVersionUID() + " whereas Target (Rep. ID " + repositoryID + - ") = " + targetRepid.getSerialVersionUID(); - //com.sun.corba.se.impl.io.ValueUtility.log("RepositoryId",mssg); - throw new IOException(mssg); - } - else { - return true; - } - } - else { - - throw new IOException("The repository ID is not of an RMI value type (Expected ID = " + clazzRepIDStr + "; Received ID = " + repositoryID +")"); - } - } - - private static String createHashString(java.io.Serializable ser) { - - return createHashString(ser.getClass()); - } - - private static String createHashString(java.lang.Class clazz) { - - if (clazz.isInterface() || !java.io.Serializable.class.isAssignableFrom(clazz)) - return kInterfaceHashCode; - - //ObjectStreamClass osc = ObjectStreamClass.lookup(clazz); - - long actualLong = ObjectStreamClass_1_3_1.getActualSerialVersionUID(clazz); - String hash = null; - if (actualLong == 0) - hash = kInterfaceOnlyHashStr; - else if (actualLong == 1) - hash = kExternalizableHashStr; - else - hash = Long.toHexString(actualLong).toUpperCase(); - while(hash.length() < 16){ - hash = "0" + hash; - } - - long declaredLong = ObjectStreamClass_1_3_1.getSerialVersionUID(clazz); - String declared = null; - if (declaredLong == 0) - declared = kInterfaceOnlyHashStr; - else if (declaredLong == 1) - declared = kExternalizableHashStr; - else - declared = Long.toHexString(declaredLong).toUpperCase(); - while (declared.length() < 16){ - declared = "0" + declared; - } - hash = hash + ":" + declared; - - return ":" + hash; - } - - /** - * Creates a repository ID for a sequence. This is for expert users only as - * this method assumes the object passed is an array. If passed an object - * that is not an array, it will produce a rep id for a sequence of zero - * length. This would be an error. - * @param ser The Java object to create a repository ID for - **/ - public static String createSequenceRepID(java.lang.Object ser){ - return createSequenceRepID(ser.getClass()); - } - - /** - * Creates a repository ID for a sequence. This is for expert users only as - * this method assumes the object passed is an array. If passed an object - * that is not an array, it will produce a malformed rep id. - * @param clazz The Java class to create a repository ID for - **/ - public static String createSequenceRepID(java.lang.Class clazz){ - synchronized (classSeqToRepStr){ - - String repid = (String)classSeqToRepStr.get(clazz); - if (repid != null) - return repid; - - Class originalClazz = clazz; - - Class type = null; - int numOfDims = 0; - - while ((type = clazz.getComponentType()) != null) { - numOfDims++; - clazz = type; - } - - if (clazz.isPrimitive()) - repid = kValuePrefix + originalClazz.getName() + kPrimitiveSequenceValueHash; - else { - StringBuffer buf = new StringBuffer(); - buf.append(kValuePrefix); - while(numOfDims-- > 0) { - buf.append("["); - } - buf.append("L"); - buf.append(convertToISOLatin1(clazz.getName())); - buf.append(";"); - buf.append(createHashString(clazz)); - repid = buf.toString(); - } - classSeqToRepStr.put(originalClazz,repid); - return repid; - } - - } - - - public static String createForSpecialCase(java.lang.Class clazz){ - if (clazz.isArray()){ - return createSequenceRepID(clazz); - } - else { - return (String)kSpecialCasesRepIDs.get(clazz); - } - } - - public static String createForSpecialCase(java.io.Serializable ser){ - Class clazz = ser.getClass(); - if (clazz.isArray()){ - return createSequenceRepID(ser); - } - else - return createForSpecialCase(clazz); - } - - /** - * Creates a repository ID for a normal Java Type. - * @param ser The Java object to create a repository ID for - * @exception com.sun.corba.se.impl.io.TypeMismatchException if ser implements the - * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. - **/ - public static String createForJavaType(java.io.Serializable ser) - throws com.sun.corba.se.impl.io.TypeMismatchException - { - synchronized (classToRepStr) { - String repid = createForSpecialCase(ser); - if (repid != null) - return repid; - Class clazz = ser.getClass(); - repid = (String)classToRepStr.get(clazz); - - if (repid != null) - return repid; - - repid = kValuePrefix + convertToISOLatin1(clazz.getName()) + - createHashString(clazz); - - classToRepStr.put(clazz, repid); - repStrToClass.put(repid, clazz); - return repid; - } - } - - /** - * Creates a repository ID for a normal Java Type. - * @param clz The Java class to create a repository ID for - * @exception com.sun.corba.se.impl.io.TypeMismatchException if ser implements the - * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. - **/ - public static String createForJavaType(Class clz) - throws com.sun.corba.se.impl.io.TypeMismatchException - { - synchronized (classToRepStr){ - String repid = createForSpecialCase(clz); - if (repid != null) - return repid; - - repid = (String)classToRepStr.get(clz); - if (repid != null) - return repid; - - repid = kValuePrefix + convertToISOLatin1(clz.getName()) + - createHashString(clz); - - classToRepStr.put(clz, repid); - repStrToClass.put(repid, clz); - return repid; - } - } - - /** - * Creates a repository ID for an IDL Java Type. - * @param ser The IDL Value object to create a repository ID for - * @param major The major version number - * @param minor The minor version number - * @exception com.sun.corba.se.impl.io.TypeMismatchException if ser does not implement the - * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. - **/ - public static String createForIDLType(Class ser, int major, int minor) - throws com.sun.corba.se.impl.io.TypeMismatchException - { - synchronized (classIDLToRepStr){ - String repid = (String)classIDLToRepStr.get(ser); - if (repid != null) - return repid; - - repid = kIDLPrefix + convertToISOLatin1(ser.getName()).replace('.','/') + - ":" + major + "." + minor; - classIDLToRepStr.put(ser, repid); - return repid; - } - } - - private static String getIdFromHelper(Class clazz){ - try { - Class helperClazz = Utility.loadClassForClass(clazz.getName()+"Helper", null, - clazz.getClassLoader(), clazz, clazz.getClassLoader()); - Method idMethod = helperClazz.getDeclaredMethod("id", kNoParamTypes); - return (String)idMethod.invoke(null, kNoArgs); - } - catch(java.lang.ClassNotFoundException cnfe) - { - throw new org.omg.CORBA.MARSHAL(cnfe.toString()); - } - catch(java.lang.NoSuchMethodException nsme) - { - throw new org.omg.CORBA.MARSHAL(nsme.toString()); - } - catch(java.lang.reflect.InvocationTargetException ite) - { - throw new org.omg.CORBA.MARSHAL(ite.toString()); - } - catch(java.lang.IllegalAccessException iae) - { - throw new org.omg.CORBA.MARSHAL(iae.toString()); - } - } - - /** - * Createa a repository ID for the type if it is either a java type - * or an IDL type. - * @param type The type to create rep. id for - * @return The rep. id. - **/ - public static String createForAnyType(Class type) { - try{ - if (type.isArray()) - return createSequenceRepID(type); - else if (IDLEntity.class.isAssignableFrom(type)) - { - try{ - return getIdFromHelper(type); - } - catch(Throwable t) { - return createForIDLType(type, 1, 0); - } - } - else return createForJavaType(type); - } - catch(com.sun.corba.se.impl.io.TypeMismatchException e){ - return null; - } - - } - - public static boolean isAbstractBase(Class clazz) { - return (clazz.isInterface() && - IDLEntity.class.isAssignableFrom(clazz) && - (!ValueBase.class.isAssignableFrom(clazz)) && - (!org.omg.CORBA.Object.class.isAssignableFrom(clazz))); - - } - - public static boolean isAnyRequired(Class clazz) { - return ((clazz == java.lang.Object.class) || - (clazz == java.io.Serializable.class) || - (clazz == java.io.Externalizable.class)); - } - - public static long fromHex(String hexNumber) { - if (hexNumber.startsWith("0x")) - return Long.valueOf(hexNumber.substring(2), 16).longValue(); - else return Long.valueOf(hexNumber, 16).longValue(); - } - - /** - * Convert strings with illegal IDL identifier characters. - *

    - * Section 5.5.7 of OBV spec. - */ - private static String convertToISOLatin1 (String name) { - - int length = name.length(); - if (length == 0) { - return name; - } - StringBuffer buffer = null; - - for (int i = 0; i < length; i++) { - - char c = name.charAt(i); - - if (c > 255 || IDL_IDENTIFIER_CHARS[c] == 0) { - - // We gotta convert. Have we already started? - - if (buffer == null) { - - // No, so get set up... - - buffer = new StringBuffer(name.substring(0,i)); - } - - // Convert the character into the IDL escape syntax... - buffer.append( - "\\U" + - (char)ASCII_HEX[(c & 0xF000) >>> 12] + - (char)ASCII_HEX[(c & 0x0F00) >>> 8] + - (char)ASCII_HEX[(c & 0x00F0) >>> 4] + - (char)ASCII_HEX[(c & 0x000F)]); - - } else { - if (buffer != null) { - buffer.append(c); - } - } - } - - if (buffer != null) { - name = buffer.toString(); - } - - return name; - } - - /** - * Convert strings with ISO Latin 1 escape sequences back to original strings. - *

    - * Section 5.5.7 of OBV spec. - */ - private static String convertFromISOLatin1 (String name) { - - int index = -1; - StringBuffer buf = new StringBuffer(name); - - while ((index = buf.toString().indexOf("\\U")) != -1){ - String str = "0000" + buf.toString().substring(index+2, index+6); - - // Convert Hexadecimal - byte[] buffer = new byte[(str.length() - 4) / 2]; - for (int i=4, j=0; i < str.length(); i +=2, j++) { - buffer[j] = (byte)((ORBUtility.hexOf(str.charAt(i)) << 4) & 0xF0); - buffer[j] |= (byte)((ORBUtility.hexOf(str.charAt(i+1)) << 0) & 0x0F); - } - buf = new StringBuffer(delete(buf.toString(), index, index+6)); - buf.insert(index, (char)buffer[1]); - } - - return buf.toString(); - - - } - - private static String delete(String str, int from, int to) - { - return str.substring(0, from) + str.substring(to, str.length()); - } - - private static String replace(String target, String arg, String source) - { - int i = 0; - i = target.indexOf(arg); - - while(i != -1) - { - String left = target.substring(0, i); - String right = target.substring(i+arg.length()); - target = new String(left+source+right); - i = target.indexOf(arg); - } - return target; - } - - public static int computeValueTag(boolean codeBasePresent, int typeInfo, boolean chunkedEncoding){ - int value_tag = kInitialValueTag; - - if (codeBasePresent) - value_tag = value_tag | 0x00000001; - - value_tag = value_tag | typeInfo; - - if (chunkedEncoding) - value_tag = value_tag | kChunkedMask; - - return value_tag; - } - - public static boolean isCodeBasePresent(int value_tag){ - return ((value_tag & 0x00000001) == 1); - } - - public static int getTypeInfo(int value_tag){ - return (value_tag & 0x00000006); - } - - public static boolean isChunkedEncoding(int value_tag){ - return ((value_tag & kChunkedMask) != 0); - } - - public static String getServerURL(){ - return defaultServerURL; - } - - /* - * Load a class and check that it is assignable to a given type. - * @param className the class name. - * @param remoteCodebase the codebase to use. May be null. - * @param loader the class loader of last resort. May be null. - * @param expectedType the expected type. May be null. - * @return the loaded class. - */ - private Class loadClassOfType (String className, - String remoteCodebase, - ClassLoader loader, - Class expectedType, - ClassLoader expectedTypeClassLoader) - throws ClassNotFoundException { - - Class loadedClass = null; - - try { - //Sequence finding of the stubs according to spec - try{ - //If-else is put here for speed up of J2EE. - //According to the OMG spec, the if clause is not dead code. - //It can occur if some compiler has allowed generation - //into org.omg.stub hierarchy for non-offending - //classes. This will encourage people to - //produce non-offending class stubs in their own hierarchy. - if(!PackagePrefixChecker - .hasOffendingPrefix(PackagePrefixChecker - .withoutPackagePrefix(className))){ - loadedClass = Util.loadClass - (PackagePrefixChecker.withoutPackagePrefix(className), - remoteCodebase, - loader); - } else { - loadedClass = Util.loadClass - (className, - remoteCodebase, - loader); - } - } catch (ClassNotFoundException cnfe) { - loadedClass = Util.loadClass - (className, - remoteCodebase, - loader); - } - if (expectedType == null) - return loadedClass; - } catch (ClassNotFoundException cnfe) { - if (expectedType == null) - throw cnfe; - } - - // If no class was not loaded, or if the loaded class is not of the - // correct type, make a further attempt to load the correct class - // using the classloader of the expected type. - // _REVISIT_ Is this step necessary, or should the Util,loadClass - // algorithm always produce a valid class if the setup is correct? - // Does the OMG standard algorithm need to be changed to include - // this step? - if (loadedClass == null || !expectedType.isAssignableFrom(loadedClass)) { - if (expectedType.getClassLoader() != expectedTypeClassLoader) - throw new IllegalArgumentException("expectedTypeClassLoader not class loader of expectedType."); - - if (expectedTypeClassLoader != null) - loadedClass = expectedTypeClassLoader.loadClass(className); - else - loadedClass = Class.forName(className); - } - - return loadedClass; - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ValueHandlerImpl_1_3.java 2013-02-07 17:08:09.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,251 +0,0 @@ -/* - * Copyright (c) 2000, 2003, 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. - */ -/* - * Licensed Materials - Property of IBM - * RMI-IIOP v1.0 - * Copyright IBM Corp. 1998 1999 All Rights Reserved - * - */ - -package com.sun.corba.se.impl.orbutil; - -import javax.rmi.CORBA.Util; -import javax.rmi.PortableRemoteObject; - -import java.util.Hashtable; -import java.util.Stack; -import java.io.IOException; -import java.util.EmptyStackException; - -import com.sun.corba.se.impl.util.Utility; -import com.sun.corba.se.impl.io.IIOPInputStream; -import com.sun.corba.se.impl.io.IIOPOutputStream; -import com.sun.corba.se.impl.util.RepositoryId; -import com.sun.corba.se.impl.util.Utility; - -import org.omg.CORBA.TCKind; -import org.omg.CORBA.MARSHAL; -import org.omg.CORBA.CompletionStatus; -import org.omg.CORBA.portable.IndirectionException; -import com.sun.org.omg.SendingContext.CodeBase; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -/** - * This class overrides behavior of our current ValueHandlerImpl to - * provide backwards compatibility with JDK 1.3.0. - */ -public class ValueHandlerImpl_1_3 extends com.sun.corba.se.impl.io.ValueHandlerImpl { - - public ValueHandlerImpl_1_3(){ - super(); - } - - public ValueHandlerImpl_1_3(boolean isInputStream) { - super(isInputStream); - } - - /** - * Writes the value to the stream using java semantics. - * @param out The stream to write the value to - * @param value The value to be written to the stream - **/ - public void writeValue(org.omg.CORBA.portable.OutputStream _out, java.io.Serializable value) { - super.writeValue(_out, value); - } - - /** - * Reads a value from the stream using java semantics. - * @param in The stream to read the value from - * @param clazz The type of the value to be read in - * @param sender The sending context runtime - **/ - public java.io.Serializable readValue(org.omg.CORBA.portable.InputStream _in, - int offset, - java.lang.Class clazz, - String repositoryID, - org.omg.SendingContext.RunTime _sender) - { - return super.readValue(_in, offset, clazz, repositoryID, _sender); - } - - /** - * Returns the repository ID for the given RMI value Class. - * @param clz The class to return a repository ID for. - * @return the repository ID of the Class. - **/ - public java.lang.String getRMIRepositoryID(java.lang.Class clz) { - return RepositoryId_1_3.createForJavaType(clz); - } - - /** - * Indicates whether the given Class performs custom or - * default marshaling. - * @param clz The class to test for custom marshaling. - * @return True if the class performs custom marshaling, false - * if it does not. - **/ - public boolean isCustomMarshaled(java.lang.Class clz) { - return super.isCustomMarshaled(clz); - } - - /** - * Returns the CodeBase for this ValueHandler. This is used by - * the ORB runtime. The server sends the service context containing - * the IOR for this CodeBase on the first GIOP reply. The clients - * do the same on the first GIOP request. - * @return the SendingContext.CodeBase of this ValueHandler. - **/ - public org.omg.SendingContext.RunTime getRunTimeCodeBase() { - return super.getRunTimeCodeBase(); - } - - /** - * If the value contains a writeReplace method then the result - * is returned. Otherwise, the value itself is returned. - * @return the true value to marshal on the wire. - **/ - public java.io.Serializable writeReplace(java.io.Serializable value) { - return super.writeReplace(value); - } - - // methods supported for backward compatability so that the appropriate - // Rep-id calculations take place based on the ORB version - - /** - * Returns a boolean of whether or not RepositoryId indicates - * FullValueDescriptor. - * used for backward compatability - */ - - public boolean useFullValueDescription(Class clazz, String repositoryID) - throws IOException - - { - return RepositoryId_1_3.useFullValueDescription(clazz, repositoryID); - } - - public String getClassName(String id) - { - RepositoryId_1_3 repID = RepositoryId_1_3.cache.getId(id); - return repID.getClassName(); - } - - public Class getClassFromType(String id) - throws ClassNotFoundException - { - RepositoryId_1_3 repId = RepositoryId_1_3.cache.getId(id); - return repId.getClassFromType(); - } - - public Class getAnyClassFromType(String id) - throws ClassNotFoundException - { - RepositoryId_1_3 repId = RepositoryId_1_3.cache.getId(id); - return repId.getAnyClassFromType(); - } - - public String createForAnyType(Class cl) - { - return RepositoryId_1_3.createForAnyType(cl); - } - - public String getDefinedInId(String id) - { - RepositoryId_1_3 repId = RepositoryId_1_3.cache.getId(id); - return repId.getDefinedInId(); - } - - public String getUnqualifiedName(String id) - { - RepositoryId_1_3 repId = RepositoryId_1_3.cache.getId(id); - return repId.getUnqualifiedName(); - } - - public String getSerialVersionUID(String id) - { - RepositoryId_1_3 repId = RepositoryId_1_3.cache.getId(id); - return repId.getSerialVersionUID(); - } - - public boolean isAbstractBase(Class clazz) - { - return RepositoryId_1_3.isAbstractBase(clazz); - } - - public boolean isSequence(String id) - { - RepositoryId_1_3 repId = RepositoryId_1_3.cache.getId(id); - return repId.isSequence(); - } - - /** - * Preserves the incorrect 1.3 behavior which truncates Java chars in - * arrays to 8-bit CORBA chars. Bug 4367783. This enables us to - * continue interoperating with our legacy ORBs. If this goes into - * Ladybird, then Ladybird and Kestrel will interoperate as long as - * people don't use chars greater than 8-bits. - */ - protected void writeCharArray(org.omg.CORBA_2_3.portable.OutputStream out, - char[] array, - int offset, - int length) - { - out.write_char_array(array, offset, length); - } - - /** - * Preserves the incorrect 1.3 behavior which truncates Java chars in - * arrays to 8-bit CORBA chars. Bug 4367783. This enables us to - * continue interoperating with our legacy ORBs. If this goes into - * Ladybird, then Ladybird and Kestrel will interoperate as long as - * people don't use chars greater than 8-bits. - */ - protected void readCharArray(org.omg.CORBA_2_3.portable.InputStream in, - char[] array, - int offset, - int length) - { - in.read_char_array(array, offset, length); - } - - protected final String getOutputStreamClassName() { - return "com.sun.corba.se.impl.orbutil.IIOPOutputStream_1_3"; - } - - protected final String getInputStreamClassName() { - return "com.sun.corba.se.impl.orbutil.IIOPInputStream_1_3"; - } - - /** - * Our JDK 1.3 and JDK 1.3.1 behavior subclasses override this. - * The correct behavior is for a Java char to map to a CORBA wchar, - * but our older code mapped it to a CORBA char. - */ - protected TCKind getJavaCharTCKind() { - return TCKind.tk_char; - } -} --- old/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ValueHandlerImpl_1_3_1.java 2013-02-07 17:08:09.000000000 +0100 +++ /dev/null 2013-02-05 10:56:25.513074029 +0100 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2001, 2002, 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.corba.se.impl.orbutil; - -import org.omg.CORBA.TCKind; - -/** - * This class overrides behavior of our current ValueHandlerImpl to - * provide backwards compatibility with JDK 1.3.1. - */ -public class ValueHandlerImpl_1_3_1 - extends com.sun.corba.se.impl.io.ValueHandlerImpl -{ - public ValueHandlerImpl_1_3_1() {} - - public ValueHandlerImpl_1_3_1(boolean isInputStream) { - super(isInputStream); - } - - /** - * Our JDK 1.3 and JDK 1.3.1 behavior subclasses override this. - * The correct behavior is for a Java char to map to a CORBA wchar, - * but our older code mapped it to a CORBA char. - */ - protected TCKind getJavaCharTCKind() { - return TCKind.tk_char; - } - - /** - * RepositoryId_1_3_1 performs an incorrect repId calculation - * when using serialPersistentFields and one of the fields no longer - * exists on the class itself. - */ - public boolean useFullValueDescription(Class clazz, String repositoryID) - throws java.io.IOException - { - return RepositoryId_1_3_1.useFullValueDescription(clazz, repositoryID); - } - - /** - * Installs the legacy IIOPOutputStream_1_3_1 which does - * PutFields/GetFields incorrectly. Bug 4407244. - */ - protected final String getOutputStreamClassName() { - return "com.sun.corba.se.impl.orbutil.IIOPOutputStream_1_3_1"; - } - - /** - * Installs the legacy IIOPInputStream_1_3_1 which does - * PutFields/GetFields incorrectly. Bug 4407244. - */ - protected final String getInputStreamClassName() { - return "com.sun.corba.se.impl.orbutil.IIOPInputStream_1_3_1"; - } -} --- old/hotspot/.hgtags 2013-02-07 17:08:10.000000000 +0100 +++ new/hotspot/.hgtags 2013-02-07 17:08:10.000000000 +0100 @@ -346,6 +346,14 @@ c6b78bbaf6976197ead9d5aa3f65e0224cd13541 jdk7u10-b30 25a92b94ad538963d009bf8a53ce548e13f55c82 jdk7u11-b20 7a2cf85fc36e845db9ccb2a22af195c70af33bdf jdk7u11-b21 +db7028c8a953f46225fceb6148f97de87c784dda jdk7u11-b03 +4d418a1b8be04220f504cf414b47877821a22a26 jdk7u11-b04 +f71032f398a3baea567710ba7161c64b94495cac jdk7u11-b05 +0cbce123c9027d531e585fd81fbc361c5f8407f1 jdk7u11-b06 +94bf1e3dafef3cc06d3f97f81d304313ccd999ee jdk7u11-b07 +2b543aa340e4a75671fe05803fcee08bf3e136db jdk7u11-b08 +34a7b6dda06e2ff6f7e9ad563e3fc3ecd8993579 jdk7u13-b09 +e0e52e35e0c53a84daadae95f626e36fd74f3eba jdk7u13-b20 02a6c89432d724119565f9ba25672829b136fc5f jdk7u8-b01 528502f930967f70c320472a002418f1e38029e0 jdk7u8-b02 db63a909e1ad950ef2b9050389f51e68581b2d4e jdk7u8-b03 --- old/hotspot/src/share/vm/interpreter/linkResolver.cpp 2013-02-07 17:08:10.000000000 +0100 +++ new/hotspot/src/share/vm/interpreter/linkResolver.cpp 2013-02-07 17:08:10.000000000 +0100 @@ -786,7 +786,7 @@ if (check_access && // a) check if ACC_SUPER flag is set for the current class - current_klass->is_super() && + (current_klass->is_super() || !AllowNonVirtualCalls) && // b) check if the method class is a superclass of the current class (superclass relation is not reflexive!) current_klass->is_subtype_of(method_klass()) && current_klass() != method_klass() && // c) check if the method is not --- old/hotspot/src/share/vm/runtime/globals.hpp 2013-02-07 17:08:11.000000000 +0100 +++ new/hotspot/src/share/vm/runtime/globals.hpp 2013-02-07 17:08:11.000000000 +0100 @@ -3619,6 +3619,9 @@ "EINTR for I/O operations results in OS_INTRPT. The default value"\ " of this flag is true for JDK 6 and earlier") \ \ + product(bool, AllowNonVirtualCalls, false, \ + "Obey the ACC_SUPER flag and allow invokenonvirtual calls") \ + \ diagnostic(bool, WhiteBoxAPI, false, \ "Enable internal testing APIs") \ \ --- old/jaxp/.hgtags 2013-02-07 17:08:12.000000000 +0100 +++ new/jaxp/.hgtags 2013-02-07 17:08:12.000000000 +0100 @@ -225,6 +225,14 @@ c59eb287de720ae5ce8087f179ec01f4f6525a32 jdk7u10-b30 853059839d38432f86e345ba951397ede235a374 jdk7u11-b20 453a52320a1b8bd425fdb55e14b64067b536f1e2 jdk7u11-b21 +5df9207c4378b7f4b24d70b365714c5ee6318982 jdk7u11-b03 +6ee19b9c8313db32e6d8989aa3782830d2b09710 jdk7u11-b04 +3312b258392eaeab9c4a20e3deb36d3ae3337efe jdk7u11-b05 +86d0250b62bbb4aabab2a7c249aeb14847be2631 jdk7u11-b06 +225aa78c36e9b776c87e585329bbb7ee0e3259a3 jdk7u11-b07 +48491f5a58172f0fbdf9b774842c2ec1a42f609a jdk7u11-b08 +eb9d57159e5126cf4316c9571ac39324a8b442a8 jdk7u13-b09 +f9fe0d38b1103cb33073538c959d982e28ed7b11 jdk7u13-b20 1365e7472a3b737dda4a73e06ad41718d667d9be jdk7u8-b01 0a313d4307930be3a64106b9b8c90f9342673aa0 jdk7u8-b02 36cba5ea434944cef64fa281112b158fae93c0fa jdk7u8-b03 --- old/jaxp/src/com/sun/org/apache/xpath/internal/functions/FuncSystemProperty.java 2013-02-07 17:08:12.000000000 +0100 +++ new/jaxp/src/com/sun/org/apache/xpath/internal/functions/FuncSystemProperty.java 2013-02-07 17:08:12.000000000 +0100 @@ -165,7 +165,7 @@ * should already be fully qualified as path/filename * @param target The target property bag the file will be placed into. */ - public void loadPropertyFile(String file, Properties target) + private void loadPropertyFile(String file, Properties target) { try {