changeset 16494:6efc826d3cd0

Merge
author lana
date Thu, 19 May 2016 19:46:20 +0000
parents f8a3c1510f95 e53f8c34880e
children f0c1d4d90df6
files src/java.desktop/share/native/libmlib_image/mlib_ImageColorTrue2Index.c src/java.desktop/share/native/libmlib_image/mlib_ImageColormap.h src/java.desktop/share/native/libmlib_image/mlib_ImageConv2x2_f.c src/java.desktop/share/native/libmlib_image/mlib_c_ImageAffineIndex_BC.c src/java.desktop/share/native/libmlib_image/mlib_c_ImageAffineIndex_BL.c src/java.desktop/share/native/libmlib_image/mlib_c_ImageBlendTable.c src/java.desktop/share/native/libmlib_image/mlib_c_ImageBlendTable.h src/java.desktop/share/native/libmlib_image/mlib_c_ImageThresh1.h src/java.desktop/share/native/libmlib_image/mlib_c_ImageThresh1_U8.c src/java.desktop/share/native/libmlib_image/mlib_image_blend_proto.h src/java.desktop/unix/native/libawt/awt/medialib/mlib_v_ImageCopy.c src/java.desktop/unix/native/libawt/awt/medialib/mlib_v_ImageCopy_blk.s src/java.desktop/unix/native/libawt/awt/medialib/vis_asi.h src/java.desktop/unix/native/libmlib_image/mlib_v_ImageAffineIndex_BC.c src/java.desktop/unix/native/libmlib_image/mlib_v_ImageChannelExtract.c src/java.desktop/unix/native/libmlib_image/mlib_v_ImageChannelExtract_f.c src/java.desktop/unix/native/libmlib_image/mlib_v_ImageChannelInsert.c src/java.desktop/unix/native/libmlib_image/mlib_v_ImageChannelInsert_34.c src/java.desktop/unix/native/libmlib_image/mlib_v_ImageConvIndex3_8_16nw.c src/java.desktop/unix/native/libmlib_image/mlib_v_ImageConvIndex3_8_8nw.c src/java.httpclient/share/classes/java/net/http/HttpHeaders1.java src/jdk.jcmd/share/classes/jdk/internal/vm/agent/spi/ToolProvider.java src/jdk.jcmd/share/classes/jdk/internal/vm/agent/spi/ToolProviderFinder.java src/jdk.jlink/share/classes/jdk/tools/jlink/internal/PluginContextImpl.java src/jdk.jlink/share/classes/jdk/tools/jlink/internal/PoolImpl.java src/jdk.jlink/share/classes/jdk/tools/jlink/plugin/PluginContext.java src/jdk.jlink/share/classes/jdk/tools/jlink/plugin/Pool.java src/jdk.unsupported/share/classes/sun/misc/SoftCache.java src/jdk.unsupported/unix/classes/sun/misc/GThreadHelper.java test/java/awt/dnd/Button2DragTest/Button2DragTest.html test/java/awt/print/Dialog/RestoreActiveWindowTest/RestoreActiveWindowTest.html test/javax/sound/sampled/spi/AudioFileReader/RecognizeHugeWaveFloatFiles.java test/javax/xml/bind/xjc/8032884/compile-schema.sh test/jdk/modules/scenarios/overlappingpackages/src/misc/sun/misc/Unsafe.java test/sun/tools/jinfo/JInfoHelper.java test/sun/tools/jinfo/JInfoLauncherTest.java test/sun/tools/jinfo/JInfoRunningProcessFlagTest.java test/sun/tools/jinfo/JInfoRunningProcessTest.java test/sun/tools/jinfo/JInfoSanityTest.java test/sun/tools/jmap/heapconfig/JMapHeapConfigTest.java test/sun/tools/jmap/heapconfig/TmtoolTestScenario.java test/tools/launcher/modules/patch/PatchTest.java test/tools/launcher/modules/patch/src/test/jdk/test/Main.java test/tools/launcher/modules/patch/src/test/module-info.java test/tools/launcher/modules/patch/src1/java.base/java/text/Annotation.java test/tools/launcher/modules/patch/src1/java.base/java/text/AnnotationBuddy.java test/tools/launcher/modules/patch/src1/jdk.compiler/com/sun/tools/javac/Main.java test/tools/launcher/modules/patch/src1/jdk.compiler/com/sun/tools/javac/MainBuddy.java test/tools/launcher/modules/patch/src1/jdk.naming.dns/com/sun/jndi/dns/DnsClient.java test/tools/launcher/modules/patch/src1/jdk.naming.dns/com/sun/jndi/dns/DnsClientBuddy.java test/tools/launcher/modules/patch/src2/java.base/java/lang2/Object.java test/tools/launcher/modules/patch/src2/jdk.compiler/com/sun/tools/javac2/Main.java test/tools/launcher/modules/patch/src2/jdk.naming.dns/com/sun/jndi/dns2/Zone.java
diffstat 428 files changed, 14944 insertions(+), 43824 deletions(-) [+]
line wrap: on
line diff
--- a/make/Import.gmk	Thu May 19 17:48:02 2016 +0000
+++ b/make/Import.gmk	Thu May 19 19:46:20 2016 +0000
@@ -112,7 +112,7 @@
 	$(LN) -s ../$(@F) $@
 
 ifeq ($(OPENJDK_TARGET_OS), macosx)
-  $(BASE_INSTALL_LIBRARIES_HERE)/server/%.dSYM : $(BASE_INSTALL_LIBRARIES_HERE)/%.dSYM
+  $(BASE_INSTALL_LIBRARIES_HERE)/server/%.dSYM:
 	$(MKDIR) -p $(@D)
 	$(RM) $@
 	$(LN) -s ../$(@F) $@
--- a/make/lib/Awt2dLibraries.gmk	Thu May 19 17:48:02 2016 +0000
+++ b/make/lib/Awt2dLibraries.gmk	Thu May 19 19:46:20 2016 +0000
@@ -96,10 +96,7 @@
       mlib_c_ImageAffine_BL.c \
       mlib_c_ImageAffine_BL_S16.c \
       mlib_c_ImageAffine_BL_U16.c \
-      mlib_c_ImageAffineIndex_BC.c \
-      mlib_c_ImageAffineIndex_BL.c \
       mlib_c_ImageAffine_NN.c \
-      mlib_c_ImageBlendTable.c \
       mlib_c_ImageConvClearEdge.c \
       mlib_c_ImageConvCopyEdge.c \
       mlib_c_ImageConv_f.c \
@@ -107,14 +104,6 @@
       mlib_c_ImageCopy.c \
       mlib_c_ImageLookUp.c \
       mlib_c_ImageLookUp_f.c \
-      mlib_v_ImageChannelExtract.c \
-      mlib_v_ImageChannelExtract_f.c \
-      mlib_v_ImageChannelInsert_34.c \
-      mlib_v_ImageChannelInsert.c \
-      mlib_v_ImageConvIndex3_8_16nw.c \
-      mlib_v_ImageConvIndex3_8_8nw.c \
-      mlib_v_ImageCopy.c \
-      mlib_v_ImageCopy_blk.s \
       #
 
   LIBMLIB_IMAGE_V_CFLAGS += $(filter-out -DMLIB_NO_LIBSUNMATH, $(BUILD_LIBMLIB_CFLAGS))
--- a/src/demo/share/jvmti/index.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/demo/share/jvmti/index.html	Thu May 19 19:46:20 2016 +0000
@@ -415,7 +415,7 @@
 Various technical articles are also available through this website.
 And don't forget the 
 Java Tutorials at 
-<A HREF="http://java.sun.com/docs/books/tutorial">http://java.sun.com/docs/books/tutorial</A>
+<A HREF="http://docs.oracle.com/javase/tutorial">http://docs.oracle.com/javase/tutorial</A>
 for getting a quick start on all the various interfaces.
 
 <h2>Comments and Feedback</h2>
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/Constants.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/Constants.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,9 +43,10 @@
         1.0 to 1.3.X 45,3
         1.4 to 1.4.X 46,0
         1.5 to 1.5.X 49,0
-        1.6 to 1.5.x 50,0
-        1.7 to 1.6.x 51,0
-        1.8 to 1.7.x 52,0
+        1.6 to 1.6.X 50,0
+        1.7 to 1.7.X 51,0
+        1.8 to 1.8.X 52,0
+        1.9 to 1.9.X 53,0
     */
 
     public static final Package.Version JAVA_MIN_CLASS_VERSION =
@@ -63,6 +64,9 @@
     public static final Package.Version JAVA8_MAX_CLASS_VERSION =
             Package.Version.of(52, 00);
 
+    public static final Package.Version JAVA9_MAX_CLASS_VERSION =
+            Package.Version.of(53, 00);
+
     public static final int JAVA_PACKAGE_MAGIC = 0xCAFED00D;
 
     public static final Package.Version JAVA5_PACKAGE_VERSION =
@@ -79,7 +83,7 @@
 
     // upper limit, should point to the latest class version
     public static final Package.Version JAVA_MAX_CLASS_VERSION =
-            JAVA8_MAX_CLASS_VERSION;
+            JAVA9_MAX_CLASS_VERSION;
 
     // upper limit should point to the latest package version, for version info!.
     public static final Package.Version MAX_PACKAGE_VERSION =
--- a/src/java.base/share/classes/java/io/BufferedWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/BufferedWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -153,13 +153,18 @@
      * needed.  If the requested length is at least as large as the buffer,
      * however, then this method will flush the buffer and write the characters
      * directly to the underlying stream.  Thus redundant
-     * <code>BufferedWriter</code>s will not copy data unnecessarily.
+     * {@code BufferedWriter}s will not copy data unnecessarily.
      *
      * @param  cbuf  A character array
      * @param  off   Offset from which to start reading characters
      * @param  len   Number of characters to write
      *
