Merge
authorasaha
Thu, 25 Mar 2010 07:12:43 -0700
changeset 5196 d6b7fa6e317f
parent 5195 dcc229e35a4e (diff)
parent 5165 5693cc1e95c6 (current diff)
child 5197 ddb703ff8889
Merge
--- a/jdk/src/share/classes/java/beans/EventHandler.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/beans/EventHandler.java	Thu Mar 25 07:12:43 2010 -0700
@@ -32,7 +32,6 @@
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
-import java.util.EventObject;
 import sun.reflect.misc.MethodUtil;
 
 /**
@@ -279,9 +278,9 @@
 public class EventHandler implements InvocationHandler {
     private Object target;
     private String action;
-    private String eventPropertyName;
-    private String listenerMethodName;
-    private AccessControlContext acc;
+    private final String eventPropertyName;
+    private final String listenerMethodName;
+    private final AccessControlContext acc = AccessController.getContext();
 
     /**
      * Creates a new <code>EventHandler</code> object;
@@ -310,7 +309,6 @@
      */
     @ConstructorProperties({"target", "action", "eventPropertyName", "listenerMethodName"})
     public EventHandler(Object target, String action, String eventPropertyName, String listenerMethodName) {
-        this.acc = AccessController.getContext();
         this.target = target;
         this.action = action;
         if (target == null) {
@@ -422,7 +420,11 @@
      * @see EventHandler
      */
     public Object invoke(final Object proxy, final Method method, final Object[] arguments) {
-        return AccessController.doPrivileged(new PrivilegedAction() {
+        AccessControlContext acc = this.acc;
+        if ((acc == null) && (System.getSecurityManager() != null)) {
+            throw new SecurityException("AccessControlContext is not set");
+        }
+        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
             public Object run() {
                 return invokeInternal(proxy, method, arguments);
             }
@@ -482,7 +484,10 @@
                 throw new RuntimeException(ex);
             }
             catch (InvocationTargetException ex) {
-                throw new RuntimeException(ex.getTargetException());
+                Throwable th = ex.getTargetException();
+                throw (th instanceof RuntimeException)
+                        ? (RuntimeException) th
+                        : new RuntimeException(th);
             }
         }
         return null;
--- a/jdk/src/share/classes/java/beans/Statement.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/beans/Statement.java	Thu Mar 25 07:12:43 2010 -0700
@@ -29,6 +29,10 @@
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
 
 import com.sun.beans.finder.ClassFinder;
 import com.sun.beans.finder.ConstructorFinder;
@@ -63,9 +67,10 @@
         }
     };
 
-    Object target;
-    String methodName;
-    Object[] arguments;
+    private final AccessControlContext acc = AccessController.getContext();
+    private final Object target;
+    private final String methodName;
+    private final Object[] arguments;
     ClassLoader loader;
 
     /**
@@ -160,6 +165,26 @@
     }
 
     Object invoke() throws Exception {
+        AccessControlContext acc = this.acc;
+        if ((acc == null) && (System.getSecurityManager() != null)) {
+            throw new SecurityException("AccessControlContext is not set");
+        }
+        try {
+            return AccessController.doPrivileged(
+                    new PrivilegedExceptionAction<Object>() {
+                        public Object run() throws Exception {
+                            return invokeInternal();
+                        }
+                    },
+                    acc
+            );
+        }
+        catch (PrivilegedActionException exception) {
+            throw exception.getException();
+        }
+    }
+
+    private Object invokeInternal() throws Exception {
         Object target = getTarget();
         String methodName = getMethodName();
 
--- a/jdk/src/share/classes/java/io/File.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/io/File.java	Thu Mar 25 07:12:43 2010 -0700
@@ -2064,11 +2064,12 @@
     private synchronized void readObject(java.io.ObjectInputStream s)
          throws IOException, ClassNotFoundException
     {
-        s.defaultReadObject();
+        ObjectInputStream.GetField fields = s.readFields();
+        String pathField = (String)fields.get("path", null);
         char sep = s.readChar(); // read the previous separator char
         if (sep != separatorChar)
-            this.path = this.path.replace(sep, separatorChar);
-        this.path = fs.normalize(this.path);
+            pathField = pathField.replace(sep, separatorChar);
+        this.path = fs.normalize(pathField);
         this.prefixLength = fs.prefixLength(this.path);
     }
 
--- a/jdk/src/share/classes/java/lang/ProcessBuilder.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/lang/ProcessBuilder.java	Thu Mar 25 07:12:43 2010 -0700
@@ -994,6 +994,8 @@
         // Must convert to array first -- a malicious user-supplied
         // list might try to circumvent the security check.
         String[] cmdarray = command.toArray(new String[command.size()]);
+        cmdarray = cmdarray.clone();
+
         for (String arg : cmdarray)
             if (arg == null)
                 throw new NullPointerException();
--- a/jdk/src/share/classes/java/lang/ThreadGroup.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/lang/ThreadGroup.java	Thu Mar 25 07:12:43 2010 -0700
@@ -55,7 +55,7 @@
  */
 public
 class ThreadGroup implements Thread.UncaughtExceptionHandler {
-    ThreadGroup parent;
+    private final ThreadGroup parent;
     String name;
     int maxPriority;
     boolean destroyed;
@@ -76,6 +76,7 @@
     private ThreadGroup() {     // called from C code
         this.name = "system";
         this.maxPriority = Thread.MAX_PRIORITY;
+        this.parent = null;
     }
 
     /**
@@ -113,10 +114,10 @@
      * @since   JDK1.0
      */
     public ThreadGroup(ThreadGroup parent, String name) {
-        if (parent == null) {
-            throw new NullPointerException();
-        }
-        parent.checkAccess();
+        this(checkParentAccess(parent), parent, name);
+    }
+
+    private ThreadGroup(Void unused, ThreadGroup parent, String name) {
         this.name = name;
         this.maxPriority = parent.maxPriority;
         this.daemon = parent.daemon;
@@ -125,6 +126,16 @@
         parent.add(this);
     }
 
+    /*
+     * @throws  NullPointerException  if the parent argument is {@code null}
+     * @throws  SecurityException     if the current thread cannot create a
+     *                                thread in the specified thread group.
+     */
+    private static Void checkParentAccess(ThreadGroup parent) {
+        parent.checkAccess();
+        return null;
+    }
+
     /**
      * Returns the name of this thread group.
      *
--- a/jdk/src/share/classes/java/net/DatagramSocket.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/net/DatagramSocket.java	Thu Mar 25 07:12:43 2010 -0700
@@ -118,6 +118,7 @@
         if (address == null) {
             throw new IllegalArgumentException("connect: null address");
         }
+        checkAddress (address, "connect");
         if (isClosed())
             return;
         SecurityManager security = System.getSecurityManager();
@@ -363,13 +364,15 @@
         InetSocketAddress epoint = (InetSocketAddress) addr;
         if (epoint.isUnresolved())
             throw new SocketException("Unresolved address");
+        InetAddress iaddr = epoint.getAddress();
+        int port = epoint.getPort();
+        checkAddress(iaddr, "bind");
         SecurityManager sec = System.getSecurityManager();
         if (sec != null) {
-            sec.checkListen(epoint.getPort());
+            sec.checkListen(port);
         }
         try {
-            getImpl().bind(epoint.getPort(),
-                           epoint.getAddress());
+            getImpl().bind(port, iaddr);
         } catch (SocketException e) {
             getImpl().close();
             throw e;
@@ -377,6 +380,15 @@
         bound = true;
     }
 
+    void checkAddress (InetAddress addr, String op) {
+        if (addr == null) {
+            return;
+        }
+        if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
+            throw new IllegalArgumentException(op + ": invalid address type");
+        }
+    }
+
     /**
      * Connects the socket to a remote address for this socket. When a
      * socket is connected to a remote address, packets may only be
@@ -603,6 +615,7 @@
         synchronized (p) {
             if (isClosed())
                 throw new SocketException("Socket is closed");
+            checkAddress (p.getAddress(), "send");
             if (connectState == ST_NOT_CONNECTED) {
                 // check the address is ok wiht the security manager on every send.
                 SecurityManager security = System.getSecurityManager();
--- a/jdk/src/share/classes/java/net/InetAddress.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/net/InetAddress.java	Thu Mar 25 07:12:43 2010 -0700
@@ -35,6 +35,7 @@
 import java.security.AccessController;
 import java.io.ObjectStreamException;
 import java.io.IOException;
+import java.io.ObjectInputStream;
 import sun.security.action.*;
 import sun.net.InetAddressCachePolicy;
 import sun.net.util.IPAddressUtil;
@@ -1472,6 +1473,23 @@
 
         return impl;
     }
+
+    private void readObjectNoData (ObjectInputStream s) throws
+                         IOException, ClassNotFoundException {
+        if (getClass().getClassLoader() != null) {
+            throw new SecurityException ("invalid address type");
+        }
+    }
+
+    private void readObject (ObjectInputStream s) throws
+                         IOException, ClassNotFoundException {
+        s.defaultReadObject ();
+        if (getClass().getClassLoader() != null) {
+            hostName = null;
+            address = 0;
+            throw new SecurityException ("invalid address type");
+        }
+    }
 }
 
 /*
--- a/jdk/src/share/classes/java/net/MulticastSocket.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/net/MulticastSocket.java	Thu Mar 25 07:12:43 2010 -0700
@@ -289,6 +289,7 @@
             throw new SocketException("Socket is closed");
         }
 
+        checkAddress(mcastaddr, "joinGroup");
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             security.checkMulticast(mcastaddr);
@@ -323,6 +324,7 @@
             throw new SocketException("Socket is closed");
         }
 
+        checkAddress(mcastaddr, "leaveGroup");
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             security.checkMulticast(mcastaddr);
@@ -370,6 +372,7 @@
         if (oldImpl)
             throw new UnsupportedOperationException();
 
+        checkAddress(((InetSocketAddress)mcastaddr).getAddress(), "joinGroup");
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             security.checkMulticast(((InetSocketAddress)mcastaddr).getAddress());
@@ -416,6 +419,7 @@
         if (oldImpl)
             throw new UnsupportedOperationException();
 
+        checkAddress(((InetSocketAddress)mcastaddr).getAddress(), "leaveGroup");
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             security.checkMulticast(((InetSocketAddress)mcastaddr).getAddress());
@@ -441,6 +445,7 @@
         if (isClosed()) {
             throw new SocketException("Socket is closed");
         }
+        checkAddress(inf, "setInterface");
         synchronized (infLock) {
             getImpl().setOption(SocketOptions.IP_MULTICAST_IF, inf);
             infAddress = inf;
@@ -632,6 +637,7 @@
         throws IOException {
             if (isClosed())
                 throw new SocketException("Socket is closed");
+            checkAddress(p.getAddress(), "send");
             synchronized(ttlLock) {
                 synchronized(p) {
                     if (connectState == ST_NOT_CONNECTED) {
--- a/jdk/src/share/classes/java/net/NetworkInterface.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/net/NetworkInterface.java	Thu Mar 25 07:12:43 2010 -0700
@@ -290,8 +290,12 @@
      *          If the specified address is <tt>null</tt>.
      */
     public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException {
-        if (addr == null)
+        if (addr == null) {
             throw new NullPointerException();
+        }
+        if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
+            throw new IllegalArgumentException ("invalid address type");
+        }
         return getByInetAddress0(addr);
     }
 
--- a/jdk/src/share/classes/java/net/Socket.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/net/Socket.java	Thu Mar 25 07:12:43 2010 -0700
@@ -122,6 +122,9 @@
         if (p.type() == Proxy.Type.SOCKS) {
             SecurityManager security = System.getSecurityManager();
             InetSocketAddress epoint = (InetSocketAddress) p.address();
+            if (epoint.getAddress() != null) {
+                checkAddress (epoint.getAddress(), "Socket");
+            }
             if (security != null) {
                 if (epoint.isUnresolved())
                     security.checkConnect(epoint.getHostName(),
@@ -558,15 +561,16 @@
             throw new IllegalArgumentException("Unsupported address type");
 
         InetSocketAddress epoint = (InetSocketAddress) endpoint;
+        InetAddress addr = epoint.getAddress ();
+        int port = epoint.getPort();
+        checkAddress(addr, "connect");
 
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             if (epoint.isUnresolved())
-                security.checkConnect(epoint.getHostName(),
-                                      epoint.getPort());
+                security.checkConnect(epoint.getHostName(), port);
             else
-                security.checkConnect(epoint.getAddress().getHostAddress(),
-                                      epoint.getPort());
+                security.checkConnect(addr.getHostAddress(), port);
         }
         if (!created)
             createImpl(true);
@@ -574,10 +578,9 @@
             impl.connect(epoint, timeout);
         else if (timeout == 0) {
             if (epoint.isUnresolved())
-                impl.connect(epoint.getAddress().getHostName(),
-                             epoint.getPort());
+                impl.connect(addr.getHostName(), port);
             else
-                impl.connect(epoint.getAddress(), epoint.getPort());
+                impl.connect(addr, port);
         } else
             throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");
         connected = true;
@@ -614,14 +617,25 @@
         InetSocketAddress epoint = (InetSocketAddress) bindpoint;
         if (epoint != null && epoint.isUnresolved())
             throw new SocketException("Unresolved address");
-        if (bindpoint == null)
-            getImpl().bind(InetAddress.anyLocalAddress(), 0);
-        else
-            getImpl().bind(epoint.getAddress(),
-                           epoint.getPort());
+        if (epoint == null) {
+            epoint = new InetSocketAddress(0);
+        }
+        InetAddress addr = epoint.getAddress();
+        int port = epoint.getPort();
+        checkAddress (addr, "bind");
+        getImpl().bind (addr, port);
         bound = true;
     }
 
+    private void checkAddress (InetAddress addr, String op) {
+        if (addr == null) {
+            return;
+        }
+        if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
+            throw new IllegalArgumentException(op + ": invalid address type");
+        }
+    }
+
     /**
      * set the flags after an accept() call.
      */
--- a/jdk/src/share/classes/java/security/Policy.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/security/Policy.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,19 +28,17 @@
 
 import java.io.*;
 import java.lang.RuntimePermission;
+import java.lang.reflect.*;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.Enumeration;
 import java.util.Hashtable;
-import java.util.Vector;
+import java.util.PropertyPermission;
 import java.util.StringTokenizer;
-import java.util.PropertyPermission;
-
-import java.lang.reflect.*;
-
+import java.util.Vector;
 import java.util.WeakHashMap;
+import sun.security.jca.GetInstance;
 import sun.security.util.Debug;
-import sun.security.jca.GetInstance;
 import sun.security.util.SecurityConstants;
 
 
@@ -113,8 +111,8 @@
 
     private static final Debug debug = Debug.getInstance("policy");
 
-    // Cache mapping  ProtectionDomain to PermissionCollection
-    private WeakHashMap<ProtectionDomain, PermissionCollection> pdMapping;
+    // Cache mapping ProtectionDomain.Key to PermissionCollection
+    private WeakHashMap<ProtectionDomain.Key, PermissionCollection> pdMapping;
 
     /** package private for AccessControlContext */
     static boolean isSet()
@@ -307,7 +305,7 @@
         synchronized (p) {
             if (p.pdMapping == null) {
                 p.pdMapping =
-                    new WeakHashMap<ProtectionDomain, PermissionCollection>();
+                    new WeakHashMap<ProtectionDomain.Key, PermissionCollection>();
            }
         }
 
@@ -323,7 +321,7 @@
 
             synchronized (p.pdMapping) {
                 // cache of pd to permissions
-                p.pdMapping.put(policyDomain, policyPerms);
+                p.pdMapping.put(policyDomain.key, policyPerms);
             }
         }
         return;