-     * @exception  IOException  If an I/O error occurs
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given array
+     *
+     * @throws  IOException  If an I/O error occurs
      */
     public void write(char cbuf[], int off, int len) throws IOException {
         synchronized (lock) {
@@ -195,17 +200,24 @@
     /**
      * Writes a portion of a String.
      *
-     * <p> If the value of the {@code len} parameter is negative then no
-     * characters are written.  This is contrary to the specification of this
-     * method in the {@linkplain java.io.Writer#write(java.lang.String,int,int)
-     * superclass}, which requires that an {@link IndexOutOfBoundsException} be
-     * thrown.
+     * @implSpec
+     * While the specification of this method in the
+     * {@linkplain java.io.Writer#write(java.lang.String,int,int) superclass}
+     * recommends that an {@link IndexOutOfBoundsException} be thrown
+     * if {@code len} is negative or {@code off + len} is negative,
+     * the implementation in this class does not throw such an exception in
+     * these cases but instead simply writes no characters.
      *
      * @param  s     String to be written
      * @param  off   Offset from which to start reading characters
      * @param  len   Number of characters to be written
      *
-     * @exception  IOException  If an I/O error occurs
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative,
+     *          or {@code off + len} is greater than the length
+     *          of the given string
+     *
+     * @throws  IOException  If an I/O error occurs
      */
     public void write(String s, int off, int len) throws IOException {
         synchronized (lock) {
--- a/src/java.base/share/classes/java/io/CharArrayWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/CharArrayWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -91,6 +91,11 @@
      * @param c the data to be written
      * @param off       the start offset in the data
      * @param len       the number of chars that are written
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given array
      */
     public void write(char c[], int off, int len) {
         if ((off < 0) || (off > c.length) || (len < 0) ||
@@ -114,6 +119,11 @@
      * @param  str  String to be written from
      * @param  off  Offset from which to start reading characters
      * @param  len  Number of characters to be written
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given string
      */
     public void write(String str, int off, int len) {
         synchronized (lock) {
--- a/src/java.base/share/classes/java/io/FilterWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/FilterWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,7 +72,12 @@
      * @param  off   Offset from which to start reading characters
      * @param  len   Number of characters to be written
      *
-     * @exception  IOException  If an I/O error occurs
+     * @throws  IndexOutOfBoundsException
+     *          If the values of the {@code off} and {@code len} parameters
+     *          cause the corresponding method of the underlying {@code Writer}
+     *          to throw an {@code IndexOutOfBoundsException}
+     *
+     * @throws  IOException  If an I/O error occurs
      */
     public void write(char cbuf[], int off, int len) throws IOException {
         out.write(cbuf, off, len);
@@ -85,7 +90,12 @@
      * @param  off  Offset from which to start reading characters
      * @param  len  Number of characters to be written
      *
-     * @exception  IOException  If an I/O error occurs
+     * @throws  IndexOutOfBoundsException
+     *          If the values of the {@code off} and {@code len} parameters
+     *          cause the corresponding method of the underlying {@code Writer}
+     *          to throw an {@code IndexOutOfBoundsException}
+     *
+     * @throws  IOException  If an I/O error occurs
      */
     public void write(String str, int off, int len) throws IOException {
         out.write(str, off, len);
--- a/src/java.base/share/classes/java/io/OutputStreamWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/OutputStreamWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -202,7 +202,12 @@
      * @param  off   Offset from which to start writing characters
      * @param  len   Number of characters to write
      *
-     * @exception  IOException  If an I/O error occurs
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given array
+     *
+     * @throws  IOException  If an I/O error occurs
      */
     public void write(char cbuf[], int off, int len) throws IOException {
         se.write(cbuf, off, len);
@@ -215,7 +220,12 @@
      * @param  off  Offset from which to start writing characters
      * @param  len  Number of characters to write
      *
-     * @exception  IOException  If an I/O error occurs
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given string
+     *
+     * @throws  IOException  If an I/O error occurs
      */
     public void write(String str, int off, int len) throws IOException {
         se.write(str, off, len);
--- a/src/java.base/share/classes/java/io/PipedWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/PipedWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -125,19 +125,25 @@
     }
 
     /**
-     * Writes <code>len</code> characters from the specified character array
-     * starting at offset <code>off</code> to this piped output stream.
+     * Writes {@code len} characters from the specified character array
+     * starting at offset {@code off} to this piped output stream.
      * This method blocks until all the characters are written to the output
      * stream.
      * If a thread was reading data characters from the connected piped input
      * stream, but the thread is no longer alive, then an
-     * <code>IOException</code> is thrown.
+     * {@code IOException} is thrown.
      *
      * @param      cbuf  the data.
      * @param      off   the start offset in the data.
      * @param      len   the number of characters to write.
-     * @exception  IOException  if the pipe is
-     *          <a href=PipedOutputStream.html#BROKEN> <code>broken</code></a>,
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given array
+     *
+     * @throws  IOException  if the pipe is
+     *          <a href=PipedOutputStream.html#BROKEN><code>broken</code></a>,
      *          {@link #connect(java.io.PipedReader) unconnected}, closed
      *          or an I/O error occurs.
      */
--- a/src/java.base/share/classes/java/io/PrintWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/PrintWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -410,6 +410,11 @@
      * @param buf Array of characters
      * @param off Offset from which to start writing characters
      * @param len Number of characters to write
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If the values of the {@code off} and {@code len} parameters
+     *          cause the corresponding method of the underlying {@code Writer}
+     *          to throw an {@code IndexOutOfBoundsException}
      */
     public void write(char buf[], int off, int len) {
         try {
@@ -440,6 +445,11 @@
      * @param s A String
      * @param off Offset from which to start writing characters
      * @param len Number of characters to write
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If the values of the {@code off} and {@code len} parameters
+     *          cause the corresponding method of the underlying {@code Writer}
+     *          to throw an {@code IndexOutOfBoundsException}
      */
     public void write(String s, int off, int len) {
         try {
--- a/src/java.base/share/classes/java/io/StringWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/StringWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -83,6 +83,11 @@
      * @param  cbuf  Array of characters
      * @param  off   Offset from which to start writing characters
      * @param  len   Number of characters to write
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given array
      */
     public void write(char cbuf[], int off, int len) {
         if ((off < 0) || (off > cbuf.length) || (len < 0) ||
@@ -107,6 +112,11 @@
      * @param  str  String to be written
      * @param  off  Offset from which to start writing characters
      * @param  len  Number of characters to write
+     *
+     * @throws  IndexOutOfBoundsException
+     *          If {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given string
      */
     public void write(String str, int off, int len)  {
         buf.append(str, off, off + len);
--- a/src/java.base/share/classes/java/io/Writer.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/io/Writer.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,12 +32,11 @@
  * Most subclasses, however, will override some of the methods defined here in
  * order to provide higher efficiency, additional functionality, or both.
  *
- * @see Writer
  * @see   BufferedWriter
  * @see   CharArrayWriter
  * @see   FilterWriter
  * @see   OutputStreamWriter
- * @see     FileWriter
+ * @see   FileWriter
  * @see   PipedWriter
  * @see   PrintWriter
  * @see   StringWriter
@@ -139,6 +138,12 @@
      * @param  len
      *         Number of characters to write
      *
+     * @throws  IndexOutOfBoundsException
+     *          Implementations should throw this exception
+     *          if {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
+     *          of the given array
+     *
      * @throws  IOException
      *          If an I/O error occurs
      */
@@ -160,6 +165,11 @@
     /**
      * Writes a portion of a string.
      *
+     * @implSpec
+     * The implementation in this class throws an
+     * {@code IndexOutOfBoundsException} for the indicated conditions;
+     * overriding methods may choose to do otherwise.
+     *
      * @param  str
      *         A String
      *
@@ -170,8 +180,9 @@
      *         Number of characters to write
      *
      * @throws  IndexOutOfBoundsException
-     *          If {@code off} is negative, or {@code len} is negative,
-     *          or {@code off+len} is negative or greater than the length
+     *          Implementations should throw this exception
+     *          if {@code off} is negative, or {@code len} is negative,
+     *          or {@code off + len} is negative or greater than the length
      *          of the given string
      *
      * @throws  IOException
--- a/src/java.base/share/classes/java/lang/Thread.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/Thread.java	Thu May 19 19:46:20 2016 +0000
@@ -341,6 +341,45 @@
     }
 
     /**
+     * Indicates that the caller is momentarily unable to progress, until the
+     * occurrence of one or more actions on the part of other activities. By
+     * invoking this method within each iteration of a spin-wait loop construct,
+     * the calling thread indicates to the runtime that it is busy-waiting.
+     * The runtime may take action to improve the performance of invoking
+     * spin-wait loop constructions.
+     * <p>
+     * @apiNote
+     * As an example consider a method in a class that spins in a loop until
+     * some flag is set outside of that method. A call to the {@code onSpinWait}
+     * method should be placed inside the spin loop.
+     * <pre>{@code
+     *     class EventHandler {
+     *         volatile boolean eventNotificationNotReceived;
+     *         void waitForEventAndHandleIt() {
+     *             while ( eventNotificationNotReceived ) {
+     *                 java.lang.Thread.onSpinWait();
+     *             }
+     *             readAndProcessEvent();
+     *         }
+     *
+     *         void readAndProcessEvent() {
+     *             // Read event from some source and process it
+     *              . . .
+     *         }
+     *     }
+     * }</pre>
+     * <p>
+     * The code above would remain correct even if the {@code onSpinWait}
+     * method was not called at all. However on some architectures the Java
+     * Virtual Machine may issue the processor instructions to address such
+     * code patterns in a more beneficial way.
+     * <p>
+     * @since 9
+     */
+    @HotSpotIntrinsicCandidate
+    public static void onSpinWait() {}
+
+    /**
      * Initializes a Thread with the current AccessControlContext.
      * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext,boolean)
      */
--- a/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Thu May 19 19:46:20 2016 +0000
@@ -706,6 +706,9 @@
                 case ARRAY_STORE:
                     emitArrayStore(name);
                     continue;
+                case ARRAY_LENGTH:
+                    emitArrayLength(name);
+                    continue;
                 case IDENTITY:
                     assert(name.arguments.length == 1);
                     emitPushArguments(name);
@@ -740,15 +743,16 @@
         return classFile;
     }
 
-    void emitArrayLoad(Name name)  { emitArrayOp(name, Opcodes.AALOAD);  }
-    void emitArrayStore(Name name) { emitArrayOp(name, Opcodes.AASTORE); }
+    void emitArrayLoad(Name name)   { emitArrayOp(name, Opcodes.AALOAD);      }
+    void emitArrayStore(Name name)  { emitArrayOp(name, Opcodes.AASTORE);     }
+    void emitArrayLength(Name name) { emitArrayOp(name, Opcodes.ARRAYLENGTH); }
 
     void emitArrayOp(Name name, int arrayOpcode) {
-        assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE;
+        assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
         assert elementType != null;
         emitPushArguments(name);
-        if (elementType.isPrimitive()) {
+        if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
             Wrapper w = Wrapper.forPrimitiveType(elementType);
             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
         }
--- a/src/java.base/share/classes/java/lang/invoke/Invokers.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/Invokers.java	Thu May 19 19:46:20 2016 +0000
@@ -95,12 +95,12 @@
 
     /*non-public*/ MethodHandle varHandleMethodInvoker(VarHandle.AccessMode ak) {
         // TODO cache invoker
-        return makeVarHandleMethodInvoker(ak);
+        return makeVarHandleMethodInvoker(ak, false);
     }
 
     /*non-public*/ MethodHandle varHandleMethodExactInvoker(VarHandle.AccessMode ak) {
         // TODO cache invoker
-        return makeVarHandleMethodExactInvoker(ak);
+        return makeVarHandleMethodInvoker(ak, true);
     }
 
     private MethodHandle cachedInvoker(int idx) {
@@ -127,26 +127,11 @@
         return invoker;
     }
 
-    private MethodHandle makeVarHandleMethodInvoker(VarHandle.AccessMode ak) {
+    private MethodHandle makeVarHandleMethodInvoker(VarHandle.AccessMode ak, boolean isExact) {
         MethodType mtype = targetType;
         MethodType invokerType = mtype.insertParameterTypes(0, VarHandle.class);
 
-        LambdaForm lform = varHandleMethodGenericInvokerHandleForm(ak.methodName(), mtype);
-        VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
-        MethodHandle invoker = BoundMethodHandle.bindSingle(invokerType, lform, ad);
-
-        invoker = invoker.withInternalMemberName(MemberName.makeVarHandleMethodInvoke(ak.methodName(), mtype), false);
-        assert(checkVarHandleInvoker(invoker));
-
-        maybeCompileToBytecode(invoker);
-        return invoker;
-    }
-
-    private MethodHandle makeVarHandleMethodExactInvoker(VarHandle.AccessMode ak) {
-        MethodType mtype = targetType;
-        MethodType invokerType = mtype.insertParameterTypes(0, VarHandle.class);
-
-        LambdaForm lform = varHandleMethodExactInvokerHandleForm(ak.methodName(), mtype);
+        LambdaForm lform = varHandleMethodInvokerHandleForm(ak.methodName(), mtype, isExact);
         VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
         MethodHandle invoker = BoundMethodHandle.bindSingle(invokerType, lform, ad);
 
@@ -400,59 +385,7 @@
         return lform;
     }
 
-    private static LambdaForm varHandleMethodExactInvokerHandleForm(String name, MethodType mtype) {
-        // TODO Cache form?
-
-        final int THIS_MH      = 0;
-        final int CALL_VH      = THIS_MH + 1;
-        final int ARG_BASE     = CALL_VH + 1;
-        final int ARG_LIMIT = ARG_BASE + mtype.parameterCount();
-        int nameCursor = ARG_LIMIT;
-        final int VAD_ARG      = nameCursor++;
-        final int CHECK_TYPE   = nameCursor++;
-        final int GET_MEMBER   = nameCursor++;
-        final int LINKER_CALL  = nameCursor++;
-
-        MethodType invokerFormType = mtype.insertParameterTypes(0, VarHandle.class)
-                .basicType()
-                .appendParameterTypes(MemberName.class);
-
-        MemberName linker = new MemberName(MethodHandle.class, "linkToStatic", invokerFormType, REF_invokeStatic);
-        try {
-            linker = MemberName.getFactory().resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class);
-        } catch (ReflectiveOperationException ex) {
-            throw newInternalError(ex);
-        }
-
-        Name[] names = new Name[LINKER_CALL + 1];
-        names[THIS_MH] = argument(THIS_MH, BasicType.basicType(Object.class));
-        names[CALL_VH] = argument(CALL_VH, BasicType.basicType(Object.class));
-        for (int i = 0; i < mtype.parameterCount(); i++) {
-            names[ARG_BASE + i] = argument(ARG_BASE + i, BasicType.basicType(mtype.parameterType(i)));
-        }
-
-        BoundMethodHandle.SpeciesData speciesData = BoundMethodHandle.speciesData_L();
-        names[THIS_MH] = names[THIS_MH].withConstraint(speciesData);
-
-        NamedFunction getter = speciesData.getterFunction(0);
-        names[VAD_ARG] = new Name(getter, names[THIS_MH]);
-
-        Object[] outArgs = Arrays.copyOfRange(names, CALL_VH, ARG_LIMIT + 1, Object[].class);
-
-        names[CHECK_TYPE] = new Name(NF_checkVarHandleExactType, names[CALL_VH], names[VAD_ARG]);
-
-        names[GET_MEMBER] = new Name(NF_getVarHandleMemberName, names[CALL_VH], names[VAD_ARG]);
-        outArgs[outArgs.length - 1] = names[GET_MEMBER];
-
-        names[LINKER_CALL] = new Name(linker, outArgs);
-        LambdaForm lform = new LambdaForm(name + ":VarHandle_exactInvoker" + shortenSignature(basicTypeSignature(mtype)),
-                                          ARG_LIMIT, names);
-
-        lform.compileToBytecode();
-        return lform;
-    }
-
-    private static LambdaForm varHandleMethodGenericInvokerHandleForm(String name, MethodType mtype) {
+    private static LambdaForm varHandleMethodInvokerHandleForm(String name, MethodType mtype, boolean isExact) {
         // TODO Cache form?
 
         final int THIS_MH      = 0;
@@ -477,8 +410,11 @@
         NamedFunction getter = speciesData.getterFunction(0);
         names[VAD_ARG] = new Name(getter, names[THIS_MH]);
 
-        names[CHECK_TYPE] = new Name(NF_checkVarHandleGenericType, names[CALL_VH], names[VAD_ARG]);
-
+        if (isExact) {
+            names[CHECK_TYPE] = new Name(NF_checkVarHandleExactType, names[CALL_VH], names[VAD_ARG]);
+        } else {
+            names[CHECK_TYPE] = new Name(NF_checkVarHandleGenericType, names[CALL_VH], names[VAD_ARG]);
+        }
         Object[] outArgs = new Object[ARG_LIMIT];
         outArgs[0] = names[CHECK_TYPE];
         for (int i = 1; i < ARG_LIMIT; i++) {
@@ -488,7 +424,8 @@
         MethodType outCallType = mtype.insertParameterTypes(0, VarHandle.class)
                 .basicType();
         names[LINKER_CALL] = new Name(outCallType, outArgs);
-        LambdaForm lform = new LambdaForm(name + ":VarHandle_invoker" + shortenSignature(basicTypeSignature(mtype)),
+        String debugName = isExact ? ":VarHandle_exactInvoker" : ":VarHandle_invoker";
+        LambdaForm lform = new LambdaForm(name + debugName + shortenSignature(basicTypeSignature(mtype)),
                                           ARG_LIMIT, names);
 
         lform.prepare();
@@ -511,21 +448,13 @@
 
     /*non-public*/ static
     @ForceInline
-    void checkVarHandleExactType(VarHandle handle, VarHandle.AccessDescriptor ad) {
-        MethodType erasedTarget = handle.vform.methodType_table[ad.type];
-        MethodType erasedSymbolic = ad.symbolicMethodTypeErased;
-        if (erasedTarget != erasedSymbolic)
-            throw newWrongMethodTypeException(erasedTarget, erasedSymbolic);
-    }
-
-    /*non-public*/ static
-    @ForceInline
-    MemberName getVarHandleMemberName(VarHandle handle, VarHandle.AccessDescriptor ad) {
-        MemberName mn = handle.vform.memberName_table[ad.mode];
-        if (mn == null) {
-            throw handle.unsupported();
+    MethodHandle checkVarHandleExactType(VarHandle handle, VarHandle.AccessDescriptor ad) {
+        MethodHandle mh = handle.getMethodHandle(ad.mode);
+        MethodType mt = mh.type();
+        if (mt != ad.symbolicMethodTypeInvoker) {
+            throw newWrongMethodTypeException(mt, ad.symbolicMethodTypeInvoker);
         }
-        return mn;
+        return mh;
     }
 
     /*non-public*/ static
@@ -649,8 +578,7 @@
         NF_getCallSiteTarget,
         NF_checkCustomized,
         NF_checkVarHandleGenericType,
-        NF_checkVarHandleExactType,
-        NF_getVarHandleMemberName;
+        NF_checkVarHandleExactType;
     static {
         try {
             NamedFunction nfs[] = {
@@ -666,8 +594,6 @@
                         .getDeclaredMethod("checkVarHandleGenericType", VarHandle.class, VarHandle.AccessDescriptor.class)),
                 NF_checkVarHandleExactType = new NamedFunction(Invokers.class
                         .getDeclaredMethod("checkVarHandleExactType", VarHandle.class, VarHandle.AccessDescriptor.class)),
-                NF_getVarHandleMemberName = new NamedFunction(Invokers.class
-                        .getDeclaredMethod("getVarHandleMemberName", VarHandle.class, VarHandle.AccessDescriptor.class))
             };
             // Each nf must be statically invocable or we get tied up in our bootstraps.
             assert(InvokerBytecodeGenerator.isStaticallyInvocable(nfs));
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Thu May 19 19:46:20 2016 +0000
@@ -41,9 +41,15 @@
 import sun.invoke.util.ValueConversions;
 import sun.invoke.util.VerifyType;
 import sun.invoke.util.Wrapper;
+
+import jdk.internal.org.objectweb.asm.AnnotationVisitor;
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.MethodVisitor;
+
 import static java.lang.invoke.LambdaForm.*;
 import static java.lang.invoke.MethodHandleStatics.*;
 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
+import static jdk.internal.org.objectweb.asm.Opcodes.*;
 
 /**
  * Trusted implementation code for MethodHandle.
@@ -66,25 +72,28 @@
 
     /// Factory methods to create method handles:
 
-    static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) {
-        if (arrayClass == Object[].class)
-            return (isSetter ? ArrayAccessor.OBJECT_ARRAY_SETTER : ArrayAccessor.OBJECT_ARRAY_GETTER);
+    static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, ArrayAccess access) {
+        if (arrayClass == Object[].class) {
+            return ArrayAccess.objectAccessor(access);
+        }
         if (!arrayClass.isArray())
             throw newIllegalArgumentException("not an array: "+arrayClass);
         MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass);
-        int cacheIndex = (isSetter ? ArrayAccessor.SETTER_INDEX : ArrayAccessor.GETTER_INDEX);
+        int cacheIndex = ArrayAccess.cacheIndex(access);
         MethodHandle mh = cache[cacheIndex];
         if (mh != null)  return mh;
-        mh = ArrayAccessor.getAccessor(arrayClass, isSetter);
-        MethodType correctType = ArrayAccessor.correctType(arrayClass, isSetter);
+        mh = ArrayAccessor.getAccessor(arrayClass, access);
+        MethodType correctType = ArrayAccessor.correctType(arrayClass, access);
         if (mh.type() != correctType) {
             assert(mh.type().parameterType(0) == Object[].class);
-            assert((isSetter ? mh.type().parameterType(2) : mh.type().returnType()) == Object.class);
-            assert(isSetter || correctType.parameterType(0).getComponentType() == correctType.returnType());
+            /* if access == SET */ assert(access != ArrayAccess.SET || mh.type().parameterType(2) == Object.class);
+            /* if access == GET */ assert(access != ArrayAccess.GET ||
+                    (mh.type().returnType() == Object.class &&
+                     correctType.parameterType(0).getComponentType() == correctType.returnType()));
             // safe to view non-strictly, because element type follows from array type
             mh = mh.viewAsType(correctType, false);
         }
-        mh = makeIntrinsic(mh, (isSetter ? Intrinsic.ARRAY_STORE : Intrinsic.ARRAY_LOAD));
+        mh = makeIntrinsic(mh, ArrayAccess.intrinsic(access));
         // Atomically update accessor cache.
         synchronized(cache) {
             if (cache[cacheIndex] == null) {
@@ -97,9 +106,52 @@
         return mh;
     }
 
+    enum ArrayAccess {
+        GET, SET, LENGTH;
+
+        // As ArrayAccess and ArrayAccessor have a circular dependency, the ArrayAccess properties cannot be stored in
+        // final fields.
+
+        static String opName(ArrayAccess a) {
+            switch (a) {
+                case GET: return "getElement";
+                case SET: return "setElement";
+                case LENGTH: return "length";
+            }
+            throw new AssertionError();
+        }
+
+        static MethodHandle objectAccessor(ArrayAccess a) {
+            switch (a) {
+                case GET: return ArrayAccessor.OBJECT_ARRAY_GETTER;
+                case SET: return ArrayAccessor.OBJECT_ARRAY_SETTER;
+                case LENGTH: return ArrayAccessor.OBJECT_ARRAY_LENGTH;
+            }
+            throw new AssertionError();
+        }
+
+        static int cacheIndex(ArrayAccess a) {
+            switch (a) {
+                case GET: return ArrayAccessor.GETTER_INDEX;
+                case SET: return ArrayAccessor.SETTER_INDEX;
+                case LENGTH: return ArrayAccessor.LENGTH_INDEX;
+            }
+            throw new AssertionError();
+        }
+
+        static Intrinsic intrinsic(ArrayAccess a) {
+            switch (a) {
+                case GET: return Intrinsic.ARRAY_LOAD;
+                case SET: return Intrinsic.ARRAY_STORE;
+                case LENGTH: return Intrinsic.ARRAY_LENGTH;
+            }
+            throw new AssertionError();
+        }
+    }
+
     static final class ArrayAccessor {
-        /// Support for array element access
-        static final int GETTER_INDEX = 0, SETTER_INDEX = 1, INDEX_LIMIT = 2;
+        /// Support for array element and length access
+        static final int GETTER_INDEX = 0, SETTER_INDEX = 1, LENGTH_INDEX = 2, INDEX_LIMIT = 3;
         static final ClassValue<MethodHandle[]> TYPED_ACCESSORS
                 = new ClassValue<MethodHandle[]>() {
                     @Override
@@ -107,14 +159,16 @@
                         return new MethodHandle[INDEX_LIMIT];
                     }
                 };
-        static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER;
+        static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER, OBJECT_ARRAY_LENGTH;
         static {
             MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class);
-            cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, false), Intrinsic.ARRAY_LOAD);
-            cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, true),  Intrinsic.ARRAY_STORE);
+            cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.GET),    Intrinsic.ARRAY_LOAD);
+            cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.SET),    Intrinsic.ARRAY_STORE);
+            cache[LENGTH_INDEX] = OBJECT_ARRAY_LENGTH = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.LENGTH), Intrinsic.ARRAY_LENGTH);
 
             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName()));
             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName()));
+            assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_LENGTH.internalMemberName()));
         }
 
         static int     getElementI(int[]     a, int i)            { return              a[i]; }
@@ -137,31 +191,47 @@
         static void    setElementC(char[]    a, int i, char    x) {              a[i] = x; }
         static void    setElementL(Object[]  a, int i, Object  x) {              a[i] = x; }
 
-        static String name(Class<?> arrayClass, boolean isSetter) {
+        static int     lengthI(int[]     a)                       { return a.length; }
+        static int     lengthJ(long[]    a)                       { return a.length; }
+        static int     lengthF(float[]   a)                       { return a.length; }
+        static int     lengthD(double[]  a)                       { return a.length; }
+        static int     lengthZ(boolean[] a)                       { return a.length; }
+        static int     lengthB(byte[]    a)                       { return a.length; }
+        static int     lengthS(short[]   a)                       { return a.length; }
+        static int     lengthC(char[]    a)                       { return a.length; }
+        static int     lengthL(Object[]  a)                       { return a.length; }
+
+        static String name(Class<?> arrayClass, ArrayAccess access) {
             Class<?> elemClass = arrayClass.getComponentType();
             if (elemClass == null)  throw newIllegalArgumentException("not an array", arrayClass);
-            return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(elemClass);
+            return ArrayAccess.opName(access) + Wrapper.basicTypeChar(elemClass);
         }
-        static MethodType type(Class<?> arrayClass, boolean isSetter) {
+        static MethodType type(Class<?> arrayClass, ArrayAccess access) {
             Class<?> elemClass = arrayClass.getComponentType();
             Class<?> arrayArgClass = arrayClass;
             if (!elemClass.isPrimitive()) {
                 arrayArgClass = Object[].class;
                 elemClass = Object.class;
             }
-            return !isSetter ?
-                    MethodType.methodType(elemClass,  arrayArgClass, int.class) :
-                    MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
+            switch (access) {
+                case GET:    return MethodType.methodType(elemClass,  arrayArgClass, int.class);
+                case SET:    return MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
+                case LENGTH: return MethodType.methodType(int.class,  arrayArgClass);
+            }
+            throw new IllegalStateException("should not reach here");
         }
-        static MethodType correctType(Class<?> arrayClass, boolean isSetter) {
+        static MethodType correctType(Class<?> arrayClass, ArrayAccess access) {
             Class<?> elemClass = arrayClass.getComponentType();
-            return !isSetter ?
-                    MethodType.methodType(elemClass,  arrayClass, int.class) :
-                    MethodType.methodType(void.class, arrayClass, int.class, elemClass);
+            switch (access) {
+                case GET:    return MethodType.methodType(elemClass,  arrayClass, int.class);
+                case SET:    return MethodType.methodType(void.class, arrayClass, int.class, elemClass);
+                case LENGTH: return MethodType.methodType(int.class,  arrayClass);
+            }
+            throw new IllegalStateException("should not reach here");
         }
-        static MethodHandle getAccessor(Class<?> arrayClass, boolean isSetter) {
-            String     name = name(arrayClass, isSetter);
-            MethodType type = type(arrayClass, isSetter);
+        static MethodHandle getAccessor(Class<?> arrayClass, ArrayAccess access) {
+            String     name = name(arrayClass, access);
+            MethodType type = type(arrayClass, access);
             try {
                 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type);
             } catch (ReflectiveOperationException ex) {
@@ -1091,6 +1161,8 @@
     // Put the whole mess into its own nested class.
     // That way we can lazily load the code and set up the constants.
     private static class BindCaller {
+        private static MethodType INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
+
         static
         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
             // Do not use this function to inject calls into system classes.
@@ -1109,38 +1181,15 @@
         }
 
         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
-            Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
-            if (hostClass.getClassLoader() != bcc.getClassLoader())
-                throw new InternalError(hostClass.getName()+" (CL)");
             try {
-                if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
-                    throw new InternalError(hostClass.getName()+" (PD)");
-            } catch (SecurityException ex) {
-                // Self-check was blocked by security manager.  This is OK.
-                // In fact the whole try body could be turned into an assertion.
-            }
-            try {
-                MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
-                init.invokeExact();  // force initialization of the class
-            } catch (Throwable ex) {
-                throw uncaughtException(ex);
-            }
-            MethodHandle bccInvoker;
-            try {
-                MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
-                bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
+                Class<?> invokerClass = UNSAFE.defineAnonymousClass(hostClass, INJECTED_INVOKER_TEMPLATE, null);
+                assert checkInjectedInvoker(hostClass, invokerClass);
+                return IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT);
             } catch (ReflectiveOperationException ex) {
                 throw uncaughtException(ex);
             }
-            // Test the invoker, to ensure that it really injects into the right place.
-            try {
-                MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
-                Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
-            } catch (Throwable ex) {
-                throw new InternalError(ex);
-            }
-            return bccInvoker;
         }
+
         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
             @Override protected MethodHandle computeValue(Class<?> hostClass) {
                 return makeInjectedInvoker(hostClass);
@@ -1171,62 +1220,82 @@
             return mh;
         }
 
+        private static boolean checkInjectedInvoker(Class<?> hostClass, Class<?> invokerClass) {
+            assert (hostClass.getClassLoader() == invokerClass.getClassLoader()) : hostClass.getName()+" (CL)";
+            try {
+                assert (hostClass.getProtectionDomain() == invokerClass.getProtectionDomain()) : hostClass.getName()+" (PD)";
+            } catch (SecurityException ex) {
+                // Self-check was blocked by security manager. This is OK.
+            }
+            try {
+                // Test the invoker to ensure that it really injects into the right place.
+                MethodHandle invoker = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT);
+                MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
+                return (boolean)invoker.invoke(vamh, new Object[]{ invokerClass });
+            } catch (Throwable ex) {
+                throw new InternalError(ex);
+            }
+        }
+
         private static final MethodHandle MH_checkCallerClass;
         static {
             final Class<?> THIS_CLASS = BindCaller.class;
-            assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
+            assert(checkCallerClass(THIS_CLASS));
             try {
                 MH_checkCallerClass = IMPL_LOOKUP
                     .findStatic(THIS_CLASS, "checkCallerClass",
-                                MethodType.methodType(boolean.class, Class.class, Class.class));
-                assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
+                                MethodType.methodType(boolean.class, Class.class));
+                assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS));
             } catch (Throwable ex) {
                 throw new InternalError(ex);
             }
         }
 
         @CallerSensitive
-        private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
-            // This method is called via MH_checkCallerClass and so it's
-            // correct to ask for the immediate caller here.
+        private static boolean checkCallerClass(Class<?> expected) {
+            // This method is called via MH_checkCallerClass and so it's correct to ask for the immediate caller here.
             Class<?> actual = Reflection.getCallerClass();
-            if (actual != expected && actual != expected2)
-                throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
-                                        +(expected == expected2 ? "" : ", or else "+expected2.getName()));
+            if (actual != expected)
+                throw new InternalError("found " + actual.getName() + ", expected " + expected.getName());
             return true;
         }
 
-        private static final byte[] T_BYTES;
-        static {
-            final Object[] values = {null};
-            AccessController.doPrivileged(new PrivilegedAction<>() {
-                    public Void run() {
-                        try {
-                            Class<T> tClass = T.class;
-                            String tName = tClass.getName();
-                            String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
-                            try (java.io.InputStream in = tClass.getResourceAsStream(tResource)) {
-                                values[0] = in.readAllBytes();
-                            }
-                        } catch (java.io.IOException ex) {
-                            throw new InternalError(ex);
-                        }
-                        return null;
-                    }
-                });
-            T_BYTES = (byte[]) values[0];
-        }
+        private static final byte[] INJECTED_INVOKER_TEMPLATE = generateInvokerTemplate();
 
-        // The following class is used as a template for Unsafe.defineAnonymousClass:
-        private static class T {
-            static void init() { }  // side effect: initializes this class
-            static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
-                return vamh.invokeExact(args);
-            }
+        /** Produces byte code for a class that is used as an injected invoker. */
+        private static byte[] generateInvokerTemplate() {
+            ClassWriter cw = new ClassWriter(0);
+
+            // private static class InjectedInvoker {
+            //     @Hidden
+            //     static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
+            //        return vamh.invokeExact(args);
+            //     }
+            // }
+            cw.visit(52, ACC_PRIVATE | ACC_SUPER, "InjectedInvoker", null, "java/lang/Object", null);
+
+            MethodVisitor mv = cw.visitMethod(ACC_STATIC, "invoke_V",
+                          "(Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;",
+                          null, null);
+
+            // Suppress invoker method in stack traces.
+            AnnotationVisitor av0 = mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
+            av0.visitEnd();
+
+            mv.visitCode();
+            mv.visitVarInsn(ALOAD, 0);
+            mv.visitVarInsn(ALOAD, 1);
+            mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeExact",
+                               "([Ljava/lang/Object;)Ljava/lang/Object;", false);
+            mv.visitInsn(ARETURN);
+            mv.visitMaxs(2, 2);
+            mv.visitEnd();
+
+            cw.visitEnd();
+            return cw.toByteArray();
         }
     }
 
-
     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
     private static final class WrappedMember extends DelegatingMethodHandle {
         private final MethodHandle target;
@@ -1282,6 +1351,7 @@
         NEW_ARRAY,
         ARRAY_LOAD,
         ARRAY_STORE,
+        ARRAY_LENGTH,
         IDENTITY,
         ZERO,
         NONE // no intrinsic associated
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Thu May 19 19:46:20 2016 +0000
@@ -2245,6 +2245,20 @@
     }
 
     /**
+     * Produces a method handle returning the length of an array.
+     * The type of the method handle will have {@code int} as return type,
+     * and its sole argument will be the array type.
+     * @param arrayClass an array type
+     * @return a method handle which can retrieve the length of an array of the given array type
+     * @throws NullPointerException if the argument is {@code null}
+     * @throws IllegalArgumentException if arrayClass is not an array type
+     */
+    public static
+    MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
+        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
+    }
+
+    /**
      * Produces a method handle giving read access to elements of an array.
      * The type of the method handle will have a return type of the array's
      * element type.  Its first argument will be the array type,
@@ -2256,7 +2270,7 @@
      */
     public static
     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
-        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
+        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
     }
 
     /**
@@ -2271,7 +2285,7 @@
      */
     public static
     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
-        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
+        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
     }
 
     /**
--- a/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java	Thu May 19 19:46:20 2016 +0000
@@ -128,7 +128,7 @@
     /**
      * Default strategy to use for concatenation.
      */
-    private static final Strategy DEFAULT_STRATEGY = Strategy.BC_SB;
+    private static final Strategy DEFAULT_STRATEGY = Strategy.MH_INLINE_SIZED_EXACT;
 
     private enum Strategy {
         /**
--- a/src/java.base/share/classes/java/lang/invoke/VarHandle.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/VarHandle.java	Thu May 19 19:46:20 2016 +0000
@@ -26,6 +26,7 @@
 package java.lang.invoke;
 
 import jdk.internal.HotSpotIntrinsicCandidate;
+import jdk.internal.util.Preconditions;
 import jdk.internal.vm.annotation.ForceInline;
 import jdk.internal.vm.annotation.Stable;
 
@@ -33,7 +34,6 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
 import java.util.function.BiFunction;
 import java.util.function.Function;
 
@@ -1475,11 +1475,11 @@
         TypesAndInvokers tis = getTypesAndInvokers();
         MethodHandle mh = tis.methodHandle_table[mode];
         if (mh == null) {
-            mh = tis.methodHandle_table[mode] = getMethodHandleUncached(tis, mode);
+            mh = tis.methodHandle_table[mode] = getMethodHandleUncached(mode);
         }
         return mh;
     }
-    private final MethodHandle getMethodHandleUncached(TypesAndInvokers tis, int mode) {
+    private final MethodHandle getMethodHandleUncached(int mode) {
         MethodType mt = accessModeType(AccessMode.values()[mode]).
                 insertParameterTypes(0, VarHandle.class);
         MemberName mn = vform.getMemberName(mode);
@@ -1501,7 +1501,7 @@
     }
 
     static final BiFunction<String, List<Integer>, ArrayIndexOutOfBoundsException>
-            AIOOBE_SUPPLIER = Objects.outOfBoundsExceptionFormatter(
+            AIOOBE_SUPPLIER = Preconditions.outOfBoundsExceptionFormatter(
             new Function<String, ArrayIndexOutOfBoundsException>() {
                 @Override
                 public ArrayIndexOutOfBoundsException apply(String s) {
--- a/src/java.base/share/classes/java/lang/invoke/X-VarHandle.java.template	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/X-VarHandle.java.template	Thu May 19 19:46:20 2016 +0000
@@ -24,8 +24,10 @@
  */
 package java.lang.invoke;
 
+import jdk.internal.util.Preconditions;
+import jdk.internal.vm.annotation.ForceInline;
+
 import java.util.Objects;
-import jdk.internal.vm.annotation.ForceInline;
 
 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
 
@@ -163,8 +165,7 @@
 
         @ForceInline
         static boolean weakCompareAndSetVolatile(FieldInstanceReadWrite handle, Object holder, $type$ expected, $type$ value) {
-            // TODO defer to strong form until new Unsafe method is added
-            return UNSAFE.compareAndSwap$Type$(Objects.requireNonNull(handle.receiverType.cast(holder)),
+            return UNSAFE.weakCompareAndSwap$Type$Volatile(Objects.requireNonNull(handle.receiverType.cast(holder)),
                                                handle.fieldOffset,
                                                {#if[Object]?handle.fieldType.cast(expected):expected},
                                                {#if[Object]?handle.fieldType.cast(value):value});
@@ -345,8 +346,7 @@
 
         @ForceInline
         static boolean weakCompareAndSetVolatile(FieldStaticReadWrite handle, $type$ expected, $type$ value) {
-            // TODO defer to strong form until new Unsafe method is added
-            return UNSAFE.compareAndSwap$Type$(handle.base,
+            return UNSAFE.weakCompareAndSwap$Type$Volatile(handle.base,
                                                handle.fieldOffset,
                                                {#if[Object]?handle.fieldType.cast(expected):expected},
                                                {#if[Object]?handle.fieldType.cast(value):value});
@@ -447,7 +447,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.get$Type$Volatile(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase);
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase);
         }
 
         @ForceInline
@@ -458,7 +458,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             UNSAFE.put$Type$Volatile(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(value):value});
         }
 
@@ -470,7 +470,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.get$Type$Opaque(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase);
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase);
         }
 
         @ForceInline
@@ -481,7 +481,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             UNSAFE.put$Type$Opaque(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(value):value});
         }
 
@@ -493,7 +493,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.get$Type$Acquire(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase);
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase);
         }
 
         @ForceInline
@@ -504,7 +504,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             UNSAFE.put$Type$Release(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(value):value});
         }
 #if[CAS]
@@ -517,7 +517,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.compareAndSwap$Type$(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -530,7 +530,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.compareAndExchange$Type$Volatile(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -543,7 +543,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.compareAndExchange$Type$Acquire(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -556,7 +556,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.compareAndExchange$Type$Release(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -569,7 +569,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.weakCompareAndSwap$Type$(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -581,9 +581,8 @@
 #else[Object]
             $type$[] array = ($type$[]) oarray;
 #end[Object]
-            // TODO defer to strong form until new Unsafe method is added
-            return UNSAFE.compareAndSwap$Type$(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+            return UNSAFE.weakCompareAndSwap$Type$Volatile(array,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -596,7 +595,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.weakCompareAndSwap$Type$Acquire(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -609,7 +608,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.weakCompareAndSwap$Type$Release(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(expected):expected},
                     {#if[Object]?handle.componentType.cast(value):value});
         }
@@ -622,7 +621,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.getAndSet$Type$(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     {#if[Object]?handle.componentType.cast(value):value});
         }
 #end[CAS]
@@ -636,7 +635,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.getAndAdd$Type$(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     value);
         }
 
@@ -648,7 +647,7 @@
             $type$[] array = ($type$[]) oarray;
 #end[Object]
             return UNSAFE.getAndAdd$Type$(array,
-                    (((long) Objects.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
+                    (((long) Preconditions.checkIndex(index, array.length, AIOOBE_SUPPLIER)) << handle.ashift) + handle.abase,
                     value) + value;
         }
 #end[AtomicAdd]
--- a/src/java.base/share/classes/java/lang/invoke/X-VarHandleByteArrayView.java.template	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/invoke/X-VarHandleByteArrayView.java.template	Thu May 19 19:46:20 2016 +0000
@@ -25,6 +25,7 @@
 package java.lang.invoke;
 
 import jdk.internal.misc.Unsafe;
+import jdk.internal.util.Preconditions;
 import jdk.internal.vm.annotation.ForceInline;
 
 import java.nio.ByteBuffer;
@@ -81,7 +82,7 @@
 
         @ForceInline
         static int index(byte[] ba, int index) {
-            return Objects.checkIndex(index, ba.length - ALIGN, null);
+            return Preconditions.checkIndex(index, ba.length - ALIGN, null);
         }
 
         @ForceInline
@@ -233,8 +234,7 @@
         @ForceInline
         static boolean weakCompareAndSetVolatile(ArrayHandle handle, Object oba, int index, $type$ expected, $type$ value) {
             byte[] ba = (byte[]) oba;
-            // TODO defer to strong form until new Unsafe method is added
-            return UNSAFE.compareAndSwap$RawType$(
+            return UNSAFE.weakCompareAndSwap$RawType$Volatile(
                     ba,
                     address(ba, index(ba, index)),
                     convEndian(handle.be, expected), convEndian(handle.be, value));
@@ -271,22 +271,33 @@
 #if[AtomicAdd]
 
         @ForceInline
-        static $type$ getAndAdd(ArrayHandle handle, Object oba, int index, $type$ value) {
+        static $type$ getAndAdd(ArrayHandle handle, Object oba, int index, $type$ delta) {
             byte[] ba = (byte[]) oba;
-            return convEndian(handle.be,
-                              UNSAFE.getAndAdd$RawType$(
-                                      ba,
-                                      address(ba, index(ba, index)),
-                                      convEndian(handle.be, value)));
+            if (handle.be == BE) {
+                return UNSAFE.getAndAdd$RawType$(
+                        ba,
+                        address(ba, index(ba, index)),
+                        delta);
+            } else {
+                return getAndAddConvEndianWithCAS(ba, index, delta);
+            }
         }
 
         @ForceInline
-        static $type$ addAndGet(ArrayHandle handle, Object oba, int index, $type$ value) {
-            byte[] ba = (byte[]) oba;
-            return convEndian(handle.be, UNSAFE.getAndAdd$RawType$(
-                    ba,
-                    address(ba, index(ba, index)),
-                    convEndian(handle.be, value))) + value;
+        static $type$ getAndAddConvEndianWithCAS(byte[] ba, int index, $type$ delta) {
+            $type$ nativeExpectedValue, expectedValue;
+            long offset = address(ba, index(ba, index));
+            do {
+                nativeExpectedValue = UNSAFE.get$RawType$Volatile(ba, offset);
+                expectedValue = $RawBoxType$.reverseBytes(nativeExpectedValue);
+            } while (!UNSAFE.weakCompareAndSwap$RawType$Volatile(ba, offset,
+                    nativeExpectedValue, $RawBoxType$.reverseBytes(expectedValue + delta)));
+            return expectedValue;
+        }
+
+        @ForceInline
+        static $type$ addAndGet(ArrayHandle handle, Object oba, int index, $type$ delta) {
+            return getAndAdd(handle, oba, index, delta) + delta;
         }
 #end[AtomicAdd]
 
@@ -307,14 +318,14 @@
 
         @ForceInline
         static int index(ByteBuffer bb, int index) {
-            return Objects.checkIndex(index, UNSAFE.getInt(bb, BUFFER_LIMIT) - ALIGN, null);
+            return Preconditions.checkIndex(index, UNSAFE.getInt(bb, BUFFER_LIMIT) - ALIGN, null);
         }
 
         @ForceInline
         static int indexRO(ByteBuffer bb, int index) {
             if (UNSAFE.getBoolean(bb, BYTE_BUFFER_IS_READ_ONLY))
                 throw new ReadOnlyBufferException();
-            return Objects.checkIndex(index, UNSAFE.getInt(bb, BUFFER_LIMIT) - ALIGN, null);
+            return Preconditions.checkIndex(index, UNSAFE.getInt(bb, BUFFER_LIMIT) - ALIGN, null);
         }
 
         @ForceInline
@@ -466,8 +477,7 @@
         @ForceInline
         static boolean weakCompareAndSetVolatile(ByteBufferHandle handle, Object obb, int index, $type$ expected, $type$ value) {
             ByteBuffer bb = (ByteBuffer) obb;
-            // TODO defer to strong form until new Unsafe method is added
-            return UNSAFE.compareAndSwap$RawType$(
+            return UNSAFE.weakCompareAndSwap$RawType$Volatile(
                     UNSAFE.getObject(bb, BYTE_BUFFER_HB),
                     address(bb, indexRO(bb, index)),
                     convEndian(handle.be, expected), convEndian(handle.be, value));
@@ -504,23 +514,34 @@
 #if[AtomicAdd]
 
         @ForceInline
-        static $type$ getAndAdd(ByteBufferHandle handle, Object obb, int index, $type$ value) {
+        static $type$ getAndAdd(ByteBufferHandle handle, Object obb, int index, $type$ delta) {
             ByteBuffer bb = (ByteBuffer) obb;
-            return convEndian(handle.be,
-                              UNSAFE.getAndAdd$RawType$(
-                                      UNSAFE.getObject(bb, BYTE_BUFFER_HB),
-                                      address(bb, indexRO(bb, index)),
-                                      convEndian(handle.be, value)));
+            if (handle.be == BE) {
+                return UNSAFE.getAndAdd$RawType$(
+                        UNSAFE.getObject(bb, BYTE_BUFFER_HB),
+                        address(bb, indexRO(bb, index)),
+                        delta);
+            } else {
+                return getAndAddConvEndianWithCAS(bb, index, delta);
+            }
         }
 
         @ForceInline
-        static $type$ addAndGet(ByteBufferHandle handle, Object obb, int index, $type$ value) {
-            ByteBuffer bb = (ByteBuffer) obb;
-            return convEndian(handle.be,
-                              UNSAFE.getAndAdd$RawType$(
-                                      UNSAFE.getObject(bb, BYTE_BUFFER_HB),
-                                      address(bb, indexRO(bb, index)),
-                                      convEndian(handle.be, value))) + value;
+        static $type$ getAndAddConvEndianWithCAS(ByteBuffer bb, int index, $type$ delta) {
+            $type$ nativeExpectedValue, expectedValue;
+            Object base = UNSAFE.getObject(bb, BYTE_BUFFER_HB);
+            long offset = address(bb, indexRO(bb, index));
+            do {
+                nativeExpectedValue = UNSAFE.get$RawType$Volatile(base, offset);
+                expectedValue = $RawBoxType$.reverseBytes(nativeExpectedValue);
+            } while (!UNSAFE.weakCompareAndSwap$RawType$Volatile(base, offset,
+                    nativeExpectedValue, $RawBoxType$.reverseBytes(expectedValue + delta)));
+            return expectedValue;
+        }
+
+        @ForceInline
+        static $type$ addAndGet(ByteBufferHandle handle, Object obb, int index, $type$ delta) {
+            return getAndAdd(handle, obb, index, delta) + delta;
         }
 #end[AtomicAdd]
 
--- a/src/java.base/share/classes/java/lang/module/ModuleInfo.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/module/ModuleInfo.java	Thu May 19 19:46:20 2016 +0000
@@ -154,7 +154,7 @@
         int minor_version = in.readUnsignedShort();
         int major_version = in.readUnsignedShort();
         if (major_version < 53) {
-            // throw invalidModuleDescriptor"Must be >= 53.0");
+            throw invalidModuleDescriptor("Must be >= 53.0");
         }
 
         ConstantPool cpool = new ConstantPool(in);
--- a/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java	Thu May 19 19:46:20 2016 +0000
@@ -45,6 +45,7 @@
 import jdk.internal.jimage.ImageReader;
 import jdk.internal.jimage.ImageReaderFactory;
 import jdk.internal.module.ModuleHashes;
+import jdk.internal.module.ModuleHashes.HashSupplier;
 import jdk.internal.module.SystemModules;
 import jdk.internal.module.ModulePatcher;
 import jdk.internal.perf.PerfCounter;
@@ -84,57 +85,23 @@
         long t0 = System.nanoTime();
         imageReader = ImageReaderFactory.getImageReader();
 
-        String[] moduleNames = SystemModules.MODULE_NAMES;
-        ModuleDescriptor[] descriptors = null;
+        String[] names = moduleNames();
+        ModuleDescriptor[] descriptors = descriptors(names);
 
-        boolean fastLoad = System.getProperty("jdk.installed.modules.disable") == null;
-        if (fastLoad) {
-            // fast loading of ModuleDescriptor of installed modules
-            descriptors = SystemModules.modules();
-        }
-
-        int n = moduleNames.length;
+        int n = names.length;
         moduleCount.add(n);
 
         Set<ModuleReference> mods = new HashSet<>(n);
         Map<String, ModuleReference> map = new HashMap<>(n);
 
         for (int i = 0; i < n; i++) {
-            String mn = moduleNames[i];
-            ModuleDescriptor md;
-            String hash;
-            if (fastLoad) {
-                md = descriptors[i];
-                hash = SystemModules.MODULES_TO_HASH[i];
-            } else {
-                // fallback to read module-info.class
-                // if fast loading of ModuleDescriptors is disabled
-                ImageLocation location = imageReader.findLocation(mn, "module-info.class");
-                md = ModuleDescriptor.read(imageReader.getResourceBuffer(location));
-                hash = null;
-            }
-            if (!md.name().equals(mn))
-                throw new InternalError();
+            ModuleDescriptor md = descriptors[i];
 
             // create the ModuleReference
-
-            URI uri = URI.create("jrt:/" + mn);
-
-            Supplier<ModuleReader> readerSupplier = new Supplier<>() {
-                @Override
-                public ModuleReader get() {
-                    return new ImageModuleReader(mn, uri);
-                }
-            };
-
-            ModuleReference mref =
-                new ModuleReference(md, uri, readerSupplier, hashSupplier(hash));
-
-            // may need a reference to a patched module if -Xpatch specified
-            mref = ModulePatcher.interposeIfNeeded(mref);
+            ModuleReference mref = toModuleReference(md, hashSupplier(i, names[i]));
 
             mods.add(mref);
-            map.put(mn, mref);
+            map.put(names[i], mref);
 
             // counters
             packageCount.add(md.packages().size());
@@ -147,16 +114,114 @@
         initTime.addElapsedTimeFrom(t0);
     }
 
-    private static ModuleHashes.HashSupplier hashSupplier(String hash) {
-        if (hash == null)
-            return null;
+    /*
+     * Returns an array of ModuleDescriptor of the given module names.
+     *
+     * This obtains ModuleDescriptors from SystemModules class that is generated
+     * from the jlink system-modules plugin.  ModuleDescriptors have already
+     * been validated at link time.
+     *
+     * If java.base is patched, or fastpath is disabled for troubleshooting
+     * purpose, it will fall back to find system modules via jrt file system.
+     */
+    private static ModuleDescriptor[] descriptors(String[] names) {
+        // fastpath is enabled by default.
+        // It can be disabled for troubleshooting purpose.
+        boolean disabled =
+            System.getProperty("jdk.system.module.finder.disabledFastPath") != null;
 
-        return new ModuleHashes.HashSupplier() {
+        // fast loading of ModuleDescriptor of system modules
+        if (isFastPathSupported() && !disabled)
+            return SystemModules.modules();
+
+        // if fast loading of ModuleDescriptors is disabled
+        // fallback to read module-info.class
+        ModuleDescriptor[] descriptors = new ModuleDescriptor[names.length];
+        for (int i = 0; i < names.length; i++) {
+            String mn = names[i];
+            ImageLocation loc = imageReader.findLocation(mn, "module-info.class");
+            descriptors[i] = ModuleDescriptor.read(imageReader.getResourceBuffer(loc));
+
+            // add the recorded hashes of tied modules
+            Hashes.add(descriptors[i]);
+        }
+        return descriptors;
+    }
+
+    private static boolean isFastPathSupported() {
+       return SystemModules.MODULE_NAMES.length > 0;
+    }
+
+    private static String[] moduleNames() {
+        if (isFastPathSupported())
+            // module names recorded at link time
+            return SystemModules.MODULE_NAMES;
+
+        // this happens when java.base is patched with java.base
+        // from an exploded image
+        return imageReader.getModuleNames();
+    }
+
+    private static ModuleReference toModuleReference(ModuleDescriptor md,
+                                                     HashSupplier hash)
+    {
+        String mn = md.name();
+        URI uri = URI.create("jrt:/" + mn);
+
+        Supplier<ModuleReader> readerSupplier = new Supplier<>() {
             @Override
-            public String generate(String algorithm) {
-                return hash;
+            public ModuleReader get() {
+                return new ImageModuleReader(mn, uri);
             }
         };
+
+        ModuleReference mref =
+            new ModuleReference(md, uri, readerSupplier, hash);
+
+        // may need a reference to a patched module if -Xpatch specified
+        mref = ModulePatcher.interposeIfNeeded(mref);
+
+        return mref;
+    }
+
+    private static HashSupplier hashSupplier(int index, String name) {
+        if (isFastPathSupported()) {
+            return new HashSupplier() {
+                @Override
+                public String generate(String algorithm) {
+                    return SystemModules.MODULES_TO_HASH[index];
+                }
+            };
+        } else {
+            return Hashes.hashFor(name);
+        }
+    }
+
+    /*
+     * This helper class is only used when SystemModules is patched.
+     * It will get the recorded hashes from module-info.class.
+     */
+    private static class Hashes {
+        static Map<String, String> hashes = new HashMap<>();
+
+        static void add(ModuleDescriptor descriptor) {
+            Optional<ModuleHashes> ohashes = descriptor.hashes();
+            if (ohashes.isPresent()) {
+                hashes.putAll(ohashes.get().hashes());
+            }
+        }
+
+        static HashSupplier hashFor(String name) {
+            if (!hashes.containsKey(name))
+                return null;
+
+            return new HashSupplier() {
+                @Override
+                public String generate(String algorithm) {
+                    return hashes.get(name);
+                }
+            };
+        }
     }
 
     SystemModuleFinder() { }
--- a/src/java.base/share/classes/java/nio/Buffer.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/nio/Buffer.java	Thu May 19 19:46:20 2016 +0000
@@ -111,7 +111,7 @@
  * to zero.
  *
  *
- * <h2> Clearing, flipping, and rewinding </h2>
+ * <h2> Additional operations </h2>
  *
  * <p> In addition to methods for accessing the position, limit, and capacity
  * values and for marking and resetting, this class also defines the following
@@ -131,6 +131,12 @@
  *   it already contains: It leaves the limit unchanged and sets the position
  *   to zero.  </p></li>
  *
+ *   <li><p> {@link #slice} creates a subsequence of a buffer: It leaves the
+ *   limit and the position unchanged. </p></li>
+ *
+ *   <li><p> {@link #duplicate} creates a shallow copy of a buffer: It leaves
+ *   the limit and the position unchanged. </p></li>
+ *
  * </ul>
  *
  *
@@ -567,6 +573,46 @@
      */
     public abstract boolean isDirect();
 
+    /**
+     * Creates a new buffer whose content is a shared subsequence of
+     * this buffer's content.
+     *
+     * <p> The content of the new buffer will start at this buffer's current
+     * position.  Changes to this buffer's content will be visible in the new
+     * buffer, and vice versa; the two buffers' position, limit, and mark
+     * values will be independent.
+     *
+     * <p> The new buffer's position will be zero, its capacity and its limit
+     * will be the number of elements remaining in this buffer, its mark will be
+     * undefined. The new buffer will be direct if, and only if, this buffer is
+     * direct, and it will be read-only if, and only if, this buffer is
+     * read-only.  </p>
+     *
+     * @return  The new buffer
+     *
+     * @since 9
+     */
+    public abstract Buffer slice();
+
+    /**
+     * Creates a new buffer that shares this buffer's content.
+     *
+     * <p> The content of the new buffer will be that of this buffer.  Changes
+     * to this buffer's content will be visible in the new buffer, and vice
+     * versa; the two buffers' position, limit, and mark values will be
+     * independent.
+     *
+     * <p> The new buffer's capacity, limit, position and mark values will be
+     * identical to those of this buffer. The new buffer will be direct if, and
+     * only if, this buffer is direct, and it will be read-only if, and only if,
+     * this buffer is read-only.  </p>
+     *
+     * @return  The new buffer
+     *
+     * @since 9
+     */
+    public abstract Buffer duplicate();
+
 
     // -- Package-private methods for bounds checking, etc. --
 
--- a/src/java.base/share/classes/java/nio/X-Buffer.java.template	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/nio/X-Buffer.java.template	Thu May 19 19:46:20 2016 +0000
@@ -70,8 +70,7 @@
  *
 #end[byte]
  *
- *   <li><p> Methods for {@link #compact compacting}, {@link
- *   #duplicate duplicating}, and {@link #slice slicing}
+ *   <li><p> A method for {@link #compact compacting}
  *   $a$ $type$ buffer.  </p></li>
  *
  * </ul>
@@ -535,6 +534,7 @@
      * @see #alignedSlice(int)
 #end[byte]
      */
+    @Override
     public abstract $Type$Buffer slice();
 
     /**
@@ -557,6 +557,7 @@
      *
      * @return  The new $type$ buffer
      */
+    @Override
     public abstract $Type$Buffer duplicate();
 
     /**
--- a/src/java.base/share/classes/java/util/Objects.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/util/Objects.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,10 +25,9 @@
 
 package java.util;
 
-import jdk.internal.HotSpotIntrinsicCandidate;
+import jdk.internal.util.Preconditions;
+import jdk.internal.vm.annotation.ForceInline;
 
-import java.util.function.BiFunction;
-import java.util.function.Function;
 import java.util.function.Supplier;
 
 /**
@@ -349,172 +348,6 @@
     }
 
     /**
-     * Maps out-of-bounds values to a runtime exception.
-     *
-     * @param checkKind the kind of bounds check, whose name may correspond
-     *        to the name of one of the range check methods, checkIndex,
-     *        checkFromToIndex, checkFromIndexSize
-     * @param args the out-of-bounds arguments that failed the range check.
-     *        If the checkKind corresponds a the name of a range check method
-     *        then the bounds arguments are those that can be passed in order
-     *        to the method.
-     * @param oobef the exception formatter that when applied with a checkKind
-     *        and a list out-of-bounds arguments returns a runtime exception.
-     *        If {@code null} then, it is as if an exception formatter was
-     *        supplied that returns {@link IndexOutOfBoundsException} for any
-     *        given arguments.
-     * @return the runtime exception
-     */
-    private static RuntimeException outOfBounds(
-            BiFunction<String, List<Integer>, ? extends RuntimeException> oobef,
-            String checkKind,
-            Integer... args) {
-        List<Integer> largs = List.of(args);
-        RuntimeException e = oobef == null
-                             ? null : oobef.apply(checkKind, largs);
-        return e == null
-               ? new IndexOutOfBoundsException(outOfBoundsMessage(checkKind, largs)) : e;
-    }
-
-    // Specific out-of-bounds exception producing methods that avoid
-    // the varargs-based code in the critical methods there by reducing their
-    // the byte code size, and therefore less likely to peturb inlining
-
-    private static RuntimeException outOfBoundsCheckIndex(
-            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
-            int index, int length) {
-        return outOfBounds(oobe, "checkIndex", index, length);
-    }
-
-    private static RuntimeException outOfBoundsCheckFromToIndex(
-            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
-            int fromIndex, int toIndex, int length) {
-        return outOfBounds(oobe, "checkFromToIndex", fromIndex, toIndex, length);
-    }
-
-    private static RuntimeException outOfBoundsCheckFromIndexSize(
-            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
-            int fromIndex, int size, int length) {
-        return outOfBounds(oobe, "checkFromIndexSize", fromIndex, size, length);
-    }
-
-    /**
-     * Returns an out-of-bounds exception formatter from an given exception
-     * factory.  The exception formatter is a function that formats an
-     * out-of-bounds message from its arguments and applies that message to the
-     * given exception factory to produce and relay an exception.
-     *
-     * <p>The exception formatter accepts two arguments: a {@code String}
-     * describing the out-of-bounds range check that failed, referred to as the
-     * <em>check kind</em>; and a {@code List<Integer>} containing the
-     * out-of-bound integer values that failed the check.  The list of
-     * out-of-bound values is not modified.
-     *
-     * <p>Three check kinds are supported {@code checkIndex},
-     * {@code checkFromToIndex} and {@code checkFromIndexSize} corresponding
-     * respectively to the specified application of an exception formatter as an
-     * argument to the out-of-bounds range check methods
-     * {@link #checkIndex(int, int, BiFunction) checkIndex},
-     * {@link #checkFromToIndex(int, int, int, BiFunction) checkFromToIndex}, and
-     * {@link #checkFromIndexSize(int, int, int, BiFunction) checkFromIndexSize}.
-     * Thus a supported check kind corresponds to a method name and the
-     * out-of-bound integer values correspond to method argument values, in
-     * order, preceding the exception formatter argument (similar in many
-     * respects to the form of arguments required for a reflective invocation of
-     * such a range check method).
-     *
-     * <p>Formatter arguments conforming to such supported check kinds will
-     * produce specific exception messages describing failed out-of-bounds
-     * checks.  Otherwise, more generic exception messages will be produced in
-     * any of the following cases: the check kind is supported but fewer
-     * or more out-of-bounds values are supplied, the check kind is not
-     * supported, the check kind is {@code null}, or the list of out-of-bound
-     * values is {@code null}.
-     *
-     * @apiNote
-     * This method produces an out-of-bounds exception formatter that can be
-     * passed as an argument to any of the supported out-of-bounds range check
-     * methods declared by {@code Objects}.  For example, a formatter producing
-     * an {@code ArrayIndexOutOfBoundsException} may be produced and stored on a
-     * {@code static final} field as follows:
-     * <pre>{@code
-     * static final
-     * BiFunction<String, List<Integer>, ArrayIndexOutOfBoundsException> AIOOBEF =
-     *     outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new);
-     * }</pre>
-     * The formatter instance {@code AIOOBEF} may be passed as an argument to an
-     * out-of-bounds range check method, such as checking if an {@code index}
-     * is within the bounds of a {@code limit}:
-     * <pre>{@code
-     * checkIndex(index, limit, AIOOBEF);
-     * }</pre>
-     * If the bounds check fails then the range check method will throw an
-     * {@code ArrayIndexOutOfBoundsException} with an appropriate exception
-     * message that is a produced from {@code AIOOBEF} as follows:
-     * <pre>{@code
-     * AIOOBEF.apply("checkIndex", List.of(index, limit));
-     * }</pre>
-     *
-     * @param f the exception factory, that produces an exception from a message
-     *        where the message is produced and formatted by the returned
-     *        exception formatter.  If this factory is stateless and side-effect
-     *        free then so is the returned formatter.
-     *        Exceptions thrown by the factory are relayed to the caller
-     *        of the returned formatter.
-     * @param <X> the type of runtime exception to be returned by the given
-     *        exception factory and relayed by the exception formatter
-     * @return the out-of-bounds exception formatter
-     */
-    public static <X extends RuntimeException>
-    BiFunction<String, List<Integer>, X> outOfBoundsExceptionFormatter(Function<String, X> f) {
-        // Use anonymous class to avoid bootstrap issues if this method is
-        // used early in startup
-        return new BiFunction<String, List<Integer>, X>() {
-            @Override
-            public X apply(String checkKind, List<Integer> args) {
-                return f.apply(outOfBoundsMessage(checkKind, args));
-            }
-        };
-    }
-
-    private static String outOfBoundsMessage(String checkKind, List<Integer> args) {
-        if (checkKind == null && args == null) {
-            return String.format("Range check failed");
-        } else if (checkKind == null) {
-            return String.format("Range check failed: %s", args);
-        } else if (args == null) {
-            return String.format("Range check failed: %s", checkKind);
-        }
-
-        int argSize = 0;
-        switch (checkKind) {
-            case "checkIndex":
-                argSize = 2;
-                break;
-            case "checkFromToIndex":
-            case "checkFromIndexSize":
-                argSize = 3;
-                break;
-            default:
-        }
-
-        // Switch to default if fewer or more arguments than required are supplied
-        switch ((args.size() != argSize) ? "" : checkKind) {
-            case "checkIndex":
-                return String.format("Index %d out-of-bounds for length %d",
-                                     args.get(0), args.get(1));
-            case "checkFromToIndex":
-                return String.format("Range [%d, %d) out-of-bounds for length %d",
-                                     args.get(0), args.get(1), args.get(2));
-            case "checkFromIndexSize":
-                return String.format("Range [%d, %<d + %d) out-of-bounds for length %d",
-                                     args.get(0), args.get(1), args.get(2));
-            default:
-                return String.format("Range check failed: %s %s", checkKind, args);
-        }
-    }
-
-    /**
      * Checks if the {@code index} is within the bounds of the range from
      * {@code 0} (inclusive) to {@code length} (exclusive).
      *
@@ -526,72 +359,16 @@
      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
      * </ul>
      *
-     * <p>This method behaves as if {@link #checkIndex(int, int, BiFunction)}
-     * was called with same out-of-bounds arguments and an exception formatter
-     * argument produced from an invocation of
-     * {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} (though it may
-     * be more efficient).
-     *
      * @param index the index
      * @param length the upper-bound (exclusive) of the range
      * @return {@code index} if it is within bounds of the range
      * @throws IndexOutOfBoundsException if the {@code index} is out-of-bounds
      * @since 9
      */
+    @ForceInline
     public static
     int checkIndex(int index, int length) {
-        return checkIndex(index, length, null);
-    }
-
-    /**
-     * Checks if the {@code index} is within the bounds of the range from
-     * {@code 0} (inclusive) to {@code length} (exclusive).
-     *
-     * <p>The {@code index} is defined to be out-of-bounds if any of the
-     * following inequalities is true:
-     * <ul>
-     *  <li>{@code index < 0}</li>
-     *  <li>{@code index >= length}</li>
-     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
-     * </ul>
-     *
-     * <p>If the {@code index} is out-of-bounds, then a runtime exception is
-     * thrown that is the result of applying the following arguments to the
-     * exception formatter: the name of this method, {@code checkIndex};
-     * and an unmodifiable list integers whose values are, in order, the
-     * out-of-bounds arguments {@code index} and {@code length}.
-     *
-     * @param <X> the type of runtime exception to throw if the arguments are
-     *        out-of-bounds
-     * @param index the index
-     * @param length the upper-bound (exclusive) of the range
-     * @param oobef the exception formatter that when applied with this
-     *        method name and out-of-bounds arguments returns a runtime
-     *        exception.  If {@code null} or returns {@code null} then, it is as
-     *        if an exception formatter produced from an invocation of
-     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
-     *        instead (though it may be more efficient).
-     *        Exceptions thrown by the formatter are relayed to the caller.
-     * @return {@code index} if it is within bounds of the range
-     * @throws X if the {@code index} is out-of-bounds and the exception
-     *         formatter is non-{@code null}
-     * @throws IndexOutOfBoundsException if the {@code index} is out-of-bounds
-     *         and the exception formatter is {@code null}
-     * @since 9
-     *
-     * @implNote
-     * This method is made intrinsic in optimizing compilers to guide them to
-     * perform unsigned comparisons of the index and length when it is known the
-     * length is a non-negative value (such as that of an array length or from
-     * the upper bound of a loop)
-    */
-    @HotSpotIntrinsicCandidate
-    public static <X extends RuntimeException>
-    int checkIndex(int index, int length,
-                   BiFunction<String, List<Integer>, X> oobef) {
-        if (index < 0 || index >= length)
-            throw outOfBoundsCheckIndex(oobef, index, length);
-        return index;
+        return Preconditions.checkIndex(index, length, null);
     }
 
     /**
@@ -608,12 +385,6 @@
      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
      * </ul>
      *
-     * <p>This method behaves as if {@link #checkFromToIndex(int, int, int, BiFunction)}
-     * was called with same out-of-bounds arguments and an exception formatter
-     * argument produced from an invocation of
-     * {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} (though it may
-     * be more efficient).
-     *
      * @param fromIndex the lower-bound (inclusive) of the sub-range
      * @param toIndex the upper-bound (exclusive) of the sub-range
      * @param length the upper-bound (exclusive) the range
@@ -623,54 +394,7 @@
      */
     public static
     int checkFromToIndex(int fromIndex, int toIndex, int length) {
-        return checkFromToIndex(fromIndex, toIndex, length, null);
-    }
-
-    /**
-     * Checks if the sub-range from {@code fromIndex} (inclusive) to
-     * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
-     * (inclusive) to {@code length} (exclusive).
-     *
-     * <p>The sub-range is defined to be out-of-bounds if any of the following
-     * inequalities is true:
-     * <ul>
-     *  <li>{@code fromIndex < 0}</li>
-     *  <li>{@code fromIndex > toIndex}</li>
-     *  <li>{@code toIndex > length}</li>
-     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
-     * </ul>
-     *
-     * <p>If the sub-range  is out-of-bounds, then a runtime exception is
-     * thrown that is the result of applying the following arguments to the
-     * exception formatter: the name of this method, {@code checkFromToIndex};
-     * and an unmodifiable list integers whose values are, in order, the
-     * out-of-bounds arguments {@code fromIndex}, {@code toIndex}, and {@code length}.
-     *
-     * @param <X> the type of runtime exception to throw if the arguments are
-     *        out-of-bounds
-     * @param fromIndex the lower-bound (inclusive) of the sub-range
-     * @param toIndex the upper-bound (exclusive) of the sub-range
-     * @param length the upper-bound (exclusive) the range
-     * @param oobef the exception formatter that when applied with this
-     *        method name and out-of-bounds arguments returns a runtime
-     *        exception.  If {@code null} or returns {@code null} then, it is as
-     *        if an exception formatter produced from an invocation of
-     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
-     *        instead (though it may be more efficient).
-     *        Exceptions thrown by the formatter are relayed to the caller.
-     * @return {@code fromIndex} if the sub-range within bounds of the range
-     * @throws X if the sub-range is out-of-bounds and the exception factory
-     *         function is non-{@code null}
-     * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
-     *         the exception factory function is {@code null}
-     * @since 9
-     */
-    public static <X extends RuntimeException>
-    int checkFromToIndex(int fromIndex, int toIndex, int length,
-                         BiFunction<String, List<Integer>, X> oobef) {
-        if (fromIndex < 0 || fromIndex > toIndex || toIndex > length)
-            throw outOfBoundsCheckFromToIndex(oobef, fromIndex, toIndex, length);
-        return fromIndex;
+        return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
     }
 
     /**
@@ -687,12 +411,6 @@
      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
      * </ul>
      *
-     * <p>This method behaves as if {@link #checkFromIndexSize(int, int, int, BiFunction)}
-     * was called with same out-of-bounds arguments and an exception formatter
-     * argument produced from an invocation of
-     * {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} (though it may
-     * be more efficient).
-     *
      * @param fromIndex the lower-bound (inclusive) of the sub-interval
      * @param size the size of the sub-range
      * @param length the upper-bound (exclusive) of the range
@@ -702,54 +420,7 @@
      */
     public static
     int checkFromIndexSize(int fromIndex, int size, int length) {
-        return checkFromIndexSize(fromIndex, size, length, null);
+        return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
     }
 
-    /**
-     * Checks if the sub-range from {@code fromIndex} (inclusive) to
-     * {@code fromIndex + size} (exclusive) is within the bounds of range from
-     * {@code 0} (inclusive) to {@code length} (exclusive).
-     *
-     * <p>The sub-range is defined to be out-of-bounds if any of the following
-     * inequalities is true:
-     * <ul>
-     *  <li>{@code fromIndex < 0}</li>
-     *  <li>{@code size < 0}</li>
-     *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
-     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
-     * </ul>
-     *
-     * <p>If the sub-range  is out-of-bounds, then a runtime exception is
-     * thrown that is the result of applying the following arguments to the
-     * exception formatter: the name of this method, {@code checkFromIndexSize};
-     * and an unmodifiable list integers whose values are, in order, the
-     * out-of-bounds arguments {@code fromIndex}, {@code size}, and
-     * {@code length}.
-     *
-     * @param <X> the type of runtime exception to throw if the arguments are
-     *        out-of-bounds
-     * @param fromIndex the lower-bound (inclusive) of the sub-interval
-     * @param size the size of the sub-range
-     * @param length the upper-bound (exclusive) of the range
-     * @param oobef the exception formatter that when applied with this
-     *        method name and out-of-bounds arguments returns a runtime
-     *        exception.  If {@code null} or returns {@code null} then, it is as
-     *        if an exception formatter produced from an invocation of
-     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
-     *        instead (though it may be more efficient).
-     *        Exceptions thrown by the formatter are relayed to the caller.
-     * @return {@code fromIndex} if the sub-range within bounds of the range
-     * @throws X if the sub-range is out-of-bounds and the exception factory
-     *         function is non-{@code null}
-     * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
-     *         the exception factory function is {@code null}
-     * @since 9
-     */
-    public static <X extends RuntimeException>
-    int checkFromIndexSize(int fromIndex, int size, int length,
-                           BiFunction<String, List<Integer>, X> oobef) {
-        if ((length | fromIndex | size) < 0 || size > length - fromIndex)
-            throw outOfBoundsCheckFromIndexSize(oobef, fromIndex, size, length);
-        return fromIndex;
-    }
 }
--- a/src/java.base/share/classes/java/util/zip/ZipFile.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/java/util/zip/ZipFile.java	Thu May 19 19:46:20 2016 +0000
@@ -462,9 +462,13 @@
 
     private class ZipEntryIterator implements Enumeration<ZipEntry>, Iterator<ZipEntry> {
         private int i = 0;
+        private final int entryCount;
 
         public ZipEntryIterator() {
-            ensureOpen();
+            synchronized (ZipFile.this) {
+                ensureOpen();
+                this.entryCount = zsrc.total;
+            }
         }
 
         public boolean hasMoreElements() {
@@ -472,10 +476,7 @@
         }
 
         public boolean hasNext() {
-            synchronized (ZipFile.this) {
-                ensureOpen();
-                return i < zsrc.total;
-            }
+            return i < entryCount;
         }
 
         public ZipEntry nextElement() {
@@ -485,7 +486,7 @@
         public ZipEntry next() {
             synchronized (ZipFile.this) {
                 ensureOpen();
-                if (i >= zsrc.total) {
+                if (!hasNext()) {
                     throw new NoSuchElementException();
                 }
                 // each "entry" has 3 ints in table entries
@@ -526,34 +527,34 @@
     /* Checks ensureOpen() before invoke this method */
     private ZipEntry getZipEntry(String name, int pos) {
         byte[] cen = zsrc.cen;
-        ZipEntry e = new ZipEntry();
         int nlen = CENNAM(cen, pos);
         int elen = CENEXT(cen, pos);
         int clen = CENCOM(cen, pos);
-        e.flag = CENFLG(cen, pos);  // get the flag first
-        if (name != null) {
-            e.name = name;
-        } else {
-            if (!zc.isUTF8() && (e.flag & EFS) != 0) {
-                e.name = zc.toStringUTF8(cen, pos + CENHDR, nlen);
+        int flag = CENFLG(cen, pos);
+        if (name == null) {
+            if (!zc.isUTF8() && (flag & EFS) != 0) {
+                name = zc.toStringUTF8(cen, pos + CENHDR, nlen);
             } else {
-                e.name = zc.toString(cen, pos + CENHDR, nlen);
+                name = zc.toString(cen, pos + CENHDR, nlen);
             }
         }
+        ZipEntry e = new ZipEntry(name);
+        e.flag = flag;
         e.xdostime = CENTIM(cen, pos);
         e.crc = CENCRC(cen, pos);
         e.size = CENLEN(cen, pos);
         e.csize = CENSIZ(cen, pos);
         e.method = CENHOW(cen, pos);
         if (elen != 0) {
-            e.setExtra0(Arrays.copyOfRange(cen, pos + CENHDR + nlen,
-                                           pos + CENHDR + nlen + elen), true);
+            int start = pos + CENHDR + nlen;
+            e.setExtra0(Arrays.copyOfRange(cen, start, start + elen), true);
         }
         if (clen != 0) {
-            if (!zc.isUTF8() && (e.flag & EFS) != 0) {
-                e.comment = zc.toStringUTF8(cen, pos + CENHDR + nlen + elen, clen);
+            int start = pos + CENHDR + nlen + elen;
+            if (!zc.isUTF8() && (flag & EFS) != 0) {
+                e.comment = zc.toStringUTF8(cen, start, clen);
             } else {
-                e.comment = zc.toString(cen, pos + CENHDR + nlen + elen, clen);
+                e.comment = zc.toString(cen, start, clen);
             }
         }
         return e;
@@ -817,7 +818,7 @@
         );
     }
 
-    /*
+    /**
      * Returns an array of strings representing the names of all entries
      * that begin with "META-INF/" (case ignored). This method is used
      * in JarFile, via SharedSecrets, as an optimization when looking up
@@ -827,14 +828,14 @@
     private String[] getMetaInfEntryNames() {
         synchronized (this) {
             ensureOpen();
-            if (zsrc.metanames.size() == 0) {
+            if (zsrc.metanames == null) {
                 return null;
             }
-            String[] names = new String[zsrc.metanames.size()];
+            String[] names = new String[zsrc.metanames.length];
             byte[] cen = zsrc.cen;
             for (int i = 0; i < names.length; i++) {
-                int pos = zsrc.metanames.get(i);
-                names[i] = new String(cen, pos + CENHDR,  CENNAM(cen, pos),
+                int pos = zsrc.metanames[i];
+                names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos),
                                       StandardCharsets.UTF_8);
             }
             return names;
@@ -850,7 +851,7 @@
         private long locpos;                 // position of first LOC header (usually 0)
         private byte[] comment;              // zip file comment
                                              // list of meta entries in META-INF dir
-        private ArrayList<Integer> metanames = new ArrayList<>();
+        private int[] metanames;
         private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)
 
         // A Hashmap for all entries.
@@ -1159,7 +1160,7 @@
             int next = -1;
 
             // list for all meta entries
-            metanames = new ArrayList<>();
+            ArrayList<Integer> metanamesList = null;
 
             // Iterate through the entries in the central directory
             int i = 0;
@@ -1194,13 +1195,21 @@
                 idx = addEntry(idx, hash, next, pos);
                 // Adds name to metanames.
                 if (isMetaName(cen, pos + CENHDR, nlen)) {
-                    metanames.add(pos);
+                    if (metanamesList == null)
+                        metanamesList = new ArrayList<>(4);
+                    metanamesList.add(pos);
                 }
                 // skip ext and comment
                 pos += (CENHDR + nlen + elen + clen);
                 i++;
             }
             total = i;
+            if (metanamesList != null) {
+                metanames = new int[metanamesList.size()];
+                for (int j = 0, len = metanames.length; j < len; j++) {
+                    metanames[j] = metanamesList.get(j);
+                }
+            }
             if (pos + ENDHDR != cen.length) {
                 zerror("invalid CEN header (bad header size)");
             }
@@ -1265,30 +1274,23 @@
             }
         }
 
-        private static byte[] metainf = new byte[] {
-            'M', 'E', 'T', 'A', '-', 'I' , 'N', 'F', '/',
-        };
-
-        /*
-         * Returns true if the specified entry's name begins with the string
-         * "META-INF/" irrespective of case.
+        /**
+         * Returns true if the bytes represent a non-directory name
+         * beginning with "META-INF/", disregarding ASCII case.
          */
-        private static boolean isMetaName(byte[] name,  int off, int len) {
-            if (len < 9 || (name[off] != 'M' && name[off] != 'm')) {  //  sizeof("META-INF/") - 1
-                return false;
-            }
-            off++;
-            for (int i = 1; i < metainf.length; i++) {
-                byte c = name[off++];
-                // Avoid toupper; it's locale-dependent
-                if (c >= 'a' && c <= 'z') {
-                    c += 'A' - 'a';
-                }
-                if (metainf[i] != c) {
-                    return false;
-                }
-            }
-            return true;
+        private static boolean isMetaName(byte[] name, int off, int len) {
+            // Use the "oldest ASCII trick in the book"
+            return len > 9                     // "META-INF/".length()
+                && name[off + len - 1] != '/'  // non-directory
+                && (name[off++] | 0x20) == 'm'
+                && (name[off++] | 0x20) == 'e'
+                && (name[off++] | 0x20) == 't'
+                && (name[off++] | 0x20) == 'a'
+                && (name[off++]       ) == '-'
+                && (name[off++] | 0x20) == 'i'
+                && (name[off++] | 0x20) == 'n'
+                && (name[off++] | 0x20) == 'f'
+                && (name[off]         ) == '/';
         }
 
         /*
--- a/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java	Thu May 19 19:46:20 2016 +0000
@@ -149,6 +149,17 @@
         return reader.getEntryNames();
     }
 
+    public String[] getModuleNames() {
+        Objects.requireNonNull(reader, "image file closed");
+        int off = "/modules/".length();
+        return reader.findNode("/modules")
+                     .getChildren()
+                     .stream()
+                     .map(Node::getNameString)
+                     .map(s -> s.substring(off, s.length()))
+                     .toArray(String[]::new);
+    }
+
     public long[] getAttributes(int offset) {
         Objects.requireNonNull(reader, "image file closed");
         return reader.getAttributes(offset);
--- a/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java	Thu May 19 19:46:20 2016 +0000
@@ -68,13 +68,14 @@
         if (s != null && s.length() > 0)
             bcp = toURLClassPath(s);
 
-        // we have a class path if -cp is specified or -m is not specified
+        // we have a class path if -cp is specified or -m is not specified.
+        // If neither is specified then default to -cp <working directory>.
         URLClassPath ucp = null;
         String mainMid = System.getProperty("jdk.module.main");
         String cp = System.getProperty("java.class.path");
-        if (mainMid == null && (cp == null || cp.length() == 0))
-            cp = ".";
-        if (cp != null && cp.length() > 0)
+        if (mainMid == null && cp == null)
+            cp = "";
+        if (cp != null)
             ucp = toURLClassPath(cp);
 
 
@@ -197,7 +198,7 @@
          * @see java.lang.instrument.Instrumentation#appendToSystemClassLoaderSearch
          */
         void appendToClassPathForInstrumentation(String path) {
-            appendToUCP(path, ucp);
+            addClassPathToUCP(path, ucp);
         }
 
         /**
@@ -224,7 +225,7 @@
      */
     private static URLClassPath toURLClassPath(String cp) {
         URLClassPath ucp = new URLClassPath(new URL[0]);
-        appendToUCP(cp, ucp);
+        addClassPathToUCP(cp, ucp);
         return ucp;
     }
 
@@ -232,20 +233,28 @@
      * Converts the elements in the given class path to file URLs and adds
      * them to the given URLClassPath.
      */
-    private static void appendToUCP(String cp, URLClassPath ucp) {
-        String[] elements = cp.split(File.pathSeparator);
-        if (elements.length == 0) {
-            // contains path separator(s) only, default to current directory
-            // to be compatible with long standing behavior
-            elements = new String[] { "" };
+    private static void addClassPathToUCP(String cp, URLClassPath ucp) {
+        int off = 0;
+        int next;
+        while ((next = cp.indexOf(File.pathSeparator, off)) != -1) {
+            addURLToUCP(cp.substring(off, next), ucp);
+            off = next + 1;
         }
-        for (String s: elements) {
-            try {
-                URL url = Paths.get(s).toRealPath().toUri().toURL();
-                ucp.addURL(url);
-            } catch (InvalidPathException | IOException ignore) {
-                // malformed path string or class path element does not exist
-            }
+
+        // remaining
+        addURLToUCP(cp.substring(off), ucp);
+    }
+
+    /**
+     * Attempts to convert to the given string to a file URL and adds it
+     * to the given URLClassPath.
+     */
+    private static void addURLToUCP(String s, URLClassPath ucp) {
+        try {
+            URL url = Paths.get(s).toRealPath().toUri().toURL();
+            ucp.addURL(url);
+        } catch (InvalidPathException | IOException ignore) {
+            // malformed path string or class path element does not exist
         }
     }
 
--- a/src/java.base/share/classes/jdk/internal/misc/Unsafe.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/jdk/internal/misc/Unsafe.java	Thu May 19 19:46:20 2016 +0000
@@ -33,6 +33,7 @@
 import jdk.internal.misc.VM;
 
 import jdk.internal.HotSpotIntrinsicCandidate;
+import jdk.internal.vm.annotation.ForceInline;
 
 
 /**
@@ -209,46 +210,103 @@
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native boolean getBoolean(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putBoolean(Object o, long offset, boolean x);
+
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native byte    getByte(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putByte(Object o, long offset, byte x);
+
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native short   getShort(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putShort(Object o, long offset, short x);
+
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native char    getChar(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putChar(Object o, long offset, char x);
+
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native long    getLong(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putLong(Object o, long offset, long x);
+
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native float   getFloat(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putFloat(Object o, long offset, float x);
+
     /** @see #getInt(Object, long) */
     @HotSpotIntrinsicCandidate
     public native double  getDouble(Object o, long offset);
+
     /** @see #putInt(Object, long, int) */
     @HotSpotIntrinsicCandidate
     public native void    putDouble(Object o, long offset, double x);
 
+    /**
+     * Fetches a native pointer from a given memory address.  If the address is
+     * zero, or does not point into a block obtained from {@link
+     * #allocateMemory}, the results are undefined.
+     *
+     * <p>If the native pointer is less than 64 bits wide, it is extended as
+     * an unsigned number to a Java long.  The pointer may be indexed by any
+     * given byte offset, simply by adding that offset (as a simple integer) to
+     * the long representing the pointer.  The number of bytes actually read
+     * from the target address may be determined by consulting {@link
+     * #addressSize}.
+     *
+     * @see #allocateMemory
+     * @see #getInt(Object, long)
+     */
+    @ForceInline
+    public long getAddress(Object o, long offset) {
+        if (ADDRESS_SIZE == 4) {
+            return Integer.toUnsignedLong(getInt(o, offset));
+        } else {
+            return getLong(o, offset);
+        }
+    }
+
+    /**
+     * Stores a native pointer into a given memory address.  If the address is
+     * zero, or does not point into a block obtained from {@link
+     * #allocateMemory}, the results are undefined.
+     *
+     * <p>The number of bytes actually written at the target address may be
+     * determined by consulting {@link #addressSize}.
+     *
+     * @see #allocateMemory
+     * @see #putInt(Object, long, int)
+     */
+    @ForceInline
+    public void putAddress(Object o, long offset, long x) {
+        if (ADDRESS_SIZE == 4) {
+            putInt(o, offset, (int)x);
+        } else {
+            putLong(o, offset, x);
+        }
+    }
+
     // These read VM internal data.
 
     /**
@@ -287,8 +345,10 @@
      *
      * @see #allocateMemory
      */
-    @HotSpotIntrinsicCandidate
-    public native byte    getByte(long address);
+    @ForceInline
+    public byte getByte(long address) {
+        return getByte(null, address);
+    }
 
     /**
      * Stores a value into a given memory address.  If the address is zero, or
@@ -297,75 +357,94 @@
      *
      * @see #getByte(long)
      */
-    @HotSpotIntrinsicCandidate
-    public native void    putByte(long address, byte x);
+    @ForceInline
+    public void putByte(long address, byte x) {
+        putByte(null, address, x);
+    }
 
     /** @see #getByte(long) */
-    @HotSpotIntrinsicCandidate
-    public native short   getShort(long address);
+    @ForceInline
+    public short getShort(long address) {
+        return getShort(null, address);
+    }
+
     /** @see #putByte(long, byte) */
-    @HotSpotIntrinsicCandidate
-    public native void    putShort(long address, short x);
+    @ForceInline
+    public void putShort(long address, short x) {
+        putShort(null, address, x);
+    }
+
     /** @see #getByte(long) */
-    @HotSpotIntrinsicCandidate
-    public native char    getChar(long address);
+    @ForceInline
+    public char getChar(long address) {
+        return getChar(null, address);
+    }
+
     /** @see #putByte(long, byte) */
-    @HotSpotIntrinsicCandidate
-    public native void    putChar(long address, char x);
+    @ForceInline
+    public void putChar(long address, char x) {
+        putChar(null, address, x);
+    }
+
     /** @see #getByte(long) */
-    @HotSpotIntrinsicCandidate
-    public native int     getInt(long address);
+    @ForceInline
+    public int getInt(long address) {
+        return getInt(null, address);
+    }
+
     /** @see #putByte(long, byte) */
-    @HotSpotIntrinsicCandidate
-    public native void    putInt(long address, int x);
+    @ForceInline
+    public void putInt(long address, int x) {
+        putInt(null, address, x);
+    }
+
     /** @see #getByte(long) */
-    @HotSpotIntrinsicCandidate
-    public native long    getLong(long address);
+    @ForceInline
+    public long getLong(long address) {
+        return getLong(null, address);
+    }
+
     /** @see #putByte(long, byte) */
-    @HotSpotIntrinsicCandidate
-    public native void    putLong(long address, long x);
+    @ForceInline
+    public void putLong(long address, long x) {
+        putLong(null, address, x);
+    }
+
     /** @see #getByte(long) */
-    @HotSpotIntrinsicCandidate
-    public native float   getFloat(long address);
+    @ForceInline
+    public float getFloat(long address) {
+        return getFloat(null, address);
+    }
+
     /** @see #putByte(long, byte) */
-    @HotSpotIntrinsicCandidate
-    public native void    putFloat(long address, float x);
+    @ForceInline
+    public void putFloat(long address, float x) {
+        putFloat(null, address, x);
+    }
+
     /** @see #getByte(long) */
-    @HotSpotIntrinsicCandidate
-    public native double  getDouble(long address);
+    @ForceInline
+    public double getDouble(long address) {
+        return getDouble(null, address);
+    }
+
     /** @see #putByte(long, byte) */
-    @HotSpotIntrinsicCandidate
-    public native void    putDouble(long address, double x);
+    @ForceInline
+    public void putDouble(long address, double x) {
+        putDouble(null, address, x);
+    }
 
-    /**
-     * Fetches a native pointer from a given memory address.  If the address is
-     * zero, or does not point into a block obtained from {@link
-     * #allocateMemory}, the results are undefined.
-     *
-     * <p>If the native pointer is less than 64 bits wide, it is extended as
-     * an unsigned number to a Java long.  The pointer may be indexed by any
-     * given byte offset, simply by adding that offset (as a simple integer) to
-     * the long representing the pointer.  The number of bytes actually read
-     * from the target address may be determined by consulting {@link
-     * #addressSize}.
-     *
-     * @see #allocateMemory
-     */
-    @HotSpotIntrinsicCandidate
-    public native long getAddress(long address);
+    /** @see #getAddress(Object, long) */
+    @ForceInline
+    public long getAddress(long address) {
+        return getAddress(null, address);
+    }
 
-    /**
-     * Stores a native pointer into a given memory address.  If the address is
-     * zero, or does not point into a block obtained from {@link
-     * #allocateMemory}, the results are undefined.
-     *
-     * <p>The number of bytes actually written at the target address may be
-     * determined by consulting {@link #addressSize}.
-     *
-     * @see #getAddress(long)
-     */
-    @HotSpotIntrinsicCandidate
-    public native void putAddress(long address, long x);
+    /** @see #putAddress(Object, long, long) */
+    @ForceInline
+    public void putAddress(long address, long x) {
+        putAddress(null, address, x);
+    }
 
 
 
@@ -1271,6 +1350,13 @@
         return compareAndSwapObject(o, offset, expected, x);
     }
 
+    @HotSpotIntrinsicCandidate
+    public final boolean weakCompareAndSwapObjectVolatile(Object o, long offset,
+                                                                Object expected,
+                                                                Object x) {
+        return compareAndSwapObject(o, offset, expected, x);
+    }
+
     /**
      * Atomically updates Java variable to {@code x} if it is currently
      * holding {@code expected}.
@@ -1325,6 +1411,13 @@
         return compareAndSwapInt(o, offset, expected, x);
     }
 
+    @HotSpotIntrinsicCandidate
+    public final boolean weakCompareAndSwapIntVolatile(Object o, long offset,
+                                                             int expected,
+                                                             int x) {
+        return compareAndSwapInt(o, offset, expected, x);
+    }
+
     /**
      * Atomically updates Java variable to {@code x} if it is currently
      * holding {@code expected}.
@@ -1379,6 +1472,13 @@
         return compareAndSwapLong(o, offset, expected, x);
     }
 
+    @HotSpotIntrinsicCandidate
+    public final boolean weakCompareAndSwapLongVolatile(Object o, long offset,
+                                                              long expected,
+                                                              long x) {
+        return compareAndSwapLong(o, offset, expected, x);
+    }
+
     /**
      * Fetches a reference value from a given Java variable, with volatile
      * load semantics. Otherwise identical to {@link #getObject(Object, long)}
--- a/src/java.base/share/classes/jdk/internal/module/ModuleInfoWriter.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/jdk/internal/module/ModuleInfoWriter.java	Thu May 19 19:46:20 2016 +0000
@@ -54,7 +54,7 @@
         ClassWriter cw = new ClassWriter(0);
 
         String name = md.name().replace('.', '/') + "/module-info";
-        cw.visit(Opcodes.V1_8, ACC_MODULE, name, null, null, null);
+        cw.visit(Opcodes.V1_9, ACC_MODULE, name, null, null, null);
 
         cw.visitAttribute(new ModuleAttribute(md));
         cw.visitAttribute(new ConcealedPackagesAttribute(md.conceals()));
--- a/src/java.base/share/classes/jdk/internal/module/SystemModules.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/jdk/internal/module/SystemModules.java	Thu May 19 19:46:20 2016 +0000
@@ -46,12 +46,12 @@
      * and read module-info.class from the run-time image instead of
      * the fastpath.
      */
-    public static final String[] MODULE_NAMES = new String[1];
+    public static final String[] MODULE_NAMES = new String[0];
 
     /**
      * Hash of system modules.
      */
-    public static String[] MODULES_TO_HASH = new String[1];
+    public static String[] MODULES_TO_HASH = new String[0];
 
     /**
      * Number of packages in the boot layer from the installed modules.
@@ -67,7 +67,7 @@
      * When running an exploded image it returns an empty array.
      */
     public static ModuleDescriptor[] modules() {
-        return new ModuleDescriptor[0];
+        throw new InternalError("should not reach here");
     }
 
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/jdk/internal/util/Preconditions.java	Thu May 19 19:46:20 2016 +0000
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package jdk.internal.util;
+
+import jdk.internal.HotSpotIntrinsicCandidate;
+
+import java.util.List;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+
+/**
+ * Utility methods to check if state or arguments are correct.
+ *
+ */
+public class Preconditions {
+
+    /**
+     * Maps out-of-bounds values to a runtime exception.
+     *
+     * @param checkKind the kind of bounds check, whose name may correspond
+     *        to the name of one of the range check methods, checkIndex,
+     *        checkFromToIndex, checkFromIndexSize
+     * @param args the out-of-bounds arguments that failed the range check.
+     *        If the checkKind corresponds a the name of a range check method
+     *        then the bounds arguments are those that can be passed in order
+     *        to the method.
+     * @param oobef the exception formatter that when applied with a checkKind
+     *        and a list out-of-bounds arguments returns a runtime exception.
+     *        If {@code null} then, it is as if an exception formatter was
+     *        supplied that returns {@link IndexOutOfBoundsException} for any
+     *        given arguments.
+     * @return the runtime exception
+     */
+    private static RuntimeException outOfBounds(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobef,
+            String checkKind,
+            Integer... args) {
+        List<Integer> largs = List.of(args);
+        RuntimeException e = oobef == null
+                             ? null : oobef.apply(checkKind, largs);
+        return e == null
+               ? new IndexOutOfBoundsException(outOfBoundsMessage(checkKind, largs)) : e;
+    }
+
+    private static RuntimeException outOfBoundsCheckIndex(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
+            int index, int length) {
+        return outOfBounds(oobe, "checkIndex", index, length);
+    }
+
+    private static RuntimeException outOfBoundsCheckFromToIndex(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
+            int fromIndex, int toIndex, int length) {
+        return outOfBounds(oobe, "checkFromToIndex", fromIndex, toIndex, length);
+    }
+
+    private static RuntimeException outOfBoundsCheckFromIndexSize(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
+            int fromIndex, int size, int length) {
+        return outOfBounds(oobe, "checkFromIndexSize", fromIndex, size, length);
+    }
+
+    /**
+     * Returns an out-of-bounds exception formatter from an given exception
+     * factory.  The exception formatter is a function that formats an
+     * out-of-bounds message from its arguments and applies that message to the
+     * given exception factory to produce and relay an exception.
+     *
+     * <p>The exception formatter accepts two arguments: a {@code String}
+     * describing the out-of-bounds range check that failed, referred to as the
+     * <em>check kind</em>; and a {@code List<Integer>} containing the
+     * out-of-bound integer values that failed the check.  The list of
+     * out-of-bound values is not modified.
+     *
+     * <p>Three check kinds are supported {@code checkIndex},
+     * {@code checkFromToIndex} and {@code checkFromIndexSize} corresponding
+     * respectively to the specified application of an exception formatter as an
+     * argument to the out-of-bounds range check methods
+     * {@link #checkIndex(int, int, BiFunction) checkIndex},
+     * {@link #checkFromToIndex(int, int, int, BiFunction) checkFromToIndex}, and
+     * {@link #checkFromIndexSize(int, int, int, BiFunction) checkFromIndexSize}.
+     * Thus a supported check kind corresponds to a method name and the
+     * out-of-bound integer values correspond to method argument values, in
+     * order, preceding the exception formatter argument (similar in many
+     * respects to the form of arguments required for a reflective invocation of
+     * such a range check method).
+     *
+     * <p>Formatter arguments conforming to such supported check kinds will
+     * produce specific exception messages describing failed out-of-bounds
+     * checks.  Otherwise, more generic exception messages will be produced in
+     * any of the following cases: the check kind is supported but fewer
+     * or more out-of-bounds values are supplied, the check kind is not
+     * supported, the check kind is {@code null}, or the list of out-of-bound
+     * values is {@code null}.
+     *
+     * @apiNote
+     * This method produces an out-of-bounds exception formatter that can be
+     * passed as an argument to any of the supported out-of-bounds range check
+     * methods declared by {@code Objects}.  For example, a formatter producing
+     * an {@code ArrayIndexOutOfBoundsException} may be produced and stored on a
+     * {@code static final} field as follows:
+     * <pre>{@code
+     * static final
+     * BiFunction<String, List<Integer>, ArrayIndexOutOfBoundsException> AIOOBEF =
+     *     outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new);
+     * }</pre>
+     * The formatter instance {@code AIOOBEF} may be passed as an argument to an
+     * out-of-bounds range check method, such as checking if an {@code index}
+     * is within the bounds of a {@code limit}:
+     * <pre>{@code
+     * checkIndex(index, limit, AIOOBEF);
+     * }</pre>
+     * If the bounds check fails then the range check method will throw an
+     * {@code ArrayIndexOutOfBoundsException} with an appropriate exception
+     * message that is a produced from {@code AIOOBEF} as follows:
+     * <pre>{@code
+     * AIOOBEF.apply("checkIndex", List.of(index, limit));
+     * }</pre>
+     *
+     * @param f the exception factory, that produces an exception from a message
+     *        where the message is produced and formatted by the returned
+     *        exception formatter.  If this factory is stateless and side-effect
+     *        free then so is the returned formatter.
+     *        Exceptions thrown by the factory are relayed to the caller
+     *        of the returned formatter.
+     * @param <X> the type of runtime exception to be returned by the given
+     *        exception factory and relayed by the exception formatter
+     * @return the out-of-bounds exception formatter
+     */
+    public static <X extends RuntimeException>
+    BiFunction<String, List<Integer>, X> outOfBoundsExceptionFormatter(Function<String, X> f) {
+        // Use anonymous class to avoid bootstrap issues if this method is
+        // used early in startup
+        return new BiFunction<String, List<Integer>, X>() {
+            @Override
+            public X apply(String checkKind, List<Integer> args) {
+                return f.apply(outOfBoundsMessage(checkKind, args));
+            }
+        };
+    }
+
+    private static String outOfBoundsMessage(String checkKind, List<Integer> args) {
+        if (checkKind == null && args == null) {
+            return String.format("Range check failed");
+        } else if (checkKind == null) {
+            return String.format("Range check failed: %s", args);
+        } else if (args == null) {
+            return String.format("Range check failed: %s", checkKind);
+        }
+
+        int argSize = 0;
+        switch (checkKind) {
+            case "checkIndex":
+                argSize = 2;
+                break;
+            case "checkFromToIndex":
+            case "checkFromIndexSize":
+                argSize = 3;
+                break;
+            default:
+        }
+
+        // Switch to default if fewer or more arguments than required are supplied
+        switch ((args.size() != argSize) ? "" : checkKind) {
+            case "checkIndex":
+                return String.format("Index %d out-of-bounds for length %d",
+                                     args.get(0), args.get(1));
+            case "checkFromToIndex":
+                return String.format("Range [%d, %d) out-of-bounds for length %d",
+                                     args.get(0), args.get(1), args.get(2));
+            case "checkFromIndexSize":
+                return String.format("Range [%d, %<d + %d) out-of-bounds for length %d",
+                                     args.get(0), args.get(1), args.get(2));
+            default:
+                return String.format("Range check failed: %s %s", checkKind, args);
+        }
+    }
+
+    /**
+     * Checks if the {@code index} is within the bounds of the range from
+     * {@code 0} (inclusive) to {@code length} (exclusive).
+     *
+     * <p>The {@code index} is defined to be out-of-bounds if any of the
+     * following inequalities is true:
+     * <ul>
+     *  <li>{@code index < 0}</li>
+     *  <li>{@code index >= length}</li>
+     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
+     * </ul>
+     *
+     * <p>If the {@code index} is out-of-bounds, then a runtime exception is
+     * thrown that is the result of applying the following arguments to the
+     * exception formatter: the name of this method, {@code checkIndex};
+     * and an unmodifiable list integers whose values are, in order, the
+     * out-of-bounds arguments {@code index} and {@code length}.
+     *
+     * @param <X> the type of runtime exception to throw if the arguments are
+     *        out-of-bounds
+     * @param index the index
+     * @param length the upper-bound (exclusive) of the range
+     * @param oobef the exception formatter that when applied with this
+     *        method name and out-of-bounds arguments returns a runtime
+     *        exception.  If {@code null} or returns {@code null} then, it is as
+     *        if an exception formatter produced from an invocation of
+     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
+     *        instead (though it may be more efficient).
+     *        Exceptions thrown by the formatter are relayed to the caller.
+     * @return {@code index} if it is within bounds of the range
+     * @throws X if the {@code index} is out-of-bounds and the exception
+     *         formatter is non-{@code null}
+     * @throws IndexOutOfBoundsException if the {@code index} is out-of-bounds
+     *         and the exception formatter is {@code null}
+     * @since 9
+     *
+     * @implNote
+     * This method is made intrinsic in optimizing compilers to guide them to
+     * perform unsigned comparisons of the index and length when it is known the
+     * length is a non-negative value (such as that of an array length or from
+     * the upper bound of a loop)
+    */
+    @HotSpotIntrinsicCandidate
+    public static <X extends RuntimeException>
+    int checkIndex(int index, int length,
+                   BiFunction<String, List<Integer>, X> oobef) {
+        if (index < 0 || index >= length)
+            throw outOfBoundsCheckIndex(oobef, index, length);
+        return index;
+    }
+
+    /**
+     * Checks if the sub-range from {@code fromIndex} (inclusive) to
+     * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
+     * (inclusive) to {@code length} (exclusive).
+     *
+     * <p>The sub-range is defined to be out-of-bounds if any of the following
+     * inequalities is true:
+     * <ul>
+     *  <li>{@code fromIndex < 0}</li>
+     *  <li>{@code fromIndex > toIndex}</li>
+     *  <li>{@code toIndex > length}</li>
+     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
+     * </ul>
+     *
+     * <p>If the sub-range  is out-of-bounds, then a runtime exception is
+     * thrown that is the result of applying the following arguments to the
+     * exception formatter: the name of this method, {@code checkFromToIndex};
+     * and an unmodifiable list integers whose values are, in order, the
+     * out-of-bounds arguments {@code fromIndex}, {@code toIndex}, and {@code length}.
+     *
+     * @param <X> the type of runtime exception to throw if the arguments are
+     *        out-of-bounds
+     * @param fromIndex the lower-bound (inclusive) of the sub-range
+     * @param toIndex the upper-bound (exclusive) of the sub-range
+     * @param length the upper-bound (exclusive) the range
+     * @param oobef the exception formatter that when applied with this
+     *        method name and out-of-bounds arguments returns a runtime
+     *        exception.  If {@code null} or returns {@code null} then, it is as
+     *        if an exception formatter produced from an invocation of
+     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
+     *        instead (though it may be more efficient).
+     *        Exceptions thrown by the formatter are relayed to the caller.
+     * @return {@code fromIndex} if the sub-range within bounds of the range
+     * @throws X if the sub-range is out-of-bounds and the exception factory
+     *         function is non-{@code null}
+     * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
+     *         the exception factory function is {@code null}
+     * @since 9
+     */
+    public static <X extends RuntimeException>
+    int checkFromToIndex(int fromIndex, int toIndex, int length,
+                         BiFunction<String, List<Integer>, X> oobef) {
+        if (fromIndex < 0 || fromIndex > toIndex || toIndex > length)
+            throw outOfBoundsCheckFromToIndex(oobef, fromIndex, toIndex, length);
+        return fromIndex;
+    }
+
+    /**
+     * Checks if the sub-range from {@code fromIndex} (inclusive) to
+     * {@code fromIndex + size} (exclusive) is within the bounds of range from
+     * {@code 0} (inclusive) to {@code length} (exclusive).
+     *
+     * <p>The sub-range is defined to be out-of-bounds if any of the following
+     * inequalities is true:
+     * <ul>
+     *  <li>{@code fromIndex < 0}</li>
+     *  <li>{@code size < 0}</li>
+     *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
+     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
+     * </ul>
+     *
+     * <p>If the sub-range  is out-of-bounds, then a runtime exception is
+     * thrown that is the result of applying the following arguments to the
+     * exception formatter: the name of this method, {@code checkFromIndexSize};
+     * and an unmodifiable list integers whose values are, in order, the
+     * out-of-bounds arguments {@code fromIndex}, {@code size}, and
+     * {@code length}.
+     *
+     * @param <X> the type of runtime exception to throw if the arguments are
+     *        out-of-bounds
+     * @param fromIndex the lower-bound (inclusive) of the sub-interval
+     * @param size the size of the sub-range
+     * @param length the upper-bound (exclusive) of the range
+     * @param oobef the exception formatter that when applied with this
+     *        method name and out-of-bounds arguments returns a runtime
+     *        exception.  If {@code null} or returns {@code null} then, it is as
+     *        if an exception formatter produced from an invocation of
+     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
+     *        instead (though it may be more efficient).
+     *        Exceptions thrown by the formatter are relayed to the caller.
+     * @return {@code fromIndex} if the sub-range within bounds of the range
+     * @throws X if the sub-range is out-of-bounds and the exception factory
+     *         function is non-{@code null}
+     * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
+     *         the exception factory function is {@code null}
+     * @since 9
+     */
+    public static <X extends RuntimeException>
+    int checkFromIndexSize(int fromIndex, int size, int length,
+                           BiFunction<String, List<Integer>, X> oobef) {
+        if ((length | fromIndex | size) < 0 || size > length - fromIndex)
+            throw outOfBoundsCheckFromIndexSize(oobef, fromIndex, size, length);
+        return fromIndex;
+    }
+}
--- a/src/java.base/share/classes/sun/launcher/resources/launcher.properties	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/sun/launcher/resources/launcher.properties	Thu May 19 19:46:20 2016 +0000
@@ -100,7 +100,6 @@
 \    -Xdiag            show additional diagnostic messages\n\
 \    -Xdiag:resolver   show resolver diagnostic messages\n\
 \    -Xnoclassgc       disable class garbage collection\n\
-\    -Xincgc           enable incremental garbage collection\n\
 \    -Xloggc:<file>    log GC status to a file with time stamps\n\
 \    -Xbatch           disable background compilation\n\
 \    -Xms<size>        set initial Java heap size\n\
--- a/src/java.base/share/classes/sun/security/provider/PolicyFile.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/sun/security/provider/PolicyFile.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -259,14 +259,10 @@
 
     private static final Debug debug = Debug.getInstance("policy");
 
-    private static final String NONE = "NONE";
-    private static final String P11KEYSTORE = "PKCS11";
-
     private static final String SELF = "${{self}}";
     private static final String X500PRINCIPAL =
                         "javax.security.auth.x500.X500Principal";
     private static final String POLICY = "java.security.policy";
-    private static final String SECURITY_MANAGER = "java.security.manager";
     private static final String POLICY_URL = "policy.url.";
     private static final String AUTH_POLICY = "java.security.auth.policy";
     private static final String AUTH_POLICY_URL = "auth.policy.url.";
@@ -288,6 +284,17 @@
     private static final Class<?>[] PARAMS2 = { String.class, String.class };
 
     /**
+     * When a policy file has a syntax error, the exception code may generate
+     * another permission check and this can cause the policy file to be parsed
+     * repeatedly, leading to a StackOverflowError or ClassCircularityError.
+     * To avoid this, this set is populated with policy files that have been
+     * previously parsed and have syntax errors, so that they can be
+     * subsequently ignored.
+     */
+    private static AtomicReference<Set<URL>> badPolicyURLs =
+        new AtomicReference<>(new HashSet<>());
+
+    /**
      * Initializes the Policy object and reads the default policy
      * configuration file(s) into the Policy object.
      */
@@ -580,6 +587,16 @@
      * @param policyFile the policy Reader object.
      */
     private boolean init(URL policy, PolicyInfo newInfo) {
+
+        // skip parsing policy file if it has been previously parsed and
+        // has syntax errors
+        if (badPolicyURLs.get().contains(policy)) {
+            if (debug != null) {
+                debug.println("skipping bad policy file: " + policy);
+            }
+            return false;
+        }
+
         boolean success = false;
         PolicyParser pp = new PolicyParser(expandProperties);
         InputStreamReader isr = null;
@@ -622,13 +639,18 @@
                 addGrantEntry(ge, keyStore, newInfo);
             }
         } catch (PolicyParser.ParsingException pe) {
+            // record bad policy file to avoid later reparsing it
+            badPolicyURLs.updateAndGet(k -> {
+                k.add(policy);
+                return k;
+            });
             MessageFormat form = new MessageFormat(ResourcesMgr.getString
                 (POLICY + ".error.parsing.policy.message"));
             Object[] source = {policy, pe.getLocalizedMessage()};
             System.err.println(form.format(source));
-            if (debug != null)
+            if (debug != null) {
                 pe.printStackTrace();
-
+            }
         } catch (Exception e) {
             if (debug != null) {
                 debug.println("error parsing "+policy);
--- a/src/java.base/share/classes/sun/security/provider/PolicyParser.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/sun/security/provider/PolicyParser.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -213,7 +213,9 @@
                             new MessageFormat(ResourcesMgr.getString(
                                 "duplicate.keystore.domain.name"));
                         Object[] source = {domainName};
-                        throw new ParsingException(form.format(source));
+                        String msg = "duplicate keystore domain name: " +
+                                     domainName;
+                        throw new ParsingException(msg, form, source);
                     }
                 }
             } else {
@@ -743,7 +745,8 @@
                     ResourcesMgr.getString
                             ("expected.expect.read.end.of.file."));
             Object[] source = {expect};
-            throw new ParsingException(form.format(source));
+            String msg = "expected [" + expect + "], read [end of file]";
+            throw new ParsingException(msg, form, source);
         case StreamTokenizer.TT_WORD:
             if (expect.equalsIgnoreCase(st.sval)) {
                 lookahead = st.nextToken();
@@ -1244,7 +1247,8 @@
                 MessageFormat form = new MessageFormat(ResourcesMgr.getString(
                     "duplicate.keystore.name"));
                 Object[] source = {keystoreName};
-                throw new ParsingException(form.format(source));
+                String msg = "duplicate keystore name: " + keystoreName;
+                throw new ParsingException(msg, form, source);
             }
         }
 
@@ -1316,6 +1320,8 @@
         private static final long serialVersionUID = -4330692689482574072L;
 
         private String i18nMessage;
+        private MessageFormat form;
+        private Object[] source;
 
         /**
          * Constructs a ParsingException with the specified
@@ -1330,26 +1336,34 @@
             i18nMessage = msg;
         }
 
+        public ParsingException(String msg, MessageFormat form,
+                                Object[] source) {
+            super(msg);
+            this.form = form;
+            this.source = source;
+        }
+
         public ParsingException(int line, String msg) {
             super("line " + line + ": " + msg);
-            MessageFormat form = new MessageFormat
-                (ResourcesMgr.getString("line.number.msg"));
-            Object[] source = {line, msg};
-            i18nMessage = form.format(source);
+            // don't call form.format unless getLocalizedMessage is called
+            // to avoid unnecessary permission checks
+            form = new MessageFormat(ResourcesMgr.getString("line.number.msg"));
+            source = new Object[] {line, msg};
         }
 
         public ParsingException(int line, String expect, String actual) {
             super("line " + line + ": expected [" + expect +
                 "], found [" + actual + "]");
-            MessageFormat form = new MessageFormat(ResourcesMgr.getString
+            // don't call form.format unless getLocalizedMessage is called
+            // to avoid unnecessary permission checks
+            form = new MessageFormat(ResourcesMgr.getString
                 ("line.number.expected.expect.found.actual."));
-            Object[] source = {line, expect, actual};
-            i18nMessage = form.format(source);
+            source = new Object[] {line, expect, actual};
         }
 
         @Override
         public String getLocalizedMessage() {
-            return i18nMessage;
+            return i18nMessage != null ? i18nMessage : form.format(source);
         }
     }
 
--- a/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java	Thu May 19 19:46:20 2016 +0000
@@ -145,11 +145,10 @@
      */
     public static boolean isBlockOrSF(String s) {
         // we currently only support DSA and RSA PKCS7 blocks
-        if (s.endsWith(".SF") || s.endsWith(".DSA") ||
-                s.endsWith(".RSA") || s.endsWith(".EC")) {
-            return true;
-        }
-        return false;
+        return s.endsWith(".SF")
+            || s.endsWith(".DSA")
+            || s.endsWith(".RSA")
+            || s.endsWith(".EC");
     }
 
     /**
--- a/src/java.base/share/conf/security/java.policy	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/conf/security/java.policy	Thu May 19 19:46:20 2016 +0000
@@ -80,6 +80,10 @@
         permission java.security.AllPermission;
 };
 
+grant codeBase "jrt:/java.scripting" {
+        permission java.security.AllPermission;
+};
+
 grant codeBase "jrt:/jdk.scripting.nashorn" {
         permission java.security.AllPermission;
 };
--- a/src/java.base/share/conf/security/java.security	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/conf/security/java.security	Thu May 19 19:46:20 2016 +0000
@@ -713,6 +713,12 @@
 # See SSL/TLS specifications and "Java Cryptography Architecture Standard
 # Algorithm Name Documentation" for information about the algorithm names.
 #
+# Note: If a legacy algorithm is also restricted through the
+# jdk.tls.disabledAlgorithms property or the
+# java.security.AlgorithmConstraints API (See
+# javax.net.ssl.SSLParameters.setAlgorithmConstraints()),
+# then the algorithm is completely disabled and will not be negotiated.
+#
 # Note: This property is currently used by Oracle's JSSE implementation.
 # It is not guaranteed to be examined and used by other implementations.
 # There is no guarantee the property will continue to exist or be of the
--- a/src/java.base/share/native/include/jvmti.h	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.base/share/native/include/jvmti.h	Thu May 19 19:46:20 2016 +0000
@@ -704,7 +704,8 @@
     unsigned int can_generate_resource_exhaustion_heap_events : 1;
     unsigned int can_generate_resource_exhaustion_threads_events : 1;
     unsigned int can_generate_early_vmstart : 1;
-    unsigned int : 6;
+    unsigned int can_generate_early_class_hook_events : 1;
+    unsigned int : 5;
     unsigned int : 16;
     unsigned int : 16;
     unsigned int : 16;
--- a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java	Thu May 19 19:46:20 2016 +0000
@@ -112,7 +112,7 @@
     private AncestorListener ancestorListener = null;
     private DropTarget dragAndDropTarget = null;
 
-    private final AcceptAllFileFilter acceptAllFileFilter = new AcceptAllFileFilter();
+    private static final AcceptAllFileFilter acceptAllFileFilter = new AcceptAllFileFilter();
 
     private AquaFileSystemModel model;
 
@@ -997,7 +997,7 @@
     // *****************************************
     // ***** default AcceptAll file filter *****
     // *****************************************
-    protected class AcceptAllFileFilter extends FileFilter {
+    private static class AcceptAllFileFilter extends FileFilter {
         public AcceptAllFileFilter() {
         }
 
@@ -1305,6 +1305,8 @@
     protected class FilterComboBoxModel extends AbstractListModel<FileFilter> implements ComboBoxModel<FileFilter>,
             PropertyChangeListener {
         protected FileFilter[] filters;
+        Object oldFileFilter = getFileChooser().getFileFilter();
+
         protected FilterComboBoxModel() {
             super();
             filters = getFileChooser().getChoosableFileFilters();
@@ -1321,12 +1323,17 @@
         }
 
         public void setSelectedItem(Object filter) {
-            if (filter != null && !containsFileFilter(filter)) {
+            if (filter != null && !isSelectedFileFilterInModel(filter)) {
+                oldFileFilter = filter;
                 getFileChooser().setFileFilter((FileFilter) filter);
                 fireContentsChanged(this, -1, -1);
             }
         }
 
+        private boolean isSelectedFileFilterInModel(Object filter) {
+            return Objects.equals(filter, oldFileFilter);
+        }
+
         public Object getSelectedItem() {
             // Ensure that the current filter is in the list.
             // NOTE: we shouldnt' have to do this, since JFileChooser adds
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTEvent.m	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTEvent.m	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -282,12 +282,20 @@
         //kCGSFlagsMaskAppleLeftAlternateKey,
         //kCGSFlagsMaskAppleRightAlternateKey,
         58,
-        61,
+        0,
         java_awt_event_InputEvent_ALT_DOWN_MASK,
         java_awt_event_InputEvent_ALT_MASK,
         java_awt_event_KeyEvent_VK_ALT
     },
     {
+        NSAlternateKeyMask,
+        0,
+        61,
+        java_awt_event_InputEvent_ALT_DOWN_MASK | java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK,
+        java_awt_event_InputEvent_ALT_MASK | java_awt_event_InputEvent_ALT_GRAPH_MASK,
+        java_awt_event_KeyEvent_VK_ALT
+    },
+    {
         NSCommandKeyMask,
         //kCGSFlagsMaskAppleLeftCommandKey,
         //kCGSFlagsMaskAppleRightCommandKey,
@@ -310,6 +318,8 @@
     {0, 0, 0, 0, 0, 0}
 };
 
+static BOOL leftAltKeyPressed;
+
 /*
  * Almost all unicode characters just go from NS to Java with no translation.
  *  For the few exceptions, we handle it here with this small table.
@@ -523,13 +533,17 @@
             //    *javaKeyLocation = java_awt_event_KeyEvent_KEY_LOCATION_RIGHT;
             //}
             if (eventKeyCode == cur->leftKeyCode) {
+                leftAltKeyPressed = YES;
                 *javaKeyLocation = java_awt_event_KeyEvent_KEY_LOCATION_LEFT;
             } else if (eventKeyCode == cur->rightKeyCode) {
                 *javaKeyLocation = java_awt_event_KeyEvent_KEY_LOCATION_RIGHT;
+            } else if (cur->nsMask == NSAlternateKeyMask) {
+                leftAltKeyPressed = NO;
+                continue;
             }
             *javaKeyType = (cur->nsMask & nsFlags) ?
-                java_awt_event_KeyEvent_KEY_PRESSED :
-                java_awt_event_KeyEvent_KEY_RELEASED;
+            java_awt_event_KeyEvent_KEY_PRESSED :
+            java_awt_event_KeyEvent_KEY_RELEASED;
             break;
         }
     }
@@ -545,7 +559,11 @@
 
     for (cur = nsKeyToJavaModifierTable; cur->nsMask != 0; ++cur) {
         if ((cur->nsMask & nsFlags) != 0) {
-            javaModifiers |= isExtMods? cur->javaExtMask : cur->javaMask;
+            javaModifiers |= isExtMods ? cur->javaExtMask : cur->javaMask;
+            if (cur->nsMask == NSAlternateKeyMask && leftAltKeyPressed == NO) {
+                continue;
+            }
+            break;
         }
     }
 
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CMenuItem.m	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CMenuItem.m	Thu May 19 19:46:20 2016 +0000
@@ -25,7 +25,6 @@
 
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
 #include <Carbon/Carbon.h>
-
 #import "CMenuItem.h"
 #import "CMenu.h"
 #import "AWTEvent.h"
@@ -64,42 +63,6 @@
 - (BOOL) worksWhenModal {
     return YES;
 }
-// This is a method written using Carbon framework methods to remove
-// All modifiers including "Shift" modifier.
-// Example 1: Shortcut set is "Command Shift m" returns "m"
-// Example 2: Shortcut set is "Command m" returns "m"
-// Example 3: Shortcut set is "Alt Shift ," returns ","
-
-CFStringRef createStringForKey(CGKeyCode keyCode)
-{
-    TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
-//  currentKeyboard now contains the current input source
-    CFDataRef layoutData =
-    TISGetInputSourceProperty(currentKeyboard,
-                              kTISPropertyUnicodeKeyLayoutData);
-//  the UNICODE keyLayout is fetched from currentKeyboard in layoutData
-    const UCKeyboardLayout *keyboardLayout =
-    (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
-//  A read-only data pointer is fetched from layoutData
-    UInt32 keysDown = 0;
-    UniChar chars[4];
-    UniCharCount realLength;
-    
-    UCKeyTranslate(keyboardLayout,
-                   keyCode,
-                   kUCKeyActionDisplay,
-                   0,
-                   LMGetKbdType(),
-                   kUCKeyTranslateNoDeadKeysBit,
-                   &keysDown,
-                   sizeof(chars) / sizeof(chars[0]),
-                   &realLength,
-                   chars);
-    CFRelease(currentKeyboard);
-//  Converts keyCode, modifier and dead-key state into UNICODE characters
-    return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1);
-}
-
 // Events
 - (void)handleAction:(NSMenuItem *)sender {
     AWT_ASSERT_APPKIT_THREAD;
@@ -116,35 +79,6 @@
     // from this "frameless" menu, because there are no active windows. This
     // means we have to handle it here.
     NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
-    if ([currEvent type] == NSKeyDown) {
-        NSString *menuKey = [sender keyEquivalent];
-//      If shortcut is "Command Shift ," the menuKey gets the value ","
-//      But [currEvent charactersIgnoringModifiers]; returns "<" and not ","
-//      because the charactersIgnoreingModifiers does not ignore "Shift"
-//      So a shortcut like "Command Shift m" will return "M" where as the
-//      MenuKey will have the value "m". To remove this issue the below
-//      createStringForKey is used.
-        NSString *eventKey = createStringForKey([currEvent keyCode]);
-        
-//      Apple uses characters from private Unicode range for some of the
-//      keys, so we need to do the same translation here that we do
-//      for the regular key down events
-                if ([eventKey length] == 1) {
-                    unichar origChar = [eventKey characterAtIndex:0];
-                    unichar newChar =  NsCharToJavaChar(origChar, 0);
-                    if (newChar == java_awt_event_KeyEvent_CHAR_UNDEFINED) {
-                        newChar = origChar;
-                    }
-        
-                    eventKey = [NSString stringWithCharacters: &newChar length: 1];
-                }
-        
-        NSWindow *keyWindow = [NSApp keyWindow];
-        if ([menuKey isEqualToString:eventKey] && keyWindow != nil) {
-            return;
-        }
-    }
-    
     if (fIsCheckbox) {
         static JNF_CLASS_CACHE(jc_CCheckboxMenuItem, "sun/lwawt/macosx/CCheckboxMenuItem");
         static JNF_MEMBER_CACHE(jm_ckHandleAction, jc_CCheckboxMenuItem, "handleAction", "(Z)V");
@@ -154,16 +88,47 @@
         NSInteger state = [sender state];
         jboolean newState = (state == NSOnState ? JNI_FALSE : JNI_TRUE);
         JNFCallVoidMethod(env, fPeer, jm_ckHandleAction, newState);
-    } else {
-        static JNF_CLASS_CACHE(jc_CMenuItem, "sun/lwawt/macosx/CMenuItem");
-        static JNF_MEMBER_CACHE(jm_handleAction, jc_CMenuItem, "handleAction", "(JI)V"); // AWT_THREADING Safe (event)
-        
-        NSUInteger modifiers = [currEvent modifierFlags];
-        jint javaModifiers = NsKeyModifiersToJavaModifiers(modifiers, NO);
-        
-        JNFCallVoidMethod(env, fPeer, jm_handleAction, UTC(currEvent), javaModifiers); // AWT_THREADING Safe (event)
+    }
+    else {
+        if ([currEvent type] == NSKeyDown) {
+            
+            // Event available through sender variable hence NSApplication
+            // not needed for checking the keyboard input sans the modifier keys
+            // Also, the method used to fetch eventKey earlier would be locale dependent
+            // With earlier implementation, if MenuKey: e EventKey: ा ; if input method
+            // is not U.S. (Devanagari in this case)
+            // With current implementation, EventKey = MenuKey = e irrespective of
+            // input method
+            
+            NSString *eventKey = [sender keyEquivalent];
+            // Apple uses characters from private Unicode range for some of the
+            // keys, so we need to do the same translation here that we do
+            // for the regular key down events
+            if ([eventKey length] == 1) {
+                unichar origChar = [eventKey characterAtIndex:0];
+                unichar newChar =  NsCharToJavaChar(origChar, 0);
+                if (newChar == java_awt_event_KeyEvent_CHAR_UNDEFINED) {
+                    newChar = origChar;
+                }
+                eventKey = [NSString stringWithCharacters: &newChar length: 1];
+            }
+            NSWindow *keyWindow = [NSApp keyWindow];
+            if (keyWindow != nil) {
+                return;
+            }
+            else {
+                static JNF_CLASS_CACHE(jc_CMenuItem, "sun/lwawt/macosx/CMenuItem");
+                static JNF_MEMBER_CACHE(jm_handleAction, jc_CMenuItem, "handleAction", "(JI)V"); // AWT_THREADING Safe (event)
+                
+                NSUInteger modifiers = [currEvent modifierFlags];
+                jint javaModifiers = NsKeyModifiersToJavaModifiers(modifiers, NO);
+                
+                JNFCallVoidMethod(env, fPeer, jm_handleAction, UTC(currEvent), javaModifiers); // AWT_THREADING Safe (event)
+            }
+        }
     }
     JNF_COCOA_EXIT(env);
+    
 }
 
 - (void) setJavaLabel:(NSString *)theLabel shortcut:(NSString *)theKeyEquivalent modifierMask:(jint)modifiers {
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m	Thu May 19 19:46:20 2016 +0000
@@ -25,7 +25,7 @@
 
 // External Java Accessibility links:
 //
-// <http://java.sun.com/j2se/1.4.2/docs/guide/access/index.html>
+// <https://docs.oracle.com/javase/8/docs/technotes/guides/access/index.html>
 // <http://www-106.ibm.com/developerworks/library/j-access/?n-j-10172>
 // <http://archives.java.sun.com/archives/java-access.html> (Sun's mailing list for Java accessibility)
 
@@ -1030,7 +1030,7 @@
 // Element's value (id)
 // note that the appKit meaning of "accessibilityValue" is different from the java
 // meaning of "accessibleValue", which is specific to numerical values
-// (http://java.sun.com/j2se/1.3/docs/api/javax/accessibility/AccessibleValue.html#setCurrentAccessibleValue(java.lang.Number))
+// (https://docs.oracle.com/javase/8/docs/api/javax/accessibility/AccessibleValue.html#setCurrentAccessibleValue-java.lang.Number-)
 - (id)accessibilityValueAttribute
 {
     static JNF_STATIC_MEMBER_CACHE(jm_getCurrentAccessibleValue, sjc_CAccessibility, "getCurrentAccessibleValue", "(Ljavax/accessibility/AccessibleValue;Ljava/awt/Component;)Ljava/lang/Number;");
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SimpleCMYKColorSpace.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SimpleCMYKColorSpace.java	Thu May 19 19:46:20 2016 +0000
@@ -31,7 +31,7 @@
  * color space.
  */
 public final class SimpleCMYKColorSpace extends ColorSpace {
-    private static final long serialVersionUID = 666L; // XXX Revise UID value
+    private static final long serialVersionUID = 5387117338644522424L;
 
     private static ColorSpace theInstance = null;
     private ColorSpace csRGB;
--- a/src/java.desktop/share/classes/com/sun/media/sound/AiffFileFormat.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/AiffFileFormat.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,17 +25,14 @@
 
 package com.sun.media.sound;
 
-import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFormat;
 
-
 /**
  * AIFF file format.
  *
  * @author Jan Borgersen
  */
-
-final class AiffFileFormat extends AudioFileFormat {
+final class AiffFileFormat extends StandardFileFormat {
 
     static final int AIFF_MAGIC         = 1179603533;
 
@@ -70,11 +67,8 @@
     /** FVER chunk size in bytes, inclusive magic and length field */
     private final int fverChunkSize=0;
 
-    AiffFileFormat( AudioFileFormat aff ) {
-        this( aff.getType(), aff.getByteLength(), aff.getFormat(), aff.getFrameLength() );
-    }
-
-    AiffFileFormat(Type type, int byteLength, AudioFormat format, int frameLength) {
+    AiffFileFormat(final Type type, final long byteLength,
+                   final AudioFormat format, final long frameLength) {
         super(type, byteLength, format, frameLength);
     }
 
--- a/src/java.desktop/share/classes/com/sun/media/sound/AiffFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/AiffFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -45,7 +45,7 @@
 public final class AiffFileReader extends SunFileReader {
 
     @Override
-    AudioFileFormat getAudioFileFormatImpl(final InputStream stream)
+    StandardFileFormat getAudioFileFormatImpl(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
         DataInputStream dis = new DataInputStream(stream);
 
@@ -60,11 +60,11 @@
             throw new UnsupportedAudioFileException("not an AIFF file");
         }
 
-        int frameLength = 0;
+        long /* unsigned 32bit */ frameLength = 0;
         int length = dis.readInt();
         int iffType = dis.readInt();
 
-        int totallength;
+        final long totallength;
         if(length <= 0 ) {
             length = AudioSystem.NOT_SPECIFIED;
             totallength = AudioSystem.NOT_SPECIFIED;
@@ -106,12 +106,7 @@
                 if (channels <= 0) {
                     throw new UnsupportedAudioFileException("Invalid number of channels");
                 }
-                frameLength = dis.readInt(); // numSampleFrames
-                if (frameLength < 0) {
-                    // AiffFileFormat uses int, unlike AIS which uses long
-                    //TODO this (negative) value should be passed as long to AIS
-                    frameLength = AudioSystem.NOT_SPECIFIED;
-                }
+                frameLength = dis.readInt() & 0xffffffffL; // numSampleFrames
 
                 int sampleSizeInBits = dis.readUnsignedShort();
                 if (sampleSizeInBits < 1 || sampleSizeInBits > 32) {
--- a/src/java.desktop/share/classes/com/sun/media/sound/AuFileFormat.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/AuFileFormat.java	Thu May 19 19:46:20 2016 +0000
@@ -33,7 +33,7 @@
  *
  * @author Jan Borgersen
  */
-final class AuFileFormat extends AudioFileFormat {
+final class AuFileFormat extends StandardFileFormat {
 
     // magic numbers
     static final int AU_SUN_MAGIC = 0x2e736e64; // ".snd"
@@ -55,11 +55,18 @@
 
     static final int AU_HEADERSIZE       = 24;
 
+    /**
+     * According the specification of AU file format this is the value for
+     * length field if length is not known. This is a maximum possible value for
+     * the unsigned int.
+     */
+    static final long /*unsigned int */ UNKNOWN_SIZE = 0xffffffffL;
+
     private int auType;
 
-    AuFileFormat(AudioFileFormat.Type type, int lengthInBytes, AudioFormat format, int lengthInFrames) {
-
-        super(type,lengthInBytes,format,lengthInFrames);
+    AuFileFormat(final AudioFileFormat.Type type, final long byteLength,
+                 final AudioFormat format, final long frameLength) {
+        super(type, byteLength, format, frameLength);
 
         AudioFormat.Encoding encoding = format.getEncoding();
 
--- a/src/java.desktop/share/classes/com/sun/media/sound/AuFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/AuFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -29,7 +29,6 @@
 import java.io.IOException;
 import java.io.InputStream;
 
-import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFileFormat.Type;
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioSystem;
@@ -45,7 +44,7 @@
 public final class AuFileReader extends SunFileReader {
 
     @Override
-    public AudioFileFormat getAudioFileFormatImpl(final InputStream stream)
+    public StandardFileFormat getAudioFileFormatImpl(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
         final DataInputStream dis = new DataInputStream(stream);
         final int magic = dis.readInt();
@@ -56,7 +55,7 @@
         }
 
         final int headerSize = dis.readInt();
-        final int dataSize = dis.readInt();
+        final long /* unsigned int */ dataSize = dis.readInt() & 0xffffffffL;
         final int auType = dis.readInt();
         final int sampleRate = dis.readInt();
         final int channels = dis.readInt();
@@ -120,21 +119,21 @@
                 // unsupported filetype, throw exception
                 throw new UnsupportedAudioFileException("not a valid AU file");
         }
+        // now seek past the header
+        dis.skipBytes(headerSize - AuFileFormat.AU_HEADERSIZE);
 
         final int frameSize = calculatePCMFrameSize(sampleSizeInBits, channels);
         //$$fb 2002-11-02: fix for 4629669: AU file reader: problems with empty files
-        final int length;
-        if (dataSize < 0) {
-            length = AudioSystem.NOT_SPECIFIED;
-        } else {
-            //$$fb 2003-10-20: fix for 4940459: AudioInputStream.getFrameLength() returns 0 instead of NOT_SPECIFIED
-            length = dataSize / frameSize;
+        //$$fb 2003-10-20: fix for 4940459: AudioInputStream.getFrameLength() returns 0 instead of NOT_SPECIFIED
+        long frameLength = AudioSystem.NOT_SPECIFIED;
+        long byteLength = AudioSystem.NOT_SPECIFIED;
+        if (dataSize != AuFileFormat.UNKNOWN_SIZE) {
+            frameLength = dataSize / frameSize;
+            byteLength = dataSize + headerSize;
         }
-        // now seek past the header
-        dis.skipBytes(headerSize - AuFileFormat.AU_HEADERSIZE);
         final AudioFormat format = new AudioFormat(encoding, sampleRate,
                                                    sampleSizeInBits, channels,
                                                    frameSize, sampleRate, true);
-        return new AuFileFormat(Type.AU, dataSize + headerSize, format, length);
+        return new AuFileFormat(Type.AU, byteLength, format, frameLength);
     }
 }
--- a/src/java.desktop/share/classes/com/sun/media/sound/SoftMidiAudioFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftMidiAudioFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,6 @@
 import javax.sound.midi.Receiver;
 import javax.sound.midi.Sequence;
 import javax.sound.midi.Track;
-import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFileFormat.Type;
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioInputStream;
@@ -56,10 +55,10 @@
     private static final AudioFormat format = new AudioFormat(44100, 16, 2,
                                                               true, false);
 
-    private static AudioFileFormat getAudioFileFormat(final Sequence seq) {
+    private static StandardFileFormat getAudioFileFormat(final Sequence seq) {
         long totallen = seq.getMicrosecondLength() / 1000000;
         long len = (long) (format.getFrameRate() * (totallen + 4));
-        return new AudioFileFormat(MIDI, format, (int) len);
+        return new StandardFileFormat(MIDI, format, len);
     }
 
     private AudioInputStream getAudioInputStream(final Sequence seq)
@@ -140,7 +139,7 @@
     }
 
     @Override
-    AudioFileFormat getAudioFileFormatImpl(final InputStream stream)
+    StandardFileFormat getAudioFileFormatImpl(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
         try {
             return getAudioFileFormat(MidiSystem.getSequence(stream));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/StandardFileFormat.java	Thu May 19 19:46:20 2016 +0000
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.media.sound;
+
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioSystem;
+
+/**
+ * An instance of the {@code StandardFileFormat} describes the file's length in
+ * bytes and the length in sample frames as longs. This will provide an
+ * additional precision unlike the {@code AudioFileFormat}.
+ */
+class StandardFileFormat extends AudioFileFormat {
+
+    /**
+     * File length in bytes stored as long.
+     */
+    private final long byteLength;
+
+    /**
+     * Audio data length in sample frames stored as long.
+     */
+    private final long frameLength;
+
+    /**
+     * Constructs {@code StandardFileFormat} object.
+     *
+     * @param  type the type of the audio file
+     * @param  format the format of the audio data contained in the file
+     * @param  frameLength the audio data length in sample frames, or
+     *         {@code AudioSystem.NOT_SPECIFIED}
+     */
+    StandardFileFormat(final Type type, final AudioFormat format,
+                       final long frameLength) {
+        this(type, AudioSystem.NOT_SPECIFIED, format, frameLength);
+    }
+
+    /**
+     * Constructs {@code StandardFileFormat} object.
+     *
+     * @param  type the type of the audio file
+     * @param  byteLength the length of the file in bytes, or
+     *         {@code AudioSystem.NOT_SPECIFIED}
+     * @param  format the format of the audio data contained in the file
+     * @param  frameLength the audio data length in sample frames, or
+     *         {@code AudioSystem.NOT_SPECIFIED}
+     */
+    StandardFileFormat(final Type type, final long byteLength,
+                       final AudioFormat format, final long frameLength) {
+        super(type, clip(byteLength), format, clip(frameLength));
+        this.byteLength = byteLength;
+        this.frameLength = frameLength;
+    }
+
+    /**
+     * Replaces the passed value to {@code AudioSystem.NOT_SPECIFIED} if the
+     * value is greater than {@code Integer.MAX_VALUE}.
+     *
+     * @param  value which should be clipped
+     * @return the clipped value
+     */
+    private static int clip(final long value) {
+        if (value > Integer.MAX_VALUE) {
+            return AudioSystem.NOT_SPECIFIED;
+        }
+        return (int) value;
+    }
+
+    /**
+     * Obtains the length of the audio data contained in the file, expressed in
+     * sample frames. The long precision is used.
+     *
+     * @return the number of sample frames of audio data in the file
+     * @see AudioSystem#NOT_SPECIFIED
+     */
+    public final long getLongFrameLength() {
+        return frameLength;
+    }
+
+    /**
+     * Obtains the size in bytes of the entire audio file (not just its audio
+     * data). The long precision is used.
+     *
+     * @return the audio file length in bytes
+     * @see AudioSystem#NOT_SPECIFIED
+     */
+    public final long getLongByteLength() {
+        return byteLength;
+    }
+}
--- a/src/java.desktop/share/classes/com/sun/media/sound/SunFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/SunFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,7 +47,7 @@
 abstract class SunFileReader extends AudioFileReader {
 
     @Override
-    public final AudioFileFormat getAudioFileFormat(final InputStream stream)
+    public final StandardFileFormat getAudioFileFormat(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
         stream.mark(200); // The biggest value which was historically used
         try {
@@ -87,11 +87,11 @@
             throws UnsupportedAudioFileException, IOException {
         stream.mark(200); // The biggest value which was historically used
         try {
-            final AudioFileFormat fileFormat = getAudioFileFormatImpl(stream);
+            final StandardFileFormat format = getAudioFileFormatImpl(stream);
             // we've got everything, the stream is supported and it is at the
             // beginning of the audio data, so return an AudioInputStream
-            return new AudioInputStream(stream, fileFormat.getFormat(),
-                                        fileFormat.getFrameLength());
+            return new AudioInputStream(stream, format.getFormat(),
+                                        format.getLongFrameLength());
         } catch (UnsupportedAudioFileException | EOFException ignored) {
             // stream is unsupported or the header is less than was expected
             stream.reset();
@@ -140,7 +140,7 @@
      *         UnsupportedAudioFileException if the header is less than was
      *         expected
      */
-    abstract AudioFileFormat getAudioFileFormatImpl(InputStream stream)
+    abstract StandardFileFormat getAudioFileFormatImpl(InputStream stream)
             throws UnsupportedAudioFileException, IOException;
 
     // HELPER METHODS
--- a/src/java.desktop/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -34,7 +34,6 @@
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioFormat.Encoding;
 import javax.sound.sampled.AudioInputStream;
-import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
 
 /**
@@ -167,7 +166,7 @@
     }
 
     @Override
-    AudioFileFormat getAudioFileFormatImpl(final InputStream stream)
+    StandardFileFormat getAudioFileFormatImpl(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
 
         RIFFReader riffiterator = new RIFFReader(stream);
@@ -249,19 +248,17 @@
         } else {
             throw new UnsupportedAudioFileException();
         }
-        long frameLength = dataSize / audioformat.getFrameSize();
-        if (frameLength > Integer.MAX_VALUE) {
-            frameLength = AudioSystem.NOT_SPECIFIED;
-        }
-        return new AudioFileFormat(AudioFileFormat.Type.WAVE, audioformat,
-                                   (int) frameLength);
+        return new StandardFileFormat(AudioFileFormat.Type.WAVE, audioformat,
+                                      dataSize / audioformat.getFrameSize());
     }
 
     @Override
     public AudioInputStream getAudioInputStream(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
 
-        final AudioFileFormat format = getAudioFileFormat(stream);
+        final StandardFileFormat format = getAudioFileFormat(stream);
+        final AudioFormat af = format.getFormat();
+        final long length = format.getLongFrameLength();
         // we've got everything, the stream is supported and it is at the
         // beginning of the header, so find the data chunk again and return an
         // AudioInputStream
@@ -269,8 +266,6 @@
         while (riffiterator.hasNextChunk()) {
             RIFFReader chunk = riffiterator.nextChunk();
             if (chunk.getFormat().equals("data")) {
-                final AudioFormat af = format.getFormat();
-                final long length = chunk.getSize() / af.getFrameSize();
                 return new AudioInputStream(chunk, af, length);
             }
         }
--- a/src/java.desktop/share/classes/com/sun/media/sound/WaveFileFormat.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/WaveFileFormat.java	Thu May 19 19:46:20 2016 +0000
@@ -33,7 +33,7 @@
  *
  * @author Jan Borgersen
  */
-final class WaveFileFormat extends AudioFileFormat {
+final class WaveFileFormat extends StandardFileFormat {
 
     /**
      * Wave format type.
@@ -73,9 +73,9 @@
     static final int WAVE_FORMAT_SX7383    = 0x1C07;
     static final int WAVE_FORMAT_EXTENSIBLE= 0xFFFE;
 
-    WaveFileFormat(AudioFileFormat.Type type, int lengthInBytes, AudioFormat format, int lengthInFrames) {
-
-        super(type,lengthInBytes,format,lengthInFrames);
+    WaveFileFormat(final AudioFileFormat.Type type, final long byteLength,
+                   final AudioFormat format, final long frameLength) {
+        super(type, byteLength, format, frameLength);
 
         AudioFormat.Encoding encoding = format.getEncoding();
 
--- a/src/java.desktop/share/classes/com/sun/media/sound/WaveFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/WaveFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,7 +45,7 @@
 public final class WaveFileReader extends SunFileReader {
 
     @Override
-    AudioFileFormat getAudioFileFormatImpl(final InputStream stream)
+    StandardFileFormat getAudioFileFormatImpl(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
 
         // assumes sream is rewound
@@ -64,9 +64,9 @@
         DataInputStream dis = new DataInputStream( stream );
 
         int magic = dis.readInt();
-        int fileLength = rllong(dis);
+        long /* unsigned int */ fileLength = rllong(dis) & 0xffffffffL;
         int waveMagic = dis.readInt();
-        int totallength;
+        long totallength;
         if (fileLength <= 0) {
             fileLength = AudioSystem.NOT_SPECIFIED;
             totallength = AudioSystem.NOT_SPECIFIED;
@@ -186,19 +186,18 @@
             }
         }
         // this is the length of the data chunk
-        int dataLength = rllong(dis); nread += 4;
+        long /* unsigned int */ dataLength = rllong(dis) & 0xffffffffL; nread += 4;
 
         // now build the new AudioFileFormat and return
-
+        final int frameSize = calculatePCMFrameSize(sampleSizeInBits, channels);
         AudioFormat format = new AudioFormat(encoding,
                                              (float)sampleRate,
                                              sampleSizeInBits, channels,
-                                             calculatePCMFrameSize(sampleSizeInBits, channels),
+                                             frameSize,
                                              (float)sampleRate, false);
 
-        return new WaveFileFormat(AudioFileFormat.Type.WAVE,
-                                  totallength,
-                                  format,
-                                  dataLength / format.getFrameSize());
+        long frameLength = dataLength / format.getFrameSize();
+        return new WaveFileFormat(AudioFileFormat.Type.WAVE, totallength,
+                                  format, frameLength);
     }
 }
--- a/src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Thu May 19 19:46:20 2016 +0000
@@ -32,7 +32,6 @@
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioFormat.Encoding;
 import javax.sound.sampled.AudioInputStream;
-import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
 
 /**
@@ -43,7 +42,7 @@
 public final class WaveFloatFileReader extends SunFileReader {
 
     @Override
-    AudioFileFormat getAudioFileFormatImpl(final InputStream stream)
+    StandardFileFormat getAudioFileFormatImpl(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
 
         RIFFReader riffiterator = new RIFFReader(stream);
@@ -88,20 +87,17 @@
         AudioFormat audioformat = new AudioFormat(
                 Encoding.PCM_FLOAT, samplerate, bits, channels,
                 framesize, samplerate, false);
-        long frameLength = dataSize / audioformat.getFrameSize();
-        if (frameLength > Integer.MAX_VALUE) {
-            frameLength = AudioSystem.NOT_SPECIFIED;
-        }
-
-        return new AudioFileFormat(AudioFileFormat.Type.WAVE, audioformat,
-                                   (int) frameLength);
+        return new StandardFileFormat(AudioFileFormat.Type.WAVE, audioformat,
+                                      dataSize / audioformat.getFrameSize());
     }
 
     @Override
     public AudioInputStream getAudioInputStream(final InputStream stream)
             throws UnsupportedAudioFileException, IOException {
 
-        final AudioFileFormat format = getAudioFileFormat(stream);
+        final StandardFileFormat format = getAudioFileFormat(stream);
+        final AudioFormat af = format.getFormat();
+        final long length = format.getLongFrameLength();
         // we've got everything, the stream is supported and it is at the
         // beginning of the header, so find the data chunk again and return an
         // AudioInputStream
@@ -109,8 +105,6 @@
         while (riffiterator.hasNextChunk()) {
             RIFFReader chunk = riffiterator.nextChunk();
             if (chunk.getFormat().equals("data")) {
-                final AudioFormat af = format.getFormat();
-                final long length = chunk.getSize() / af.getFrameSize();
                 return new AudioInputStream(chunk, af, length);
             }
         }
--- a/src/java.desktop/share/classes/java/awt/Component.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/java/awt/Component.java	Thu May 19 19:46:20 2016 +0000
@@ -9739,19 +9739,24 @@
      */
     int getAccessibleIndexInParent() {
         synchronized (getTreeLock()) {
-            int index = -1;
-            Container parent = this.getParent();
-            if (parent != null && parent instanceof Accessible) {
-                Component ca[] = parent.getComponents();
-                for (int i = 0; i < ca.length; i++) {
-                    if (ca[i] instanceof Accessible) {
-                        index++;
-                    }
-                    if (this.equals(ca[i])) {
-                        return index;
-                    }
+
+            AccessibleContext accContext = getAccessibleContext();
+            if (accContext == null) {
+                return -1;
+            }
+
+            Accessible parent = accContext.getAccessibleParent();
+            if (parent == null) {
+                return -1;
+            }
+
+            accContext = parent.getAccessibleContext();
+            for (int i = 0; i < accContext.getAccessibleChildrenCount(); i++) {
+                if (this.equals(accContext.getAccessibleChild(i))) {
+                    return i;
                 }
             }
+
             return -1;
         }
     }
--- a/src/java.desktop/share/classes/java/awt/Toolkit.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/java/awt/Toolkit.java	Thu May 19 19:46:20 2016 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -89,7 +89,7 @@
  * <br>For more information, see
  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#transferTiming">Timing
  * Focus Transfers</a>, a section in
- * <a href="http://java.sun.com/docs/books/tutorial/uiswing/">The Swing
+ * <a href="http://docs.oracle.com/javase/tutorial/uiswing/">The Swing
  * Tutorial</a>.
  *
  * <li>Making a top-level container visible.
@@ -207,30 +207,34 @@
     }
 
     /**
-     * Returns whether dynamic layout of Containers on resize is
-     * currently active (both set in program
-     *( {@code isDynamicLayoutSet()} )
-     *, and supported
-     * by the underlying operating system and/or window manager).
-     * If dynamic layout is currently inactive then Containers
-     * re-layout their components when resizing is completed. As a result
-     * the {@code Component.validate()} method will be invoked only
-     * once per resize.
-     * If dynamic layout is currently active then Containers
-     * re-layout their components on every native resize event and
-     * the {@code validate()} method will be invoked each time.
-     * The OS/WM support can be queried using
-     * the getDesktopProperty("awt.dynamicLayoutSupported") method.
+     * Returns whether dynamic layout of Containers on resize is currently
+     * enabled on the underlying operating system and/or window manager). If the
+     * platform supports it, {@code setDynamicLayout(boolean)} may be used to
+     * programmatically enable or disable platform dynamic layout. Regardless of
+     * whether that toggling is supported, or whether {@code true} or {@code
+     * false} is specified as an argument, or has never been called at all, this
+     * method will return the active current platform behavior and which will be
+     * followed by the JDK in determining layout policy during resizing.
+     * <p>
+     * If dynamic layout is currently inactive then Containers re-layout their
+     * components when resizing is completed. As a result the
+     * {@code Component.validate()} method will be invoked only once per resize.
+     * If dynamic layout is currently active then Containers re-layout their
+     * components on every native resize event and the {@code validate()} method
+     * will be invoked each time. The OS/WM support can be queried using the
+     * getDesktopProperty("awt.dynamicLayoutSupported") method. This property
+     * will reflect the platform capability but is not sufficient to tell if it
+     * is presently enabled.
      *
-     * @return    true if dynamic layout of Containers on resize is
-     *            currently active, false otherwise.
-     * @exception HeadlessException if the GraphicsEnvironment.isHeadless()
-     *            method returns true
-     * @see       #setDynamicLayout(boolean dynamic)
-     * @see       #isDynamicLayoutSet()
-     * @see       #getDesktopProperty(String propertyName)
-     * @see       java.awt.GraphicsEnvironment#isHeadless
-     * @since     1.4
+     * @return true if dynamic layout of Containers on resize is currently
+     *         active, false otherwise.
+     * @throws HeadlessException if the GraphicsEnvironment.isHeadless() method
+     *         returns true
+     * @see #setDynamicLayout(boolean dynamic)
+     * @see #isDynamicLayoutSet()
+     * @see #getDesktopProperty(String propertyName)
+     * @see java.awt.GraphicsEnvironment#isHeadless
+     * @since 1.4
      */
     public boolean isDynamicLayoutActive()
         throws HeadlessException {
--- a/src/java.desktop/share/classes/java/beans/XMLDecoder.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/java/beans/XMLDecoder.java	Thu May 19 19:46:20 2016 +0000
@@ -53,8 +53,8 @@
  *
  *<p>
  * For more information you might also want to check out
- * <a
- href="http://java.sun.com/products/jfc/tsc/articles/persistence3">Long Term Persistence of JavaBeans Components: XML Schema</a>,
+ * <a href="http://www.oracle.com/technetwork/java/persistence3-139471.html">
+ * Long Term Persistence of JavaBeans Components: XML Schema</a>,
  * an article in <em>The Swing Connection.</em>
  * @see XMLEncoder
  * @see java.io.ObjectInputStream
@@ -284,7 +284,8 @@
      * The {@code null} value may cause illegal parsing in such case.
      * The same problem may occur, if the {@code owner} class
      * does not contain expected method to call. See details <a
-     * href="http://java.sun.com/products/jfc/tsc/articles/persistence3/">here</a>.
+     * href="http://www.oracle.com/technetwork/java/persistence3-139471.html">
+     * here</a>.
      *
      * @param owner  the owner of the default handler
      *               that can be used as a value of &lt;java&gt; element
--- a/src/java.desktop/share/classes/java/beans/XMLEncoder.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/java/beans/XMLEncoder.java	Thu May 19 19:46:20 2016 +0000
@@ -193,8 +193,8 @@
  *
  *<p>
  * For more information you might also want to check out
- * <a
- href="http://java.sun.com/products/jfc/tsc/articles/persistence4">Using XMLEncoder</a>,
+ * <a href="http://www.oracle.com/technetwork/java/persistence4-140124.html">
+ * Using XMLEncoder</a>,
  * an article in <em>The Swing Connection.</em>
  * @see XMLDecoder
  * @see java.io.ObjectOutputStream
@@ -438,7 +438,8 @@
      * <P>
      * For more information about using resource bundles with the
      * XMLEncoder, see
-     * http://java.sun.com/products/jfc/tsc/articles/persistence4/#i18n
+     * <a href="http://www.oracle.com/technetwork/java/persistence4-140124.html#i18n">
+     * Creating Internationalized Applications</a>,
      *
      * @param oldExp The expression that will be written
      *               to the stream.
--- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/GeoTIFFTagSet.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/GeoTIFFTagSet.java	Thu May 19 19:46:20 2016 +0000
@@ -87,9 +87,9 @@
         }
     }
 
-    static class ModelTiePoint extends TIFFTag {
-        public ModelTiePoint() {
-            super("ModelTiePointTag",
+    static class ModelTiepoint extends TIFFTag {
+        public ModelTiepoint() {
+            super("ModelTiepointTag",
                   TAG_MODEL_TIE_POINT,
                   1 << TIFFTag.TIFF_DOUBLE);
         }
@@ -126,7 +126,7 @@
 
         tags.add(new GeoTIFFTagSet.ModelPixelScale());
         tags.add(new GeoTIFFTagSet.ModelTransformation());
-        tags.add(new GeoTIFFTagSet.ModelTiePoint());
+        tags.add(new GeoTIFFTagSet.ModelTiepoint());
         tags.add(new GeoTIFFTagSet.GeoKeyDirectory());
         tags.add(new GeoTIFFTagSet.GeoDoubleParams());
         tags.add(new GeoTIFFTagSet.GeoAsciiParams());
--- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/TIFFField.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/TIFFField.java	Thu May 19 19:46:20 2016 +0000
@@ -412,7 +412,7 @@
 
     /**
      * Creates a {@code TIFFField} from a TIFF native image
-     * metadata node. If the value of the <tt>"tagNumber"</tt> attribute
+     * metadata node. If the value of the <tt>"number"</tt> attribute
      * of the node is not found in {@code tagSet} then a new
      * {@code TIFFTag} with name {@code TIFFTag.UNKNOWN_TAG_NAME}
      * will be created and assigned to the field.
@@ -424,6 +424,10 @@
      * {@code null}.
      * @throws IllegalArgumentException if the name of the node is not
      * {@code "TIFFField"}.
+     * @throws NullPointerException if the node does not contain any data.
+     * @throws IllegalArgumentException if the combination of node attributes
+     * and data is not legal per the {@link #TIFFField(TIFFTag,int,int,Object)}
+     * constructor specification.
      * @return A new {@code TIFFField}.
      */
     public static TIFFField createFromMetadataNode(TIFFTagSet tagSet,
@@ -1089,6 +1093,15 @@
      * {@code TIFF_SBYTE} data will be returned in the range
      * [-128, 127].
      *
+     * <p> Data in {@code TIFF_FLOAT} and {@code TIFF_DOUBLE} are
+     * simply cast to {@code long} and may suffer from truncation.
+     *
+     * <p> Data in {@code TIFF_SRATIONAL} or
+     * {@code TIFF_RATIONAL} format are evaluated by dividing the
+     * numerator into the denominator using double-precision
+     * arithmetic and then casting to {@code long}.  Loss of
+     * precision and truncation may occur.
+     *
      * <p> Data in {@code TIFF_ASCII} format will be parsed as by
      * the {@code Double.parseDouble} method, with the result
      * cast to {@code long}.
@@ -1112,6 +1125,10 @@
         case TIFFTag.TIFF_LONG:
         case TIFFTag.TIFF_IFD_POINTER:
             return ((long[])data)[index];
+        case TIFFTag.TIFF_FLOAT:
+            return (long)((float[])data)[index];
+        case TIFFTag.TIFF_DOUBLE:
+            return (long)((double[])data)[index];
         case TIFFTag.TIFF_SRATIONAL:
             int[] ivalue = getAsSRational(index);
             return (long)((double)ivalue[0]/ivalue[1]);
@@ -1286,7 +1303,11 @@
      * version of the data item.  Data of type
      * {@code TIFFTag.TIFF_RATIONAL} or {@code TIFF_SRATIONAL} are
      * represented as a pair of integers separated by a
-     * {@code '/'} character.
+     * {@code '/'} character.  If the numerator of a
+     * {@code TIFFTag.TIFF_RATIONAL} or {@code TIFF_SRATIONAL} is an integral
+     * multiple of the denominator, then the value is represented as
+     * {@code "q/1"} where {@code q} is the quotient of the numerator and
+     * denominator.
      *
      * @param index The index of the data.
      * @return The data at the given index as a {@code String}.
--- a/src/java.desktop/share/classes/javax/swing/JRootPane.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/JRootPane.java	Thu May 19 19:46:20 2016 +0000
@@ -194,7 +194,7 @@
  * @see JComponent
  * @see BoxLayout
  *
- * @see <a href="http://java.sun.com/products/jfc/tsc/articles/mixing/">
+ * @see <a href="http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html">
  * Mixing Heavy and Light Components</a>
  *
  * @author David Kloba
--- a/src/java.desktop/share/classes/javax/swing/colorchooser/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/colorchooser/package.html	Thu May 19 19:46:20 2016 +0000
@@ -37,10 +37,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 
@@ -49,7 +49,7 @@
 This document forms the complete API specification.  For overviews, tutorials, 
 examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/colorchooser.html" target="_top">How to Use Color Choosers</a>, 
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html" target="_top">How to Use Color Choosers</a>,
       a section in <em>The Java Tutorial</em>
 
   <li><a href="../../../../technotes/guides/intl/index.html"
--- a/src/java.desktop/share/classes/javax/swing/event/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/event/package.html	Thu May 19 19:46:20 2016 +0000
@@ -39,17 +39,17 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 <h2>Related Documentation</h2>
 
 For overviews, tutorials, examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/events/"
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/events/index.html"
       target="_top">Writing Event Listeners</a>,
       a section in <em>The Java Tutorial</em>
 </ul>
--- a/src/java.desktop/share/classes/javax/swing/filechooser/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/filechooser/package.html	Thu May 19 19:46:20 2016 +0000
@@ -37,10 +37,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 
@@ -49,7 +49,7 @@
 This document forms the complete API specification.  For overviews, tutorials,
 examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html" target="_top">How to Use File Choosers</a>,
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html" target="_top">How to Use File Choosers</a>,
       a section in <em>The Java Tutorial</em>
   <li><a href="../../../../technotes/guides/intl/index.html"
       target="_top">Internationalization Documentation</a>
--- a/src/java.desktop/share/classes/javax/swing/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/package.html	Thu May 19 19:46:20 2016 +0000
@@ -38,7 +38,7 @@
 (all-Java language) components that,
 to the maximum degree possible, work the same on all platforms.
 For a programmer's guide to using these components, see
-<a href="http://java.sun.com/docs/books/tutorial/uiswing/index.html" 
+<a href="http://docs.oracle.com/javase/tutorial/uiswing/index.html"
 target="_top">Creating
 a GUI with JFC/Swing</a>, a trail in <em>The Java Tutorial</em>.
 For other resources, see 
@@ -123,9 +123,9 @@
 processing when working with Swing.
 <p>
 More information on this topic can be found in the
-<a href="http://download.oracle.com/javase/tutorial/uiswing/">Swing tutorial</a>,
+<a href="http://docs.oracle.com/javase/tutorial/uiswing/">Swing tutorial</a>,
 in particular the section on
-<a href="http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency in Swing</a>.
+<a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency in Swing</a>.
 
 
 <H2>
@@ -134,13 +134,13 @@
 <P>For overviews, tutorials, examples, guides, and other documentation, please see:
 
 <UL>
-   <LI><A HREF="http://java.sun.com/products/jfc/tsc/" 
+   <LI><A HREF="http://www.oracle.com/technetwork/java/javase/tech/articles-jsp-139072.html"
    target="_top">The Swing Connection</A>
-   <LI><A HREF="http://java.sun.com/docs/books/tutorial/" 
+   <LI><A HREF="http://docs.oracle.com/javase/tutorial/"
    target="_top">The Java Tutorial</A>
-   <LI><A HREF="http://java.sun.com/developer/onlineTraining/" 
+   <LI><A HREF="http://www.oracle.com/technetwork/java/javase/training/index.html"
    target="_top">Online Training</A> at the Java Developer Connection<font size=-2><sup>SM</sup></font>
-   <LI><A HREF="http://java.sun.com/products/jfc/" 
+   <LI><A HREF="http://www.oracle.com/technetwork/java/javase/tech/index-jsp-142216.html"
    target="_top">Java Foundation Classes (JFC)</A> home page
 </UL>
 
--- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java	Thu May 19 19:46:20 2016 +0000
@@ -210,6 +210,16 @@
         LookAndFeel.installBorder(spinner, "Spinner.border");
         LookAndFeel.installColorsAndFont(spinner, "Spinner.background", "Spinner.foreground", "Spinner.font");
         LookAndFeel.installProperty(spinner, "opaque", Boolean.TRUE);
+
+        JComponent editor = spinner.getEditor();
+        if (editor instanceof JSpinner.DefaultEditor) {
+            JTextField tf = ((JSpinner.DefaultEditor) editor).getTextField();
+            if (tf != null) {
+                if (tf.getFont() instanceof UIResource) {
+                    tf.setFont(new FontUIResource(spinner.getFont()));
+                }
+            }
+        }
     }
 
 
--- a/src/java.desktop/share/classes/javax/swing/plaf/basic/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/package.html	Thu May 19 19:46:20 2016 +0000
@@ -55,10 +55,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 @since 1.2
--- a/src/java.desktop/share/classes/javax/swing/plaf/metal/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/package.html	Thu May 19 19:46:20 2016 +0000
@@ -51,10 +51,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 @since 1.2
--- a/src/java.desktop/share/classes/javax/swing/plaf/multi/doc-files/multi_tsc.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/multi/doc-files/multi_tsc.html	Thu May 19 19:46:20 2016 +0000
@@ -18,7 +18,7 @@
 <i>
 This document is based on an article
 originally published in
-<a href="http://java.sun.com/products/jfc/tsc/" target="_top"><em>The Swing
+<a href="http://www.oracle.com/technetwork/java/javase/tech/articles-jsp-139072.html" target="_top"><em>The Swing
 Connection</em></a>.
 </i>
 </p>
@@ -65,12 +65,12 @@
 Before reading further, you should be familiar 
 with the concept of pluggable look and feels.
 For basic information, see
-<a href="http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html">How to Set the Look and Feel</a>,
+<a href="https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html">How to Set the Look and Feel</a>,
 a section in 
 <em>The Java Tutorial</em>.
 For architectural details, you can read
 <a
-href="http://java.sun.com/products/jfc/tsc/articles/architecture/#pluggable">Pluggable look-and-feel architecture</a>, a section within
+href="http://www.oracle.com/technetwork/java/architecture-142923.html#pluggable">Pluggable look-and-feel architecture</a>, a section within
 a <em>Swing Connection</em> article.
 </p>
 
--- a/src/java.desktop/share/classes/javax/swing/plaf/multi/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/multi/package.html	Thu May 19 19:46:20 2016 +0000
@@ -53,10 +53,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 @since 1.2
--- a/src/java.desktop/share/classes/javax/swing/plaf/nimbus/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/nimbus/package.html	Thu May 19 19:46:20 2016 +0000
@@ -88,10 +88,10 @@
 <p><strong>Note:</strong>
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
-<a href="http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html"
+<a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
    target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
        target="_top">The Java Tutorial</a></em>.
 
 @since 1.7
--- a/src/java.desktop/share/classes/javax/swing/plaf/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/package.html	Thu May 19 19:46:20 2016 +0000
@@ -44,10 +44,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 @since 1.2
--- a/src/java.desktop/share/classes/javax/swing/plaf/synth/doc-files/synthFileFormat.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/doc-files/synthFileFormat.html	Thu May 19 19:46:20 2016 +0000
@@ -950,7 +950,7 @@
       Beans persistance can be used to embed any Object. This is
       typically used for embedding your own Painters, but can be used
       for other arbritrary objects as well. Refer to <a
-							href="http://java.sun.com/products/jfc/tsc/articles/persistence3/">http://java.sun.com/products/jfc/tsc/articles/persistence3/</a> for details on beans persistance.
+							href="http://www.oracle.com/technetwork/java/persistence3-139471.html">http://www.oracle.com/technetwork/java/persistence3-139471.html</a> for details on beans persistance.
 
 
     <h3>Backing Style</h3>
--- a/src/java.desktop/share/classes/javax/swing/table/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/table/package.html	Thu May 19 19:46:20 2016 +0000
@@ -43,10 +43,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 
@@ -54,7 +54,7 @@
 
 For overviews, tutorials, examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html" target="_top">How to Use Tables</a>,
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html" target="_top">How to Use Tables</a>,
       a section in <em>The Java Tutorial</em>
 </ul>
 
--- a/src/java.desktop/share/classes/javax/swing/text/Document.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/text/Document.java	Thu May 19 19:46:20 2016 +0000
@@ -166,7 +166,7 @@
  * </ul>
  *
  * <p>For more information on the <code>Document</code> class, see
- * <a href="http://java.sun.com/products/jfc/tsc">The Swing Connection</a>
+ * <a href="http://www.oracle.com/technetwork/java/javase/tech/articles-jsp-139072.html">The Swing Connection</a>
  * and most particularly the article,
  * <a href="http://java.sun.com/products/jfc/tsc/articles/text/element_interface">
  * The Element Interface</a>.
--- a/src/java.desktop/share/classes/javax/swing/text/html/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/text/html/package.html	Thu May 19 19:46:20 2016 +0000
@@ -37,10 +37,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 <h2>Package Specification</h2>
--- a/src/java.desktop/share/classes/javax/swing/text/html/parser/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/text/html/parser/package.html	Thu May 19 19:46:20 2016 +0000
@@ -40,10 +40,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 @see javax.swing.text.html.HTMLEditorKit.ParserCallback
--- a/src/java.desktop/share/classes/javax/swing/text/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/text/package.html	Thu May 19 19:46:20 2016 +0000
@@ -41,17 +41,17 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 <h2>Related Documentation</h2>
 
 For overviews, tutorials, examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/text.html" target="_top">Using Text Components</a>,
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/text.html" target="_top">Using Text Components</a>,
       a section in <em>The Java Tutorial</em>
 </ul>
 
--- a/src/java.desktop/share/classes/javax/swing/text/rtf/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/text/rtf/package.html	Thu May 19 19:46:20 2016 +0000
@@ -38,10 +38,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 @since 1.2
--- a/src/java.desktop/share/classes/javax/swing/tree/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/tree/package.html	Thu May 19 19:46:20 2016 +0000
@@ -39,10 +39,10 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 
@@ -50,7 +50,7 @@
 
 For overviews, tutorials, examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html" target="_top">How to Use Trees</a>,
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html" target="_top">How to Use Trees</a>,
       a section in <em>The Java Tutorial</em>
 </ul>
 
--- a/src/java.desktop/share/classes/javax/swing/undo/package.html	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/javax/swing/undo/package.html	Thu May 19 19:46:20 2016 +0000
@@ -37,17 +37,17 @@
 Most of the Swing API is <em>not</em> thread safe.
 For details, see
 <a
-href="http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html"
-target="_top">Threads and Swing</a>,
+href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
+target="_top">Concurrency in Swing</a>,
 a section in
-<em><a href="http://java.sun.com/docs/books/tutorial/"
+<em><a href="http://docs.oracle.com/javase/tutorial/"
 target="_top">The Java Tutorial</a></em>.
 
 <h2>Related Documentation</h2>
 
 For overviews, tutorials, examples, guides, and tool documentation, please see:
 <ul>
-  <li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#undo" target="_top">Implementing Undo and Redo</a>,
+  <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#undo" target="_top">Implementing Undo and Redo</a>,
       a section in <em>The Java Tutorial</em>
 </ul>
 
--- a/src/java.desktop/share/classes/module-info.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/module-info.java	Thu May 19 19:46:20 2016 +0000
@@ -27,8 +27,6 @@
     requires public java.datatransfer;
     requires public java.xml;
     requires java.prefs;
-    // 8147544
-    requires jdk.unsupported;
 
     exports java.applet;
     exports java.awt;
--- a/src/java.desktop/share/classes/sun/applet/Main.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/sun/applet/Main.java	Thu May 19 19:46:20 2016 +0000
@@ -104,7 +104,8 @@
     private int run(String [] args) {
         // DECODE ARGS
         try {
-            System.out.println(lookup("deprecated"));
+            System.err.println(lookup("deprecated"));
+            System.err.flush();
             if (args.length == 0) {
                 usage();
                 return 0;
--- a/src/java.desktop/share/classes/sun/applet/resources/MsgAppletViewer.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/sun/applet/resources/MsgAppletViewer.java	Thu May 19 19:46:20 2016 +0000
@@ -73,7 +73,7 @@
             {"appletviewer.parse.warning.embed.requiresheight", "Warning: <embed> tag requires height attribute."},
             {"appletviewer.parse.warning.embed.requireswidth", "Warning: <embed> tag requires width attribute."},
             {"appletviewer.parse.warning.appnotLongersupported", "Warning: <app> tag no longer supported, use <applet> instead:"},
-            {"appletviewer.deprecated", "AppletViewer is deprecated."},
+            {"appletviewer.deprecated", "Warning: Applet API and AppletViewer are deprecated."},
             {"appletviewer.usage", "Usage: appletviewer <options> url(s)\n\nwhere <options> include:\n  -encoding <encoding>    Specify character encoding used by HTML files\n  -J<runtime flag>        Pass argument to the java interpreter\n\nThe -J option is non-standard and subject to change without notice."},
             {"appletviewer.main.err.unsupportedopt", "Unsupported option: {0}"},
             {"appletviewer.main.err.unrecognizedarg", "Unrecognized argument: {0}"},
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.desktop/share/classes/sun/awt/SoftCache.java	Thu May 19 19:46:20 2016 +0000
@@ -0,0 +1,462 @@
+/*
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt;
+
+import java.lang.ref.SoftReference;
+import java.lang.ref.ReferenceQueue;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.AbstractMap;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.AbstractSet;
+import java.util.NoSuchElementException;
+
+
+/**
+ * A memory-sensitive implementation of the <code>Map</code> interface.
+ *
+ * <p> A <code>SoftCache</code> object uses {@link java.lang.ref.SoftReference
+ * soft references} to implement a memory-sensitive hash map.  If the garbage
+ * collector determines at a certain point in time that a value object in a
+ * <code>SoftCache</code> entry is no longer strongly reachable, then it may
+ * remove that entry in order to release the memory occupied by the value
+ * object.  All <code>SoftCache</code> objects are guaranteed to be completely
+ * cleared before the virtual machine will throw an
+ * <code>OutOfMemoryError</code>.  Because of this automatic clearing feature,
+ * the behavior of this class is somewhat different from that of other
+ * <code>Map</code> implementations.
+ *
+ * <p> Both null values and the null key are supported.  This class has the
+ * same performance characteristics as the <code>HashMap</code> class, and has
+ * the same efficiency parameters of <em>initial capacity</em> and <em>load
+ * factor</em>.
+ *
+ * <p> Like most collection classes, this class is not synchronized.  A
+ * synchronized <code>SoftCache</code> may be constructed using the
+ * <code>Collections.synchronizedMap</code> method.
+ *
+ * <p> In typical usage this class will be subclassed and the <code>fill</code>
+ * method will be overridden.  When the <code>get</code> method is invoked on a
+ * key for which there is no mapping in the cache, it will in turn invoke the
+ * <code>fill</code> method on that key in an attempt to construct a
+ * corresponding value.  If the <code>fill</code> method returns such a value
+ * then the cache will be updated and the new value will be returned.  Thus,
+ * for example, a simple URL-content cache can be constructed as follows:
+ *
+ * <pre>
+ *     public class URLCache extends SoftCache {
+ *         protected Object fill(Object key) {
+ *             return ((URL)key).getContent();
+ *         }
+ *     }
+ * </pre>
+ *
+ * <p> The behavior of the <code>SoftCache</code> class depends in part upon
+ * the actions of the garbage collector, so several familiar (though not
+ * required) <code>Map</code> invariants do not hold for this class.  <p>
+ * Because entries are removed from a <code>SoftCache</code> in response to
+ * dynamic advice from the garbage collector, a <code>SoftCache</code> may
+ * behave as though an unknown thread is silently removing entries.  In
+ * particular, even if you synchronize on a <code>SoftCache</code> instance and
+ * invoke none of its mutator methods, it is possible for the <code>size</code>
+ * method to return smaller values over time, for the <code>isEmpty</code>
+ * method to return <code>false</code> and then <code>true</code>, for the
+ * <code>containsKey</code> method to return <code>true</code> and later
+ * <code>false</code> for a given key, for the <code>get</code> method to
+ * return a value for a given key but later return <code>null</code>, for the
+ * <code>put</code> method to return <code>null</code> and the
+ * <code>remove</code> method to return <code>false</code> for a key that
+ * previously appeared to be in the map, and for successive examinations of the
+ * key set, the value set, and the entry set to yield successively smaller
+ * numbers of elements.
+ *
+ * @author      Mark Reinhold
+ * @since       1.2
+ * @see         java.util.HashMap
+ * @see         java.lang.ref.SoftReference
+ * @deprecated No direct replacement; {@link java.util.WeakHashMap}
+ * addresses a related by different use-case.
+ */
+
+@Deprecated
+public class SoftCache extends AbstractMap<Object, Object> implements Map<Object, Object> {
+
+    /* The basic idea of this implementation is to maintain an internal HashMap
+       that maps keys to soft references whose referents are the keys' values;
+       the various accessor methods dereference these soft references before
+       returning values.  Because we don't have access to the innards of the
+       HashMap, each soft reference must contain the key that maps to it so
+       that the processQueue method can remove keys whose values have been
+       discarded.  Thus the HashMap actually maps keys to instances of the
+       ValueCell class, which is a simple extension of the SoftReference class.
+     */
+
+
+    private static class ValueCell extends SoftReference<Object> {
+        private static Object INVALID_KEY = new Object();
+        private static int dropped = 0;
+        private Object key;
+
+        private ValueCell(Object key, Object value, ReferenceQueue<Object> queue) {
+            super(value, queue);
+            this.key = key;
+        }
+
+        private static ValueCell create(Object key, Object value,
+                                        ReferenceQueue<Object> queue)
+        {
+            if (value == null) return null;
+            return new ValueCell(key, value, queue);
+        }
+
+        private static Object strip(Object val, boolean drop) {
+            if (val == null) return null;
+            ValueCell vc = (ValueCell)val;
+            Object o = vc.get();
+            if (drop) vc.drop();
+            return o;
+        }
+
+        private boolean isValid() {
+            return (key != INVALID_KEY);
+        }
+
+        private void drop() {
+            super.clear();
+            key = INVALID_KEY;
+            dropped++;
+        }
+
+    }
+
+
+    /* Hash table mapping keys to ValueCells */
+    private Map<Object, Object> hash;
+
+    /* Reference queue for cleared ValueCells */
+    private ReferenceQueue<Object> queue = new ReferenceQueue<>();
+
+
+    /* Process any ValueCells that have been cleared and enqueued by the
+       garbage collector.  This method should be invoked once by each public
+       mutator in this class.  We don't invoke this method in public accessors
+       because that can lead to surprising ConcurrentModificationExceptions.
+     */
+    private void processQueue() {
+        ValueCell vc;
+        while ((vc = (ValueCell)queue.poll()) != null) {
+            if (vc.isValid()) hash.remove(vc.key);
+            else ValueCell.dropped--;
+        }
+    }
+
+
+    /* -- Constructors -- */
+
+    /**
+     * Construct a new, empty <code>SoftCache</code> with the given
+     * initial capacity and the given load factor.
+     *
+     * @param  initialCapacity  The initial capacity of the cache
+     *
+     * @param  loadFactor       A number between 0.0 and 1.0
+     *
+     * @throws IllegalArgumentException  If the initial capacity is less than
+     *                                   or equal to zero, or if the load
+     *                                   factor is less than zero
+     */
+    public SoftCache(int initialCapacity, float loadFactor) {
+        hash = new HashMap<>(initialCapacity, loadFactor);
+    }
+
+    /**
+     * Construct a new, empty <code>SoftCache</code> with the given
+     * initial capacity and the default load factor.
+     *
+     * @param  initialCapacity  The initial capacity of the cache
+     *
+     * @throws IllegalArgumentException  If the initial capacity is less than
+     *                                   or equal to zero
+     */
+    public SoftCache(int initialCapacity) {
+        hash = new HashMap<>(initialCapacity);
+    }
+
+    /**
+     * Construct a new, empty <code>SoftCache</code> with the default
+     * capacity and the default load factor.
+     */
+    public SoftCache() {
+        hash = new HashMap<>();
+    }
+
+
+    /* -- Simple queries -- */
+
+    /**
+     * Return the number of key-value mappings in this cache.  The time
+     * required by this operation is linear in the size of the map.
+     */
+    public int size() {
+        return entrySet().size();
+    }
+
+    /**
+     * Return <code>true</code> if this cache contains no key-value mappings.
+     */
+    public boolean isEmpty() {
+        return entrySet().isEmpty();
+    }
+
+    /**
+     * Return <code>true</code> if this cache contains a mapping for the
+     * specified key.  If there is no mapping for the key, this method will not
+     * attempt to construct one by invoking the <code>fill</code> method.
+     *
+     * @param   key   The key whose presence in the cache is to be tested
+     */
+    public boolean containsKey(Object key) {
+        return ValueCell.strip(hash.get(key), false) != null;
+    }
+
+
+    /* -- Lookup and modification operations -- */
+
+    /**
+     * Create a value object for the given <code>key</code>.  This method is
+     * invoked by the <code>get</code> method when there is no entry for
+     * <code>key</code>.  If this method returns a non-<code>null</code> value,
+     * then the cache will be updated to map <code>key</code> to that value,
+     * and that value will be returned by the <code>get</code> method.
+     *
+     * <p> The default implementation of this method simply returns
+     * <code>null</code> for every <code>key</code> value.  A subclass may
+     * override this method to provide more useful behavior.
+     *
+     * @param  key  The key for which a value is to be computed
+     *
+     * @return      A value for <code>key</code>, or <code>null</code> if one
+     *              could not be computed
+     * @see #get
+     */
+    protected Object fill(Object key) {
+        return null;
+    }
+
+    /**
+     * Return the value to which this cache maps the specified
+     * <code>key</code>.  If the cache does not presently contain a value for
+     * this key, then invoke the <code>fill</code> method in an attempt to
+     * compute such a value.  If that method returns a non-<code>null</code>
+     * value, then update the cache and return the new value.  Otherwise,
+     * return <code>null</code>.
+     *
+     * <p> Note that because this method may update the cache, it is considered
+     * a mutator and may cause <code>ConcurrentModificationException</code>s to
+     * be thrown if invoked while an iterator is in use.
+     *
+     * @param  key  The key whose associated value, if any, is to be returned
+     *
+     * @see #fill
+     */
+    public Object get(Object key) {
+        processQueue();
+        Object v = hash.get(key);
+        if (v == null) {
+            v = fill(key);
+            if (v != null) {
+                hash.put(key, ValueCell.create(key, v, queue));
+                return v;
+            }
+        }
+        return ValueCell.strip(v, false);
+    }
+
+    /**
+     * Update this cache so that the given <code>key</code> maps to the given
+     * <code>value</code>.  If the cache previously contained a mapping for
+     * <code>key</code> then that mapping is replaced and the old value is
+     * returned.
+     *
+     * @param  key    The key that is to be mapped to the given
+     *                <code>value</code>
+     * @param  value  The value to which the given <code>key</code> is to be
+     *                mapped
+     *
+     * @return  The previous value to which this key was mapped, or
+     *          <code>null</code> if there was no mapping for the key
+     */
+    public Object put(Object key, Object value) {
+        processQueue();
+        ValueCell vc = ValueCell.create(key, value, queue);
+        return ValueCell.strip(hash.put(key, vc), true);
+    }
+
+    /**
+     * Remove the mapping for the given <code>key</code> from this cache, if
+     * present.
+     *
+     * @param  key  The key whose mapping is to be removed
+     *
+     * @return  The value to which this key was mapped, or <code>null</code> if
+     *          there was no mapping for the key
+     */
+    public Object remove(Object key) {
+        processQueue();
+        return ValueCell.strip(hash.remove(key), true);
+    }
+
+    /**
+     * Remove all mappings from this cache.
+     */
+    public void clear() {
+        processQueue();
+        hash.clear();
+    }
+
+
+    /* -- Views -- */
+
+    private static boolean valEquals(Object o1, Object o2) {
+        return (o1 == null) ? (o2 == null) : o1.equals(o2);
+    }
+
+
+    /* Internal class for entries.
+       Because it uses SoftCache.this.queue, this class cannot be static.
+     */
+    private class Entry implements Map.Entry<Object, Object> {
+        private Map.Entry<Object, Object> ent;
+        private Object value;   /* Strong reference to value, to prevent the GC
+                                   from flushing the value while this Entry
+                                   exists */
+
+        Entry(Map.Entry<Object, Object> ent, Object value) {
+            this.ent = ent;
+            this.value = value;
+        }
+
+        public Object getKey() {
+            return ent.getKey();
+        }
+
+        public Object getValue() {
+            return value;
+        }
+
+        public Object setValue(Object value) {
+            return ent.setValue(ValueCell.create(ent.getKey(), value, queue));
+        }
+
+        @SuppressWarnings("unchecked")
+        public boolean equals(Object o) {
+            if (! (o instanceof Map.Entry)) return false;
+            Map.Entry<Object, Object> e = (Map.Entry<Object, Object>)o;
+            return (valEquals(ent.getKey(), e.getKey())
+                    && valEquals(value, e.getValue()));
+        }
+
+        public int hashCode() {
+            Object k;
+            return ((((k = getKey()) == null) ? 0 : k.hashCode())
+                    ^ ((value == null) ? 0 : value.hashCode()));
+        }
+
+    }
+
+
+    /* Internal class for entry sets */
+    private class EntrySet extends AbstractSet<Map.Entry<Object, Object>> {
+        Set<Map.Entry<Object, Object>> hashEntries = hash.entrySet();
+
+        public Iterator<Map.Entry<Object, Object>> iterator() {
+
+            return new Iterator<Map.Entry<Object, Object>>() {
+                Iterator<Map.Entry<Object, Object>> hashIterator = hashEntries.iterator();
+                Entry next = null;
+
+                public boolean hasNext() {
+                    while (hashIterator.hasNext()) {
+                        Map.Entry<Object, Object> ent = hashIterator.next();
+                        ValueCell vc = (ValueCell)ent.getValue();
+                        Object v = null;
+                        if ((vc != null) && ((v = vc.get()) == null)) {
+                            /* Value has been flushed by GC */
+                            continue;
+                        }
+                        next = new Entry(ent, v);
+                        return true;
+                    }
+                    return false;
+                }
+
+                public Map.Entry<Object, Object> next() {
+                    if ((next == null) && !hasNext())
+                        throw new NoSuchElementException();
+                    Entry e = next;
+                    next = null;
+                    return e;
+                }
+
+                public void remove() {
+                    hashIterator.remove();
+                }
+
+            };
+        }
+
+        public boolean isEmpty() {
+            return !(iterator().hasNext());
+        }
+
+        public int size() {
+            int j = 0;
+            for (Iterator<Map.Entry<Object, Object>> i = iterator(); i.hasNext(); i.next()) j++;
+            return j;
+        }
+
+        public boolean remove(Object o) {
+            processQueue();
+            if (o instanceof Entry) return hashEntries.remove(((Entry)o).ent);
+            else return false;
+        }
+
+    }
+
+
+    private Set<Map.Entry<Object, Object>> entrySet = null;
+
+    /**
+     * Return a <code>Set</code> view of the mappings in this cache.
+     */
+    public Set<Map.Entry<Object, Object>> entrySet() {
+        if (entrySet == null) entrySet = new EntrySet();
+        return entrySet;
+    }
+
+}
--- a/src/java.desktop/share/classes/sun/awt/SunToolkit.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/sun/awt/SunToolkit.java	Thu May 19 19:46:20 2016 +0000
@@ -65,7 +65,6 @@
 import sun.awt.image.ToolkitImage;
 import sun.awt.image.URLImageSource;
 import sun.font.FontDesignMetrics;
-import sun.misc.SoftCache;
 import sun.net.util.URLUtil;
 import sun.security.action.GetBooleanAction;
 import sun.security.action.GetPropertyAction;
--- a/src/java.desktop/share/classes/sun/awt/image/MultiResolutionToolkitImage.java	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/classes/sun/awt/image/MultiResolutionToolkitImage.java	Thu May 19 19:46:20 2016 +0000
@@ -29,7 +29,7 @@
 import java.awt.image.MultiResolutionImage;
 import java.util.Arrays;
 import java.util.List;
-import sun.misc.SoftCache;
+import sun.awt.SoftCache;
 
 public class MultiResolutionToolkitImage extends ToolkitImage implements MultiResolutionImage {
 
--- a/src/java.desktop/share/native/libmlib_image/mlib_ImageAffine.c	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/native/libmlib_image/mlib_ImageAffine.c	Thu May 19 19:46:20 2016 +0000
@@ -73,7 +73,6 @@
  */
 
 #include "mlib_ImageCheck.h"
-#include "mlib_ImageColormap.h"
 #include "mlib_ImageAffine.h"
 
 
@@ -125,18 +124,6 @@
 };
 
 /***************************************************************/
-const type_affine_i_fun mlib_AffineFunArr_bc_i[] = {
-  mlib_ImageAffineIndex_U8_U8_3CH_BC,
-  mlib_ImageAffineIndex_U8_U8_4CH_BC,
-  mlib_ImageAffineIndex_S16_U8_3CH_BC,
-  mlib_ImageAffineIndex_S16_U8_4CH_BC,
-  mlib_ImageAffineIndex_U8_S16_3CH_BC,
-  mlib_ImageAffineIndex_U8_S16_4CH_BC,
-  mlib_ImageAffineIndex_S16_S16_3CH_BC,
-  mlib_ImageAffineIndex_S16_S16_4CH_BC
-};
-
-/***************************************************************/
 #ifdef i386 /* do not perform the coping by mlib_d64 data type for x86 */
 #define MAX_T_IND  2
 #else
@@ -148,8 +135,7 @@
                                       const mlib_image *src,
                                       const mlib_d64   *mtx,
                                       mlib_filter      filter,
-                                      mlib_edge        edge,
-                                      const void       *colormap)
+                                      mlib_edge        edge)
 {
   mlib_affine_param param[1];
   mlib_status res;
@@ -213,18 +199,6 @@
   else
     return MLIB_FAILURE; /* unknown image type */
 
-  if (colormap != NULL && filter != MLIB_NEAREST) {
-    if (t_ind != 0 && t_ind != 1)
-      return MLIB_FAILURE;
-
-    if (mlib_ImageGetLutType(colormap) == MLIB_SHORT)
-      t_ind += 2;
-    t_ind = 2 * t_ind;
-
-    if (mlib_ImageGetLutChannels(colormap) == 4)
-      t_ind++;
-  }
-
   if (type == MLIB_BIT) {
     mlib_s32 s_bitoff = mlib_ImageGetBitOffset(src);
     mlib_s32 d_bitoff = mlib_ImageGetBitOffset(dst);
@@ -253,25 +227,13 @@
 
       case MLIB_BILINEAR:
 
-        if (colormap != NULL) {
-          res = mlib_AffineFunArr_bl_i[t_ind] (param, colormap);
-        }
-        else {
-          res = mlib_AffineFunArr_bl[4 * t_ind + (nchan - 1)] (param);
-        }
-
+        res = mlib_AffineFunArr_bl[4 * t_ind + (nchan - 1)] (param);
         break;
 
       case MLIB_BICUBIC:
       case MLIB_BICUBIC2:
 
-        if (colormap != NULL) {
-          res = mlib_AffineFunArr_bc_i[t_ind] (param, colormap);
-        }
-        else {
-          res = mlib_AffineFunArr_bc[4 * t_ind + (nchan - 1)] (param);
-        }
-
+        res = mlib_AffineFunArr_bc[4 * t_ind + (nchan - 1)] (param);
         break;
     }
 
@@ -303,7 +265,7 @@
 
     switch (edge) {
       case MLIB_EDGE_DST_FILL_ZERO:
-        mlib_ImageAffineEdgeZero(param, param_e, colormap);
+        mlib_ImageAffineEdgeZero(param, param_e);
         break;
 
       case MLIB_EDGE_OP_NEAREST:
@@ -313,10 +275,10 @@
       case MLIB_EDGE_SRC_EXTEND:
 
         if (filter == MLIB_BILINEAR) {
-          res = mlib_ImageAffineEdgeExtend_BL(param, param_e, colormap);
+          res = mlib_ImageAffineEdgeExtend_BL(param, param_e);
         }
         else {
-          res = mlib_ImageAffineEdgeExtend_BC(param, param_e, colormap);
+          res = mlib_ImageAffineEdgeExtend_BC(param, param_e);
         }
 
         break;
@@ -355,7 +317,7 @@
     return MLIB_FAILURE;
   }
 
-  return mlib_ImageAffine_alltypes(dst, src, mtx, filter, edge, NULL);
+  return mlib_ImageAffine_alltypes(dst, src, mtx, filter, edge);
 }
 
 /***************************************************************/
--- a/src/java.desktop/share/native/libmlib_image/mlib_ImageAffine.h	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/native/libmlib_image/mlib_ImageAffine.h	Thu May 19 19:46:20 2016 +0000
@@ -162,99 +162,25 @@
 
 /***************************************************************/
 void mlib_ImageAffineEdgeZero(mlib_affine_param *param,
-                              mlib_affine_param *param_e,
-                              const void        *colormap);
+                              mlib_affine_param *param_e);
 
 void mlib_ImageAffineEdgeNearest(mlib_affine_param *param,
                                  mlib_affine_param *param_e);
 
 mlib_status mlib_ImageAffineEdgeExtend_BL(mlib_affine_param *param,
-                                          mlib_affine_param *param_e,
-                                          const void        *colormap);
+                                          mlib_affine_param *param_e);
 
 mlib_status mlib_ImageAffineEdgeExtend_BC(mlib_affine_param *param,
-                                          mlib_affine_param *param_e,
-                                          const void        *colormap);
-
-mlib_status mlib_ImageAffineEdgeExtend_BC2(mlib_affine_param *param,
-                                           mlib_affine_param *param_e,
-                                           const void        *colormap);
-
-/***************************************************************/
-typedef mlib_status (*type_affine_i_fun)(mlib_affine_param *param, const void *colormap);
-
-mlib_status mlib_ImageAffine_u8_u8_i_bl(mlib_affine_param *param,
-                                        const void        *colormap);
-mlib_status mlib_ImageAffine_u8_s16_i_bl(mlib_affine_param *param,
-                                         const void        *colormap);
-mlib_status mlib_ImageAffine_s16_u8_i_bl(mlib_affine_param *param,
-                                         const void        *colormap);
-mlib_status mlib_ImageAffine_s16_s16_i_bl(mlib_affine_param *param,
-                                          const void        *colormap);
-
-mlib_status mlib_ImageAffine_u8_u8_i_bc(mlib_affine_param *param,
-                                        const void        *colormap);
-mlib_status mlib_ImageAffine_u8_s16_i_bc(mlib_affine_param *param,
-                                         const void        *colormap);
-mlib_status mlib_ImageAffine_s16_u8_i_bc(mlib_affine_param *param,
-                                         const void        *colormap);
-mlib_status mlib_ImageAffine_s16_s16_i_bc(mlib_affine_param *param,
-                                          const void        *colormap);
-
-void mlib_ImageAffineEdgeZeroIndex(mlib_affine_param *param,
-                                   mlib_affine_param *param_e,
-                                   const void        *colormap);
-
-void mlib_ImageAffineEdgeExtendIndex_BL(mlib_affine_param *param,
-                                        mlib_affine_param *param_e,
-                                        const void        *colormap);
-
-void mlib_ImageAffineEdgeExtendIndex_BC(mlib_affine_param *param,
-                                        mlib_affine_param *param_e,
-                                        const void        *colormap);
-
-void mlib_ImageAffineEdgeExtendIndex_BC2(mlib_affine_param *param,
-                                         mlib_affine_param *param_e,
-                                         const void        *colormap);
-
-/***************************************************************/
-#define PROT_AFFINEINDEX_BC(ITYPE, LTYPE, NCHAN)                                                 \
-  mlib_status mlib_ImageAffineIndex_##ITYPE##_##LTYPE##_##NCHAN##CH_BC(mlib_affine_param *param, \
-                                                                       const void        *colormap)
-
-PROT_AFFINEINDEX_BC(U8, U8, 3);
-PROT_AFFINEINDEX_BC(U8, S16, 3);
-PROT_AFFINEINDEX_BC(U8, U8, 4);
-PROT_AFFINEINDEX_BC(U8, S16, 4);
-PROT_AFFINEINDEX_BC(S16, U8, 3);
-PROT_AFFINEINDEX_BC(S16, S16, 3);
-PROT_AFFINEINDEX_BC(S16, U8, 4);
-PROT_AFFINEINDEX_BC(S16, S16, 4);
-
-/***************************************************************/
-#define PROT_AFFINEINDEX_BL(ITYPE, LTYPE, NCHAN)                                                 \
-  mlib_status mlib_ImageAffineIndex_##ITYPE##_##LTYPE##_##NCHAN##CH_BL(mlib_affine_param *param, \
-                                                                       const void        *colormap)
-
-PROT_AFFINEINDEX_BL(U8, U8, 3);
-PROT_AFFINEINDEX_BL(U8, S16, 3);
-PROT_AFFINEINDEX_BL(U8, U8, 4);
-PROT_AFFINEINDEX_BL(U8, S16, 4);
-PROT_AFFINEINDEX_BL(S16, U8, 3);
-PROT_AFFINEINDEX_BL(S16, S16, 3);
-PROT_AFFINEINDEX_BL(S16, U8, 4);
-PROT_AFFINEINDEX_BL(S16, S16, 4);
+                                          mlib_affine_param *param_e);
 
 /***************************************************************/
 mlib_status mlib_ImageAffine_alltypes(mlib_image       *dst,
                                       const mlib_image *src,
                                       const mlib_d64   *mtx,
                                       mlib_filter      filter,
-                                      mlib_edge        edge,
-                                      const void       *colormap);
+                                      mlib_edge        edge);
 
 /***************************************************************/
-extern const type_affine_i_fun mlib_AffineFunArr_bl_i[];
 extern const type_affine_fun mlib_AffineFunArr_nn[];
 extern const type_affine_fun mlib_AffineFunArr_bl[];
 extern const type_affine_fun mlib_AffineFunArr_bc[];
--- a/src/java.desktop/share/native/libmlib_image/mlib_ImageAffineEdge.c	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/native/libmlib_image/mlib_ImageAffineEdge.c	Thu May 19 19:46:20 2016 +0000
@@ -73,7 +73,6 @@
  */
 
 #include "mlib_image.h"
-#include "mlib_ImageColormap.h"
 #include "mlib_ImageAffine.h"
 
 /***************************************************************/
@@ -218,97 +217,6 @@
   }
 
 /***************************************************************/
-#define LUT(k, ind) plut[channels*sp[ind] + k]
-
-/***************************************************************/
-#define MLIB_EDGE_INDEX(ITYPE, DTYPE, size)                             \
-  for (j = 0; j < size; j++) {                                          \
-    ySrc = ((Y - 32768) >> MLIB_SHIFT);                                 \
-    xSrc = ((X - 32768) >> MLIB_SHIFT);                                 \
-                                                                        \
-    t = ((X - 32768) & MLIB_MASK) * scale;                              \
-    u = ((Y - 32768) & MLIB_MASK) * scale;                              \
-                                                                        \
-    xDelta = (((xSrc + 1 - srcWidth )) >> MLIB_SIGN_SHIFT) & 1;         \
-    yDelta = (((ySrc + 1 - srcHeight)) >> MLIB_SIGN_SHIFT) & srcStride; \
-                                                                        \
-    xFlag = (xSrc >> (MLIB_SIGN_SHIFT - MLIB_SHIFT));                   \
-    xSrc = xSrc + (1 & xFlag);                                          \
-    xDelta = xDelta &~ xFlag;                                           \
-                                                                        \
-    yFlag = (ySrc >> (MLIB_SIGN_SHIFT - MLIB_SHIFT));                   \
-    ySrc = ySrc + (1 & yFlag);                                          \
-    yDelta = yDelta &~ yFlag;                                           \
-                                                                        \
-    sp = (ITYPE*)lineAddr[ySrc] + xSrc;                                 \
-                                                                        \
-    for (k = 0; k < channels; k++) {                                    \
-      a00  = LUT(k, 0);                                                 \
-      a01  = LUT(k, xDelta);                                            \
-      a10  = LUT(k, yDelta);                                            \
-      a11  = LUT(k, yDelta + xDelta);                                   \
-      pix0 = (a00 * (1 - t) + a01 * t) * (1 - u) +                      \
-             (a10 * (1 - t) + a11 * t) * u;                             \
-                                                                        \
-      pbuff[k] = (mlib_s32)pix0;                                        \
-    }                                                                   \
-    pbuff += channels;                                                  \
-                                                                        \
-    X += dX;                                                            \
-    Y += dY;                                                            \
-  }
-
-/***************************************************************/
-#define MLIB_EDGE_INDEX_u8i(ITYPE, Left, Right) {                              \
-  mlib_u8  *pbuff = buff;                                                      \
-                                                                               \
-  size = Right - Left;                                                         \
-                                                                               \
-  MLIB_EDGE_INDEX(ITYPE, mlib_u8, size);                                       \
-                                                                               \
-  dp = (ITYPE*)data + Left;                                                    \
-                                                                               \
-  if (channels == 3) {                                                         \
-    if (sizeof(ITYPE) == 1) {                                                  \
-      mlib_ImageColorTrue2IndexLine_U8_U8_3 (buff, (void*)dp, size, colormap); \
-    } else {                                                                   \
-      mlib_ImageColorTrue2IndexLine_U8_S16_3(buff, (void*)dp, size, colormap); \
-    }                                                                          \
-  } else {                                                                     \
-    if (sizeof(ITYPE) == 1) {                                                  \
-      mlib_ImageColorTrue2IndexLine_U8_U8_4 (buff, (void*)dp, size, colormap); \
-    } else {                                                                   \
-      mlib_ImageColorTrue2IndexLine_U8_S16_4(buff, (void*)dp, size, colormap); \
-    }                                                                          \
-  }                                                                            \
-}
-
-/***************************************************************/
-#define MLIB_EDGE_INDEX_s16i(ITYPE, Left, Right) {                              \
-  mlib_s16 *pbuff = buff;                                                       \
-                                                                                \
-  size = Right - Left;                                                          \
-                                                                                \
-  MLIB_EDGE_INDEX(ITYPE, mlib_s16, size);                                       \
-                                                                                \
-  dp = (ITYPE*)data + Left;                                                     \
-                                                                                \
-  if (channels == 3) {                                                          \
-    if (sizeof(ITYPE) == 1) {                                                   \
-      mlib_ImageColorTrue2IndexLine_S16_U8_3 (buff, (void*)dp, size, colormap); \
-    } else {                                                                    \
-      mlib_ImageColorTrue2IndexLine_S16_S16_3(buff, (void*)dp, size, colormap); \
-    }                                                                           \
-  } else {                                                                      \
-    if (sizeof(ITYPE) == 1) {                                                   \
-      mlib_ImageColorTrue2IndexLine_S16_U8_4 (buff, (void*)dp, size, colormap); \
-    } else {                                                                    \
-      mlib_ImageColorTrue2IndexLine_S16_S16_4(buff, (void*)dp, size, colormap); \
-    }                                                                           \
-  }                                                                             \
-}
-
-/***************************************************************/
 #define GET_FLT_TBL(X, xf0, xf1, xf2, xf3)                      \
   filterpos = ((X - 32768) >> flt_shift) & flt_mask;            \
   fptr = (mlib_f32 *) ((mlib_u8 *)flt_tbl + filterpos);         \
@@ -424,47 +332,6 @@
   MLIB_EDGE_BC_LINE(TYPE, Left, Right, GET_FLT_BC2)
 
 /***************************************************************/
-#define MLIB_EDGE_INDEX_BC(ITYPE, DTYPE, size)                  \
-  for (j = 0; j < size; j++) {                                  \
-    GET_FLT_TBL(X, xf0, xf1, xf2, xf3);                         \
-    GET_FLT_TBL(Y, yf0, yf1, yf2, yf3);                         \
-                                                                \
-    CALC_SRC_POS(X, Y, 1, srcStride);                           \
-                                                                \
-    sp = (ITYPE*)lineAddr[ySrc] + xSrc;                         \
-                                                                \
-    for (k = 0; k < channels; k++) {                            \
-      c0 = LUT(k, yDelta0 + xDelta0) * xf0 +                    \
-           LUT(k, yDelta0          ) * xf1 +                    \
-           LUT(k, yDelta0 + xDelta1) * xf2 +                    \
-           LUT(k, yDelta0 + xDelta2) * xf3;                     \
-                                                                \
-      c1 = LUT(k, xDelta0) * xf0 +                              \
-           LUT(k, 0      ) * xf1 +                              \
-           LUT(k, xDelta1) * xf2 +                              \
-           LUT(k, xDelta2) * xf3;                               \
-                                                                \
-      c2 = LUT(k, yDelta1 + xDelta0) * xf0 +                    \
-           LUT(k, yDelta1          ) * xf1 +                    \
-           LUT(k, yDelta1 + xDelta1) * xf2 +                    \
-           LUT(k, yDelta1 + xDelta2) * xf3;                     \
-                                                                \
-      c3 = LUT(k, yDelta2 + xDelta0) * xf0 +                    \
-           LUT(k, yDelta2          ) * xf1 +                    \
-           LUT(k, yDelta2 + xDelta1) * xf2 +                    \
-           LUT(k, yDelta2 + xDelta2) * xf3;                     \
-                                                                \
-      val0 = c0*yf0 + c1*yf1 + c2*yf2 + c3*yf3;                 \
-                                                                \
-      SAT##DTYPE(pbuff[k], val0);                               \
-    }                                                           \
-    pbuff += channels;                                          \
-                                                                \
-    X += dX;                                                    \
-    Y += dY;                                                    \
-  }
-
-/***************************************************************/
 #define MLIB_PROCESS_EDGES_ZERO(TYPE) {                         \
   TYPE *dp, *dstLineEnd;                                        \
                                                                 \
@@ -586,16 +453,11 @@
 
 /***************************************************************/
 void mlib_ImageAffineEdgeZero(mlib_affine_param *param,
-                              mlib_affine_param *param_e,
-                              const void        *colormap)
+                              mlib_affine_param *param_e)
 {
   GET_EDGE_PARAMS_ZERO();
   mlib_s32 zero = 0;
 
-  if (colormap != NULL) {
-    zero = mlib_ImageGetLutOffset(colormap);
-  }
-
   switch (type) {
     case MLIB_BYTE:
       MLIB_PROCESS_EDGES_ZERO(mlib_u8);
@@ -654,8 +516,7 @@
 
 /***************************************************************/
 mlib_status mlib_ImageAffineEdgeExtend_BL(mlib_affine_param *param,
-                                          mlib_affine_param *param_e,
-                                          const void        *colormap)
+                                          mlib_affine_param *param_e)
 {
   GET_EDGE_PARAMS();
   mlib_d64 scale = 1.0 / (mlib_d64) MLIB_PREC;
@@ -663,79 +524,6 @@
   mlib_d64 t, u, pix0;
   mlib_d64 a00, a01, a10, a11;
 
-  if (colormap != NULL) {
-    mlib_s32 max_xsize = param_e->max_xsize;
-    mlib_type ltype = mlib_ImageGetLutType(colormap);
-    mlib_d64 *plut = (mlib_d64 *) mlib_ImageGetLutDoubleData(colormap);
-    void *buff;
-
-    channels = mlib_ImageGetLutChannels(colormap);
-    plut -= channels * mlib_ImageGetLutOffset(colormap);
-
-    if (max_xsize == 0) {
-      return MLIB_SUCCESS;
-    }
-
-    if (ltype == MLIB_BYTE) {
-      buff = mlib_malloc(channels * max_xsize);
-    }
-    else if (ltype == MLIB_SHORT) {
-      buff = mlib_malloc(channels * max_xsize * sizeof(mlib_s16));
-    } else {
-      /* Unsupported type of lookup table. Report a failure */
-      return MLIB_FAILURE;
-    }
-
-    if (buff == NULL)
-      return MLIB_FAILURE;
-
-    switch (ltype) {
-      case MLIB_BYTE:
-        switch (type) {
-          case MLIB_BYTE:
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_u8i, mlib_u8);
-            break;
-
-          case MLIB_SHORT:
-            srcStride >>= 1;
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_u8i, mlib_s16);
-            break;
-        default:
-          /* Incompatible image type. Ignore it for now. */
-          break;
-        }
-
-        break;
-
-      case MLIB_SHORT:
-        switch (type) {
-          case MLIB_BYTE:
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_s16i, mlib_u8);
-            break;
-
-          case MLIB_SHORT:
-            srcStride >>= 1;
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_s16i, mlib_s16);
-            break;
-        default:
-          /* Incompatible image type. Ignore it for now. */
-          break;
-        }
-
-        break;
-    default:
-      /* Unsupported type of lookup table.
-       * Can not be here due to check on line 685,
-       * so just ignore it.
-       */
-      break;
-    }
-
-    mlib_free(buff);
-
-    return MLIB_SUCCESS;
-  }
-
   switch (type) {
     case MLIB_BYTE:
       MLIB_PROCESS_EDGES(MLIB_EDGE_BL, mlib_u8);
@@ -775,12 +563,8 @@
 }
 
 /***************************************************************/
-#undef  MLIB_EDGE_INDEX
-#define MLIB_EDGE_INDEX MLIB_EDGE_INDEX_BC
-
 mlib_status mlib_ImageAffineEdgeExtend_BC(mlib_affine_param *param,
-                                          mlib_affine_param *param_e,
-                                          const void        *colormap)
+                                          mlib_affine_param *param_e)
 {
   GET_EDGE_PARAMS();
   mlib_d64 scale = 1.0 / (mlib_d64) MLIB_PREC;
@@ -789,7 +573,6 @@
   mlib_d64 xf0, xf1, xf2, xf3;
   mlib_d64 yf0, yf1, yf2, yf3;
   mlib_d64 c0, c1, c2, c3, val0;
-  mlib_type ltype;
   mlib_filter filter = param->filter;
   mlib_f32 *fptr;
   mlib_f32 const *flt_tbl;
@@ -798,9 +581,7 @@
   mlib_s32 yDelta0, yDelta1, yDelta2;
   mlib_d64 sat;
 
-  ltype = (colormap != NULL) ? mlib_ImageGetLutType(colormap) : type;
-
-  if (ltype == MLIB_BYTE) {
+  if (type == MLIB_BYTE) {
     flt_shift = FLT_SHIFT_U8;
     flt_mask = FLT_MASK_U8;
     flt_tbl = (filter == MLIB_BICUBIC) ? mlib_filters_u8f_bc : mlib_filters_u8f_bc2;
@@ -813,78 +594,6 @@
     sat = (mlib_d64) 0x7FFF8000;                           /* saturation for U16 */
   }
 
-  if (colormap != NULL) {
-    mlib_s32 max_xsize = param_e->max_xsize;
-    mlib_d64 *plut = (mlib_d64 *) mlib_ImageGetLutDoubleData(colormap);
-    void *buff;
-
-    channels = mlib_ImageGetLutChannels(colormap);
-    plut -= channels * mlib_ImageGetLutOffset(colormap);
-
-    if (max_xsize == 0) {
-      return MLIB_SUCCESS;
-    }
-
-    if (ltype == MLIB_BYTE) {
-      buff = mlib_malloc(channels * max_xsize);
-    }
-    else if (ltype == MLIB_SHORT) {
-      buff = mlib_malloc(channels * max_xsize * sizeof(mlib_s16));
-    } else {
-      /* Unsupported type of lookup table. */
-      return MLIB_FAILURE;
-    }
-
-    if (buff == NULL)
-      return MLIB_FAILURE;
-
-    switch (ltype) {
-      case MLIB_BYTE:
-        switch (type) {
-          case MLIB_BYTE:
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_u8i, mlib_u8);
-            break;
-
-          case MLIB_SHORT:
-            srcStride >>= 1;
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_u8i, mlib_s16);
-            break;
-        default:
-          /* Ignore incomatible image type. */
-          break;
-        }
-
-        break;
-
-      case MLIB_SHORT:
-        switch (type) {
-          case MLIB_BYTE:
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_s16i, mlib_u8);
-            break;
-
-          case MLIB_SHORT:
-            srcStride >>= 1;
-            MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_s16i, mlib_s16);
-            break;
-        default:
-          /* Ignore incomatible image type. */
-          break;
-        }
-
-        break;
-
-    default:
-      /* Unsupported type of lookup table.
-       * Can not be here due to check on line 836,
-       * so just ignore it.
-       */
-      break;
-    }
-
-    mlib_free(buff);
-
-    return MLIB_SUCCESS;
-  }
 
   switch (type) {
     case MLIB_BYTE:
--- a/src/java.desktop/share/native/libmlib_image/mlib_ImageCheck.h	Thu May 19 17:48:02 2016 +0000
+++ b/src/java.desktop/share/native/libmlib_image/mlib_ImageCheck.h	Thu May 19 19:46:20 2016 +0000
@@ -82,12 +82,6 @@
     return MLIB_FAILURE;                                        \
   }
 
-#define MLIB_IMAGE_AND_COLORMAP_ARE_COMPAT(image,colormap)                 \
-  if ((mlib_ImageGetChannels(image) != mlib_ImageGetLutChannels(colormap)) \
-    || (mlib_ImageGetLutType(colormap) != mlib_ImageGetType(image))) {     \
-    return MLIB_FAILURE;                                                   \
-  }
-
 #define MLIB_IMAGE_GET_ALL_PARAMS(image, type, nchan, width, height, stride, pdata) \
   type   = mlib_ImageGetType(image);                                                \
   nchan  = mlib_ImageGetChannels(image);                                            \
--- a/src/java.desktop/share/native/libmlib_image/mlib_ImageColorTrue2Index.c	Thu May 19 17:48:02 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,4256 +0,0 @@
-/*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * FUNCTION
- *      mlib_ImageColorTrue2Index - convert a true color image to an indexed
- *                                  color image
- *
- * SYNOPSIS
- *      mlib_status mlib_ImageColorTrue2Index(mlib_image       *dst,
- *                                            const mlib_image *src,
- *                                            const void       *colormap)
- *
- * ARGUMENTS
- *      colormap  Internal data structure for inverse color mapping.
- *      dst       Pointer to destination image.
- *      src       Pointer to source image.
- *
- * DESCRIPTION
- *      Convert a true color image to a pseudo color image with the method
- *      of finding the nearest matched lut entry for each pixel.
- *
- *      The src can be an MLIB_BYTE or MLIB_SHORT image with 3 or 4 channels.
- *      The dst must be a 1-channel MLIB_BYTE or MLIB_SHORT image.
- *
- *      The lut might have either 3 or 4 channels. The type of the lut can be
- *      one of the following:
- *              MLIB_BYTE in, MLIB_BYTE out (i.e., BYTE-to-BYTE)
- *              MLIB_BYTE in, MLIB_SHORT out (i.e., BYTE-to-SHORT)
- *              MLIB_SHORT in, MLIB_SHORT out (i.e., SHORT-to-SHORT)
- *              MLIB_SHORT in, MLIB_BYTE out (i.e., SHORT-to-BYTE)
- *
- *      The src image and the lut must have same number of channels.
- */
-
-#include "mlib_image.h"
-#include "mlib_ImageColormap.h"
-#include "mlib_ImageCheck.h"
-
-/***************************************************************/
-
-/*#define USE_VIS_CODE*/
-
-#ifdef USE_VIS_CODE
-#include "vis_proto.h"
-#define VIS_ALIGNADDR(X, Y)  vis_alignaddr((void *)(X), (Y))
-#endif
-
-/***************************************************************/
-
-#define LUT_BYTE_COLORS_3CHANNELS  1000
-#define LUT_BYTE_COLORS_4CHANNELS  3000
-#define LUT_SHORT_COLORS_3CHANNELS 1000
-#define LUT_SHORT_COLORS_4CHANNELS 1000
-
-/***************************************************************/
-
-#define MAIN_COLORTRUE2INDEX_LOOP( FROM_TYPE, TO_TYPE, NCHANNELS )       \
-  for( y = 0; y < height; y++ )                                          \
-  {                                                                      \
-    mlib_ImageColorTrue2IndexLine_##FROM_TYPE##_##TO_TYPE##_##NCHANNELS( \
-      sdata, ddata, width, colormap );                                   \
-                                                                         \
-    sdata += sstride;                                                    \
-    ddata += dstride;                                                    \
-  }
-
-/***************************************************************/
-
-#define COLOR_CUBE_U8_3_SEARCH( TABLE_POINTER_TYPE, SHIFT, STEP ) \
-{                                                                 \
-  const mlib_u8 *c0, *c1, *c2;                                    \
-  TABLE_POINTER_TYPE *table = s->table;                           \
-  mlib_s32 bits = s->bits;                                        \
-  mlib_s32 nbits = 8 - bits;                                      \
-  mlib_s32 mask = ~( ( 1 << nbits ) - 1 );                        \
-  mlib_s32 j;                                                     \
-                                                                  \
-  c0 = src + SHIFT;                                               \
-  c1 = src + 1 + SHIFT;                                           \
-  c2 = src + 2 + SHIFT;                                           \
-                                                                  \
-  switch( bits )                                                  \
-  {                                                               \
-    case 1:                                                       \
-    case 2:                                                       \
-    {                                                             \
-      mlib_s32 bits0 = 8 - bits;                                  \
-      mlib_s32 bits1 = bits0 - bits;                              \
-      mlib_s32 bits2 = bits1 - bits;                              \
-                                                                  \
-      for( j = 0; j < length; j++ )                               \
-      {                                                           \
-        dst[ j ] = table[ ( ( *c0 & mask ) >> bits2 ) |           \
-          ( ( *c1 & mask ) >> bits1 ) |                           \
-          ( ( *c2 & mask ) >> bits0 ) ];                          \
-                                                                  \
-        c0 += STEP;                                               \
-        c1 += STEP;                                               \
-        c2 += STEP;                                               \
-      }                                                           \
-      break;                                                      \
-    }                                                             \
-    case 3:                                                       \
-    {                                                             \
-      for( j = 0; j < length; j++ )                               \
-      {                                                           \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 1 ) |               \
-          ( ( *c1 & mask ) >> 2 ) |                               \
-          ( ( *c2 & mask ) >> 5 ) ];                              \
-                                                                  \
-        c0 += STEP;                                               \
-        c1 += STEP;                                               \
-        c2 += STEP;                                               \
-      }                                                           \
-      break;                                                      \
-    }                                                             \
-    case 4:                                                       \
-    {                                                             \
-      for( j = 0; j < length; j++ )                               \
-      {                                                           \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 4 ) |               \
-          ( *c1 & mask ) |                                        \
-          ( ( *c2 & mask ) >> 4 ) ];                              \
-                                                                  \
-        c0 += STEP;                                               \
-        c1 += STEP;                                               \
-        c2 += STEP;                                               \
-      }                                                           \
-      break;                                                      \
-    }                                                             \
-    case 5:                                                       \
-    case 6:                                                       \
-    case 7:                                                       \
-    {                                                             \
-      mlib_s32 bits0 = 8 - bits;                                  \
-      mlib_s32 bits1 = bits * 2 - 8;                              \
-      mlib_s32 bits2 = bits1 + bits;                              \
-                                                                  \
-      for( j = 0; j < length; j++ )                               \
-      {                                                           \
-        dst[ j ] = table[ ( ( *c0 & mask ) << bits2 ) |           \
-          ( ( *c1 & mask ) << bits1 ) |                           \
-          ( ( *c2 & mask ) >> bits0 ) ];                          \
-                                                                  \
-        c0 += STEP;                                               \
-        c1 += STEP;                                               \
-        c2 += STEP;                                               \
-      }                                                           \
-      break;                                                      \
-    }                                                             \
-    case 8:                                                       \
-    {                                                             \
-      for( j = 0; j < length; j++ )                               \
-      {                                                           \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 16 ) |              \
-          ( ( *c1 & mask ) << 8 ) |                               \
-          ( *c2 & mask ) ];                                       \
-                                                                  \
-        c0 += STEP;                                               \
-        c1 += STEP;                                               \
-        c2 += STEP;                                               \
-      }                                                           \
-      break;                                                      \
-    }                                                             \
-  }                                                               \
-}
-
-/***************************************************************/
-#define COLOR_CUBE_U8_4_SEARCH( TABLE_TYPE )                    \
-{                                                               \
-  const mlib_u8 *c0, *c1, *c2, *c3;                             \
-  TABLE_TYPE *table = s->table;                                 \
-  mlib_s32 bits = s->bits;                                      \
-  mlib_s32 nbits = 8 - bits;                                    \
-  mlib_s32 mask = ~( ( 1 << nbits ) - 1 );                      \
-  mlib_s32 j;                                                   \
-                                                                \
-  c0 = src;                                                     \
-  c1 = src + 1;                                                 \
-  c2 = src + 2;                                                 \
-  c3 = src + 3;                                                 \
-                                                                \
-  switch( bits )                                                \
-  {                                                             \
-    case 1:                                                     \
-    {                                                           \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( ( *c0 & mask ) >> 4 ) |             \
-          ( ( *c1 & mask ) >> 5 ) |                             \
-          ( ( *c2 & mask ) >> 6 ) |                             \
-          ( ( *c3 & mask ) >> 7 ) ];                            \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-      }                                                         \
-      break;                                                    \
-    }                                                           \
-    case 2:                                                     \
-    {                                                           \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( *c0 & mask ) |                      \
-          ( ( *c1 & mask ) >> 2 ) |                             \
-          ( ( *c2 & mask ) >> 4 ) |                             \
-          ( ( *c3 & mask ) >> 6 ) ];                            \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-          }                                                     \
-      break;                                                    \
-    }                                                           \
-    case 3:                                                     \
-    {                                                           \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 4 ) |             \
-          ( ( *c1 & mask ) << 1 ) |                             \
-          ( ( *c2 & mask ) >> 2 ) |                             \
-          ( ( *c3 & mask ) >> 5 ) ];                            \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-      }                                                         \
-      break;                                                    \
-    }                                                           \
-    case 4:                                                     \
-    {                                                           \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 8 ) |             \
-          ( ( *c1 & mask ) << 4 ) |                             \
-          ( *c2 & mask ) |                                      \
-          ( ( *c3 & mask ) >> 4 ) ];                            \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-      }                                                         \
-      break;                                                    \
-    }                                                           \
-    case 5:                                                     \
-    case 6:                                                     \
-    {                                                           \
-      mlib_s32 bits3 = bits * 4 - 8;                            \
-      mlib_s32 bits2 = bits3 - bits;                            \
-      mlib_s32 bits1 = bits2 - bits;                            \
-      mlib_s32 bits0 = 8 - bits;                                \
-                                                                \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( ( *c0 & mask ) << bits3 ) |         \
-          ( ( *c1 & mask ) << bits2 ) |                         \
-          ( ( *c2 & mask ) << bits1 ) |                         \
-          ( ( *c3 & mask ) >> bits0 ) ];                        \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-      }                                                         \
-      break;                                                    \
-    }                                                           \
-    case 7:                                                     \
-    {                                                           \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 20 ) |            \
-          ( ( *c1 & mask ) << 13 ) |                            \
-          ( ( *c2 & mask ) << 6 ) |                             \
-          ( ( *c3 & mask ) >> 1 ) ];                            \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-      }                                                         \
-      break;                                                    \
-    }                                                           \
-    case 8: /* will never be called */                          \
-    {                                                           \
-      for( j = 0; j < length; j++ )                             \
-      {                                                         \
-        dst[ j ] = table[ ( ( *c0 & mask ) << 24 ) |            \
-          ( ( *c1 & mask ) << 16 ) |                            \
-          ( ( *c2 & mask ) << 8 ) |                             \
-          ( *c3 & mask ) ];                                     \
-                                                                \
-        c0 += 4;                                                \
-        c1 += 4;                                                \
-        c2 += 4;                                                \
-        c3 += 4;                                                \
-      }                                                         \
-      break;                                                    \
-    }                                                           \
-  }                                                             \
-}
-
-/***************************************************************/
-#define COLOR_CUBE_S16_3_SEARCH( TABLE_TYPE, SHIFT, STEP )                 \
-{                                                                          \
-  const mlib_s16 *c0, *c1, *c2;                                            \
-  mlib_s32 bits = s->bits;                                                 \
-  mlib_s32 nbits = 16 - bits;                                              \
-  mlib_s32 mask = ~( ( 1 << nbits ) - 1 );                                 \
-  TABLE_TYPE *table = s->table;                                            \
-  mlib_s32 j;                                                              \
-                                                                           \
-  c0 = src + SHIFT;                                                        \
-  c1 = src + 1 + SHIFT;                                                    \
-  c2 = src + 2 + SHIFT;                                                    \
-                                                                           \
-  switch( bits )                                                           \
-  {                                                                        \
-    case 1:                                                                \
-    case 2:                                                                \
-    case 3:                                                                \
-    case 4:                                                                \
-    case 5:                                                                \
-    {                                                                      \
-      mlib_s32 bits0 = 16 - bits;                                          \
-      mlib_s32 bits1 = bits0 - bits;                                       \
-      mlib_s32 bits2 = bits1 - bits;                                       \
-                                                                           \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) >> bits2 ) | \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) >> bits1 ) |                 \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> bits0 ) ];                \
-                                                                           \
-        c0 += STEP;                                                        \
-        c1 += STEP;                                                        \
-        c2 += STEP;                                                        \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 6:                                                                \
-    case 7:                                                                \
-    {                                                                      \
-      mlib_s32 bits0 = 16 - bits;                                          \
-      mlib_s32 bits1 = bits0 - bits;                                       \
-      mlib_s32 bits2 = bits * 3 - 16;                                      \
-                                                                           \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) << bits2 ) | \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) >> bits1 ) |                 \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> bits0 ) ];                \
-                                                                           \
-        c0 += STEP;                                                        \
-        c1 += STEP;                                                        \
-        c2 += STEP;                                                        \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 8:                                                                \
-    {                                                                      \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) << 8 ) |     \
-          ( ( *c1 - MLIB_S16_MIN ) & mask ) |                              \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> 8 ) ];                    \
-                                                                           \
-        c0 += STEP;                                                        \
-        c1 += STEP;                                                        \
-        c2 += STEP;                                                        \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 9:                                                                \
-    case 10:                                                               \
-    {                                                                      \
-      mlib_s32 bits0 = 16 - bits;                                          \
-      mlib_s32 bits1 = 2 * bits - 16;                                      \
-      mlib_s32 bits2 = bits1 + bits;                                       \
-                                                                           \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) << bits2 ) | \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) << bits1 ) |                 \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> bits0 ) ];                \
-                                                                           \
-        c0 += STEP;                                                        \
-        c1 += STEP;                                                        \
-        c2 += STEP;                                                        \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    /* Other cases may not be considered as the table size will be more    \
-       than 2^32 */                                                        \
-  }                                                                        \
-}
-
-/***************************************************************/
-#define COLOR_CUBE_S16_4_SEARCH( TABLE_TYPE )                              \
-{                                                                          \
-  const mlib_s16 *c0, *c1, *c2, *c3;                                       \
-  TABLE_TYPE *table = s->table;                                            \
-  mlib_s32 bits = s->bits;                                                 \
-  mlib_s32 nbits = 16 - bits;                                              \
-  mlib_s32 mask = ~( ( 1 << nbits ) - 1 );                                 \
-  mlib_s32 j;                                                              \
-                                                                           \
-  c0 = src;                                                                \
-  c1 = src + 1;                                                            \
-  c2 = src + 2;                                                            \
-  c3 = src + 3;                                                            \
-                                                                           \
-  switch( bits )                                                           \
-  {                                                                        \
-    case 1:                                                                \
-    case 2:                                                                \
-    case 3:                                                                \
-    {                                                                      \
-      mlib_s32 bits0 = 16 - bits;                                          \
-      mlib_s32 bits1 = bits0 - bits;                                       \
-      mlib_s32 bits2 = bits1 - bits;                                       \
-      mlib_s32 bits3 = bits2 - bits;                                       \
-                                                                           \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) >> bits3 ) | \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) >> bits2 ) |                 \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> bits1 ) |                 \
-          ( ( ( *c3 - MLIB_S16_MIN ) & mask ) >> bits0 ) ];                \
-                                                                           \
-        c0 += 4;                                                           \
-        c1 += 4;                                                           \
-        c2 += 4;                                                           \
-        c3 += 4;                                                           \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 4:                                                                \
-    {                                                                      \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( *c0 - MLIB_S16_MIN ) & mask ) |              \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) >> 4 ) |                     \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> 8 ) |                     \
-          ( ( ( *c3 - MLIB_S16_MIN ) & mask ) >> 12 ) ];                   \
-                                                                           \
-        c0 += 4;                                                           \
-        c1 += 4;                                                           \
-        c2 += 4;                                                           \
-        c3 += 4;                                                           \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 5:                                                                \
-    {                                                                      \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) << 4 ) |     \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) >> 1 ) |                     \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> 6 ) |                     \
-          ( ( ( *c3 - MLIB_S16_MIN ) & mask ) >> 11 ) ];                   \
-                                                                           \
-        c0 += 4;                                                           \
-        c1 += 4;                                                           \
-        c2 += 4;                                                           \
-        c3 += 4;                                                           \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 6:                                                                \
-    case 7:                                                                \
-    {                                                                      \
-      mlib_s32 bits0 = 16 - bits;                                          \
-      mlib_s32 bits1 = bits0 - bits;                                       \
-      mlib_s32 bits3 = bits * 4 - 16;                                      \
-      mlib_s32 bits2 = bits3 - bits;                                       \
-                                                                           \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) << bits3 ) | \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) << bits2 ) |                 \
-          ( ( ( *c2 - MLIB_S16_MIN ) & mask ) >> bits1 ) |                 \
-          ( ( ( *c3 - MLIB_S16_MIN ) & mask ) >> bits0 ) ];                \
-                                                                           \
-        c0 += 4;                                                           \
-        c1 += 4;                                                           \
-        c2 += 4;                                                           \
-        c3 += 4;                                                           \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    case 8:                                                                \
-    {                                                                      \
-      for( j = 0; j < length; j++ )                                        \
-      {                                                                    \
-        dst[ j ] = table[ ( ( ( *c0 - MLIB_S16_MIN ) & mask ) << 16 ) |    \
-          ( ( ( *c1 - MLIB_S16_MIN ) & mask ) << 8 ) |                     \
-          ( ( *c2 - MLIB_S16_MIN ) & mask ) |                              \
-          ( ( ( *c3 - MLIB_S16_MIN ) & mask ) >> 8 ) ];                    \
-                                                                           \
-        c0 += 4;                                                           \
-        c1 += 4;                                                           \
-        c2 += 4;                                                           \
-        c3 += 4;                                                           \
-      }                                                                    \
-      break;                                                               \
-    }                                                                      \
-    /* Other cases may not be considered as the table size will be more    \
-       than 2^32 */                                                        \
-  }                                                                        \
-}
-
-/***************************************************************/
-#define BINARY_TREE_SEARCH_RIGHT( POSITION, COLOR_MAX, SHIFT )  \
-{                                                               \
-  if( ( distance >= ( ( ( position[ POSITION ] + current_size - \
-    c[ POSITION ] ) * ( position[ POSITION ] + current_size -   \
-    c[ POSITION ] ) ) >> SHIFT ) ) &&                           \
-    ( position[ POSITION ] + current_size != COLOR_MAX ) )      \
-    continue_up = 1;                                            \
-}
-
-/***************************************************************/
-#define BINARY_TREE_EXPLORE_RIGHT_3( POSITION, COLOR_MAX, IMAGE_TYPE,    \
-  FIRST_NEIBOUR, SECOND_NEIBOUR, SUBSTRACTION, SHIFT )                   \
-{                                                                        \
-  if( distance >= ( ( ( position[ POSITION ] + current_size -            \
-    c[ POSITION ] ) * ( position[ POSITION ] +                           \
-      current_size - c[ POSITION ] ) ) >> SHIFT ) )                      \
-  {                                                                      \
-    if( distance < ( ( ( COLOR_MAX - c[ POSITION ] ) *                   \
-      ( COLOR_MAX - c[ POSITION ] ) ) >> SHIFT ) )                       \
-    {                                                                    \
-      if( distance < ( ( ( position[ POSITION ] +                        \
-        current_size * 2 - c[ POSITION ] ) *                             \
-        ( position[ POSITION ] + current_size * 2 -                      \
-          c[ POSITION ] ) ) >> SHIFT ) )                                 \
-      {                                                                  \
-        /* Check only a part of quadrant */                              \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_corner += 1;                                               \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_left_##IMAGE_TYPE##_3(          \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] + current_size, pass - 1, POSITION ); \
-      }                                                                  \
-      else /* Check whole quadrant */                                    \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_corner += 2;                                               \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_3(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], p );         \
-      }                                                                  \
-    }                                                                    \
-    else /* Cell is on the edge of the space */                          \
-    {                                                                    \
-      if( position[ POSITION ] + current_size * 2 ==                     \
-        COLOR_MAX )                                                      \
-      {                                                                  \
-        /* Check only a part of quadrant */                              \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_corner += 1;                                               \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_left_##IMAGE_TYPE##_3(          \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] + current_size,                       \
-              pass - 1, POSITION );                                      \
-      }                                                                  \
-      else /* Check whole quadrant */                                    \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_corner += 2;                                               \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_3(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], p );         \
-      }                                                                  \
-    }                                                                    \
-  }                                                                      \
-}
-
-/***************************************************************/
-#define BINARY_TREE_EXPLORE_RIGHT_4( POSITION, COLOR_MAX, IMAGE_TYPE,    \
-  FIRST_NEIBOUR, SECOND_NEIBOUR, THIRD_NEIBOUR, SUBSTRACTION, SHIFT )    \
-{                                                                        \
-  if( distance >= ( ( ( position[ POSITION ] + current_size -            \
-    c[ POSITION ] ) * ( position[ POSITION ] +                           \
-      current_size - c[ POSITION ] ) ) >> SHIFT ) )                      \
-  {                                                                      \
-    if( distance < ( ( ( COLOR_MAX - c[ POSITION ] ) *                   \
-      ( COLOR_MAX - c[ POSITION ] ) ) >> SHIFT ) )                       \
-    {                                                                    \
-      if( distance < ( ( ( position[ POSITION ] +                        \
-        current_size * 2 - c[ POSITION ] ) *                             \
-        ( position[ POSITION ] + current_size * 2 -                      \
-          c[ POSITION ] ) ) >> SHIFT ) )                                 \
-      {                                                                  \
-        /* Check only a part of quadrant */                              \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 1;                            \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_left_##IMAGE_TYPE##_4(          \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] + current_size, pass - 1, POSITION ); \
-      }                                                                  \
-      else /* Check whole quadrant */                                    \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 2;                            \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_4(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], c[ 3 ], p ); \
-      }                                                                  \
-    }                                                                    \
-    else /* Cell is on the edge of the space */                          \
-    {                                                                    \
-      if( position[ POSITION ] + current_size * 2 ==                     \
-        COLOR_MAX )                                                      \
-      {                                                                  \
-        /* Check only a part of quadrant */                              \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 1;                            \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_left_##IMAGE_TYPE##_4(          \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] + current_size,                       \
-              pass - 1, POSITION );                                      \
-      }                                                                  \
-      else /* Check whole quadrant */                                    \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 2;                            \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_4(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], c[ 3 ], p ); \
-      }                                                                  \
-    }                                                                    \
-  }                                                                      \
-}
-
-/***************************************************************/
-#define BINARY_TREE_SEARCH_LEFT( POSITION, SHIFT )                \
-{                                                                 \
-  if( ( distance > ( ( ( position[ POSITION ] - c[ POSITION ] ) * \
-    ( position[ POSITION ] - c[ POSITION ] ) ) >> SHIFT ) )  &&   \
-    position[ POSITION ] )                                        \
-    continue_up = 1;                                              \
-}
-
-/***************************************************************/
-#define BINARY_TREE_EXPLORE_LEFT_3( POSITION, IMAGE_TYPE,                \
-  FIRST_NEIBOUR, SECOND_NEIBOUR, SUBSTRACTION, SHIFT )                   \
-{                                                                        \
-  if( distance >                                                         \
-    ( ( ( c[ POSITION ] - position[ POSITION ] ) *                       \
-    ( c[ POSITION ] - position[ POSITION ] ) ) >> SHIFT ) )              \
-  {                                                                      \
-    if( distance <= ( ( c[ POSITION ] * c[ POSITION ] ) >> SHIFT ) )     \
-    {                                                                    \
-      if( distance <= ( ( ( c[ POSITION ] + current_size -               \
-        position[ POSITION ] ) *                                         \
-        ( c[ POSITION ] + current_size -                                 \
-          position[ POSITION ] ) ) >> SHIFT ) )                          \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_corner += 1;                                               \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_right_##IMAGE_TYPE##_3(         \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] - current_size, pass - 1, POSITION ); \
-      }                                                                  \
-      else /* Check whole quadrant */                                    \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_corner += 2;                                               \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_3(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], p );         \
-      }                                                                  \
-    }                                                                    \
-    else                                                                 \
-    {                                                                    \
-      if( !( position[ POSITION ] - current_size ) )                     \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_corner += 1;                                               \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_right_##IMAGE_TYPE##_3(         \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] - current_size, pass - 1, POSITION ); \
-      }                                                                  \
-      else                                                               \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_corner += 2;                                               \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_3(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], p );         \
-      }                                                                  \
-    }                                                                    \
-  }                                                                      \
-}
-
-/***************************************************************/
-#define BINARY_TREE_EXPLORE_LEFT_4( POSITION, IMAGE_TYPE,                \
-  FIRST_NEIBOUR, SECOND_NEIBOUR, THIRD_NEIBOUR, SUBSTRACTION, SHIFT )    \
-{                                                                        \
-  if( distance >                                                         \
-    ( ( ( c[ POSITION ] - position[ POSITION ] ) *                       \
-    ( c[ POSITION ] - position[ POSITION ] ) ) >> SHIFT ) )              \
-  {                                                                      \
-    if( distance <= ( ( c[ POSITION ] * c[ POSITION ] ) >> SHIFT ) )     \
-    {                                                                    \
-      if( distance <= ( ( ( c[ POSITION ] + current_size -               \
-        position[ POSITION ] ) *                                         \
-        ( c[ POSITION ] + current_size -                                 \
-          position[ POSITION ] ) ) >> SHIFT ) )                          \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 1;                            \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_right_##IMAGE_TYPE##_4(         \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] - current_size, pass - 1, POSITION ); \
-      }                                                                  \
-      else /* Check whole quadrant */                                    \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 2;                            \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_4(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], c[ 3 ], p ); \
-      }                                                                  \
-    }                                                                    \
-    else                                                                 \
-    {                                                                    \
-      if( !( position[ POSITION ] - current_size ) )                     \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 1;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 1;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 1;                            \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Only a part of quadrant needs checking */                   \
-          distance =                                                     \
-            mlib_search_quadrant_part_to_right_##IMAGE_TYPE##_4(         \
-              node->contents.quadrants[ qq ],                            \
-              distance, &found_color, c, p,                              \
-              position[ POSITION ] - current_size, pass - 1, POSITION ); \
-      }                                                                  \
-      else                                                               \
-      {                                                                  \
-        mlib_s32 qq = q ^ ( 1 << POSITION );                             \
-                                                                         \
-        check_neibours[ FIRST_NEIBOUR ] += 2;                            \
-        check_neibours[ SECOND_NEIBOUR ] += 2;                           \
-        check_neibours[ THIRD_NEIBOUR ] += 2;                            \
-        continue_up = 1;                                                 \
-        if( node->tag & ( 1 << qq ) )                                    \
-        {                                                                \
-          /* Here is another color cell.                                 \
-             Check the distance */                                       \
-          mlib_s32 new_found_color =                                     \
-            node->contents.index[ qq ];                                  \
-          mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],                \
-            p[ 0 ][ new_found_color ] - SUBSTRACTION, c[ 1 ],            \
-            p[ 1 ][ new_found_color ] - SUBSTRACTION, c[ 2 ],            \
-            p[ 2 ][ new_found_color ] - SUBSTRACTION, c[ 3 ],            \
-            p[ 3 ][ new_found_color ] - SUBSTRACTION, SHIFT );           \
-                                                                         \
-          if( newdistance < distance )                                   \
-          {                                                              \
-            found_color = new_found_color;                               \
-            distance = newdistance;                                      \
-          }                                                              \
-        }                                                                \
-        else if( node->contents.quadrants[ qq ] )                        \
-          /* Here is a full node. Just explore it */                     \
-          distance = mlib_search_quadrant_##IMAGE_TYPE##_4(              \
-            node->contents.quadrants[ qq ],                              \
-            distance, &found_color, c[ 0 ], c[ 1 ], c[ 2 ], c[ 3 ], p ); \
-      }                                                                  \
-    }                                                                    \
-  }                                                                      \
-}
-
-/***************************************************************/
-#define CHECK_QUADRANT_U8_3( qq )                               \
-{                                                               \
-  if( node->tag & ( 1 << qq ) )                                 \
-  {                                                             \
-    /* Here is another color cell. Check the distance */        \
-    mlib_s32 new_found_color = node->contents.index[ qq ];      \
-    mlib_u32 newdistance = FIND_DISTANCE_3( c[ 0 ],             \
-      p[ 0 ][ new_found_color ], c[ 1 ],                        \
-      p[ 1 ][ new_found_color ], c[ 2 ],                        \
-      p[ 2 ][ new_found_color ], 0 );                           \
-                                                                \
-    if( newdistance < distance )                                \
-    {                                                           \
-      found_color = new_found_color;                            \
-      distance = newdistance;                                   \
-    }                                                           \
-  }                                                             \
-  else if( node->contents.quadrants[ qq ] )                     \
-    /* Here is a full node. Just explore it all */              \
-    distance = mlib_search_quadrant_U8_3(                       \
-      node->contents.quadrants[ qq ], distance, &found_color,   \
-      c[ 0 ], c[ 1 ], c[ 2 ], p );                              \
-/* Else there is just an empty cell */                          \
-}
-
-/***************************************************************/
-#define CHECK_QUADRANT_S16_3( qq )                              \
-{                                                               \
-  if( node->tag & ( 1 << qq ) )                                 \
-  {                                                             \
-    /* Here is another color cell. Check the distance */        \
-    mlib_s32 new_found_color = node->contents.index[ qq ];      \
-    mlib_u32 palc0, palc1, palc2, newdistance;                  \
-                                                                \
-    palc0 = p[ 0 ][ new_found_color ] - MLIB_S16_MIN;           \
-    palc1 = p[ 1 ][ new_found_color ] - MLIB_S16_MIN;           \
-    palc2 = p[ 2 ][ new_found_color ] - MLIB_S16_MIN;           \
-                                                                \
-    newdistance = FIND_DISTANCE_3( c[ 0 ], palc0,               \
-      c[ 1 ], palc1,                                            \
-      c[ 2 ], palc2, 2 );                                       \
-                                                                \
-    if( newdistance < distance )                                \
-    {                                                           \
-      found_color = new_found_color;                            \
-      distance = newdistance;                                   \
-    }                                                           \
-  }                                                             \
-  else if( node->contents.quadrants[ qq ] )                     \
-    /* Here is a full node. Just explore it all */              \
-    distance = mlib_search_quadrant_S16_3(                      \
-      node->contents.quadrants[ qq ], distance, &found_color,   \
-      c[ 0 ], c[ 1 ], c[ 2 ], p );                              \
-/* Else there is just an empty cell */                          \
-}
-
-/***************************************************************/
-#define BINARY_TREE_SEARCH_3( SOURCE_IMAGE, POINTER_TYPE, BITS,              \
-  COLOR_MAX, SUBTRACTION, POINTER_SHIFT, STEP, SHIFT )                       \
-{                                                                            \
-  const POINTER_TYPE *channels[ 3 ], *p[ 3 ];                                \
-  mlib_u32 c[ 3 ];                                                           \
-  mlib_s32 j;                                                                \
-                                                                             \
-  p[ 0 ] = s->lut[ 0 ];                                                      \
-  p[ 1 ] = s->lut[ 1 ];                                                      \
-  p[ 2 ] = s->lut[ 2 ];                                                      \
-  channels[ 0 ] = src + POINTER_SHIFT;                                       \
-  channels[ 1 ] = src + 1 + POINTER_SHIFT;                                   \
-  channels[ 2 ] = src + 2 + POINTER_SHIFT;                                   \
-                                                                             \
-  for( j = 0; j < length; j++ )                                              \
-  {                                                                          \
-    mlib_s32 pass = BITS - 1;                                                \
-    mlib_u32 position[ 3 ] = { 0, 0, 0 };                                    \
-    mlib_s32 we_found_it = 0;                                                \
-    struct lut_node_3 *node = s->table;                                      \
-    /* Stack pointer pointers to the first free element of stack. */         \
-    /* The node we are in is in the `node' */                                \
-    struct                                                                   \
-    {                                                                        \
-      struct lut_node_3 *node;                                               \
-      mlib_s32 q;                                                            \
-    } stack[ BITS ];                                                         \
-    mlib_s32 stack_pointer = 0;                                              \
-                                                                             \
-    c[ 0 ] = *channels[ 0 ] - SUBTRACTION;                                   \
-    c[ 1 ] = *channels[ 1 ] - SUBTRACTION;                                   \
-    c[ 2 ] = *channels[ 2 ] - SUBTRACTION;                                   \
-                                                                             \
-    do                                                                       \
-    {                                                                        \
-      mlib_s32 q;                                                            \
-      mlib_u32 current_size = 1 << pass;                                     \
-                                                                             \
-      q = ( ( c[ 0 ] >> pass ) & 1 ) |                                       \
-        ( ( ( c[ 1 ] << 1 ) >> pass ) & 2 ) |                                \
-        ( ( ( c[ 2 ] << 2 ) >> pass ) & 4 );                                 \
-                                                                             \
-      position[ 0 ] |= c[ 0 ] & current_size;                                \
-      position[ 1 ] |= c[ 1 ] & current_size;                                \
-      position[ 2 ] |= c[ 2 ] & current_size;                                \
-                                                                             \
-      if( node->tag & ( 1 << q ) )                                           \
-      {                                                                      \
-        /*                                                                   \
-          Here is a cell with one color. We need to be sure it's             \
-          the one that is the closest to our color                           \
-        */                                                                   \
-        mlib_s32 palindex = node->contents.index[ q ];                       \
-        mlib_u32 palc[ 3 ];                                                  \
-        mlib_s32 identical;                                                  \
-                                                                             \
-        palc[ 0 ] = p[ 0 ][ palindex ] - SUBTRACTION;                        \
-        palc[ 1 ] = p[ 1 ][ palindex ] - SUBTRACTION;                        \
-        palc[ 2 ] = p[ 2 ][ palindex ] - SUBTRACTION;                        \
-                                                                             \
-        identical = ( palc[ 0 ] - c[ 0 ] ) | ( palc[ 1 ] - c[ 1 ] ) |        \
-          ( palc[ 2 ] - c[ 2 ] );                                            \
-                                                                             \
-        if( !identical || BITS - pass == bits )                              \
-        {                                                                    \
-          /* Oh, here it is :) */                                            \
-          dst[ j ] = palindex + s->offset;                                   \
-          we_found_it = 1;                                                   \
-        }                                                                    \
-        else                                                                 \
-        {                                                                    \
-          mlib_u32 distance;                                                 \
-          /* First index is the channel, second is the number of the         \
-             side */                                                         \
-          mlib_s32 found_color;                                              \
-          mlib_s32 continue_up;                                              \
-                                                                             \
-          distance = FIND_DISTANCE_3( c[ 0 ], palc[ 0 ],                     \
-            c[ 1 ], palc[ 1 ], c[ 2 ], palc[ 2 ], SHIFT );                   \
-          found_color = palindex;                                            \
-                                                                             \
-          do                                                                 \
-          {                                                                  \
-            mlib_s32 check_corner;                                           \
-                                                                             \
-            /*                                                               \
-              Neibours are enumerated in a cicle:                            \
-              0 - between quadrants 0 and 1,                                 \
-              1 - between quadrants 1 and 2 and                              \
-              2 - between quadrants 2 and 0                                  \
-            */                                                               \
-            mlib_s32 check_neibours[ 3 ];                                    \
-                                                                             \
-            /*                                                               \
-              Others are three two neibour quadrants                         \
-                                                                             \
-              Side number is [ <number of the coordinate >][ <the bit        \
-              in the quadrant number of the corner, corresponding to         \
-              this coordinate> ], e.g. 2 is 0..010b, so the sides it has     \
-              near are:                                                      \
-              [ 0 (coordinate number) ][ 0 (bit 0 in the number) ]           \
-              [ 1 (coordinate number) ][ 1 (bit 1 in the number) ]           \
-                                                                             \
-              Now we can look in the three nearest quadrants. Do             \
-              we really need it ? Check it.                                  \
-            */                                                               \
-                                                                             \
-            check_corner = check_neibours[ 0 ] = check_neibours[ 1 ] =       \
-              check_neibours[ 2 ] = 0;                                       \
-            continue_up = 0;                                                 \
-                                                                             \
-            if( q & 1 )                                                      \
-            {                                                                \
-              BINARY_TREE_EXPLORE_LEFT_3( 0, SOURCE_IMAGE, 2, 0,             \
-                SUBTRACTION, SHIFT );                                        \
-            }                                                                \
-            else                                                             \
-            {                                                                \
-              BINARY_TREE_EXPLORE_RIGHT_3( 0, COLOR_MAX, SOURCE_IMAGE, 2, 0, \
-                SUBTRACTION, SHIFT );                                        \
-            }                                                                \
-                                                                             \
-            if( q & 2 )                                                      \
-            {                                                                \
-              BINARY_TREE_EXPLORE_LEFT_3( 1, SOURCE_IMAGE, 0, 1,             \
-                SUBTRACTION, SHIFT );                                        \
-            }                                                                \
-            else                                                             \
-            {                                                                \
-              BINARY_TREE_EXPLORE_RIGHT_3( 1, COLOR_MAX, SOURCE_IMAGE, 0, 1, \
-                SUBTRACTION, SHIFT );                                        \
-            }                                                                \
-                                                                             \
-            if( q & 4 )                                                      \
-            {                                                                \
-              BINARY_TREE_EXPLORE_LEFT_3( 2, SOURCE_IMAGE, 1, 2,             \
-                SUBTRACTION, SHIFT );                                        \
-            }                                                                \
-            else                                                             \
-            {                                                                \
-              BINARY_TREE_EXPLORE_RIGHT_3( 2, COLOR_MAX, SOURCE_IMAGE, 1, 2, \
-                SUBTRACTION, SHIFT );                                        \
-            }                                                                \
-                                                                             \
-            if( check_neibours[ 0 ] >= 2 )                                   \
-            {                                                                \
-              mlib_s32 qq = q ^ 3;                                           \
-              CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                       \
-            }                                                                \
-                                                                             \
-            if( check_neibours[ 1 ] >= 2 )                                   \
-            {                                                                \
-              mlib_s32 qq = q ^ 6;                                           \
-              CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                       \
-            }                                                                \
-                                                                             \
-            if( check_neibours[ 2 ] >= 2 )                                   \
-            {                                                                \
-              mlib_s32 qq = q ^ 5;                                           \
-              CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                       \
-            }                                                                \
-                                                                             \
-            if( check_corner >= 3 )                                          \
-            {                                                                \
-              mlib_s32 qq = q ^ 7;                                           \
-              CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                       \
-            }                                                                \
-                                                                             \
-            if( q & 1 )                                                      \
-            {                                                                \
-              BINARY_TREE_SEARCH_RIGHT( 0, COLOR_MAX, SHIFT );               \
-            }                                                                \
-            else                                                             \
-            {                                                                \
-              BINARY_TREE_SEARCH_LEFT( 0, SHIFT );                           \
-            }                                                                \
-                                                                             \
-            if( q & 2 )                                                      \
-            {                                                                \
-              BINARY_TREE_SEARCH_RIGHT( 1, COLOR_MAX, SHIFT );               \
-            }                                                                \
-            else                                                             \
-            {                                                                \
-              BINARY_TREE_SEARCH_LEFT( 1, SHIFT );                           \
-            }                                                                \
-                                                                             \
-            if( q & 4 )                                                      \
-            {                                                                \
-              BINARY_TREE_SEARCH_RIGHT( 2, COLOR_MAX, SHIFT );               \
-            }                                                                \
-            else                                                             \
-            {                                                                \
-              BINARY_TREE_SEARCH_LEFT( 2, SHIFT );                           \
-            }                                                                \
-                                                                             \
-            position[ 0 ] &= ~( c[ 0 ] & current_size );                     \
-            position[ 1 ] &= ~( c[ 1 ] & current_size );                     \
-            position[ 2 ] &= ~( c[ 2 ] & current_size );                     \
-                                                                             \
-            current_size <<= 1;                                              \
-                                                                             \
-            pass++;                                                          \
-                                                                             \
-            stack_pointer--;                                                 \
-            q = stack[ stack_pointer ].q;                                    \
-            node = stack[ stack_pointer ].node;                              \
-          } while( continue_up );                                            \
-                                                                             \
-          dst[ j ] = found_color + s->offset;                                \
-                                                                             \
-          we_found_it = 1;                                                   \
-        }                                                                    \
-      }                                                                      \
-      else if( node->contents.quadrants[ q ] )                               \
-      {                                                                      \
-        /* Descend one level */                                              \
-        stack[ stack_pointer ].node = node;                                  \
-        stack[ stack_pointer++ ].q = q;                                      \
-        node = node->contents.quadrants[ q ];                                \
-      }                                                                      \
-      else                                                                   \
-      {                                                                      \
-        /* Found the empty quadrant. Look around */                          \
-        mlib_u32 distance = MLIB_U32_MAX;                                    \
-        mlib_s32 found_color;                                                \
-        mlib_s32 continue_up;                                                \
-                                                                             \
-        /*                                                                   \
-          As we had come to this level, it is warranted that there           \
-          are other points on this level near the empty quadrant             \
-        */                                                                   \
-        do                                                                   \
-        {                                                                    \
-          mlib_s32 check_corner;                                             \
-          mlib_s32 check_neibours[ 3 ];                                      \
-                                                                             \
-          check_corner = check_neibours[ 0 ] = check_neibours[ 1 ] =         \
-            check_neibours[ 2 ] = 0;                                         \
-          continue_up = 0;                                                   \
-                                                                             \
-          if( q & 1 )                                                        \
-          {                                                                  \
-            BINARY_TREE_EXPLORE_LEFT_3( 0, SOURCE_IMAGE, 2, 0,               \
-              SUBTRACTION, SHIFT );                                          \
-          }                                                                  \
-          else                                                               \
-          {                                                                  \
-            BINARY_TREE_EXPLORE_RIGHT_3( 0, COLOR_MAX, SOURCE_IMAGE, 2, 0,   \
-              SUBTRACTION, SHIFT );                                          \
-          }                                                                  \
-                                                                             \
-          if( q & 2 )                                                        \
-          {                                                                  \
-            BINARY_TREE_EXPLORE_LEFT_3( 1, SOURCE_IMAGE, 0, 1,               \
-              SUBTRACTION, SHIFT );                                          \
-          }                                                                  \
-          else                                                               \
-          {                                                                  \
-            BINARY_TREE_EXPLORE_RIGHT_3( 1, COLOR_MAX, SOURCE_IMAGE, 0, 1,   \
-              SUBTRACTION, SHIFT );                                          \
-          }                                                                  \
-                                                                             \
-          if( q & 4 )                                                        \
-          {                                                                  \
-            BINARY_TREE_EXPLORE_LEFT_3( 2, SOURCE_IMAGE, 1, 2,               \
-              SUBTRACTION, SHIFT );                                          \
-          }                                                                  \
-          else                                                               \
-          {                                                                  \
-            BINARY_TREE_EXPLORE_RIGHT_3( 2, COLOR_MAX, SOURCE_IMAGE, 1, 2,   \
-              SUBTRACTION, SHIFT );                                          \
-          }                                                                  \
-                                                                             \
-          if( check_neibours[ 0 ] >= 2 )                                     \
-          {                                                                  \
-            mlib_s32 qq = q ^ 3;                                             \
-            CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                         \
-          }                                                                  \
-                                                                             \
-          if( check_neibours[ 1 ] >= 2 )                                     \
-          {                                                                  \
-            mlib_s32 qq = q ^ 6;                                             \
-            CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                         \
-          }                                                                  \
-                                                                             \
-          if( check_neibours[ 2 ] >= 2 )                                     \
-          {                                                                  \
-            mlib_s32 qq = q ^ 5;                                             \
-            CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                         \
-          }                                                                  \
-                                                                             \
-          if( check_corner >= 3 )                                            \
-          {                                                                  \
-            mlib_s32 qq = q ^ 7;                                             \
-            CHECK_QUADRANT_##SOURCE_IMAGE##_3( qq );                         \
-          }                                                                  \
-                                                                             \
-          if( q & 1 )                                                        \
-          {                                                                  \
-            BINARY_TREE_SEARCH_RIGHT( 0, COLOR_MAX, SHIFT );                 \
-          }                                                                  \
-          else                                                               \
-          {                                                                  \
-            BINARY_TREE_SEARCH_LEFT( 0, SHIFT );                             \
-          }                                                                  \
-                                                                             \
-          if( q & 2 )                                                        \
-          {                                                                  \
-            BINARY_TREE_SEARCH_RIGHT( 1, COLOR_MAX, SHIFT );                 \
-          }                                                                  \
-          else                                                               \
-          {                                                                  \
-            BINARY_TREE_SEARCH_LEFT( 1, SHIFT );                             \
-          }                                                                  \
-                                                                             \
-          if( q & 4 )                                                        \
-          {                                                                  \
-            BINARY_TREE_SEARCH_RIGHT( 2, COLOR_MAX, SHIFT );                 \
-          }                                                                  \
-          else                                                               \
-          {                                                                  \
-            BINARY_TREE_SEARCH_LEFT( 2, SHIFT );                             \
-          }                                                                  \
-                                                                             \
-          position[ 0 ] &= ~( c[ 0 ] & current_size );                       \
-          position[ 1 ] &= ~( c[ 1 ] & current_size );                       \
-          position[ 2 ] &= ~( c[ 2 ] & current_size );                       \
-                                                                             \
-          current_size <<= 1;                                                \
-                                                                             \
-          pass++;                                                            \
-                                                                             \
-          stack_pointer--;                                                   \
-          q = stack[ stack_pointer ].q;                                      \
-          node = stack[ stack_pointer ].node;                                \
-        } while( continue_up );                                              \
-                                                                             \
-        dst[ j ] = found_color + s->offset;                                  \
-        we_found_it = 1;                                                     \
-      }                                                                      \
-                                                                             \
-      pass--;                                                                \
-                                                                             \
-    } while( !we_found_it );                                                 \
-                                                                             \
-    channels[ 0 ] += STEP;                                                   \
-    channels[ 1 ] += STEP;                                                   \
-    channels[ 2 ] += STEP;                                                   \
-  }                                                                          \
-}
-
-/***************************************************************/
-#define CHECK_QUADRANT_U8_4( qq )                               \
-{                                                               \
-  if( node->tag & ( 1 << qq ) )                                 \
-  {                                                             \
-    /* Here is another color cell. Check the distance */        \
-    mlib_s32 new_found_color = node->contents.index[ qq ];      \
-    mlib_u32 newdistance = FIND_DISTANCE_4( c[ 0 ],             \
-      p[ 0 ][ new_found_color ], c[ 1 ],                        \
-      p[ 1 ][ new_found_color ], c[ 2 ],                        \
-      p[ 2 ][ new_found_color ], c[ 3 ],                        \
-      p[ 3 ][ new_found_color ], 0 );                           \
-                                                                \
-    if( newdistance < distance )                                \
-    {                                                           \
-      found_color = new_found_color;                            \
-      distance = newdistance;                                   \
-    }                                                           \
-  }                                                             \
-  else if( node->contents.quadrants[ qq ] )                     \
-    /* Here is a full node. Just explore it all */              \
-    distance = mlib_search_quadrant_U8_4(                       \
-      node->contents.quadrants[ qq ], distance, &found_color,   \
-      c[ 0 ], c[ 1 ], c[ 2 ], c[ 3 ], p );                      \
-/* Else there is just an empty cell */                          \
-}
-
-/***************************************************************/
-#define CHECK_QUADRANT_S16_4( qq )                              \
-{                                                               \
-  if( node->tag & ( 1 << qq ) )                                 \
-  {                                                             \
-    /* Here is another color cell. Check the distance */        \
-    mlib_s32 new_found_color = node->contents.index[ qq ];      \
-    mlib_u32 palc0, palc1, palc2, palc3, newdistance;           \