@@ -638,7 +636,7 @@
         }
 
         synchronized (pdMapping) {
-            pc = pdMapping.get(domain);
+            pc = pdMapping.get(domain.key);
         }
 
         if (pc != null) {
@@ -697,7 +695,7 @@
         }
 
         synchronized (pdMapping) {
-            pc = pdMapping.get(domain);
+            pc = pdMapping.get(domain.key);
         }
 
         if (pc != null) {
@@ -711,7 +709,7 @@
 
         synchronized (pdMapping) {
             // cache it
-            pdMapping.put(domain, pc);
+            pdMapping.put(domain.key, pc);
         }
 
         return pc.implies(permission);
@@ -747,21 +745,25 @@
             this.params = params;
         }
 
-        public String getType() { return type; }
+        @Override public String getType() { return type; }
+
+        @Override public Policy.Parameters getParameters() { return params; }
 
-        public Policy.Parameters getParameters() { return params; }
+        @Override public Provider getProvider() { return p; }
 
-        public Provider getProvider() { return p; }
-
+        @Override
         public PermissionCollection getPermissions(CodeSource codesource) {
             return spi.engineGetPermissions(codesource);
         }
+        @Override
         public PermissionCollection getPermissions(ProtectionDomain domain) {
             return spi.engineGetPermissions(domain);
         }
+        @Override
         public boolean implies(ProtectionDomain domain, Permission perm) {
             return spi.engineImplies(domain, perm);
         }
+        @Override
         public void refresh() {
             spi.engineRefresh();
         }
@@ -803,7 +805,7 @@
          * @exception SecurityException - if this PermissionCollection object
          *                                has been marked readonly
          */
-        public void add(Permission permission) {
+        @Override public void add(Permission permission) {
             perms.add(permission);
         }
 
@@ -816,7 +818,7 @@
          * @return true if "permission" is implied by the  permissions in
          * the collection, false if not.
          */
-        public boolean implies(Permission permission) {
+        @Override public boolean implies(Permission permission) {
             return perms.implies(permission);
         }
 
@@ -826,7 +828,7 @@
          *
          * @return an enumeration of all the Permissions.
          */
-        public Enumeration<Permission> elements() {
+        @Override public Enumeration<Permission> elements() {
             return perms.elements();
         }
     }
--- a/jdk/src/share/classes/java/security/ProtectionDomain.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/security/ProtectionDomain.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,15 @@
 
 package java.security;
 
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Enumeration;
 import java.util.List;
-import java.util.ArrayList;
+import java.util.Map;
+import java.util.WeakHashMap;
+import sun.misc.JavaSecurityProtectionDomainAccess;
+import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
+import sun.misc.SharedSecrets;
 import sun.security.util.Debug;
 import sun.security.util.SecurityConstants;
 
@@ -72,6 +78,11 @@
        or dynamic (via a policy refresh) */
     private boolean staticPermissions;
 
+    /*
+     * An object used as a key when the ProtectionDomain is stored in a Map.
+     */
+    final Key key = new Key();
+
     private static final Debug debug = Debug.getInstance("domain");
 
     /**
@@ -238,7 +249,7 @@
     /**
      * Convert a ProtectionDomain to a String.
      */
-    public String toString() {
+    @Override public String toString() {
         String pals = "<no principals>";
         if (principals != null && principals.length > 0) {
             StringBuilder palBuf = new StringBuilder("(principals ");
@@ -396,4 +407,29 @@
 
         return mergedPerms;
     }
+
+    /**
+     * Used for storing ProtectionDomains as keys in a Map.
+     */
+    final class Key {}
+
+    static {
+        SharedSecrets.setJavaSecurityProtectionDomainAccess(
+            new JavaSecurityProtectionDomainAccess() {
+                public ProtectionDomainCache getProtectionDomainCache() {
+                    return new ProtectionDomainCache() {
+                        private final Map<Key, PermissionCollection> map =
+                            Collections.synchronizedMap
+                                (new WeakHashMap<Key, PermissionCollection>());
+                        public void put(ProtectionDomain pd,
+                            PermissionCollection pc) {
+                            map.put((pd == null ? null : pd.key), pc);
+                        }
+                        public PermissionCollection get(ProtectionDomain pd) {
+                            return pd == null ? map.get(null) : map.get(pd.key);
+                        }
+                    };
+                }
+            });
+    }
 }
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java	Thu Mar 25 07:12:43 2010 -0700
@@ -57,7 +57,7 @@
     private long rawIndex(int i) {
         if (i < 0 || i >= array.length)
             throw new IndexOutOfBoundsException("index " + i);
-        return base + i * scale;
+        return base + (long) i * scale;
     }
 
     /**
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java	Thu Mar 25 07:12:43 2010 -0700
@@ -56,7 +56,7 @@
     private long rawIndex(int i) {
         if (i < 0 || i >= array.length)
             throw new IndexOutOfBoundsException("index " + i);
-        return base + i * scale;
+        return base + (long) i * scale;
     }
 
     /**
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java	Thu Mar 25 07:12:43 2010 -0700
@@ -57,7 +57,7 @@
     private long rawIndex(int i) {
         if (i < 0 || i >= array.length)
             throw new IndexOutOfBoundsException("index " + i);
-        return base + i * scale;
+        return base + (long) i * scale;
     }
 
     /**
--- a/jdk/src/share/classes/java/util/zip/Deflater.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/util/zip/Deflater.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1996-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,7 +72,8 @@
  */
 public
 class Deflater {
-    private long strm;
+
+    private final ZStreamRef zsRef;
     private byte[] buf = new byte[0];
     private int off, len;
     private int level, strategy;
@@ -165,7 +166,7 @@
     public Deflater(int level, boolean nowrap) {
         this.level = level;
         this.strategy = DEFAULT_STRATEGY;
-        strm = init(level, DEFAULT_STRATEGY, nowrap);
+        this.zsRef = new ZStreamRef(init(level, DEFAULT_STRATEGY, nowrap));
     }
 
     /**
@@ -193,16 +194,18 @@
      * @param len the length of the data
      * @see Deflater#needsInput
      */
-    public synchronized void setInput(byte[] b, int off, int len) {
+    public void setInput(byte[] b, int off, int len) {
         if (b== null) {
             throw new NullPointerException();
         }
         if (off < 0 || len < 0 || off > b.length - len) {
             throw new ArrayIndexOutOfBoundsException();
         }
-        this.buf = b;
-        this.off = off;
-        this.len = len;
+        synchronized (zsRef) {
+            this.buf = b;
+            this.off = off;
+            this.len = len;
+        }
     }
 
     /**
@@ -227,14 +230,17 @@
      * @see Inflater#inflate
      * @see Inflater#getAdler
      */
-    public synchronized void setDictionary(byte[] b, int off, int len) {
-        if (strm == 0 || b == null) {
+    public void setDictionary(byte[] b, int off, int len) {
+        if (b == null) {
             throw new NullPointerException();
         }
         if (off < 0 || len < 0 || off > b.length - len) {
             throw new ArrayIndexOutOfBoundsException();
         }
-        setDictionary(strm, b, off, len);
+        synchronized (zsRef) {
+            ensureOpen();
+            setDictionary(zsRef.address(), b, off, len);
+        }
     }
 
     /**
@@ -257,7 +263,7 @@
      * @exception IllegalArgumentException if the compression strategy is
      *                                     invalid
      */
-    public synchronized void setStrategy(int strategy) {
+    public void setStrategy(int strategy) {
         switch (strategy) {
           case DEFAULT_STRATEGY:
           case FILTERED:
@@ -266,9 +272,11 @@
           default:
             throw new IllegalArgumentException();
         }
-        if (this.strategy != strategy) {
-            this.strategy = strategy;
-            setParams = true;
+        synchronized (zsRef) {
+            if (this.strategy != strategy) {
+                this.strategy = strategy;
+                setParams = true;
+            }
         }
     }
 
@@ -277,13 +285,15 @@
      * @param level the new compression level (0-9)
      * @exception IllegalArgumentException if the compression level is invalid
      */
-    public synchronized void setLevel(int level) {
+    public void setLevel(int level) {
         if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) {
             throw new IllegalArgumentException("invalid compression level");
         }
-        if (this.level != level) {
-            this.level = level;
-            setParams = true;
+        synchronized (zsRef) {
+            if (this.level != level) {
+                this.level = level;
+                setParams = true;
+            }
         }
     }
 
@@ -301,8 +311,10 @@
      * When called, indicates that compression should end with the current
      * contents of the input buffer.
      */
-    public synchronized void finish() {
-        finish = true;
+    public void finish() {
+        synchronized (zsRef) {
+            finish = true;
+        }
     }
 
     /**
@@ -311,8 +323,10 @@
      * @return true if the end of the compressed data output stream has
      * been reached
      */
-    public synchronized boolean finished() {
-        return finished;
+    public boolean finished() {
+        synchronized (zsRef) {
+            return finished;
+        }
     }
 
     /**
@@ -399,26 +413,31 @@
      * @throws IllegalArgumentException if the flush mode is invalid
      * @since 1.7
      */
-    public synchronized int deflate(byte[] b, int off, int len, int flush) {
+    public int deflate(byte[] b, int off, int len, int flush) {
         if (b == null) {
             throw new NullPointerException();
         }
         if (off < 0 || len < 0 || off > b.length - len) {
             throw new ArrayIndexOutOfBoundsException();
         }
-        if (flush == NO_FLUSH || flush == SYNC_FLUSH ||
-            flush == FULL_FLUSH)
-            return deflateBytes(b, off, len, flush);
-        throw new IllegalArgumentException();
+        synchronized (zsRef) {
+            ensureOpen();
+            if (flush == NO_FLUSH || flush == SYNC_FLUSH ||
+                flush == FULL_FLUSH)
+                return deflateBytes(zsRef.address(), b, off, len, flush);
+            throw new IllegalArgumentException();
+        }
     }
 
     /**
      * Returns the ADLER-32 value of the uncompressed data.
      * @return the ADLER-32 value of the uncompressed data
      */
-    public synchronized int getAdler() {
-        ensureOpen();
-        return getAdler(strm);
+    public int getAdler() {
+        synchronized (zsRef) {
+            ensureOpen();
+            return getAdler(zsRef.address());
+        }
     }
 
     /**
@@ -440,9 +459,11 @@
      * @return the total (non-negative) number of uncompressed bytes input so far
      * @since 1.5
      */
-    public synchronized long getBytesRead() {
-        ensureOpen();
-        return getBytesRead(strm);
+    public long getBytesRead() {
+        synchronized (zsRef) {
+            ensureOpen();
+            return getBytesRead(zsRef.address());
+        }
     }
 
     /**
@@ -464,21 +485,25 @@
      * @return the total (non-negative) number of compressed bytes output so far
      * @since 1.5
      */
-    public synchronized long getBytesWritten() {
-        ensureOpen();
-        return getBytesWritten(strm);
+    public long getBytesWritten() {
+        synchronized (zsRef) {
+            ensureOpen();
+            return getBytesWritten(zsRef.address());
+        }
     }
 
     /**
      * Resets deflater so that a new set of input data can be processed.
      * Keeps current compression level and strategy settings.
      */
-    public synchronized void reset() {
-        ensureOpen();
-        reset(strm);
-        finish = false;
-        finished = false;
-        off = len = 0;
+    public void reset() {
+        synchronized (zsRef) {
+            ensureOpen();
+            reset(zsRef.address());
+            finish = false;
+            finished = false;
+            off = len = 0;
+        }
     }
 
     /**
@@ -488,11 +513,14 @@
      * finalize() method. Once this method is called, the behavior
      * of the Deflater object is undefined.
      */
-    public synchronized void end() {
-        if (strm != 0) {
-            end(strm);
-            strm = 0;
-            buf = null;
+    public void end() {
+        synchronized (zsRef) {
+            long addr = zsRef.address();
+            zsRef.clear();
+            if (addr != 0) {
+                end(addr);
+                buf = null;
+            }
         }
     }
 
@@ -504,18 +532,19 @@
     }
 
     private void ensureOpen() {
-        if (strm == 0)
-            throw new NullPointerException();
+        assert Thread.holdsLock(zsRef);
+        if (zsRef.address() == 0)
+            throw new NullPointerException("Deflater has been closed");
     }
 
     private static native void initIDs();
     private native static long init(int level, int strategy, boolean nowrap);
-    private native static void setDictionary(long strm, byte[] b, int off,
-                                             int len);
-    private native int deflateBytes(byte[] b, int off, int len, int flush);
-    private native static int getAdler(long strm);
-    private native static long getBytesRead(long strm);
-    private native static long getBytesWritten(long strm);
-    private native static void reset(long strm);
-    private native static void end(long strm);
+    private native static void setDictionary(long addr, byte[] b, int off, int len);
+    private native int deflateBytes(long addr, byte[] b, int off, int len,
+                                    int flush);
+    private native static int getAdler(long addr);
+    private native static long getBytesRead(long addr);
+    private native static long getBytesWritten(long addr);
+    private native static void reset(long addr);
+    private native static void end(long addr);
 }
--- a/jdk/src/share/classes/java/util/zip/Inflater.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/java/util/zip/Inflater.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1996-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1996-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,7 +72,8 @@
  */
 public
 class Inflater {
-    private long strm;
+
+    private final ZStreamRef zsRef;
     private byte[] buf = defaultBuf;
     private int off, len;
     private boolean finished;
@@ -97,7 +98,7 @@
      * @param nowrap if true then support GZIP compatible compression
      */
     public Inflater(boolean nowrap) {
-        strm = init(nowrap);
+        zsRef = new ZStreamRef(init(nowrap));
     }
 
     /**
@@ -116,16 +117,18 @@
      * @param len the length of the input data
      * @see Inflater#needsInput
      */
-    public synchronized void setInput(byte[] b, int off, int len) {
+    public void setInput(byte[] b, int off, int len) {
         if (b == null) {
             throw new NullPointerException();
         }
         if (off < 0 || len < 0 || off > b.length - len) {
             throw new ArrayIndexOutOfBoundsException();
         }
-        this.buf = b;
-        this.off = off;
-        this.len = len;
+        synchronized (zsRef) {
+            this.buf = b;
+            this.off = off;
+            this.len = len;
+        }
     }
 
     /**
@@ -150,15 +153,18 @@
      * @see Inflater#needsDictionary
      * @see Inflater#getAdler
      */
-    public synchronized void setDictionary(byte[] b, int off, int len) {
-        if (strm == 0 || b == null) {
+    public void setDictionary(byte[] b, int off, int len) {
+        if (b == null) {
             throw new NullPointerException();
         }
         if (off < 0 || len < 0 || off > b.length - len) {
             throw new ArrayIndexOutOfBoundsException();
         }
-        setDictionary(strm, b, off, len);
-        needDict = false;
+        synchronized (zsRef) {
+            ensureOpen();
+            setDictionary(zsRef.address(), b, off, len);
+            needDict = false;
+        }
     }
 
     /**
@@ -180,8 +186,10 @@
      * buffer after decompression has finished.
      * @return the total number of bytes remaining in the input buffer
      */
-    public synchronized int getRemaining() {
-        return len;
+    public int getRemaining() {
+        synchronized (zsRef) {
+            return len;
+        }
     }
 
     /**
@@ -190,8 +198,10 @@
      * to provide more input.
      * @return true if no data remains in the input buffer
      */
-    public synchronized boolean needsInput() {
-        return len <= 0;
+    public boolean needsInput() {
+        synchronized (zsRef) {
+            return len <= 0;
+        }
     }
 
     /**
@@ -199,8 +209,10 @@
      * @return true if a preset dictionary is needed for decompression
      * @see Inflater#setDictionary
      */
-    public synchronized boolean needsDictionary() {
-        return needDict;
+    public boolean needsDictionary() {
+        synchronized (zsRef) {
+            return needDict;
+        }
     }
 
     /**
@@ -209,8 +221,10 @@
      * @return true if the end of the compressed data stream has been
      * reached
      */
-    public synchronized boolean finished() {
-        return finished;
+    public boolean finished() {
+        synchronized (zsRef) {
+            return finished;
+        }
     }
 
     /**
@@ -228,7 +242,7 @@
      * @see Inflater#needsInput
      * @see Inflater#needsDictionary
      */
-    public synchronized int inflate(byte[] b, int off, int len)
+    public int inflate(byte[] b, int off, int len)
         throws DataFormatException
     {
         if (b == null) {
@@ -237,7 +251,10 @@
         if (off < 0 || len < 0 || off > b.length - len) {
             throw new ArrayIndexOutOfBoundsException();
         }
-        return inflateBytes(b, off, len);
+        synchronized (zsRef) {
+            ensureOpen();
+            return inflateBytes(zsRef.address(), b, off, len);
+        }
     }
 
     /**
@@ -261,9 +278,11 @@
      * Returns the ADLER-32 value of the uncompressed data.
      * @return the ADLER-32 value of the uncompressed data
      */
-    public synchronized int getAdler() {
-        ensureOpen();
-        return getAdler(strm);
+    public int getAdler() {
+        synchronized (zsRef) {
+            ensureOpen();
+            return getAdler(zsRef.address());
+        }
     }
 
     /**
@@ -285,9 +304,11 @@
      * @return the total (non-negative) number of compressed bytes input so far
      * @since 1.5
      */
-    public synchronized long getBytesRead() {
-        ensureOpen();
-        return getBytesRead(strm);
+    public long getBytesRead() {
+        synchronized (zsRef) {
+            ensureOpen();
+            return getBytesRead(zsRef.address());
+        }
     }
 
     /**
@@ -309,21 +330,25 @@
      * @return the total (non-negative) number of uncompressed bytes output so far
      * @since 1.5
      */
-    public synchronized long getBytesWritten() {
-        ensureOpen();
-        return getBytesWritten(strm);
+    public long getBytesWritten() {
+        synchronized (zsRef) {
+            ensureOpen();
+            return getBytesWritten(zsRef.address());
+        }
     }
 
     /**
      * Resets inflater so that a new set of input data can be processed.
      */
-    public synchronized void reset() {
-        ensureOpen();
-        reset(strm);
-        buf = defaultBuf;
-        finished = false;
-        needDict = false;
-        off = len = 0;
+    public void reset() {
+        synchronized (zsRef) {
+            ensureOpen();
+            reset(zsRef.address());
+            buf = defaultBuf;
+            finished = false;
+            needDict = false;
+            off = len = 0;
+        }
     }
 
     /**
@@ -333,11 +358,14 @@
      * method. Once this method is called, the behavior of the Inflater
      * object is undefined.
      */
-    public synchronized void end() {
-        if (strm != 0) {
-            end(strm);
-            strm = 0;
-            buf = null;
+    public void end() {
+        synchronized (zsRef) {
+            long addr = zsRef.address();
+            zsRef.clear();
+            if (addr != 0) {
+                end(addr);
+                buf = null;
+            }
         }
     }
 
@@ -349,19 +377,20 @@
     }
 
     private void ensureOpen () {
-        if (strm == 0)
-            throw new NullPointerException();
+        assert Thread.holdsLock(zsRef);
+        if (zsRef.address() == 0)
+            throw new NullPointerException("Inflater has been closed");
     }
 
     private native static void initIDs();
     private native static long init(boolean nowrap);
-    private native static void setDictionary(long strm, byte[] b, int off,
+    private native static void setDictionary(long addr, byte[] b, int off,
                                              int len);
-    private native int inflateBytes(byte[] b, int off, int len)
+    private native int inflateBytes(long addr, byte[] b, int off, int len)
             throws DataFormatException;
-    private native static int getAdler(long strm);
-    private native static long getBytesRead(long strm);
-    private native static long getBytesWritten(long strm);
-    private native static void reset(long strm);
-    private native static void end(long strm);
+    private native static int getAdler(long addr);
+    private native static long getBytesRead(long addr);
+    private native static long getBytesWritten(long addr);
+    private native static void reset(long addr);
+    private native static void end(long addr);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/util/zip/ZStreamRef.java	Thu Mar 25 07:12:43 2010 -0700
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.util.zip;
+
+/**
+ * A reference to the native zlib's z_stream structure.
+ */
+
+class ZStreamRef {
+
+    private long address;
+    ZStreamRef (long address) {
+        this.address = address;
+    }
+
+    long address() {
+        return address;
+    }
+
+    void clear() {
+        address = 0;
+    }
+}
--- a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1271,6 +1271,7 @@
      *
      * @return a String representation of this object.
      **/
+    @Override
     public String toString() {
         return super.toString() + ": connectionId=" + connectionId;
     }
@@ -1514,6 +1515,21 @@
         }
     }
 
+    private static class SetCcl implements PrivilegedExceptionAction<ClassLoader> {
+        private final ClassLoader classLoader;
+
+        SetCcl(ClassLoader classLoader) {
+            this.classLoader = classLoader;
+        }
+
+        public ClassLoader run() {
+            Thread currentThread = Thread.currentThread();
+            ClassLoader old = currentThread.getContextClassLoader();
+            currentThread.setContextClassLoader(classLoader);
+            return old;
+        }
+    }
+
     private static <T> T unwrap(final MarshalledObject<?> mo,
                                 final ClassLoader cl,
                                 final Class<T> wrappedClass)
@@ -1522,22 +1538,14 @@
             return null;
         }
         try {
-            return AccessController.doPrivileged(
-                new PrivilegedExceptionAction<T>() {
-                    public T run()
-                            throws IOException {
-                        final ClassLoader old =
-                            Thread.currentThread().getContextClassLoader();
-                        Thread.currentThread().setContextClassLoader(cl);
-                        try {
-                            return wrappedClass.cast(mo.get());
-                        } catch (ClassNotFoundException cnfe) {
-                            throw new UnmarshalException(cnfe.toString(), cnfe);
-                        } finally {
-                            Thread.currentThread().setContextClassLoader(old);
-                        }
-                    }
-                });
+            final ClassLoader old = AccessController.doPrivileged(new SetCcl(cl));
+            try {
+                return wrappedClass.cast(mo.get());
+            } catch (ClassNotFoundException cnfe) {
+                throw new UnmarshalException(cnfe.toString(), cnfe);
+            } finally {
+                AccessController.doPrivileged(new SetCcl(old));
+            }
         } catch (PrivilegedActionException pe) {
             Exception e = extractException(pe);
             if (e instanceof IOException) {
@@ -1561,14 +1569,14 @@
             return null;
         }
         try {
-            return AccessController.doPrivileged(
-                   new PrivilegedExceptionAction<T>() {
-                       public T run()
-                           throws IOException {
-                           return unwrap(mo, new OrderClassLoaders(cl1, cl2),
-                                         wrappedClass);
-                       }
-                   });
+            ClassLoader orderCL = AccessController.doPrivileged(
+                new PrivilegedExceptionAction<ClassLoader>() {
+                    public ClassLoader run() throws Exception {
+                        return new OrderClassLoaders(cl1, cl2);
+                    }
+                }
+            );
+            return unwrap(mo, orderCL, wrappedClass);
         } catch (PrivilegedActionException pe) {
             Exception e = extractException(pe);
             if (e instanceof IOException) {
--- a/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Thu Mar 25 07:12:43 2010 -0700
@@ -57,6 +57,7 @@
 import sun.awt.SunToolkit;
 import sun.awt.datatransfer.DataTransferer;
 import sun.awt.datatransfer.ToolkitThreadBlockedHandler;
+import sun.security.util.SecurityConstants;
 
 /**
  * <p>
@@ -216,6 +217,18 @@
       throws UnsupportedFlavorException, IOException,
         InvalidDnDOperationException
     {
+
+        SecurityManager sm = System.getSecurityManager();
+        try {
+            if (!dropComplete && sm != null) {
+                sm.checkSystemClipboardAccess();
+            }
+        } catch (Exception e) {
+            Thread currentThread = Thread.currentThread();
+            currentThread.getUncaughtExceptionHandler().uncaughtException(currentThread, e);
+            return null;
+        }
+
         Long lFormat = null;
         Transferable localTransferable = local;
 
--- a/jdk/src/share/classes/sun/awt/image/ImageRepresentation.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/awt/image/ImageRepresentation.java	Thu Mar 25 07:12:43 2010 -0700
@@ -333,10 +333,10 @@
         hints = h;
     }
 
-    public native void setICMpixels(int x, int y, int w, int h, int[] lut,
+    private native void setICMpixels(int x, int y, int w, int h, int[] lut,
                                     byte[] pix, int off, int scansize,
                                     IntegerComponentRaster ict);
-    public native int setDiffICM(int x, int y, int w, int h, int[] lut,
+    private native int setDiffICM(int x, int y, int w, int h, int[] lut,
                                  int transPix, int numLut, IndexColorModel icm,
                                  byte[] pix, int off, int scansize,
                                  ByteComponentRaster bct, int chanOff);
@@ -361,6 +361,64 @@
                 }
                 createBufferedImage();
             }
+
+            if (w <= 0 || h <= 0) {
+                return;
+            }
+
+            int biWidth = biRaster.getWidth();
+            int biHeight = biRaster.getHeight();
+
+            int x1 = x+w;  // Overflow protection below
+            int y1 = y+h;  // Overflow protection below
+            if (x < 0) {
+                off -= x;
+                x = 0;
+            } else if (x1 < 0) {
+                x1 = biWidth;  // Must be overflow
+            }
+            if (y < 0) {
+                off -= y*scansize;
+                y = 0;
+            } else if (y1 < 0) {
+                y1 = biHeight;  // Must be overflow
+            }
+            if (x1 > biWidth) {
+                x1 = biWidth;
+            }
+            if (y1 > biHeight) {
+                y1 = biHeight;
+            }
+            if (x >= x1 || y >= y1) {
+                return;
+            }
+            // x,y,x1,y1 are all >= 0, so w,h must be >= 0
+            w = x1-x;
+            h = y1-y;
+            // off is first pixel read so it must be in bounds
+            if (off < 0 || off >= pix.length) {
+                // They overflowed their own array
+                throw new ArrayIndexOutOfBoundsException("Data offset out of bounds.");
+            }
+            // pix.length and off are >= 0 so remainder >= 0
+            int remainder = pix.length - off;
+            if (remainder < w) {
+                // They overflowed their own array
+                throw new ArrayIndexOutOfBoundsException("Data array is too short.");
+            }
+            int num;
+            if (scansize < 0) {
+                num = (off / -scansize) + 1;
+            } else if (scansize > 0) {
+                num = ((remainder-w) / scansize) + 1;
+            } else {
+                num = h;
+            }
+            if (h > num) {
+                // They overflowed their own array.
+                throw new ArrayIndexOutOfBoundsException("Data array is too short.");
+            }
+
             if (isSameCM && (cmodel != model) && (srcLUT != null) &&
                 (model instanceof IndexColorModel) &&
                 (biRaster instanceof ByteComponentRaster))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/misc/JavaSecurityProtectionDomainAccess.java	Thu Mar 25 07:12:43 2010 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package sun.misc;
+
+import java.security.PermissionCollection;
+import java.security.ProtectionDomain;
+
+public interface JavaSecurityProtectionDomainAccess {
+    interface ProtectionDomainCache {
+        void put(ProtectionDomain pd, PermissionCollection pc);
+        PermissionCollection get(ProtectionDomain pd);
+    }
+    /**
+     * Returns the ProtectionDomainCache.
+     */
+    ProtectionDomainCache getProtectionDomainCache();
+}
--- a/jdk/src/share/classes/sun/misc/SharedSecrets.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/misc/SharedSecrets.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,6 +47,7 @@
     private static JavaNetAccess javaNetAccess;
     private static JavaNioAccess javaNioAccess;
     private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess;
+    private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess;
 
     public static JavaUtilJarAccess javaUtilJarAccess() {
         if (javaUtilJarAccess == null) {
@@ -113,4 +114,13 @@
         return javaIOFileDescriptorAccess;
     }
 
+    public static void setJavaSecurityProtectionDomainAccess
+        (JavaSecurityProtectionDomainAccess jspda) {
+            javaSecurityProtectionDomainAccess = jspda;
+    }
+
+    public static JavaSecurityProtectionDomainAccess
+        getJavaSecurityProtectionDomainAccess() {
+            return javaSecurityProtectionDomainAccess;
+    }
 }
--- a/jdk/src/share/classes/sun/nio/ch/Net.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/nio/ch/Net.java	Thu Mar 25 07:12:43 2010 -0700
@@ -68,6 +68,9 @@
         InetSocketAddress isa = (InetSocketAddress)sa;
         if (isa.isUnresolved())
             throw new UnresolvedAddressException(); // ## needs arg
+        InetAddress addr = isa.getAddress();
+        if (!(addr instanceof Inet4Address || addr instanceof Inet6Address))
+            throw new IllegalArgumentException("Invalid address type");
         return isa;
     }
 
--- a/jdk/src/share/classes/sun/security/provider/PolicyFile.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/security/provider/PolicyFile.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,6 +65,9 @@
 import javax.sound.sampled.AudioPermission;
 import javax.net.ssl.SSLPermission;
 */
+import sun.misc.JavaSecurityProtectionDomainAccess;
+import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
+import sun.misc.SharedSecrets;
 import sun.security.util.Password;
 import sun.security.util.PolicyUtil;
 import sun.security.util.PropertyExpander;
@@ -1102,7 +1105,7 @@
     /**
      * Refreshes the policy object by re-reading all the policy files.
      */
-    public void refresh() {
+    @Override public void refresh() {
         init(url);
     }
 
@@ -1119,9 +1122,10 @@
      *
      * @see java.security.ProtectionDomain
      */
+    @Override
     public boolean implies(ProtectionDomain pd, Permission p) {
         PolicyInfo pi = policyInfo.get();
-        Map<ProtectionDomain, PermissionCollection> pdMap = pi.getPdMapping();
+        ProtectionDomainCache pdMap = pi.getPdMapping();
 
         PermissionCollection pc = pdMap.get(pd);
 
@@ -1167,6 +1171,7 @@
      * @return the Permissions granted to the provided
      *          <code>ProtectionDomain</code>.
      */
+    @Override
     public PermissionCollection getPermissions(ProtectionDomain domain) {
         Permissions perms = new Permissions();
 
@@ -1202,6 +1207,7 @@
      *
      * @return the set of permissions according to the policy.
      */
+    @Override
     public PermissionCollection getPermissions(CodeSource codesource) {
         return getPermissions(new Permissions(), codesource);
     }
@@ -2119,7 +2125,7 @@
             return codesource;
         }
 
-        public String toString(){
+        @Override public String toString(){
             StringBuilder sb = new StringBuilder();
             sb.append(ResourcesMgr.getString("("));
             sb.append(getCodeSource());
@@ -2255,7 +2261,7 @@
          *
          * @return false.
          */
-        public boolean implies(Permission p) {
+        @Override public boolean implies(Permission p) {
             return false;
         }
 
@@ -2272,7 +2278,7 @@
          * type (class) name, permission name, actions, and
          * certificates as this object.
          */
-        public boolean equals(Object obj) {
+        @Override public boolean equals(Object obj) {
             if (obj == this)
                 return true;
 
@@ -2320,7 +2326,7 @@
          *
          * @return a hash code value for this object.
          */
-        public int hashCode() {
+        @Override public int hashCode() {
             int hash = type.hashCode();
             if (name != null)
                 hash ^= name.hashCode();
@@ -2339,7 +2345,7 @@
          *
          * @return the empty string "".
          */
-        public String getActions() {
+        @Override public String getActions() {
             return "";
         }
 
@@ -2366,7 +2372,7 @@
          *
          * @return information about this SelfPermission.
          */
-        public String toString() {
+        @Override public String toString() {
             return "(SelfPermission " + type + " " + name + " " + actions + ")";
         }
     }
@@ -2388,7 +2394,7 @@
         final Map aliasMapping;
 
         // Maps ProtectionDomain to PermissionCollection
-        private final Map<ProtectionDomain, PermissionCollection>[] pdMapping;
+        private final ProtectionDomainCache[] pdMapping;
         private java.util.Random random;
 
         PolicyInfo(int numCaches) {
@@ -2397,16 +2403,17 @@
                 Collections.synchronizedList(new ArrayList<PolicyEntry>(2));
             aliasMapping = Collections.synchronizedMap(new HashMap(11));
 
-            pdMapping = new Map[numCaches];
+            pdMapping = new ProtectionDomainCache[numCaches];
+            JavaSecurityProtectionDomainAccess jspda
+                = SharedSecrets.getJavaSecurityProtectionDomainAccess();
             for (int i = 0; i < numCaches; i++) {
-                pdMapping[i] = Collections.synchronizedMap
-                    (new WeakHashMap<ProtectionDomain, PermissionCollection>());
+                pdMapping[i] = jspda.getProtectionDomainCache();
             }
             if (numCaches > 1) {
                 random = new java.util.Random();
             }
         }
-        Map<ProtectionDomain, PermissionCollection> getPdMapping() {
+        ProtectionDomainCache getPdMapping() {
             if (pdMapping.length == 1) {
                 return pdMapping[0];
             } else {
--- a/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java	Thu Mar 25 07:12:43 2010 -0700
@@ -93,13 +93,17 @@
      * Constructors
      */
     ClientHandshaker(SSLSocketImpl socket, SSLContextImpl context,
-            ProtocolList enabledProtocols) {
+            ProtocolList enabledProtocols,
+            ProtocolVersion activeProtocolVersion) {
         super(socket, context, enabledProtocols, true, true);
+        this.activeProtocolVersion = activeProtocolVersion;
     }
 
     ClientHandshaker(SSLEngineImpl engine, SSLContextImpl context,
-            ProtocolList enabledProtocols) {
+            ProtocolList enabledProtocols,
+            ProtocolVersion activeProtocolVersion) {
         super(engine, context, enabledProtocols, true, true);
+        this.activeProtocolVersion = activeProtocolVersion;
     }
 
     /*
@@ -275,7 +279,42 @@
         // sent the "client hello" but the server's not seen it.
         //
         if (state < HandshakeMessage.ht_client_hello) {
-            kickstart();
+            if (!renegotiable) {    // renegotiation is not allowed.
+                if (activeProtocolVersion.v >= ProtocolVersion.TLS10.v) {
+                    // response with a no_negotiation warning,
+                    warningSE(Alerts.alert_no_negotiation);
+
+                    // invalidate the handshake so that the caller can
+                    // dispose this object.
+                    invalidated = true;
+
+                    // If there is still unread block in the handshake
+                    // input stream, it would be truncated with the disposal
+                    // and the next handshake message will become incomplete.
+                    //
+                    // However, according to SSL/TLS specifications, no more
+                    // handshake message could immediately follow ClientHello
+                    // or HelloRequest. But in case of any improper messages,
+                    // we'd better check to ensure there is no remaining bytes
+                    // in the handshake input stream.
+                    if (input.available() > 0) {
+                        fatalSE(Alerts.alert_unexpected_message,
+                            "HelloRequest followed by an unexpected  " +
+                            "handshake message");
+                    }
+
+                } else {
+                    // For SSLv3, send the handshake_failure fatal error.
+                    // Note that SSLv3 does not define a no_negotiation alert
+                    // like TLSv1. However we cannot ignore the message
+                    // simply, otherwise the other side was waiting for a
+                    // response that would never come.
+                    fatalSE(Alerts.alert_handshake_failure,
+                        "renegotiation is not allowed");
+                }
+            } else {
+                kickstart();
+            }
         }
     }
 
--- a/jdk/src/share/classes/sun/security/ssl/Handshaker.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/security/ssl/Handshaker.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1996-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1996-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,9 +60,12 @@
  */
 abstract class Handshaker {
 
-    // current protocol version
+    // protocol version being established using this Handshaker
     ProtocolVersion protocolVersion;
 
+    // the currently active protocol version during a renegotiation
+    ProtocolVersion     activeProtocolVersion;
+
     // list of enabled protocols
     ProtocolList enabledProtocols;
 
@@ -124,6 +127,13 @@
     /* Class and subclass dynamic debugging support */
     static final Debug debug = Debug.getInstance("ssl");
 
+    // By default, disable the unsafe legacy session renegotiation
+    static final boolean renegotiable = Debug.getBooleanProperty(
+                    "sun.security.ssl.allowUnsafeRenegotiation", false);
+
+    // need to dispose the object when it is invalidated
+    boolean invalidated;
+
     Handshaker(SSLSocketImpl c, SSLContextImpl context,
             ProtocolList enabledProtocols, boolean needCertVerify,
             boolean isClient) {
@@ -144,6 +154,7 @@
         this.sslContext = context;
         this.isClient = isClient;
         enableNewSession = true;
+        invalidated = false;
 
         setCipherSuite(CipherSuite.C_NULL);
 
@@ -489,7 +500,9 @@
      */
     void processLoop() throws IOException {
 
-        while (input.available() > 0) {
+        // need to read off 4 bytes at least to get the handshake
+        // message type and length.
+        while (input.available() >= 4) {
             byte messageType;
             int messageLen;
 
--- a/jdk/src/share/classes/sun/security/ssl/SSLEngineImpl.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/security/ssl/SSLEngineImpl.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -433,11 +433,12 @@
             connectionState = cs_RENEGOTIATE;
         }
         if (roleIsServer) {
-            handshaker = new ServerHandshaker
-                        (this, sslContext, enabledProtocols, doClientAuth);
+            handshaker = new ServerHandshaker(this, sslContext,
+                        enabledProtocols, doClientAuth,
+                        connectionState == cs_RENEGOTIATE, protocolVersion);
         } else {
-            handshaker = new ClientHandshaker
-                        (this, sslContext, enabledProtocols);
+            handshaker = new ClientHandshaker(this, sslContext,
+                        enabledProtocols, protocolVersion);
         }
         handshaker.enabledCipherSuites = enabledCipherSuites;
         handshaker.setEnableSessionCreation(enableSessionCreation);
@@ -639,6 +640,10 @@
             break;
 
         case cs_DATA:
+            if (!Handshaker.renegotiable) {
+                throw new SSLHandshakeException("renegotiation is not allowed");
+            }
+
             // initialize the handshaker, move to cs_RENEGOTIATE
             initHandshaker();
             break;
@@ -966,7 +971,13 @@
                     handshaker.process_record(inputRecord, expectingFinished);
                     expectingFinished = false;
 
-                    if (handshaker.isDone()) {
+                    if (handshaker.invalidated) {
+                        handshaker = null;
+                        // if state is cs_RENEGOTIATE, revert it to cs_DATA
+                        if (connectionState == cs_RENEGOTIATE) {
+                            connectionState = cs_DATA;
+                        }
+                    } else if (handshaker.isDone()) {
                         sess = handshaker.getSession();
                         if (!writer.hasOutboundData()) {
                             hsStatus = HandshakeStatus.FINISHED;
--- a/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java	Thu Mar 25 07:12:43 2010 -0700
@@ -907,7 +907,13 @@
                     handshaker.process_record(r, expectingFinished);
                     expectingFinished = false;
 
-                    if (handshaker.isDone()) {
+                    if (handshaker.invalidated) {
+                        handshaker = null;
+                        // if state is cs_RENEGOTIATE, revert it to cs_DATA
+                        if (connectionState == cs_RENEGOTIATE) {
+                            connectionState = cs_DATA;
+                        }
+                    } else if (handshaker.isDone()) {
                         sess = handshaker.getSession();
                         handshaker = null;
                         connectionState = cs_DATA;
@@ -925,6 +931,7 @@
                             t.start();
                         }
                     }
+
                     if (needAppData || connectionState != cs_DATA) {
                         continue;
                     } else {
@@ -1083,11 +1090,12 @@
             connectionState = cs_RENEGOTIATE;
         }
         if (roleIsServer) {
-            handshaker = new ServerHandshaker
-                        (this, sslContext, enabledProtocols, doClientAuth);
+            handshaker = new ServerHandshaker(this, sslContext,
+                        enabledProtocols, doClientAuth,
+                        connectionState == cs_RENEGOTIATE, protocolVersion);
         } else {
-            handshaker = new ClientHandshaker
-                        (this, sslContext, enabledProtocols);
+            handshaker = new ClientHandshaker(this, sslContext,
+                        enabledProtocols, protocolVersion);
         }
         handshaker.enabledCipherSuites = enabledCipherSuites;
         handshaker.setEnableSessionCreation(enableSessionCreation);
@@ -1192,6 +1200,10 @@
             break;
 
         case cs_DATA:
+            if (!Handshaker.renegotiable) {
+                throw new SSLHandshakeException("renegotiation is not allowed");
+            }
+
             // initialize the handshaker, move to cs_RENEGOTIATE
             initHandshaker();
             break;
--- a/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java	Thu Mar 25 07:12:43 2010 -0700
@@ -69,6 +69,9 @@
     // flag to check for clientCertificateVerify message
     private boolean             needClientVerify = false;
 
+    // indicate a renegotiation handshaking
+    private boolean             isRenegotiation = false;
+
     /*
      * For exportable ciphersuites using non-exportable key sizes, we use
      * ephemeral RSA keys. We could also do anonymous RSA in the same way
@@ -96,20 +99,28 @@
      * Constructor ... use the keys found in the auth context.
      */
     ServerHandshaker(SSLSocketImpl socket, SSLContextImpl context,
-            ProtocolList enabledProtocols, byte clientAuth) {
+            ProtocolList enabledProtocols, byte clientAuth,
+            boolean isRenegotiation, ProtocolVersion activeProtocolVersion) {
+
         super(socket, context, enabledProtocols,
                         (clientAuth != SSLEngineImpl.clauth_none), false);
         doClientAuth = clientAuth;
+        this.isRenegotiation = isRenegotiation;
+        this.activeProtocolVersion = activeProtocolVersion;
     }
 
     /*
      * Constructor ... use the keys found in the auth context.
      */
     ServerHandshaker(SSLEngineImpl engine, SSLContextImpl context,
-            ProtocolList enabledProtocols, byte clientAuth) {
+            ProtocolList enabledProtocols, byte clientAuth,
+            boolean isRenegotiation, ProtocolVersion activeProtocolVersion) {
+
         super(engine, context, enabledProtocols,
                         (clientAuth != SSLEngineImpl.clauth_none), false);
         doClientAuth = clientAuth;
+        this.isRenegotiation = isRenegotiation;
+        this.activeProtocolVersion = activeProtocolVersion;
     }
 
     /*
@@ -257,6 +268,45 @@
         if (debug != null && Debug.isOn("handshake")) {
             mesg.print(System.out);
         }
+
+        // if it is a renegotiation request and renegotiation is not allowed
+        if (isRenegotiation && !renegotiable) {
+            if (activeProtocolVersion.v >= ProtocolVersion.TLS10.v) {
+                // response with a no_negotiation warning,
+                warningSE(Alerts.alert_no_negotiation);
+
+                // invalidate the handshake so that the caller can
+                // dispose this object.
+                invalidated = true;
+
+                // If there is still unread block in the handshake
+                // input stream, it would be truncated with the disposal
+                // and the next handshake message will become incomplete.
+                //
+                // However, according to SSL/TLS specifications, no more
+                // handshake message could immediately follow ClientHello
+                // or HelloRequest. But in case of any improper messages,
+                // we'd better check to ensure there is no remaining bytes
+                // in the handshake input stream.
+                if (input.available() > 0) {
+                    fatalSE(Alerts.alert_unexpected_message,
+                        "ClientHello followed by an unexpected  " +
+                        "handshake message");
+
+                }
+
+                return;
+            } else {
+                // For SSLv3, send the handshake_failure fatal error.
+                // Note that SSLv3 does not define a no_negotiation alert
+                // like TLSv1. However we cannot ignore the message
+                // simply, otherwise the other side was waiting for a
+                // response that would never come.
+                fatalSE(Alerts.alert_handshake_failure,
+                    "renegotiation is not allowed");
+            }
+        }
+
         /*
          * Always make sure this entire record has been digested before we
          * start emitting output, to ensure correct digesting order.
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/bytes.cpp	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/bytes.cpp	Thu Mar 25 07:12:43 2010 -0700
@@ -40,7 +40,7 @@
 
 void bytes::malloc(size_t len_) {
   len = len_;
-  ptr = NEW(byte, len_+1);  // add trailing zero byte always
+  ptr = NEW(byte, add_size(len_, 1));  // add trailing zero byte always
   if (ptr == null) {
     // set ptr to some victim memory, to ease escape
     set(dummy, sizeof(dummy)-1);
@@ -56,7 +56,7 @@
     return;
   }
   byte* oldptr = ptr;
-  ptr = (len_ >= PSIZE_MAX) ? null : (byte*)::realloc(ptr, len_+1);
+  ptr = (len_ >= PSIZE_MAX) ? null : (byte*)::realloc(ptr, add_size(len_, 1));
   if (ptr != null)  {
     mtrace('r', oldptr, 0);
     mtrace('m', ptr, len_+1);
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp	Thu Mar 25 07:12:43 2010 -0700
@@ -507,7 +507,7 @@
 
 maybe_inline
 void unpacker::saveTo(bytes& b, byte* ptr, size_t len) {
-  b.ptr = U_NEW(byte, len+1);
+  b.ptr = U_NEW(byte, add_size(len,1));
   if (aborting()) {
     b.len = 0;
     return;
@@ -1154,7 +1154,7 @@
     *fillp = 0;  // bigbuf must contain a well-formed Utf8 string
     int length = (int)(fillp - bigbuf.ptr);
     bytes& value = cpMap[i].value.b;
-    value.set(U_NEW(byte, length+1), length);
+    value.set(U_NEW(byte, add_size(length,1)), length);
     value.copyFrom(bigbuf.ptr, length);
     CHECK;
     // Index all Utf8 strings
@@ -1626,7 +1626,7 @@
     return no_bands;
   } else {
     int nb = bs_limit - bs_base;
-    band** res = U_NEW(band*, nb+1);
+    band** res = U_NEW(band*, add_size(nb, 1));
     CHECK_(no_bands);
     for (int i = 0; i < nb; i++) {
       band* b = (band*) band_stack.get(bs_base + i);
@@ -1735,7 +1735,7 @@
             }
             // save away the case labels
             int ntags = band_stack.length() - case_base;
-            int* tags = U_NEW(int, 1+ntags);
+            int* tags = U_NEW(int, add_size(ntags, 1));
             CHECK_(lp);
             k_case.le_casetags = tags;
             *tags++ = ntags;
@@ -3139,8 +3139,8 @@
   int*     field_counts  = T_NEW(int, nclasses);
   int*     method_counts = T_NEW(int, nclasses);
   cpindex* all_indexes   = U_NEW(cpindex, nclasses*2);
-  entry**  field_ix      = U_NEW(entry*, nfields+nclasses);
-  entry**  method_ix     = U_NEW(entry*, nmethods+nclasses);
+  entry**  field_ix      = U_NEW(entry*, add_size(nfields, nclasses));
+  entry**  method_ix     = U_NEW(entry*, add_size(nmethods, nclasses));
 
   for (j = 0; j < nfields; j++) {
     entry& f = fields[j];
@@ -4132,7 +4132,7 @@
           }
           const char* suffix = ".java";
           int len = (int)(prefix.len + strlen(suffix));
-          bytes name; name.set(T_NEW(byte, len + 1), len);
+          bytes name; name.set(T_NEW(byte, add_size(len, 1)), len);
           name.strcat(prefix).strcat(suffix);
           ref = cp.ensureUtf8(name);
         }
@@ -4647,7 +4647,7 @@
       bytes& prefix = cur_class->ref(0)->value.b;
       const char* suffix = ".class";
       int len = (int)(prefix.len + strlen(suffix));
-      bytes name; name.set(T_NEW(byte, len + 1), len);
+      bytes name; name.set(T_NEW(byte, add_size(len, 1)), len);
       cur_file.name = name.strcat(prefix).strcat(suffix).strval();
     }
   } else {
@@ -4714,6 +4714,7 @@
         input.ensureSize(fleft);
       }
       rplimit = rp = input.base();
+      CHECK;
       input.setLimit(rp + fleft);
       if (!ensure_input(fleft))
         abort("EOF reading resource file");
--- a/jdk/src/share/native/java/util/zip/Deflater.c	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/java/util/zip/Deflater.c	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,6 @@
 
 #define DEF_MEM_LEVEL 8
 
-static jfieldID strmID;
 static jfieldID levelID;
 static jfieldID strategyID;
 static jfieldID setParamsID;
@@ -49,7 +48,6 @@
 JNIEXPORT void JNICALL
 Java_java_util_zip_Deflater_initIDs(JNIEnv *env, jclass cls)
 {
-    strmID = (*env)->GetFieldID(env, cls, "strm", "J");
     levelID = (*env)->GetFieldID(env, cls, "level", "I");
     strategyID = (*env)->GetFieldID(env, cls, "strategy", "I");
     setParamsID = (*env)->GetFieldID(env, cls, "setParams", "Z");
@@ -94,7 +92,7 @@
 }
 
 JNIEXPORT void JNICALL
-Java_java_util_zip_Deflater_setDictionary(JNIEnv *env, jclass cls, jlong strm,
+Java_java_util_zip_Deflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
                                           jarray b, jint off, jint len)
 {
     Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
@@ -102,7 +100,7 @@
     if (buf == 0) {/* out of memory */
         return;
     }
-    res = deflateSetDictionary((z_stream *)jlong_to_ptr(strm), buf + off, len);
+    res = deflateSetDictionary((z_stream *)jlong_to_ptr(addr), buf + off, len);
     (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
     switch (res) {
     case Z_OK:
@@ -111,151 +109,144 @@
         JNU_ThrowIllegalArgumentException(env, 0);
         break;
     default:
-        JNU_ThrowInternalError(env, ((z_stream *)jlong_to_ptr(strm))->msg);
+        JNU_ThrowInternalError(env, ((z_stream *)jlong_to_ptr(addr))->msg);
         break;
     }
 }
 
 JNIEXPORT jint JNICALL
-Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this,
+Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr,
                                          jarray b, jint off, jint len, jint flush)
 {
-    z_stream *strm = jlong_to_ptr((*env)->GetLongField(env, this, strmID));
+    z_stream *strm = jlong_to_ptr(addr);
 
-    if (strm == 0) {
-        JNU_ThrowNullPointerException(env, 0);
-        return 0;
-    } else {
-        jarray this_buf = (*env)->GetObjectField(env, this, bufID);
-        jint this_off = (*env)->GetIntField(env, this, offID);
-        jint this_len = (*env)->GetIntField(env, this, lenID);
-        jbyte *in_buf;
-        jbyte *out_buf;
-        int res;
-        if ((*env)->GetBooleanField(env, this, setParamsID)) {
-            int level = (*env)->GetIntField(env, this, levelID);
-            int strategy = (*env)->GetIntField(env, this, strategyID);
+    jarray this_buf = (*env)->GetObjectField(env, this, bufID);
+    jint this_off = (*env)->GetIntField(env, this, offID);
+    jint this_len = (*env)->GetIntField(env, this, lenID);
+    jbyte *in_buf;
+    jbyte *out_buf;
+    int res;
+    if ((*env)->GetBooleanField(env, this, setParamsID)) {
+        int level = (*env)->GetIntField(env, this, levelID);
+        int strategy = (*env)->GetIntField(env, this, strategyID);
 
-            in_buf = (jbyte *) malloc(this_len);
-            if (in_buf == 0) {
-                JNU_ThrowOutOfMemoryError(env, 0);
-                return 0;
-            }
-            (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
+        in_buf = (jbyte *) malloc(this_len);
+        if (in_buf == 0) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
+        (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
+        out_buf = (jbyte *) malloc(len);
+        if (out_buf == 0) {
+            free(in_buf);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
 
-            out_buf = (jbyte *) malloc(len);
-            if (out_buf == 0) {
-                free(in_buf);
-                JNU_ThrowOutOfMemoryError(env, 0);
-                return 0;
-            }
+        strm->next_in = (Bytef *) in_buf;
+        strm->next_out = (Bytef *) out_buf;
+        strm->avail_in = this_len;
+        strm->avail_out = len;
+        res = deflateParams(strm, level, strategy);
 
-            strm->next_in = (Bytef *) in_buf;
-            strm->next_out = (Bytef *) out_buf;
-            strm->avail_in = this_len;
-            strm->avail_out = len;
-            res = deflateParams(strm, level, strategy);
-
-            if (res == Z_OK) {
-                (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
-            }
-            free(out_buf);
-            free(in_buf);
+        if (res == Z_OK) {
+            (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
+        }
+        free(out_buf);
+        free(in_buf);
 
-            switch (res) {
-            case Z_OK:
-                (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE);
-                this_off += this_len - strm->avail_in;
-                (*env)->SetIntField(env, this, offID, this_off);
-                (*env)->SetIntField(env, this, lenID, strm->avail_in);
-                return len - strm->avail_out;
-            case Z_BUF_ERROR:
-                (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE);
-                return 0;
-            default:
-                JNU_ThrowInternalError(env, strm->msg);
-                return 0;
-            }
-        } else {
-            jboolean finish = (*env)->GetBooleanField(env, this, finishID);
-
-            in_buf = (jbyte *) malloc(this_len);
-            if (in_buf == 0) {
-                JNU_ThrowOutOfMemoryError(env, 0);
-                return 0;
-            }
-            (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
+        switch (res) {
+        case Z_OK:
+            (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE);
+            this_off += this_len - strm->avail_in;
+            (*env)->SetIntField(env, this, offID, this_off);
+            (*env)->SetIntField(env, this, lenID, strm->avail_in);
+            return len - strm->avail_out;
+        case Z_BUF_ERROR:
+            (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE);
+            return 0;
+        default:
+            JNU_ThrowInternalError(env, strm->msg);
+            return 0;
+        }
+    } else {
+        jboolean finish = (*env)->GetBooleanField(env, this, finishID);
+        in_buf = (jbyte *) malloc(this_len);
+        if (in_buf == 0) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
+        (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
 
-            out_buf = (jbyte *) malloc(len);
-            if (out_buf == 0) {
-                free(in_buf);
-                JNU_ThrowOutOfMemoryError(env, 0);
-                return 0;
-            }
+        out_buf = (jbyte *) malloc(len);
+        if (out_buf == 0) {
+            free(in_buf);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
 
-            strm->next_in = (Bytef *) in_buf;
-            strm->next_out = (Bytef *) out_buf;
-            strm->avail_in = this_len;
-            strm->avail_out = len;
-            res = deflate(strm, finish ? Z_FINISH : flush);
+        strm->next_in = (Bytef *) in_buf;
+        strm->next_out = (Bytef *) out_buf;
+        strm->avail_in = this_len;
+        strm->avail_out = len;
+        res = deflate(strm, finish ? Z_FINISH : flush);
 
-            if (res == Z_STREAM_END || res == Z_OK) {
-                (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
-            }
-            free(out_buf);
-            free(in_buf);
+        if (res == Z_STREAM_END || res == Z_OK) {
+            (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
+        }
+        free(out_buf);
+        free(in_buf);
 
-            switch (res) {
-            case Z_STREAM_END:
-                (*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
-                /* fall through */
-            case Z_OK:
-                this_off += this_len - strm->avail_in;
-                (*env)->SetIntField(env, this, offID, this_off);
-                (*env)->SetIntField(env, this, lenID, strm->avail_in);
-                return len - strm->avail_out;
-            case Z_BUF_ERROR:
-                return 0;
+        switch (res) {
+        case Z_STREAM_END:
+            (*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
+            /* fall through */
+        case Z_OK:
+            this_off += this_len - strm->avail_in;
+            (*env)->SetIntField(env, this, offID, this_off);
+            (*env)->SetIntField(env, this, lenID, strm->avail_in);
+            return len - strm->avail_out;
+        case Z_BUF_ERROR:
+            return 0;
             default:
-                JNU_ThrowInternalError(env, strm->msg);
-                return 0;
-            }
+            JNU_ThrowInternalError(env, strm->msg);
+            return 0;
         }
     }
 }
 
 JNIEXPORT jint JNICALL
-Java_java_util_zip_Deflater_getAdler(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Deflater_getAdler(JNIEnv *env, jclass cls, jlong addr)
 {
-    return ((z_stream *)jlong_to_ptr(strm))->adler;
+    return ((z_stream *)jlong_to_ptr(addr))->adler;
 }
 
 JNIEXPORT jlong JNICALL
-Java_java_util_zip_Deflater_getBytesRead(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Deflater_getBytesRead(JNIEnv *env, jclass cls, jlong addr)
 {
-    return ((z_stream *)jlong_to_ptr(strm))->total_in;
+    return ((z_stream *)jlong_to_ptr(addr))->total_in;
 }
 
 JNIEXPORT jlong JNICALL
-Java_java_util_zip_Deflater_getBytesWritten(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Deflater_getBytesWritten(JNIEnv *env, jclass cls, jlong addr)
 {
-    return ((z_stream *)jlong_to_ptr(strm))->total_out;
+    return ((z_stream *)jlong_to_ptr(addr))->total_out;
 }
 
 JNIEXPORT void JNICALL
-Java_java_util_zip_Deflater_reset(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Deflater_reset(JNIEnv *env, jclass cls, jlong addr)
 {
-    if (deflateReset((z_stream *)jlong_to_ptr(strm)) != Z_OK) {
+    if (deflateReset((z_stream *)jlong_to_ptr(addr)) != Z_OK) {
         JNU_ThrowInternalError(env, 0);
     }
 }
 
 JNIEXPORT void JNICALL
-Java_java_util_zip_Deflater_end(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Deflater_end(JNIEnv *env, jclass cls, jlong addr)
 {
-    if (deflateEnd((z_stream *)jlong_to_ptr(strm)) == Z_STREAM_ERROR) {
+    if (deflateEnd((z_stream *)jlong_to_ptr(addr)) == Z_STREAM_ERROR) {
         JNU_ThrowInternalError(env, 0);
     } else {
-        free((z_stream *)jlong_to_ptr(strm));
+        free((z_stream *)jlong_to_ptr(addr));
     }
 }
--- a/jdk/src/share/native/java/util/zip/Inflater.c	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/java/util/zip/Inflater.c	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,7 +41,6 @@
 #define ThrowDataFormatException(env, msg) \
         JNU_ThrowByName(env, "java/util/zip/DataFormatException", msg)
 
-static jfieldID strmID;
 static jfieldID needDictID;
 static jfieldID finishedID;
 static jfieldID bufID, offID, lenID;
@@ -49,7 +48,6 @@
 JNIEXPORT void JNICALL
 Java_java_util_zip_Inflater_initIDs(JNIEnv *env, jclass cls)
 {
-    strmID = (*env)->GetFieldID(env, cls, "strm", "J");
     needDictID = (*env)->GetFieldID(env, cls, "needDict", "Z");
     finishedID = (*env)->GetFieldID(env, cls, "finished", "Z");
     bufID = (*env)->GetFieldID(env, cls, "buf", "[B");
@@ -84,134 +82,129 @@
 }
 
 JNIEXPORT void JNICALL
-Java_java_util_zip_Inflater_setDictionary(JNIEnv *env, jclass cls, jlong strm,
+Java_java_util_zip_Inflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
                                           jarray b, jint off, jint len)
 {
     Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
     int res;
     if (buf == 0) /* out of memory */
         return;
-    res = inflateSetDictionary(jlong_to_ptr(strm), buf + off, len);
+    res = inflateSetDictionary(jlong_to_ptr(addr), buf + off, len);
     (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
     switch (res) {
     case Z_OK:
         break;
     case Z_STREAM_ERROR:
     case Z_DATA_ERROR:
-        JNU_ThrowIllegalArgumentException(env, ((z_stream *)jlong_to_ptr(strm))->msg);
+        JNU_ThrowIllegalArgumentException(env, ((z_stream *)jlong_to_ptr(addr))->msg);
         break;
     default:
-        JNU_ThrowInternalError(env, ((z_stream *)jlong_to_ptr(strm))->msg);
+        JNU_ThrowInternalError(env, ((z_stream *)jlong_to_ptr(addr))->msg);
         break;
     }
 }
 
 JNIEXPORT jint JNICALL
-Java_java_util_zip_Inflater_inflateBytes(JNIEnv *env, jobject this,
+Java_java_util_zip_Inflater_inflateBytes(JNIEnv *env, jobject this, jlong addr,
                                          jarray b, jint off, jint len)
 {
-    z_stream *strm = jlong_to_ptr((*env)->GetLongField(env, this, strmID));
+    z_stream *strm = jlong_to_ptr(addr);
 
-    if (strm == 0) {
-        JNU_ThrowNullPointerException(env, 0);
-        return 0;
-    } else {
-        jarray this_buf = (jarray)(*env)->GetObjectField(env, this, bufID);
-        jint this_off = (*env)->GetIntField(env, this, offID);
-        jint this_len = (*env)->GetIntField(env, this, lenID);
-        jbyte *in_buf;
-        jbyte *out_buf;
-        int ret;
+    jarray this_buf = (jarray)(*env)->GetObjectField(env, this, bufID);
+    jint this_off = (*env)->GetIntField(env, this, offID);
+    jint this_len = (*env)->GetIntField(env, this, lenID);
+    jbyte *in_buf;
+    jbyte *out_buf;
+    int ret;
 
-        in_buf = (jbyte *) malloc(this_len);
-        if (in_buf == 0) {
-            JNU_ThrowOutOfMemoryError(env, 0);
-            return 0;
-        }
-        (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
+    in_buf = (jbyte *) malloc(this_len);
+    if (in_buf == 0) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+    }
+    (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
 
-        out_buf = (jbyte *) malloc(len);
-        if (out_buf == 0) {
-            free(in_buf);
-            JNU_ThrowOutOfMemoryError(env, 0);
-            return 0;
-        }
+    out_buf = (jbyte *) malloc(len);
+    if (out_buf == 0) {
+        free(in_buf);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+    }
 
-        strm->next_in  = (Bytef *) in_buf;
-        strm->next_out = (Bytef *) out_buf;
-        strm->avail_in  = this_len;
-        strm->avail_out = len;
-        ret = inflate(strm, Z_PARTIAL_FLUSH);
+    strm->next_in  = (Bytef *) in_buf;
+    strm->next_out = (Bytef *) out_buf;
+    strm->avail_in  = this_len;
+    strm->avail_out = len;
+    ret = inflate(strm, Z_PARTIAL_FLUSH);
 
-        if (ret == Z_STREAM_END || ret == Z_OK) {
-            (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
-        }
-        free(out_buf);
-        free(in_buf);
+    if (ret == Z_STREAM_END || ret == Z_OK) {
+        (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
+    }
+    free(out_buf);
+    free(in_buf);
 
-        switch (ret) {
-        case Z_STREAM_END:
-            (*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
-            /* fall through */
-        case Z_OK:
-            this_off += this_len - strm->avail_in;
-            (*env)->SetIntField(env, this, offID, this_off);
-            (*env)->SetIntField(env, this, lenID, strm->avail_in);
-            return len - strm->avail_out;
-        case Z_NEED_DICT:
-            (*env)->SetBooleanField(env, this, needDictID, JNI_TRUE);
-            /* Might have consumed some input here! */
-            this_off += this_len - strm->avail_in;
-            (*env)->SetIntField(env, this, offID, this_off);
-            (*env)->SetIntField(env, this, lenID, strm->avail_in);
-            return 0;
-        case Z_BUF_ERROR:
-            return 0;
-        case Z_DATA_ERROR:
-            ThrowDataFormatException(env, strm->msg);
-            return 0;
-        case Z_MEM_ERROR:
-            JNU_ThrowOutOfMemoryError(env, 0);
-            return 0;
-        default:
-            JNU_ThrowInternalError(env, strm->msg);
-            return 0;
-        }
+    switch (ret) {
+    case Z_STREAM_END:
+        (*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
+        /* fall through */
+    case Z_OK:
+        this_off += this_len - strm->avail_in;
+        (*env)->SetIntField(env, this, offID, this_off);
+        (*env)->SetIntField(env, this, lenID, strm->avail_in);
+        return len - strm->avail_out;
+    case Z_NEED_DICT:
+        (*env)->SetBooleanField(env, this, needDictID, JNI_TRUE);
+        /* Might have consumed some input here! */
+        this_off += this_len - strm->avail_in;
+        (*env)->SetIntField(env, this, offID, this_off);
+        (*env)->SetIntField(env, this, lenID, strm->avail_in);
+        return 0;
+    case Z_BUF_ERROR:
+        return 0;
+    case Z_DATA_ERROR:
+        ThrowDataFormatException(env, strm->msg);
+        return 0;
+    case Z_MEM_ERROR:
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+    default:
+        JNU_ThrowInternalError(env, strm->msg);
+        return 0;
     }
 }
 
 JNIEXPORT jint JNICALL
-Java_java_util_zip_Inflater_getAdler(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Inflater_getAdler(JNIEnv *env, jclass cls, jlong addr)
 {
-    return ((z_stream *)jlong_to_ptr(strm))->adler;
+    return ((z_stream *)jlong_to_ptr(addr))->adler;
 }
 
 JNIEXPORT jlong JNICALL
-Java_java_util_zip_Inflater_getBytesRead(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Inflater_getBytesRead(JNIEnv *env, jclass cls, jlong addr)
 {
-    return ((z_stream *)jlong_to_ptr(strm))->total_in;
+    return ((z_stream *)jlong_to_ptr(addr))->total_in;
 }
 
 JNIEXPORT jlong JNICALL
-Java_java_util_zip_Inflater_getBytesWritten(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Inflater_getBytesWritten(JNIEnv *env, jclass cls, jlong addr)
 {
-    return ((z_stream *)jlong_to_ptr(strm))->total_out;
+    return ((z_stream *)jlong_to_ptr(addr))->total_out;
 }
 
 JNIEXPORT void JNICALL
-Java_java_util_zip_Inflater_reset(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Inflater_reset(JNIEnv *env, jclass cls, jlong addr)
 {
-    if (inflateReset(jlong_to_ptr(strm)) != Z_OK) {
+    if (inflateReset(jlong_to_ptr(addr)) != Z_OK) {
         JNU_ThrowInternalError(env, 0);
     }
 }
 
 JNIEXPORT void JNICALL
-Java_java_util_zip_Inflater_end(JNIEnv *env, jclass cls, jlong strm)
+Java_java_util_zip_Inflater_end(JNIEnv *env, jclass cls, jlong addr)
 {
-    if (inflateEnd(jlong_to_ptr(strm)) == Z_STREAM_ERROR) {
+    if (inflateEnd(jlong_to_ptr(addr)) == Z_STREAM_ERROR) {
         JNU_ThrowInternalError(env, 0);
     } else {
-        free(jlong_to_ptr(strm));
+        free(jlong_to_ptr(addr));
     }
 }
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c	Thu Mar 25 07:12:43 2010 -0700
@@ -258,6 +258,7 @@
 
 typedef struct pixelBufferStruct {
     jobject hpixelObject;   // Usually a DataBuffer bank as a byte array
+    unsigned int byteBufferLength;
     union pixptr {
         INT32         *ip;  // Pinned buffer pointer, as 32-bit ints
         unsigned char *bp;  // Pinned buffer pointer, as bytes
@@ -270,6 +271,7 @@
  */
 static void initPixelBuffer(pixelBufferPtr pb) {
     pb->hpixelObject = NULL;
+    pb->byteBufferLength = 0;
     pb->buf.ip = NULL;
 }
 
@@ -279,13 +281,13 @@
  */
 static int setPixelBuffer(JNIEnv *env, pixelBufferPtr pb, jobject obj) {
     pb->hpixelObject = (*env)->NewGlobalRef(env, obj);
-
     if (pb->hpixelObject == NULL) {
         JNU_ThrowByName( env,
                          "java/lang/OutOfMemoryError",
                          "Setting Pixel Buffer");
         return NOT_OK;
     }
+    pb->byteBufferLength = (*env)->GetArrayLength(env, pb->hpixelObject);
     return OK;
 }
 
@@ -302,6 +304,7 @@
         unpinPixelBuffer(env, pb);
         (*env)->DeleteGlobalRef(env, pb->hpixelObject);
         pb->hpixelObject = NULL;
+        pb->byteBufferLength = 0;
     }
 }
 
@@ -1828,6 +1831,7 @@
     boolean orderedBands = TRUE;
     imageIODataPtr data = (imageIODataPtr) ptr;
     j_decompress_ptr cinfo;
+    unsigned int numBytes;
 
     /* verify the inputs */
 
@@ -2027,15 +2031,22 @@
                 // scanline buffer into the raster.
                 in = scanLinePtr + (sourceXStart * cinfo->output_components);
                 if (pixelLimit > in) {
-                    memcpy(out, in, pixelLimit - in);
+                    numBytes = pixelLimit - in;
+                    if (numBytes > data->pixelBuf.byteBufferLength) {
+                        numBytes = data->pixelBuf.byteBufferLength;
+                    }
+                    memcpy(out, in, numBytes);
                 }
             } else {
+                numBytes = numBands;
                 for (in = scanLinePtr+sourceXStart*cinfo->output_components;
-                     in < pixelLimit;
+                     in < pixelLimit &&
+                       numBytes <= data->pixelBuf.byteBufferLength;
                      in += pixelStride) {
                     for (i = 0; i < numBands; i++) {
                         *out++ = *(in+bands[i]);
                     }
+                    numBytes += numBands;
                 }
             }
 
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Thu Mar 25 07:12:43 2010 -0700
@@ -2239,7 +2239,8 @@
     int dataType = BYTE_DATA_TYPE;
     int width;
     int height;
-    int size = rasterP->width * rasterP->height * rasterP->numBands;
+    int dataSize;
+    int offset;
 
     *dataPP = NULL;
 
@@ -2292,6 +2293,22 @@
 #endif
     switch (rasterP->type) {
     case sun_awt_image_IntegerComponentRaster_TYPE_INT_8BIT_SAMPLES:
+        if (!((rasterP->chanOffsets[0] == 0 || SAFE_TO_ALLOC_2(rasterP->chanOffsets[0], 4)) &&
+              SAFE_TO_ALLOC_2(width, 4) &&
+              SAFE_TO_ALLOC_3(height, rasterP->scanlineStride, 4)))
+        {
+            return -1;
+        }
+        offset = 4 * rasterP->chanOffsets[0];
+        dataSize = 4 * (*env)->GetArrayLength(env, rasterP->jdata);
+
+        if (offset < 0 || offset >= dataSize ||
+            width > rasterP->scanlineStride ||
+            height * rasterP->scanlineStride * 4 > dataSize - offset)
+        {
+            // raster data buffer is too short
+            return -1;
+        }
         dataP = (void *) (*env)->GetPrimitiveArrayCritical(env, rasterP->jdata,
                                                            NULL);
         if (dataP == NULL) {
@@ -2300,11 +2317,25 @@
         *mlibImagePP = (*sMlibSysFns.createStructFP)(MLIB_BYTE, 4,
                                               width, height,
                                               rasterP->scanlineStride*4,
-                                              (unsigned char *)dataP
-                                              + rasterP->chanOffsets[0]*4);
+                                              (unsigned char *)dataP + offset);
         *dataPP = dataP;
         return 0;
     case sun_awt_image_IntegerComponentRaster_TYPE_BYTE_SAMPLES:
+        if (!(SAFE_TO_ALLOC_2(width, rasterP->numBands) &&
+              SAFE_TO_ALLOC_2(height, rasterP->scanlineStride)))
+        {
+            return -1;
+        }
+        offset = rasterP->chanOffsets[0];
+        dataSize = (*env)->GetArrayLength(env, rasterP->jdata);
+
+        if (offset < 0 || offset >= dataSize ||
+            width * rasterP->numBands > rasterP->scanlineStride ||
+            height * rasterP->scanlineStride > dataSize - offset)
+        {
+            // raster data buffer is too short
+            return -1;
+        }
         dataP = (void *) (*env)->GetPrimitiveArrayCritical(env, rasterP->jdata,
                                                            NULL);
         if (dataP == NULL) {
@@ -2313,11 +2344,26 @@
         *mlibImagePP = (*sMlibSysFns.createStructFP)(MLIB_BYTE, rasterP->numBands,
                                               width, height,
                                               rasterP->scanlineStride,
-                                              (unsigned char *)dataP
-                                              + rasterP->chanOffsets[0]);
+                                              (unsigned char *)dataP + offset);
         *dataPP = dataP;
         return 0;
     case sun_awt_image_IntegerComponentRaster_TYPE_USHORT_SAMPLES:
+        if (!((rasterP->chanOffsets[0] == 0 || SAFE_TO_ALLOC_2(rasterP->chanOffsets[0], 2)) &&
+              SAFE_TO_ALLOC_3(width, rasterP->numBands, 2) &&
+              SAFE_TO_ALLOC_3(height, rasterP->scanlineStride, 2)))
+        {
+              return -1;
+        }
+        offset = rasterP->chanOffsets[0] * 2;
+        dataSize = 2 * (*env)->GetArrayLength(env, rasterP->jdata);
+
+        if (offset < 0 || offset >= dataSize ||
+            width * rasterP->numBands > rasterP->scanlineStride ||
+            height * rasterP->scanlineStride * 2 > dataSize - offset)
+        {
+            // raster data buffer is too short
+             return -1;
+        }
         dataP = (void *) (*env)->GetPrimitiveArrayCritical(env, rasterP->jdata,
                                                            NULL);
         if (dataP == NULL) {
@@ -2327,8 +2373,7 @@
                                                      rasterP->numBands,
                                                      width, height,
                                                      rasterP->scanlineStride*2,
-                                                     (unsigned char *)dataP
-                                                     + rasterP->chanOffsets[0]*2);
+                                                     (unsigned char *)dataP + offset);
         *dataPP = dataP;
         return 0;
 
--- a/jdk/src/share/native/sun/awt/medialib/safe_alloc.h	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/sun/awt/medialib/safe_alloc.h	Thu Mar 25 07:12:43 2010 -0700
@@ -35,11 +35,11 @@
  */
 #define SAFE_TO_ALLOC_2(c, sz)                                             \
     (((c) > 0) && ((sz) > 0) &&                                            \
-     ((0xffffffffu / ((juint)(c))) > (sz)))
+     ((0xffffffffu / ((juint)(c))) > ((juint)(sz))))
 
 #define SAFE_TO_ALLOC_3(w, h, sz)                                          \
     (((w) > 0) && ((h) > 0) && ((sz) > 0) &&                               \
-    (((0xffffffffu / ((juint)(w))) / ((juint)(h))) > (sz)))
+     (((0xffffffffu / ((juint)(w))) / ((juint)(h))) > ((juint)(sz))))
 
 
 #endif // __SAFE_ALLOC_H__
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c	Thu Mar 25 07:12:43 2010 -0700
@@ -1433,6 +1433,9 @@
 
     // If is in memory, the LUT is already there, so throw a copy
     if (Icc -> TagPtrs[n]) {
+        if (!_cmsValidateLUT((LPLUT) Icc ->TagPtrs[n])) {
+            return NULL;
+        }
 
         return cmsDupLUT((LPLUT) Icc ->TagPtrs[n]);
     }
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c	Thu Mar 25 07:12:43 2010 -0700
@@ -1969,6 +1969,10 @@
                 goto ErrorCleanup;
         }
 
+        if (Transforms[i] == NULL) {
+            cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateMultiprofileTransform: unable to create transform");
+            goto ErrorCleanup;
+        }
         CurrentColorSpace = ColorSpaceOut;
 
     }
--- a/jdk/test/java/beans/EventHandler/Test6277246.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/java/beans/EventHandler/Test6277246.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,10 +49,10 @@
         catch (NoSuchMethodException exception) {
             throw new Error("unexpected exception", exception);
         }
+        catch (SecurityException exception) {
+            // expected security exception
+        }
         catch (RuntimeException exception) {
-            if (exception.getCause() instanceof SecurityException) {
-                return; // expected security exception
-            }
             throw new Error("unexpected exception", exception);
         }
     }
--- a/jdk/test/java/beans/EventHandler/Test6277266.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/java/beans/EventHandler/Test6277266.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,7 @@
             );
             throw new Error("SecurityException expected");
         } catch (InvocationTargetException exception) {
-            if (exception.getCause().getCause() instanceof SecurityException){
+            if (exception.getCause() instanceof SecurityException){
                 return; // expected security exception
             }
             throw new Error("unexpected exception", exception);
--- a/jdk/test/lib/security/cacerts/VerifyCACerts.java	Thu Mar 25 09:38:56 2010 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,141 +0,0 @@
-/*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- */
-
-/**
- * @test
- * @bug 4400624 6321453 6728890 6732157 6754779 6768559
- * @summary Make sure all self-signed root cert signatures are valid
- */
-import java.io.FileInputStream;
-import java.security.KeyStore;
-import java.security.MessageDigest;
-import java.security.cert.*;
-import java.util.*;
-
-public class VerifyCACerts {
-
-    private final static String cacertsFileName =
-        System.getProperty("java.home") +
-        System.getProperty("file.separator") + "lib" +
-        System.getProperty("file.separator") + "security" +
-        System.getProperty("file.separator") + "cacerts";
-
-    private static boolean atLeastOneFailed = false;
-
-    private static MessageDigest md;
-
-    // map of cert alias to SHA1 fingerprint
-    private static Map<String, String> fpMap = new HashMap<String, String>();
-
-    private static String[][] entries = {
-        { "swisssignsilverg2ca", "9B:AA:E5:9F:56:EE:21:CB:43:5A:BE:25:93:DF:A7:F0:40:D1:1D:CB"},
-        { "swisssigngoldg2ca", "D8:C5:38:8A:B7:30:1B:1B:6E:D4:7A:E6:45:25:3A:6F:9F:1A:27:61"},
-        { "swisssignplatinumg2ca", "56:E0:FA:C0:3B:8F:18:23:55:18:E5:D3:11:CA:E8:C2:43:31:AB:66"},
-        { "verisigntsaca", "BE:36:A4:56:2F:B2:EE:05:DB:B3:D3:23:23:AD:F4:45:08:4E:D6:56"},
-        { "camerfirmachambersignca", "4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C"},
-        { "camerfirmachambersca", "78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C"},
-        { "camerfirmachamberscommerceca", "6E:3A:55:A4:19:0C:19:5C:93:84:3C:C0:DB:72:2E:31:30:61:F0:B1"},
-        { "deutschetelekomrootca2", "85:A4:08:C0:9C:19:3E:5D:51:58:7D:CD:D6:13:30:FD:8C:DE:37:BF"},
-    };
-
-    static {
-        for (String[] entry : entries) {
-            fpMap.put(entry[0], entry[1]);
-        }
-    };
-
-    public static void main(String[] args) throws Exception {
-        md = MessageDigest.getInstance("SHA1");
-        KeyStore ks = KeyStore.getInstance("JKS");
-        ks.load(new FileInputStream(cacertsFileName), "changeit".toCharArray());
-
-        // check that all entries in the map are in the keystore
-        for (String alias : fpMap.keySet()) {
-            if (!ks.isCertificateEntry(alias)) {
-                atLeastOneFailed = true;
-                System.err.println(alias + " is not in cacerts");
-            }
-        }
-        // pull all the trusted self-signed CA certs out of the cacerts file
-        // and verify their signatures
-        Enumeration<String> aliases = ks.aliases();
-        while (aliases.hasMoreElements()) {
-            String alias = aliases.nextElement();
-            System.out.println("Verifying " + alias);
-            if (!ks.isCertificateEntry(alias)) {
-                atLeastOneFailed = true;
-                System.err.println(alias + " is not a trusted cert entry");
-            }
-            Certificate cert = ks.getCertificate(alias);
-            // remember the GTE CyberTrust CA cert for further tests
-            if (alias.equals("gtecybertrustca")) {
-                atLeastOneFailed = true;
-                System.err.println
-                    ("gtecybertrustca is expired and should be deleted");
-            }
-            cert.verify(cert.getPublicKey());
-            if (!checkFingerprint(alias, cert)) {
-                atLeastOneFailed = true;
-                System.err.println
-                    (alias + " SHA1 fingerprint is incorrect");
-            }
-        }
-
-        if (atLeastOneFailed) {
-            throw new Exception("At least one cacert test failed");
-        }
-    }
-
-    private static boolean checkFingerprint(String alias, Certificate cert)
-        throws Exception {
-        String fingerprint = fpMap.get(alias);
-        if (fingerprint == null) {
-            // no entry for alias
-            return true;
-        }
-        System.out.println("Checking fingerprint of " + alias);
-        byte[] digest = md.digest(cert.getEncoded());
-        return fingerprint.equals(toHexString(digest));
-    }
-
-    private static String toHexString(byte[] block) {
-        StringBuffer buf = new StringBuffer();
-        int len = block.length;
-        for (int i = 0; i < len; i++) {
-             byte2hex(block[i], buf);
-             if (i < len-1) {
-                 buf.append(":");
-             }
-        }
-        return buf.toString();
-    }
-
-    private static void byte2hex(byte b, StringBuffer buf) {
-        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
-                            '9', 'A', 'B', 'C', 'D', 'E', 'F' };
-        int high = ((b & 0xf0) >> 4);
-        int low = (b & 0x0f);
-        buf.append(hexChars[high]);
-        buf.append(hexChars[low]);
-    }
-}
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/InvalidateServerSessionRenegotiate.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/InvalidateServerSessionRenegotiate.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
  * @test
  * @bug 4403428
  * @summary Invalidating JSSE session on server causes SSLProtocolException
+ * @ignore incompatible with disabled unsafe renegotiation (6898739), please
+ *         reenable when safe renegotiation is implemented.
  * @author Brad Wetmore
  */
 
--- a/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/JSSERenegotiate.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/JSSERenegotiate.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 4280338
  * @summary "Unsupported SSL message version" SSLProtocolException
  *      w/SSL_RSA_WITH_NULL_MD5
+ * @ignore incompatible with disabled unsafe renegotiation (6898739), please
+ *         reenable when safe renegotiation is implemented.
  *
  * @author Ram Marti
  * @author Brad Wetmore
--- a/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/CheckStatus.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/CheckStatus.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
  * @test
  * @bug 4948079
  * @summary SSLEngineResult needs updating [none yet]
+ * @ignore incompatible with disabled unsafe renegotiation (6898739), please
+ *         reenable when safe renegotiation is implemented.
  *
  * This is a simple hack to test a bunch of conditions and check
  * their return codes.
--- a/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/ConnectionTest.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/ConnectionTest.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 4495742
  * @summary Add non-blocking SSL/TLS functionality, usable with any
  *      I/O abstraction
+ * @ignore incompatible with disabled unsafe renegotiation (6898739), please
+ *         reenable when safe renegotiation is implemented.
  *
  * This is a bit hacky, meant to test various conditions.  The main
  * thing I wanted to do with this was to do buffer reads/writes
--- a/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/NoAuthClientAuth.java	Thu Mar 25 09:38:56 2010 +0000
+++ b/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/NoAuthClientAuth.java	Thu Mar 25 07:12:43 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
  * @test
  * @bug 4495742
  * @summary Demonstrate SSLEngine switch from no client auth to client auth.
+ * @ignore incompatible with disabled unsafe renegotiation (6898739), please
+ *         reenable when safe renegotiation is implemented.
  *
  * @author Brad R. Wetmore
  */