changeset 13306:9da3ff5cd435 jdk8u202-b01

Merge
author aefimov
date Mon, 15 Oct 2018 15:05:59 +0100
parents f1b4a14c8e04 (current diff) efd8398ea738 (diff)
children b5c6ff776bee 4ff26197d540
files .hgtags THIRD_PARTY_README test/sun/security/tools/jarsigner/warnings.sh
diffstat 86 files changed, 4325 insertions(+), 1915 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Sun Oct 14 19:45:50 2018 -0400
+++ b/.hgtags	Mon Oct 15 15:05:59 2018 +0100
@@ -857,6 +857,13 @@
 95df717479b19f5ea244afc67434827f2f851287 jdk8u162-b11
 ddae5cb11d6c04130b8002b852bc7f80e0c8bcd2 jdk8u162-b12
 8e40acfcc41a631f5922824712d4336742652eac jdk8u162-b31
+c00bdbbd9a77150f565298af9c305d7e6863eb59 jdk8u162-b32
+70a653814e61a5552312345308b85330fa8f27bc jdk8u162-b33
+f1f949ac13549c6fb3766279848539b124ad835e jdk8u162-b34
+b3de2b1e82fb2427cd40bb230aa26d9b7d8fb09c jdk8u162-b35
+e03fff22900242d92a97839a9c095bb106bdc68f jdk8u162-b36
+19696e8204b0e77e0f10af106c384b7ba6dd5bda jdk8u162-b37
+305c40e81a6fd59699036d4c35d8994f8501f116 jdk8u162-b38
 b6195815c4bbbf275f1aefd337d805eb66f2b5b8 jdk8u171-b00
 f1792a59f1fa20e47fe5d4561754012440564bec jdk8u171-b01
 cac020298633fc736f5e21afddf00145665ef0a7 jdk8u171-b02
@@ -875,6 +882,8 @@
 db8272cb8c99eea536a66c4c368c4bf2bf013a81 jdk8u172-b02
 bd24ee3a9a0494121fd1d96c308b9738f585001b jdk8u172-b03
 cf952b84daa1e74403a4d1df541c0ecca830717d jdk8u172-b04
+e7e27f446209924f66a4bf86738f3e5f2fbbef5f jdk8u181-b00
+a8746b41e23a1deda3d0f41ed2eca3d3a4cc74de jdk8u191-b00
 076daed81c0a851f6d13fac538834ac465cdc122 jdk8u172-b05
 94491d0dc59590535339a2ffae510166bb16f34c jdk8u172-b06
 7e9eeb74e84beb6d8a6f562441eb7dd0ab0befa9 jdk8u172-b07
@@ -885,6 +894,16 @@
 d902fae6241006af3c4cfc4ce82ebcb3efb9d725 jdk8u181-b01
 baac18e216fb47b4cfa04169b3c3de58d667de7c jdk8u181-b02
 d237c59d14e1c1fb1f750e9cdabcea6e711f4d34 jdk8u181-b03
+f3185b46a35b82727f39d52ac7fad7c4c78ddcdd jdk8u172-b31
+0939503b7477ba081484c54f26f177f9a66d92e4 jdk8u172-b32
+f4b138a6c95cf17f6138598fe04a90dfe1086bf4 jdk8u172-b33
+93b4d31ee70576a45a87607e2f5474d90ba31653 jdk8u172-b34
+6b4e239c74929b86b46113e92fe36d355157e235 jdk8u172-b35
+010852525831e0e88f622167d615438b82002e1f jdk8u172-b36
+9ac2466ffdbb1b9d9005b50aa633a5986617a002 jdk8u172-b37
+d902fae6241006af3c4cfc4ce82ebcb3efb9d725 jdk8u181-b01
+baac18e216fb47b4cfa04169b3c3de58d667de7c jdk8u181-b02
+d237c59d14e1c1fb1f750e9cdabcea6e711f4d34 jdk8u181-b03
 6eeca4fb7748e8bdca4afbd6785b04376b1d44cc jdk8u181-b04
 f34c24087b0e6f52391f491d6c3a608616d1db2c jdk8u181-b05
 076f5fd6258846fce7010a598de2c7583628bb1e jdk8u181-b06
@@ -895,9 +914,34 @@
 112f3576f12e24d5e35d8d31782698e7d9a8fa52 jdk8u181-b11
 22e01e7c5c39bfa3f5e2d18be76c7bf0dc71033a jdk8u181-b12
 0cb452d66676bc1b3824bea4a0c16ac76e58b070 jdk8u181-b13
+b01c6e5aa43c784fc66465b56227ddd9aa29eee6 jdk8u191-b01
+2db6890a956723ac347b573217d91bbbedbb0528 jdk8u191-b02
+89e2889d02d2f5dabdeda7f60cf80a8df3100eb4 jdk8u191-b03
+94e4769c6d69241f9eb7164a85fc91fc83faab5c jdk8u191-b04
+6329d17c17d7a40a8747b346e324d39476b045d1 jdk8u191-b05
+ca864c999536f7b036b704c03a7e6e7b3ce12702 jdk8u191-b06
+8d7260f7df9e122a74ab7fe6a91e07ab103d1c54 jdk8u191-b07
+f1e4b0f8695fed5ae0f506e27cbf247e7c8ef5aa jdk8u191-b08
+dca9c1978ed662fae851a38ad260a2811c80da21 jdk8u191-b09
+0f52237f12920603bba74cbfb337e4657a4f8217 jdk8u191-b10
+af544b6bf744cddf59121f40dbf4e0ec0a2533b2 jdk8u191-b25
+5eaf8c860c22512b8b5c82cdcdca8ddd4a99e754 jdk8u191-b11
+5ca18caa6a571dc12d3f920d7714481a67a990bc jdk8u191-b12
+574e92cf225bf1967b6c6f08224d4df469809a13 jdk8u191-b26
 51b6cc7fbd98a87c6cdb5c70b7dbe25bb10e0dd7 jdk8u182-b00
 bead1ed7344f2911f5bed83639cf5160596561ef jdk8u192-b00
 444b4528c8ecdd39b5923820fa2ed6d583808b5e jdk8u192-b01
 e56bb18a4dff4c234c5949c750f910a1ed92fafe jdk8u192-b02
 cadea780bc765ccca4aa919522e876b368c58145 jdk8u192-b03
 cadea780bc765ccca4aa919522e876b368c58145 jdk8u202-b00
+b17237c1ab9c4670d939fef09a6bbecdecad824a jdk8u192-b04
+fde7fd2a2fd225c4e2d469943b14ea84d3772853 jdk8u192-b05
+4a23ff05b4f9f8a6345e8ae6c25ce0010db71249 jdk8u192-b06
+6b29c26e864aca83a6b7e481003d95d3704e928a jdk8u192-b07
+7556b6a2aa3266fb4a213c4fbbca2a403d4df306 jdk8u192-b08
+f47b81dbed2dd730d34a8dc3e3d14e2aa9f9c493 jdk8u192-b09
+621105274477152934059d58a116222f09d966a2 jdk8u192-b10
+89f64de4cebd640247fc17448f19c24fce2cc6fd jdk8u192-b25
+2cd82eb879dd0f853dbfb7ffa2441e81e2413447 jdk8u192-b11
+f877dad22786f92aa495a595a1a4a16f0163c573 jdk8u192-b12
+996dd3ce1ec5437da8b5a742c60a5ff7b6028122 jdk8u192-b26
--- a/THIRD_PARTY_README	Sun Oct 14 19:45:50 2018 -0400
+++ b/THIRD_PARTY_README	Mon Oct 15 15:05:59 2018 +0100
@@ -1497,7 +1497,7 @@
 
 -------------------------------------------------------------------------------
 
-%% This notice is provided with respect to libpng 1.6.16, which may be 
+%% This notice is provided with respect to libpng 1.6.35, which may be
 included with JRE 8, JDK 8, and OpenJDK 8.
 
 --- begin of LICENSE ---
@@ -1513,21 +1513,21 @@
 
 This code is released under the libpng license.
 
-libpng versions 1.2.6, August 15, 2004, through 1.6.16, December 22, 2014, are
-Copyright (c) 2004, 2006-2014 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-1.2.5
-with the following individual added to the list of Contributing Authors
-
-   Cosmin Truta
-
-libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are
-Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-1.0.6
-with the following individuals added to the list of Contributing Authors
+libpng versions 1.0.7, July 1, 2000 through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
 
    Simon-Pierre Cadieux
    Eric S. Raymond
+   Mans Rullgard
+   Cosmin Truta
    Gilles Vollant
+   James Yu
+   Mandar Sahastrabuddhe
+   Google Inc.
+   Vadim Barkov
 
 and with the following additions to the disclaimer:
 
@@ -1538,19 +1538,25 @@
    risk of satisfactory quality, performance, accuracy, and effort is with
    the user.
 
+Some files in the "contrib" directory and some configure-generated
+files that are distributed with libpng have other copyright owners and
+are released under other open source licenses.
+
 libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
-Copyright (c) 1998, 1999 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-0.96,
-with the following individuals added to the list of Contributing Authors:
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the list
+of Contributing Authors:
 
    Tom Lane
    Glenn Randers-Pehrson
    Willem van Schaik
 
 libpng versions 0.89, June 1996, through 0.96, May 1997, are
-Copyright (c) 1996, 1997 Andreas Dilger
-Distributed according to the same disclaimer and license as libpng-0.88,
-with the following individuals added to the list of Contributing Authors:
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
 
    John Bowler
    Kevin Bracey
@@ -1559,8 +1565,11 @@
    Greg Roelofs
    Tom Tanner
 
+Some files in the "scripts" directory have other copyright owners
+but are released under this license.
+
 libpng versions 0.5, May 1995, through 0.88, January 1996, are
-Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
 
 For the purposes of this copyright and license, "Contributing Authors"
 is defined as the following set of individuals:
@@ -1583,13 +1592,13 @@
 source code, or portions hereof, for any purpose, without fee, subject
 to the following restrictions:
 
-1. The origin of this source code must not be misrepresented.
-
-2. Altered versions must be plainly marked as such and must not
-   be misrepresented as being the original source.
-
-3. This Copyright notice may not be removed or altered from any
-   source or altered source distribution.
+  1. The origin of this source code must not be misrepresented.
+
+  2. Altered versions must be plainly marked as such and must not
+     be misrepresented as being the original source.
+
+  3. This Copyright notice may not be removed or altered from any
+     source or altered source distribution.
 
 The Contributing Authors and Group 42, Inc. specifically permit, without
 fee, and encourage the use of this source code as a component to
@@ -1597,21 +1606,34 @@
 source code in a product, acknowledgment is not required but would be
 appreciated.
 
-
-A "png_get_copyright" function is available, for convenient use in "about"
-boxes and the like:
-
-   printf("%s",png_get_copyright(NULL));
-
-Also, the PNG logo (in PNG format, of course) is supplied in the
-files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
-
-Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is a
-certification mark of the Open Source Initiative.
+END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
+
+TRADEMARK:
+
+The name "libpng" has not been registered by the Copyright owner
+as a trademark in any jurisdiction.  However, because libpng has
+been distributed and maintained world-wide, continually since 1995,
+the Copyright owner claims "common-law trademark protection" in any
+jurisdiction where common-law trademark is recognized.
+
+OSI CERTIFICATION:
+
+Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
+a certification mark of the Open Source Initiative. OSI has not addressed
+the additional disclaimers inserted at version 1.0.7.
+
+EXPORT CONTROL:
+
+The Copyright owner believes that the Export Control Classification
+Number (ECCN) for libpng is EAR99, which means not subject to export
+controls or International Traffic in Arms Regulations (ITAR) because
+it is open source, publicly available software, that does not contain
+any encryption software.  See the EAR, paragraphs 734.3(b)(3) and
+734.7(b).
 
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-December 22, 2014
+July 15, 2018
 
 --- end of LICENSE ---
 
--- a/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Mon Oct 15 15:05:59 2018 +0100
@@ -548,7 +548,7 @@
         long count = riff.readUnsignedInt();
 
         if (size - 8 != 0)
-            riff.skipBytes(size - 8);
+            riff.skip(size - 8);
 
         for (int i = 0; i < count; i++) {
             DLSModulator modulator = new DLSModulator();
@@ -568,7 +568,7 @@
         long count = riff.readUnsignedInt();
 
         if (size - 8 != 0)
-            riff.skipBytes(size - 8);
+            riff.skip(size - 8);
 
         for (int i = 0; i < count; i++) {
             DLSModulator modulator = new DLSModulator();
@@ -661,7 +661,7 @@
         long loops = riff.readInt();
 
         if (size > 20)
-            riff.skipBytes(size - 20);
+            riff.skip(size - 20);
 
         for (int i = 0; i < loops; i++) {
             DLSSampleLoop loop = new DLSSampleLoop();
@@ -671,7 +671,7 @@
             loop.length = riff.readUnsignedInt();
             sampleOptions.loops.add(loop);
             if (size2 > 16)
-                riff.skipBytes(size2 - 16);
+                riff.skip(size2 - 16);
         }
     }
 
--- a/src/share/classes/com/sun/media/sound/RIFFReader.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/com/sun/media/sound/RIFFReader.java	Mon Oct 15 15:05:59 2018 +0100
@@ -172,49 +172,41 @@
         }
     }
 
-    public final long skipBytes(long n) throws IOException {
-        if (n < 0)
+    @Override
+    public long skip(final long n) throws IOException {
+        if (n <= 0 || avail == 0) {
             return 0;
-        long skipped = 0;
-        while (skipped != n) {
-            long s = skip(n - skipped);
-            if (s < 0)
-                break;
-            if (s == 0)
+        }
+        // will not skip more than
+        long remaining = Math.min(n, avail);
+        while (remaining > 0) {
+            // Some input streams like FileInputStream can return more bytes,
+            // when EOF is reached.
+            long ret = Math.min(stream.skip(remaining), remaining);
+            if (ret == 0) {
+                // EOF or not? we need to check.
                 Thread.yield();
-            skipped += s;
+                if (stream.read() == -1) {
+                    avail = 0;
+                    break;
+                }
+                ret = 1;
+            }
+            remaining -= ret;
+            avail -= ret;
+            filepointer += ret;
         }
-        return skipped;
+        return n - remaining;
     }
 
-    public long skip(long n) throws IOException {
-        if (avail == 0)
-            return -1;
-        if (n > avail) {
-            long len = stream.skip(avail);
-            if (len != -1)
-                filepointer += len;
-            avail = 0;
-            return len;
-        } else {
-            long ret = stream.skip(n);
-            if (ret == -1) {
-                avail = 0;
-                return -1;
-            }
-            avail -= ret;
-            filepointer += ret;
-            return ret;
-        }
-    }
-
+    @Override
     public int available() {
         return (int)avail;
     }
 
     public void finish() throws IOException {
         if (avail != 0) {
-            skipBytes(avail);
+            skip(avail);
         }
     }
 
@@ -337,6 +329,7 @@
         return ch1 + (ch2 << 8) | (ch3 << 16) | (ch4 << 24);
     }
 
+    @Override
     public void close() throws IOException {
         finish();
         if (this == root)
--- a/src/share/classes/com/sun/naming/internal/VersionHelper12.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/com/sun/naming/internal/VersionHelper12.java	Mon Oct 15 15:05:59 2018 +0100
@@ -62,6 +62,25 @@
     }
 
     /**
+     * Determines whether classes may be loaded from an arbitrary URL code base.
+     */
+    private static final String TRUST_URL_CODEBASE_PROPERTY =
+            "com.sun.jndi.ldap.object.trustURLCodebase";
+    private static final String trustURLCodebase =
+            AccessController.doPrivileged(
+                new PrivilegedAction<String>() {
+                    public String run() {
+                        try {
+                        return System.getProperty(TRUST_URL_CODEBASE_PROPERTY,
+                            "false");
+                        } catch (SecurityException e) {
+                        return "false";
+                        }
+                    }
+                }
+            );
+
+    /**
      * Package private.
      *
      * This internal method is used with Thread Context Class Loader (TCCL),
@@ -79,12 +98,15 @@
      */
     public Class<?> loadClass(String className, String codebase)
             throws ClassNotFoundException, MalformedURLException {
+        if ("true".equalsIgnoreCase(trustURLCodebase)) {
+            ClassLoader parent = getContextClassLoader();
+            ClassLoader cl =
+                    URLClassLoader.newInstance(getUrlArray(codebase), parent);
 
-        ClassLoader parent = getContextClassLoader();
-        ClassLoader cl =
-                 URLClassLoader.newInstance(getUrlArray(codebase), parent);
-
-        return loadClass(className, cl);
+            return loadClass(className, cl);
+        } else {
+            return null;
+        }
     }
 
     String getJndiProperty(final int i) {
--- a/src/share/classes/com/sun/rowset/RowSetResourceBundle_de.properties	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/com/sun/rowset/RowSetResourceBundle_de.properties	Mon Oct 15 15:05:59 2018 +0100
@@ -26,7 +26,7 @@
 # CacheRowSetImpl exceptions
 cachedrowsetimpl.populate = Ung\u00FCltiges ResultSet-Objekt zum Auff\u00FCllen der Methode angegeben
 cachedrowsetimpl.invalidp = Ung\u00FCltiger Persistence-Provider generiert
-cachedrowsetimpl.nullhash = CachedRowSetImpl-Instanz kann nicht instanziiert werden. Null-Hash-Tabelle f\u00FCr Constructor angegeben
+cachedrowsetimpl.nullhash = CachedRowSetImpl-Instanz kann nicht instanziiert werden. Null-Hashtabelle f\u00FCr Constructor angegeben
 cachedrowsetimpl.invalidop = Ung\u00FCltiger Vorgang beim Zeileneinf\u00FCgen
 cachedrowsetimpl.accfailed = acceptChanges nicht erfolgreich
 cachedrowsetimpl.invalidcp = Ung\u00FCltige Cursorposition
@@ -80,7 +80,7 @@
 cachedrowsetimpl.featnotsupp = Feature nicht unterst\u00FCtzt
 
 # WebRowSetImpl exceptions
-webrowsetimpl.nullhash = WebRowSetImpl-Instanz kann nicht instanziiert werden. Null-Hash-Tabelle f\u00FCr Constructor angegeben
+webrowsetimpl.nullhash = WebRowSetImpl-Instanz kann nicht instanziiert werden. Null-Hashtabelle f\u00FCr Constructor angegeben
 webrowsetimpl.invalidwr = Ung\u00FCltiger Writer
 webrowsetimpl.invalidrd = Ung\u00FCltiger Reader
 
--- a/src/share/classes/java/net/InetAddress.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/net/InetAddress.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2018, 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
@@ -37,6 +37,7 @@
 import java.io.ObjectStreamException;
 import java.io.ObjectStreamField;
 import java.io.IOException;
+import java.io.InvalidObjectException;
 import java.io.ObjectInputStream;
 import java.io.ObjectInputStream.GetField;
 import java.io.ObjectOutputStream;
@@ -1602,8 +1603,11 @@
         }
         GetField gf = s.readFields();
         String host = (String)gf.get("hostName", null);
-        int address= gf.get("address", 0);
-        int family= gf.get("family", 0);
+        int address = gf.get("address", 0);
+        int family = gf.get("family", 0);
+        if (family != IPv4 && family != IPv6) {
+            throw new InvalidObjectException("invalid address family type: " + family);
+        }
         InetAddressHolder h = new InetAddressHolder(host, address, family);
         UNSAFE.putObject(this, FIELDS_OFFSET, h);
     }
--- a/src/share/classes/java/net/NetworkInterface.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/net/NetworkInterface.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, 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
@@ -319,8 +319,20 @@
         if (addr == null) {
             throw new NullPointerException();
         }
-        if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
-            throw new IllegalArgumentException ("invalid address type");
+        if (addr instanceof Inet4Address) {
+            Inet4Address inet4Address = (Inet4Address) addr;
+            if (inet4Address.holder.family != InetAddress.IPv4) {
+                throw new IllegalArgumentException("invalid family type: "
+                        + inet4Address.holder.family);
+            }
+        } else if (addr instanceof Inet6Address) {
+            Inet6Address inet6Address = (Inet6Address) addr;
+            if (inet6Address.holder.family != InetAddress.IPv6) {
+                throw new IllegalArgumentException("invalid family type: "
+                        + inet6Address.holder.family);
+            }
+        } else {
+            throw new IllegalArgumentException("invalid address type: " + addr);
         }
         return getByInetAddress0(addr);
     }
--- a/src/share/classes/java/net/URLClassLoader.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/net/URLClassLoader.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -50,6 +50,7 @@
 import java.util.jar.JarFile;
 import java.util.jar.Manifest;
 import sun.misc.Resource;
+import sun.misc.SharedSecrets;
 import sun.misc.URLClassPath;
 import sun.net.www.ParseUtil;
 import sun.security.util.SecurityConstants;
@@ -486,13 +487,13 @@
     protected Package definePackage(String name, Manifest man, URL url)
         throws IllegalArgumentException
     {
-        String path = name.replace('.', '/').concat("/");
         String specTitle = null, specVersion = null, specVendor = null;
         String implTitle = null, implVersion = null, implVendor = null;
         String sealed = null;
         URL sealBase = null;
 
-        Attributes attr = man.getAttributes(path);
+        Attributes attr = SharedSecrets.javaUtilJarAccess()
+                .getTrustedAttributes(man, name.replace('.', '/').concat("/"));
         if (attr != null) {
             specTitle   = attr.getValue(Name.SPECIFICATION_TITLE);
             specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
@@ -536,10 +537,12 @@
     /*
      * Returns true if the specified package name is sealed according to the
      * given manifest.
+     *
+     * @throws SecurityException if the package name is untrusted in the manifest
      */
     private boolean isSealed(String name, Manifest man) {
-        String path = name.replace('.', '/').concat("/");
-        Attributes attr = man.getAttributes(path);
+        Attributes attr = SharedSecrets.javaUtilJarAccess()
+                .getTrustedAttributes(man, name.replace('.', '/').concat("/"));
         String sealed = null;
         if (attr != null) {
             sealed = attr.getValue(Name.SEALED);
--- a/src/share/classes/java/util/jar/JarFile.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/util/jar/JarFile.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -191,10 +191,10 @@
             if (manEntry != null) {
                 if (verify) {
                     byte[] b = getBytes(manEntry);
-                    man = new Manifest(new ByteArrayInputStream(b));
                     if (!jvInitialized) {
                         jv = new JarVerifier(b);
                     }
+                    man = new Manifest(jv, new ByteArrayInputStream(b));
                 } else {
                     man = new Manifest(super.getInputStream(manEntry));
                 }
@@ -602,7 +602,7 @@
         return false;
     }
 
-    private synchronized void ensureInitialization() {
+    synchronized void ensureInitialization() {
         try {
             maybeInstantiateVerifier();
         } catch (IOException e) {
--- a/src/share/classes/java/util/jar/JarVerifier.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/util/jar/JarVerifier.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -879,4 +879,24 @@
     static CodeSource getUnsignedCS(URL url) {
         return new VerifierCodeSource(null, url, (java.security.cert.Certificate[]) null);
     }
+
+    /**
+     * Returns whether the name is trusted. Used by
+     * {@link Manifest#getTrustedAttributes(String)}.
+     */
+    boolean isTrustedManifestEntry(String name) {
+        // How many signers? MANIFEST.MF is always verified
+        CodeSigner[] forMan = verifiedSigners.get(JarFile.MANIFEST_NAME);
+        if (forMan == null) {
+            return true;
+        }
+        // Check sigFileSigners first, because we are mainly dealing with
+        // non-file entries which will stay in sigFileSigners forever.
+        CodeSigner[] forName = sigFileSigners.get(name);
+        if (forName == null) {
+            forName = verifiedSigners.get(name);
+        }
+        // Returns trusted if all signers sign the entry
+        return forName != null && forName.length == forMan.length;
+    }
 }
--- a/src/share/classes/java/util/jar/JavaUtilJarAccessImpl.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/util/jar/JavaUtilJarAccessImpl.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, 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
@@ -60,4 +60,12 @@
     public List<Object> getManifestDigests(JarFile jar) {
         return jar.getManifestDigests();
     }
+
+    public Attributes getTrustedAttributes(Manifest man, String name) {
+        return man.getTrustedAttributes(name);
+    }
+
+    public void ensureInitialization(JarFile jar) {
+        jar.ensureInitialization();
+    }
 }
--- a/src/share/classes/java/util/jar/Manifest.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/java/util/jar/Manifest.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -48,15 +48,19 @@
  */
 public class Manifest implements Cloneable {
     // manifest main attributes
-    private Attributes attr = new Attributes();
+    private final Attributes attr = new Attributes();
 
     // manifest entries
-    private Map<String, Attributes> entries = new HashMap<>();
+    private final Map<String, Attributes> entries = new HashMap<>();
+
+    // associated JarVerifier, not null when called by JarFile::getManifest.
+    private final JarVerifier jv;
 
     /**
      * Constructs a new, empty Manifest.
      */
     public Manifest() {
+        jv = null;
     }
 
     /**
@@ -66,7 +70,16 @@
      * @throws IOException if an I/O error has occurred
      */
     public Manifest(InputStream is) throws IOException {
+        this(null, is);
+    }
+
+    /**
+     * Constructs a new Manifest from the specified input stream
+     * and associates it with a JarVerifier.
+     */
+    Manifest(JarVerifier jv, InputStream is) throws IOException {
         read(is);
+        this.jv = jv;
     }
 
     /**
@@ -77,6 +90,7 @@
     public Manifest(Manifest man) {
         attr.putAll(man.getMainAttributes());
         entries.putAll(man.getEntries());
+        jv = man.jv;
     }
 
     /**
@@ -127,6 +141,27 @@
     }
 
     /**
+     * Returns the Attributes for the specified entry name, if trusted.
+     *
+     * @param name entry name
+     * @return returns the same result as {@link #getAttributes(String)}
+     * @throws SecurityException if the associated jar is signed but this entry
+     *      has been modified after signing (i.e. the section in the manifest
+     *      does not exist in SF files of all signers).
+     */
+    Attributes getTrustedAttributes(String name) {
+        // Note: Before the verification of MANIFEST.MF/.SF/.RSA files is done,
+        // jv.isTrustedManifestEntry() isn't able to detect MANIFEST.MF change.
+        // Users of this method should call SharedSecrets.javaUtilJarAccess()
+        // .ensureInitialization() first.
+        Attributes result = getAttributes(name);
+        if (result != null && jv != null && ! jv.isTrustedManifestEntry(name)) {
+            throw new SecurityException("Untrusted manifest entry: " + name);
+        }
+        return result;
+    }
+
+    /**
      * Clears the main Attributes as well as the entries in this Manifest.
      */
     public void clear() {
--- a/src/share/classes/javax/crypto/Cipher.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/javax/crypto/Cipher.java	Mon Oct 15 15:05:59 2018 +0100
@@ -2703,7 +2703,7 @@
 
         // Input sanity check
         if ((src == null) || (offset < 0) || (len < 0)
-                || ((len + offset) > src.length)) {
+                || (len > (src.length - offset))) {
             throw new IllegalArgumentException("Bad arguments");
         }
 
--- a/src/share/classes/javax/crypto/CipherInputStream.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/javax/crypto/CipherInputStream.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -50,6 +50,13 @@
  * that are not thrown by its ancestor classes.  In particular, the
  * <code>skip</code> method skips, and the <code>available</code>
  * method counts only data that have been processed by the encapsulated Cipher.
+ * This class may catch BadPaddingException and other exceptions thrown by
+ * failed integrity checks during decryption. These exceptions are not
+ * re-thrown, so the client may not be informed that integrity checks
+ * failed. Because of this behavior, this class may not be suitable
+ * for use with decryption in an authenticated mode of operation (e.g. GCM).
+ * Applications that require authenticated encryption can use the Cipher API
+ * directly as an alternative to using this class.
  *
  * <p> It is crucial for a programmer using this class not to use
  * methods that are not defined or overriden in this class (such as a
--- a/src/share/classes/javax/crypto/spec/GCMParameterSpec.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/javax/crypto/spec/GCMParameterSpec.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, 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
@@ -120,7 +120,7 @@
 
         // Input sanity check
         if ((src == null) ||(len < 0) || (offset < 0)
-                || ((len + offset) > src.length)) {
+                || (len > (src.length - offset))) {
             throw new IllegalArgumentException("Invalid buffer arguments");
         }
 
--- a/src/share/classes/sun/misc/JavaUtilJarAccess.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/misc/JavaUtilJarAccess.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,8 +30,10 @@
 import java.security.CodeSource;
 import java.util.Enumeration;
 import java.util.List;
+import java.util.jar.Attributes;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
+import java.util.jar.Manifest;
 
 public interface JavaUtilJarAccess {
     public boolean jarFileHasClassPathAttribute(JarFile jar) throws IOException;
@@ -41,4 +43,6 @@
     public Enumeration<JarEntry> entries2(JarFile jar);
     public void setEagerValidation(JarFile jar, boolean eager);
     public List<Object> getManifestDigests(JarFile jar);
+    public Attributes getTrustedAttributes(Manifest man, String name);
+    public void ensureInitialization(JarFile jar);
 }
--- a/src/share/classes/sun/misc/URLClassPath.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/misc/URLClassPath.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -37,6 +37,7 @@
 import java.util.jar.Attributes.Name;
 import java.net.JarURLConnection;
 import java.net.MalformedURLException;
+import java.net.URI;
 import java.net.URL;
 import java.net.URLClassLoader;
 import java.net.URLConnection;
@@ -69,6 +70,8 @@
     private static final boolean DEBUG_LOOKUP_CACHE;
     private static final boolean DISABLE_JAR_CHECKING;
     private static final boolean DISABLE_ACC_CHECKING;
+    private static final boolean DISABLE_CP_URL_CHECK;
+    private static final boolean DEBUG_CP_URL_CHECK;
 
     static {
         JAVA_VERSION = java.security.AccessController.doPrivileged(
@@ -84,6 +87,13 @@
         p = AccessController.doPrivileged(
             new GetPropertyAction("jdk.net.URLClassPath.disableRestrictedPermissions"));
         DISABLE_ACC_CHECKING = p != null ? p.equals("true") || p.equals("") : false;
+
+        // This property will be removed in a later release
+        p = AccessController.doPrivileged(
+            new GetPropertyAction("jdk.net.URLClassPath.disableClassPathURLCheck", "true"));
+
+        DISABLE_CP_URL_CHECK = p != null ? p.equals("true") || p.isEmpty() : false;
+        DEBUG_CP_URL_CHECK = "debug".equals(p);
     }
 
     /* The original search path of URLs. */
@@ -977,8 +987,10 @@
                     { return jar.getInputStream(entry); }
                 public int getContentLength()
                     { return (int)entry.getSize(); }
-                public Manifest getManifest() throws IOException
-                    { return jar.getManifest(); };
+                public Manifest getManifest() throws IOException {
+                    SharedSecrets.javaUtilJarAccess().ensureInitialization(jar);
+                    return jar.getManifest();
+                }
                 public Certificate[] getCertificates()
                     { return entry.getCertificates(); };
                 public CodeSigner[] getCodeSigners()
@@ -1217,11 +1229,51 @@
             int i = 0;
             while (st.hasMoreTokens()) {
                 String path = st.nextToken();
-                urls[i] = new URL(base, path);
-                i++;
+                URL url = DISABLE_CP_URL_CHECK ? new URL(base, path) : safeResolve(base, path);
+                if (url != null) {
+                    urls[i] = url;
+                    i++;
+                }
+            }
+            if (i == 0) {
+                urls = null;
+            } else if (i != urls.length) {
+                // Truncate nulls from end of array
+                urls = Arrays.copyOf(urls, i);
             }
             return urls;
         }
+
+        /*
+         * Return a URL for the given path resolved against the base URL, or
+         * null if the resulting URL is invalid.
+         */
+        static URL safeResolve(URL base, String path) {
+            String child = path.replace(File.separatorChar, '/');
+            try {
+                if (!URI.create(child).isAbsolute()) {
+                    URL url = new URL(base, child);
+                    if (base.getProtocol().equalsIgnoreCase("file")) {
+                        return url;
+                    } else {
+                        String bp = base.getPath();
+                        String urlp = url.getPath();
+                        int pos = bp.lastIndexOf('/');
+                        if (pos == -1) {
+                            pos = bp.length() - 1;
+                        }
+                        if (urlp.regionMatches(0, bp, 0, pos + 1)
+                            && urlp.indexOf("..", pos) == -1) {
+                            return url;
+                        }
+                    }
+                }
+            } catch (MalformedURLException | IllegalArgumentException e) {}
+            if (DEBUG_CP_URL_CHECK) {
+                System.err.println("Class-Path entry: \"" + path + "\" ignored in JAR file " + base);
+            }
+            return null;
+        }
     }
 
     /*
--- a/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2018, 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
@@ -2686,6 +2686,8 @@
             // doesn't know about proxy.
             useProxyResponseCode = true;
         } else {
+            final URL prevURL = url;
+
             // maintain previous headers, just change the name
             // of the file we're getting
             url = locUrl;
@@ -2714,6 +2716,14 @@
                 poster = null;
                 if (!checkReuseConnection())
                     connect();
+
+                if (!sameDestination(prevURL, url)) {
+                    // Ensures pre-redirect user-set cookie will not be reset.
+                    // CookieHandler, if any, will be queried to determine
+                    // cookies for redirected URL, if any.
+                    userCookies = null;
+                    userCookies2 = null;
+                }
             } else {
                 if (!checkReuseConnection())
                     connect();
@@ -2736,11 +2746,52 @@
                     }
                     requests.set("Host", host);
                 }
+
+                if (!sameDestination(prevURL, url)) {
+                    // Redirecting to a different destination will drop any
+                    // security-sensitive headers, regardless of whether
+                    // they are user-set or not. CookieHandler, if any, will be
+                    // queried to determine cookies for redirected URL, if any.
+                    userCookies = null;
+                    userCookies2 = null;
+                    requests.remove("Cookie");
+                    requests.remove("Cookie2");
+                    requests.remove("Authorization");
+
+                    // check for preemptive authorization
+                    AuthenticationInfo sauth =
+                            AuthenticationInfo.getServerAuth(url);
+                    if (sauth != null && sauth.supportsPreemptiveAuthorization() ) {
+                        // Sets "Authorization"
+                        requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method));
+                        currentServerCredentials = sauth;
+                    }
+                }
             }
         }
         return true;
     }
 
+    /* Returns true iff the given URLs have the same host and effective port. */
+    private static boolean sameDestination(URL firstURL, URL secondURL) {
+        assert firstURL.getProtocol().equalsIgnoreCase(secondURL.getProtocol()):
+               "protocols not equal: " + firstURL +  " - " + secondURL;
+
+        if (!firstURL.getHost().equalsIgnoreCase(secondURL.getHost()))
+            return false;
+
+        int firstPort = firstURL.getPort();
+        if (firstPort == -1)
+            firstPort = firstURL.getDefaultPort();
+        int secondPort = secondURL.getPort();
+        if (secondPort == -1)
+            secondPort = secondURL.getDefaultPort();
+        if (firstPort != secondPort)
+            return false;
+
+        return true;
+    }
+
     /* dummy byte buffer for reading off socket prior to closing */
     byte[] cdata = new byte [128];
 
--- a/src/share/classes/sun/rmi/registry/resources/rmiregistry_it.properties	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/rmi/registry/resources/rmiregistry_it.properties	Mon Oct 15 15:05:59 2018 +0100
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -24,5 +24,5 @@
 # questions.
 #
 
-rmiregistry.usage=Uso: {0} <opzioni> <porta>\n\ndove <opzioni> include:\n  -J<flag fase di esecuzione> Passa l''argomento all''interprete java
+rmiregistry.usage=Uso: {0} <opzioni> <porta>\n\ndove <opzioni> include:\n  -J<flag runtime> Passa l''argomento all''interprete java
 rmiregistry.port.badnumber=l''argomento della porta, {0}, non \u00E8 un numero.
--- a/src/share/classes/sun/rmi/server/resources/rmid_it.properties	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/rmi/server/resources/rmid_it.properties	Mon Oct 15 15:05:59 2018 +0100
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1998, 2018, 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
@@ -75,7 +75,7 @@
 
 # "rmid", "-port", "-log", "-stop", "-C" and "-J" should not be translated,
 # because they are syntax
-rmid.usage=Uso: {0} <opzioni>\n\ndove <opzioni> include:\n  -port <porta>       Specifica la porta usata da rmid\n  -log <directory>    Specifica la directory in cui rmid scrive il log\n  -stop              Arresta l''invocazione corrente di rmid (per la porta specificata)\n  -C<flag fase di esecuzione>    Passa l''argomento a ciascun processo figlio (gruppo di attivazione)\n  -J<flag fase di esecuzione>    Passa l''argomento all''interprete java\n
+rmid.usage=Uso: {0} <opzioni>\n\ndove <opzioni> include:\n  -port <porta>       Specifica la porta usata da rmid\n  -log <directory>    Specifica la directory in cui rmid scrive il log\n  -stop              Arresta l''invocazione corrente di rmid (per la porta specificata)\n  -C<flag runtime>    Passa l''argomento a ciascun processo figlio (gruppo di attivazione)\n  -J<flag runtime>    Passa l''argomento all''interprete java\n
 # This means "The currently running activation daemon has been shut down,
 # and is about to exit".
 rmid.daemon.shutdown=daemon di attivazione terminato
--- a/src/share/classes/sun/security/ssl/ClientHandshaker.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/ssl/ClientHandshaker.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2018, 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
@@ -719,7 +719,8 @@
         session = new SSLSessionImpl(protocolVersion, cipherSuite,
                             getLocalSupportedSignAlgs(),
                             mesg.sessionId, getHostSE(), getPortSE(),
-                            (extendedMasterSecretExt != null));
+                            (extendedMasterSecretExt != null),
+                            getEndpointIdentificationAlgorithmSE());
         session.setRequestedServerNames(requestedServerNames);
         setHandshakeSessionSE(session);
         if (debug != null && Debug.isOn("handshake")) {
@@ -1391,6 +1392,24 @@
                 }
             }
 
+            // ensure that the endpoint identification algorithm matches the
+            // one in the session
+            String identityAlg = getEndpointIdentificationAlgorithmSE();
+            if (session != null && identityAlg != null) {
+
+                String sessionIdentityAlg =
+                    session.getEndpointIdentificationAlgorithm();
+                if (!Objects.equals(identityAlg, sessionIdentityAlg)) {
+
+                    if (debug != null && Debug.isOn("session")) {
+                        System.out.println("%% can't resume, endpoint id" +
+                            " algorithm does not match, requested: " +
+                            identityAlg + ", cached: " + sessionIdentityAlg);
+                    }
+                    session = null;
+                }
+            }
+
             if (session != null) {
                 if (debug != null) {
                     if (Debug.isOn("handshake") || Debug.isOn("session")) {
--- a/src/share/classes/sun/security/ssl/SSLSessionImpl.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/ssl/SSLSessionImpl.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -115,6 +115,10 @@
     private Principal peerPrincipal;
     private Principal localPrincipal;
 
+    // The endpoint identification algorithm used to check certificates
+    // in this session.
+    private final String              endpointIdentificationAlgorithm;
+
     /*
      * Is the session currently re-established with a session-resumption
      * abbreviated initial handshake?
@@ -146,7 +150,7 @@
      */
     private SSLSessionImpl() {
         this(ProtocolVersion.NONE, CipherSuite.C_NULL, null,
-            new SessionId(false, null), null, -1, false);
+            new SessionId(false, null), null, -1, false, null);
     }
 
     /*
@@ -157,10 +161,10 @@
     SSLSessionImpl(ProtocolVersion protocolVersion, CipherSuite cipherSuite,
             Collection<SignatureAndHashAlgorithm> algorithms,
             SecureRandom generator, String host, int port,
-            boolean useExtendedMasterSecret) {
+            boolean useExtendedMasterSecret, String endpointIdAlgorithm) {
         this(protocolVersion, cipherSuite, algorithms,
              new SessionId(defaultRejoinable, generator), host, port,
-             useExtendedMasterSecret);
+             useExtendedMasterSecret, endpointIdAlgorithm);
     }
 
     /*
@@ -169,7 +173,8 @@
     SSLSessionImpl(ProtocolVersion protocolVersion, CipherSuite cipherSuite,
             Collection<SignatureAndHashAlgorithm> algorithms,
             SessionId id, String host, int port,
-            boolean useExtendedMasterSecret) {
+            boolean useExtendedMasterSecret,
+            String endpointIdAlgorithm){
         this.protocolVersion = protocolVersion;
         sessionId = id;
         peerCerts = null;
@@ -182,6 +187,7 @@
         localSupportedSignAlgs =
             SignatureAndHashAlgorithm.getAlgorithmNames(algorithms);
         this.useExtendedMasterSecret = useExtendedMasterSecret;
+        this.endpointIdentificationAlgorithm = endpointIdAlgorithm;
 
         if (debug != null && Debug.isOn("session")) {
             System.out.println("%% Initialized:  " + this);
@@ -247,6 +253,10 @@
         localPrincipal = principal;
     }
 
+    String getEndpointIdentificationAlgorithm() {
+        return this.endpointIdentificationAlgorithm;
+    }
+
     /**
      * Returns true iff this session may be resumed ... sessions are
      * usually resumable.  Security policies may suggest otherwise,
--- a/src/share/classes/sun/security/ssl/ServerHandshaker.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/ssl/ServerHandshaker.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2018, 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
@@ -698,6 +698,25 @@
                     }
                 }
 
+                // ensure that the endpoint identification algorithm matches the
+                // one in the session
+                String identityAlg = getEndpointIdentificationAlgorithmSE();
+                if (resumingSession && identityAlg != null) {
+
+                    String sessionIdentityAlg =
+                    previous.getEndpointIdentificationAlgorithm();
+                    if (!Objects.equals(identityAlg, sessionIdentityAlg)) {
+
+                        if (debug != null && Debug.isOn("session")) {
+                            System.out.println("%% can't resume, endpoint id"
+                                + " algorithm does not match, requested: " +
+                                identityAlg + ", cached: " +
+                                sessionIdentityAlg);
+                        }
+                        resumingSession = false;
+                    }
+                }
+
                 if (resumingSession) {
                     CipherSuite suite = previous.getSuite();
                     // verify that the ciphersuite from the cached session
@@ -769,7 +788,8 @@
                         sslContext.getSecureRandom(),
                         getHostAddressSE(), getPortSE(),
                         (requestedToUseEMS &&
-                                (protocolVersion.v >= ProtocolVersion.TLS10.v)));
+                                (protocolVersion.v >= ProtocolVersion.TLS10.v)),
+                        getEndpointIdentificationAlgorithmSE());
 
             if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                 if (peerSupportedSignAlgs != null) {
--- a/src/share/classes/sun/security/tools/KeyStoreUtil.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/tools/KeyStoreUtil.java	Mon Oct 15 15:05:59 2018 +0100
@@ -35,6 +35,7 @@
 
 import java.security.KeyStore;
 
+import java.security.cert.X509Certificate;
 import java.text.Collator;
 
 import java.util.Locale;
@@ -59,6 +60,25 @@
     };
 
     /**
+     * Returns true if the certificate is self-signed, false otherwise.
+     */
+    public static boolean isSelfSigned(X509Certificate cert) {
+        return signedBy(cert, cert);
+    }
+
+    public static boolean signedBy(X509Certificate end, X509Certificate ca) {
+        if (!ca.getSubjectX500Principal().equals(end.getIssuerX500Principal())) {
+            return false;
+        }
+        try {
+            end.verify(ca.getPublicKey());
+            return true;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    /**
      * Returns true if KeyStore has a password. This is true except for
      * MSCAPI KeyStores
      */
--- a/src/share/classes/sun/security/tools/jarsigner/Main.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/tools/jarsigner/Main.java	Mon Oct 15 15:05:59 2018 +0100
@@ -26,6 +26,8 @@
 package sun.security.tools.jarsigner;
 
 import java.io.*;
+import java.security.cert.CertPathValidatorException;
+import java.security.cert.PKIXBuilderParameters;
 import java.util.*;
 import java.util.zip.*;
 import java.util.jar.*;
@@ -46,11 +48,9 @@
 import java.net.URL;
 import java.net.URLClassLoader;
 import java.security.cert.CertPath;
-import java.security.cert.CertPathValidator;
 import java.security.cert.CertificateExpiredException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.CertificateNotYetValidException;
-import java.security.cert.PKIXParameters;
 import java.security.cert.TrustAnchor;
 import java.util.Map.Entry;
 import sun.security.pkcs.PKCS7;
@@ -58,6 +58,8 @@
 import sun.security.timestamp.TimestampToken;
 import sun.security.tools.KeyStoreUtil;
 import sun.security.tools.PathList;
+import sun.security.validator.Validator;
+import sun.security.validator.ValidatorException;
 import sun.security.x509.*;
 import sun.security.util.*;
 import java.util.Base64;
@@ -173,22 +175,34 @@
     private boolean noTimestamp = false;
     private Date expireDate = new Date(0L);     // used in noTimestamp warning
 
-    // Severe warnings
+    // Severe warnings.
+
+    // jarsigner used to check signer cert chain validity and key usages
+    // itself and set various warnings. Later CertPath validation is
+    // added but chainNotValidated is only flagged when no other existing
+    // warnings are set. TSA cert chain check is added separately and
+    // only tsaChainNotValidated is set, i.e. has no affect on hasExpiredCert,
+    // notYetValidCert, or any badXyzUsage.
+
+    private int weakAlg = 0; // 1. digestalg, 2. sigalg, 4. tsadigestalg
     private boolean hasExpiredCert = false;
     private boolean notYetValidCert = false;
     private boolean chainNotValidated = false;
+    private boolean tsaChainNotValidated = false;
     private boolean notSignedByAlias = false;
     private boolean aliasNotInStore = false;
     private boolean hasUnsignedEntry = false;
     private boolean badKeyUsage = false;
     private boolean badExtendedKeyUsage = false;
     private boolean badNetscapeCertType = false;
+    private boolean signerSelfSigned = false;
+
+    private Throwable chainNotValidatedReason = null;
+    private Throwable tsaChainNotValidatedReason = null;
 
     private boolean seeWeak = false;
 
-    CertificateFactory certificateFactory;
-    CertPathValidator validator;
-    PKIXParameters pkixParameters;
+    PKIXBuilderParameters pkixParameters;
 
     public void run(String args[]) {
         try {
@@ -275,7 +289,8 @@
 
         if (strict) {
             int exitCode = 0;
-            if (chainNotValidated || hasExpiredCert || notYetValidCert) {
+            if (weakAlg != 0 || chainNotValidated
+                    || hasExpiredCert || notYetValidCert || signerSelfSigned) {
                 exitCode |= 4;
             }
             if (badKeyUsage || badExtendedKeyUsage || badNetscapeCertType) {
@@ -287,6 +302,9 @@
             if (notSignedByAlias || aliasNotInStore) {
                 exitCode |= 32;
             }
+            if (tsaChainNotValidated) {
+                exitCode |= 64;
+            }
             if (exitCode != 0) {
                 System.exit(exitCode);
             }
@@ -807,6 +825,9 @@
                 System.out.println(rb.getString("no.manifest."));
             }
 
+            // If there is a time stamp block inside the PKCS7 block file
+            boolean hasTimestampBlock = false;
+
             // Even if the verbose option is not specified, all out strings
             // must be generated so seeWeak can be updated.
             if (!digestMap.isEmpty()
@@ -835,6 +856,7 @@
                             PublicKey key = signer.getPublicKey();
                             PKCS7 tsToken = si.getTsToken();
                             if (tsToken != null) {
+                                hasTimestampBlock = true;
                                 SignerInfo tsSi = tsToken.getSignerInfos()[0];
                                 X509Certificate tsSigner = tsSi.getCertificate(tsToken);
                                 byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
@@ -890,6 +912,12 @@
             }
             System.out.println();
 
+            // If signer is a trusted cert or private entry in user's own
+            // keystore, it can be self-signed.
+            if (!aliasNotInStore) {
+                signerSelfSigned = false;
+            }
+
             if (!anySigned) {
                 if (seeWeak) {
                     if (verbose != null) {
@@ -910,8 +938,8 @@
                 boolean errorAppeared = false;
                 if (badKeyUsage || badExtendedKeyUsage || badNetscapeCertType ||
                         notYetValidCert || chainNotValidated || hasExpiredCert ||
-                        hasUnsignedEntry ||
-                        aliasNotInStore || notSignedByAlias) {
+                        hasUnsignedEntry || signerSelfSigned || (weakAlg != 0) ||
+                        aliasNotInStore || notSignedByAlias || tsaChainNotValidated) {
 
                     if (strict) {
                         System.out.println(rb.getString("jar.verified.with.signer.errors."));
@@ -925,6 +953,12 @@
                         warningAppeared = true;
                     }
 
+                    if (weakAlg != 0) {
+                        // In fact, jarsigner verification did not catch this
+                        // since it has not read the JarFile content itself.
+                        // Everything is done with JarFile API.
+                    }
+
                     if (badKeyUsage) {
                         System.out.println(
                             rb.getString("This.jar.contains.entries.whose.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing."));
@@ -954,8 +988,15 @@
                     }
 
                     if (chainNotValidated) {
-                        System.out.println(
-                                rb.getString("This.jar.contains.entries.whose.certificate.chain.is.not.validated."));
+                        System.out.println(String.format(
+                                rb.getString("This.jar.contains.entries.whose.certificate.chain.is.invalid.reason.1"),
+                                chainNotValidatedReason.getLocalizedMessage()));
+                    }
+
+                    if (tsaChainNotValidated) {
+                        System.out.println(String.format(
+                                rb.getString("This.jar.contains.entries.whose.tsa.certificate.chain.is.invalid.reason.1"),
+                                tsaChainNotValidatedReason.getLocalizedMessage()));
                     }
 
                     if (notSignedByAlias) {
@@ -966,6 +1007,11 @@
                     if (aliasNotInStore) {
                         System.out.println(rb.getString("This.jar.contains.signed.entries.that.s.not.signed.by.alias.in.this.keystore."));
                     }
+
+                    if (signerSelfSigned) {
+                        System.out.println(rb.getString(
+                                "This.jar.contains.entries.whose.signer.certificate.is.self.signed."));
+                    }
                 } else {
                     System.out.println(rb.getString("jar.verified."));
                 }
@@ -980,8 +1026,15 @@
                                 "This.jar.contains.entries.whose.signer.certificate.will.expire.within.six.months."));
                     }
                     if (noTimestamp) {
-                        System.out.println(
-                                String.format(rb.getString("no.timestamp.verifying"), expireDate));
+                        if (hasTimestampBlock) {
+                            // JarSigner API has not seen the timestamp,
+                            // might have ignored it due to weak alg, etc.
+                            System.out.println(
+                                    String.format(rb.getString("bad.timestamp.verifying"), expireDate));
+                        } else {
+                            System.out.println(
+                                    String.format(rb.getString("no.timestamp.verifying"), expireDate));
+                        }
                     }
                 }
                 if (warningAppeared || errorAppeared) {
@@ -1032,16 +1085,23 @@
     private static MessageFormat expiredTimeForm = null;
     private static MessageFormat expiringTimeForm = null;
 
-    /*
-     * Display some details about a certificate:
+    /**
+     * Returns a string about a certificate:
      *
      * [<tab>] <cert-type> [", " <subject-DN>] [" (" <keystore-entry-alias> ")"]
      * [<validity-period> | <expiry-warning>]
+     * [<key-usage-warning>]
      *
-     * Note: no newline character at the end
+     * Note: no newline character at the end.
+     *
+     * When isTsCert is true, this method sets global flags like hasExpiredCert,
+     * notYetValidCert, badKeyUsage, badExtendedKeyUsage, badNetscapeCertType.
+     *
+     * @param isTsCert true if c is in the TSA cert chain, false otherwise.
+     * @param checkUsage true to check code signer keyUsage
      */
-    String printCert(String tab, Certificate c, boolean checkValidityPeriod,
-        Date timestamp, boolean checkUsage) {
+    String printCert(boolean isTsCert, String tab, Certificate c,
+        Date timestamp, boolean checkUsage) throws Exception {
 
         StringBuilder certStr = new StringBuilder();
         String space = rb.getString("SPACE");
@@ -1061,7 +1121,7 @@
             certStr.append(space).append(alias);
         }
 
-        if (checkValidityPeriod && x509Cert != null) {
+        if (x509Cert != null) {
 
             certStr.append("\n").append(tab).append("[");
             Date notAfter = x509Cert.getNotAfter();
@@ -1074,7 +1134,7 @@
                     x509Cert.checkValidity();
                     // test if cert will expire within six months
                     if (notAfter.getTime() < System.currentTimeMillis() + SIX_MONTHS) {
-                        hasExpiringCert = true;
+                        if (!isTsCert) hasExpiringCert = true;
                         if (expiringTimeForm == null) {
                             expiringTimeForm = new MessageFormat(
                                 rb.getString("certificate.will.expire.on"));
@@ -1095,7 +1155,7 @@
                     certStr.append(validityTimeForm.format(source));
                 }
             } catch (CertificateExpiredException cee) {
-                hasExpiredCert = true;
+                if (!isTsCert) hasExpiredCert = true;
 
                 if (expiredTimeForm == null) {
                     expiredTimeForm = new MessageFormat(
@@ -1105,7 +1165,7 @@
                 certStr.append(expiredTimeForm.format(source));
 
             } catch (CertificateNotYetValidException cnyve) {
-                notYetValidCert = true;
+                if (!isTsCert) notYetValidCert = true;
 
                 if (notYetTimeForm == null) {
                     notYetTimeForm = new MessageFormat(
@@ -1218,7 +1278,25 @@
     }
 
     void signJar(String jarName, String alias, String[] args)
-        throws Exception {
+            throws Exception {
+
+        DisabledAlgorithmConstraints dac =
+                new DisabledAlgorithmConstraints(
+                        DisabledAlgorithmConstraints.PROPERTY_CERTPATH_DISABLED_ALGS);
+
+        if (digestalg != null && !dac.permits(
+                Collections.singleton(CryptoPrimitive.MESSAGE_DIGEST), digestalg, null)) {
+            weakAlg |= 1;
+        }
+        if (tSADigestAlg != null && !dac.permits(
+                Collections.singleton(CryptoPrimitive.MESSAGE_DIGEST), tSADigestAlg, null)) {
+            weakAlg |= 4;
+        }
+        if (sigalg != null && !dac.permits(
+                Collections.singleton(CryptoPrimitive.SIGNATURE), sigalg, null)) {
+            weakAlg |= 2;
+        }
+
         boolean aliasUsed = false;
         X509Certificate tsaCert = null;
 
@@ -1494,7 +1572,7 @@
                             tsaURI);
                     }
                     System.out.println(rb.getString("TSA.certificate.") +
-                        printCert("", tsaCert, false, null, false));
+                            printCert(true, "", tsaCert, null, false));
                 }
                 if (signingMechanism != null) {
                     System.out.println(
@@ -1557,6 +1635,30 @@
             }
         }
 
+        // The JarSigner API always accepts the timestamp received.
+        // We need to extract the certs from the signed jar to
+        // validate it.
+        if (!noTimestamp) {
+            try (JarFile check = new JarFile(signedJarFile)) {
+                PKCS7 p7 = new PKCS7(check.getInputStream(check.getEntry(
+                        "META-INF/" + sigfile + "." + privateKey.getAlgorithm())));
+                SignerInfo si = p7.getSignerInfos()[0];
+                PKCS7 tsToken = si.getTsToken();
+                SignerInfo tsSi = tsToken.getSignerInfos()[0];
+                try {
+                    validateCertChain(Validator.VAR_TSA_SERVER,
+                            tsSi.getCertificateChain(tsToken), null);
+                } catch (Exception e) {
+                    tsaChainNotValidated = true;
+                    tsaChainNotValidatedReason = e;
+                }
+            } catch (Exception e) {
+                if (debug) {
+                    e.printStackTrace();
+                }
+            }
+        }
+
         // no IOException thrown in the follow try clause, so disable
         // the try clause.
         // try {
@@ -1586,8 +1688,10 @@
             }
 
             boolean warningAppeared = false;
-            if (badKeyUsage || badExtendedKeyUsage || badNetscapeCertType ||
-                    notYetValidCert || chainNotValidated || hasExpiredCert) {
+            if (weakAlg != 0 || badKeyUsage || badExtendedKeyUsage
+                    || badNetscapeCertType || notYetValidCert
+                    || chainNotValidated || tsaChainNotValidated
+                    || hasExpiredCert || signerSelfSigned) {
                 if (strict) {
                     System.out.println(rb.getString("jar.signed.with.signer.errors."));
                     System.out.println();
@@ -1623,8 +1727,37 @@
                 }
 
                 if (chainNotValidated) {
+                    System.out.println(String.format(
+                            rb.getString("The.signer.s.certificate.chain.is.invalid.reason.1"),
+                            chainNotValidatedReason.getLocalizedMessage()));
+                }
+
+                if (tsaChainNotValidated) {
+                    System.out.println(String.format(
+                            rb.getString("The.tsa.certificate.chain.is.invalid.reason.1"),
+                            tsaChainNotValidatedReason.getLocalizedMessage()));
+                }
+
+                if (signerSelfSigned) {
                     System.out.println(
-                            rb.getString("The.signer.s.certificate.chain.is.not.validated."));
+                            rb.getString("The.signer.s.certificate.is.self.signed."));
+                }
+
+                if ((weakAlg & 1) == 1) {
+                    System.out.println(String.format(
+                            rb.getString("The.1.algorithm.specified.for.the.2.option.is.considered.a.security.risk."),
+                            digestalg, "-digestalg"));
+                }
+
+                if ((weakAlg & 2) == 2) {
+                    System.out.println(String.format(
+                            rb.getString("The.1.algorithm.specified.for.the.2.option.is.considered.a.security.risk."),
+                            sigalg, "-sigalg"));
+                }
+                if ((weakAlg & 4) == 4) {
+                    System.out.println(String.format(
+                            rb.getString("The.1.algorithm.specified.for.the.2.option.is.considered.a.security.risk."),
+                            tSADigestAlg, "-tsadigestalg"));
                 }
             } else {
                 System.out.println(rb.getString("jar.signed."));
@@ -1700,18 +1833,18 @@
     /**
      * Returns a string of singer info, with a newline at the end
      */
-    private String signerInfo(CodeSigner signer, String tab) {
+    private String signerInfo(CodeSigner signer, String tab) throws Exception {
         if (cacheForSignerInfo.containsKey(signer)) {
             return cacheForSignerInfo.get(signer);
         }
-        StringBuffer s = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         List<? extends Certificate> certs = signer.getSignerCertPath().getCertificates();
         // display the signature timestamp, if present
         Date timestamp;
         Timestamp ts = signer.getTimestamp();
         if (ts != null) {
-            s.append(printTimestamp(tab, ts));
-            s.append('\n');
+            sb.append(printTimestamp(tab, ts));
+            sb.append('\n');
             timestamp = ts.getTimestamp();
         } else {
             timestamp = null;
@@ -1720,28 +1853,41 @@
         // display the certificate(s). The first one is end-entity cert and
         // its KeyUsage should be checked.
         boolean first = true;
+        sb.append(tab).append(rb.getString("...Signer")).append('\n');
         for (Certificate c : certs) {
-            s.append(printCert(tab, c, true, timestamp, first));
-            s.append('\n');
+            sb.append(printCert(false, tab, c, timestamp, first));
+            sb.append('\n');
             first = false;
         }
         try {
-            validateCertChain(certs);
+            validateCertChain(Validator.VAR_CODE_SIGNING, certs, ts);
         } catch (Exception e) {
-            if (debug) {
-                e.printStackTrace();
+            chainNotValidated = true;
+            chainNotValidatedReason = e;
+            sb.append(tab).append(rb.getString(".Invalid.certificate.chain."))
+                    .append(e.getLocalizedMessage()).append("]\n");
+        }
+        if (ts != null) {
+            sb.append(tab).append(rb.getString("...TSA")).append('\n');
+            for (Certificate c : ts.getSignerCertPath().getCertificates()) {
+                sb.append(printCert(true, tab, c, timestamp, false));
+                sb.append('\n');
             }
-            if (e.getCause() != null &&
-                    (e.getCause() instanceof CertificateExpiredException ||
-                     e.getCause() instanceof CertificateNotYetValidException)) {
-                // No more warning, we alreay have hasExpiredCert or notYetValidCert
-            } else {
-                chainNotValidated = true;
-                s.append(tab + rb.getString(".CertPath.not.validated.") +
-                        e.getLocalizedMessage() + "]\n");   // TODO
+            try {
+                validateCertChain(Validator.VAR_TSA_SERVER,
+                        ts.getSignerCertPath().getCertificates(), null);
+            } catch (Exception e) {
+                tsaChainNotValidated = true;
+                tsaChainNotValidatedReason = e;
+                sb.append(tab).append(rb.getString(".Invalid.TSA.certificate.chain."))
+                        .append(e.getLocalizedMessage()).append("]\n");
             }
         }
-        String result = s.toString();
+        if (certs.size() == 1
+                && KeyStoreUtil.isSelfSigned((X509Certificate)certs.get(0))) {
+            signerSelfSigned = true;
+        }
+        String result = sb.toString();
         cacheForSignerInfo.put(signer, result);
         return result;
     }
@@ -1793,9 +1939,6 @@
         }
 
         try {
-
-            certificateFactory = CertificateFactory.getInstance("X.509");
-            validator = CertPathValidator.getInstance("PKIX");
             Set<TrustAnchor> tas = new HashSet<>();
             try {
                 KeyStore caks = KeyStoreUtil.getCacertsKeyStore();
@@ -1871,7 +2014,7 @@
                 }
             } finally {
                 try {
-                    pkixParameters = new PKIXParameters(tas);
+                    pkixParameters = new PKIXBuilderParameters(tas, null);
                     pkixParameters.setRevocationEnabled(false);
                 } catch (InvalidAlgorithmParameterException ex) {
                     // Only if tas is empty
@@ -1987,7 +2130,7 @@
         }
     }
 
-    void getAliasInfo(String alias) {
+    void getAliasInfo(String alias) throws Exception {
 
         Key key = null;
 
@@ -2033,21 +2176,18 @@
 
             // We don't meant to print anything, the next call
             // checks validity and keyUsage etc
-            printCert("", certChain[0], true, null, true);
+            printCert(false, "", certChain[0], null, true);
 
             try {
-                validateCertChain(Arrays.asList(certChain));
+                validateCertChain(Validator.VAR_CODE_SIGNING,
+                        Arrays.asList(certChain), null);
             } catch (Exception e) {
-                if (debug) {
-                    e.printStackTrace();
-                }
-                if (e.getCause() != null &&
-                        (e.getCause() instanceof CertificateExpiredException ||
-                        e.getCause() instanceof CertificateNotYetValidException)) {
-                    // No more warning, we alreay have hasExpiredCert or notYetValidCert
-                } else {
-                    chainNotValidated = true;
-                }
+                chainNotValidated = true;
+                chainNotValidatedReason = e;
+            }
+
+            if (KeyStoreUtil.isSelfSigned(certChain[0])) {
+                signerSelfSigned = true;
             }
 
             try {
@@ -2101,19 +2241,55 @@
         System.exit(1);
     }
 
-    void validateCertChain(List<? extends Certificate> certs) throws Exception {
-        int cpLen = 0;
-        out: for (; cpLen<certs.size(); cpLen++) {
-            for (TrustAnchor ta: pkixParameters.getTrustAnchors()) {
-                if (ta.getTrustedCert().equals(certs.get(cpLen))) {
-                    break out;
+    /**
+     * Validates a cert chain.
+     *
+     * @param parameter this might be a timestamp
+     */
+    void validateCertChain(String variant, List<? extends Certificate> certs,
+                           Object parameter)
+            throws Exception {
+        try {
+            Validator.getInstance(Validator.TYPE_PKIX,
+                    variant,
+                    pkixParameters)
+                    .validate(certs.toArray(new X509Certificate[certs.size()]),
+                            null, parameter);
+        } catch (Exception e) {
+            if (debug) {
+                e.printStackTrace();
+            }
+
+            // Exception might be dismissed if another warning flag
+            // is already set by printCert. This is only done for
+            // code signing certs.
+
+            if (variant.equals(Validator.VAR_CODE_SIGNING) &&
+                    e instanceof ValidatorException) {
+                // Throw cause if it's CertPathValidatorException,
+                if (e.getCause() != null &&
+                        e.getCause() instanceof CertPathValidatorException) {
+                    e = (Exception) e.getCause();
+                    Throwable t = e.getCause();
+                    if ((t instanceof CertificateExpiredException &&
+                                hasExpiredCert) ||
+                            (t instanceof CertificateNotYetValidException &&
+                                    notYetValidCert)) {
+                        // we already have hasExpiredCert and notYetValidCert
+                        return;
+                    }
+                }
+                if (e instanceof ValidatorException) {
+                    ValidatorException ve = (ValidatorException)e;
+                    if (ve.getErrorType() == ValidatorException.T_EE_EXTENSIONS &&
+                            (badKeyUsage || badExtendedKeyUsage || badNetscapeCertType)) {
+                        // We already have badKeyUsage, badExtendedKeyUsage
+                        // and badNetscapeCertType
+                        return;
+                    }
                 }
             }
-        }
-        if (cpLen > 0) {
-            CertPath cp = certificateFactory.generateCertPath(
-                    (cpLen == certs.size())? certs: certs.subList(0, cpLen));
-            validator.validate(cp, pkixParameters);
+            throw e;
         }
     }
 
--- a/src/share/classes/sun/security/tools/jarsigner/Resources.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/tools/jarsigner/Resources.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -199,7 +199,8 @@
         {"certificate.is.not.valid.until",
                 "certificate is not valid until {0}"},
         {"certificate.will.expire.on", "certificate will expire on {0}"},
-        {".CertPath.not.validated.", "[CertPath not validated: "},
+        {".Invalid.certificate.chain.", "[Invalid certificate chain: "},
+        {".Invalid.TSA.certificate.chain.", "[Invalid TSA certificate chain: "},
         {"requesting.a.signature.timestamp",
                 "requesting a signature timestamp"},
         {"TSA.location.", "TSA location: "},
@@ -216,6 +217,8 @@
         {"entry.was.signed.on", "entry was signed on {0}"},
         {"Warning.", "Warning: "},
         {"Error.", "Error: "},
+        {"...Signer", ">>> Signer"},
+        {"...TSA", ">>> TSA"},
         {"This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.",
                 "This jar contains unsigned entries which have not been integrity-checked. "},
         {"This.jar.contains.entries.whose.signer.certificate.has.expired.",
@@ -224,6 +227,8 @@
                 "This jar contains entries whose signer certificate will expire within six months. "},
         {"This.jar.contains.entries.whose.signer.certificate.is.not.yet.valid.",
                 "This jar contains entries whose signer certificate is not yet valid. "},
+        {"This.jar.contains.entries.whose.signer.certificate.is.self.signed.",
+                "This jar contains entries whose signer certificate is self-signed."},
         {"Re.run.with.the.verbose.option.for.more.details.",
                 "Re-run with the -verbose option for more details."},
         {"Re.run.with.the.verbose.and.certs.options.for.more.details.",
@@ -248,14 +253,24 @@
                  "This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing."},
         {".{0}.extension.does.not.support.code.signing.",
                  "[{0} extension does not support code signing]"},
-        {"The.signer.s.certificate.chain.is.not.validated.",
-                "The signer's certificate chain is not validated."},
-        {"This.jar.contains.entries.whose.certificate.chain.is.not.validated.",
-                 "This jar contains entries whose certificate chain is not validated."},
+        {"The.signer.s.certificate.chain.is.invalid.reason.1",
+                "The signer's certificate chain is invalid. Reason: %s"},
+        {"The.tsa.certificate.chain.is.invalid.reason.1",
+                "The TSA certificate chain is invalid. Reason: %s"},
+        {"The.signer.s.certificate.is.self.signed.",
+                "The signer's certificate is self-signed."},
+        {"The.1.algorithm.specified.for.the.2.option.is.considered.a.security.risk.",
+                "The %1$s algorithm specified for the %2$s option is considered a security risk."},
+        {"This.jar.contains.entries.whose.certificate.chain.is.invalid.reason.1",
+                 "This jar contains entries whose certificate chain is invalid. Reason: %s"},
+        {"This.jar.contains.entries.whose.tsa.certificate.chain.is.invalid.reason.1",
+                "This jar contains entries whose TSA certificate chain is invalid. Reason: %s"},
         {"no.timestamp.signing",
                 "No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (%1$tY-%1$tm-%1$td) or after any future revocation date."},
         {"no.timestamp.verifying",
                 "This jar contains signatures that does not include a timestamp. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (%1$tY-%1$tm-%1$td) or after any future revocation date."},
+        {"bad.timestamp.verifying",
+                "This jar contains signatures that include an invalid timestamp. Without a valid timestamp, users may not be able to validate this jar after any of the signer certificates expire (as early as %1$tY-%1$tm-%1$td).\nRerun jarsigner with -J-Djava.security.debug=jar for more information."},
         {"Unknown.password.type.", "Unknown password type: "},
         {"Cannot.find.environment.variable.",
                 "Cannot find environment variable: "},
--- a/src/share/classes/sun/security/tools/jarsigner/Resources_ja.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/tools/jarsigner/Resources_ja.java	Mon Oct 15 15:05:59 2018 +0100
@@ -199,7 +199,8 @@
         {"certificate.is.not.valid.until",
                 "\u8A3C\u660E\u66F8\u306F{0}\u307E\u3067\u6709\u52B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093"},
         {"certificate.will.expire.on", "\u8A3C\u660E\u66F8\u306F{0}\u306B\u5931\u52B9\u3057\u307E\u3059"},
-        {".CertPath.not.validated.", "[CertPath\u304C\u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093: "},
+        {".Invalid.certificate.chain.", "[\u7121\u52B9\u306A\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3: "},
+        {".Invalid.TSA.certificate.chain.", "[\u7121\u52B9\u306ATSA\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3: "},
         {"requesting.a.signature.timestamp",
                 "\u30B7\u30B0\u30CD\u30C1\u30E3\u30FB\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u306E\u30EA\u30AF\u30A8\u30B9\u30C8"},
         {"TSA.location.", "TSA\u306E\u5834\u6240: "},
@@ -214,6 +215,8 @@
         {"entry.was.signed.on", "\u30A8\u30F3\u30C8\u30EA\u306F{0}\u306B\u7F72\u540D\u3055\u308C\u307E\u3057\u305F"},
         {"Warning.", "\u8B66\u544A: "},
         {"Error.", "\u30A8\u30E9\u30FC: "},
+        {"...Signer", ">>> \u7F72\u540D\u8005"},
+        {"...TSA", ">>> TSA"},
         {"This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.",
                 "\u3053\u306Ejar\u306B\u306F\u3001\u6574\u5408\u6027\u30C1\u30A7\u30C3\u30AF\u3092\u3057\u3066\u3044\u306A\u3044\u7F72\u540D\u306A\u3057\u306E\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002 "},
         {"This.jar.contains.entries.whose.signer.certificate.has.expired.",
@@ -222,6 +225,8 @@
                 "\u3053\u306Ejar\u306B\u306F\u3001\u7F72\u540D\u8005\u306E\u8A3C\u660E\u66F8\u304C6\u304B\u6708\u4EE5\u5185\u306B\u671F\u9650\u5207\u308C\u3068\u306A\u308B\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002 "},
         {"This.jar.contains.entries.whose.signer.certificate.is.not.yet.valid.",
                 "\u3053\u306Ejar\u306B\u306F\u3001\u7F72\u540D\u8005\u306E\u8A3C\u660E\u66F8\u304C\u307E\u3060\u6709\u52B9\u306B\u306A\u3063\u3066\u3044\u306A\u3044\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002 "},
+        {"This.jar.contains.entries.whose.signer.certificate.is.self.signed.",
+                "\u3053\u306Ejar\u306B\u306F\u3001\u7F72\u540D\u8005\u306E\u8A3C\u660E\u66F8\u304C\u81EA\u5DF1\u7F72\u540D\u3055\u308C\u3066\u3044\u308B\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002 "},
         {"Re.run.with.the.verbose.option.for.more.details.",
                 "\u8A73\u7D30\u306F\u3001-verbose\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u518D\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002"},
         {"Re.run.with.the.verbose.and.certs.options.for.more.details.",
@@ -246,14 +251,24 @@
                  "\u3053\u306Ejar\u306B\u306F\u3001\u7F72\u540D\u8005\u8A3C\u660E\u66F8\u306ENetscapeCertType\u62E1\u5F35\u6A5F\u80FD\u304C\u30B3\u30FC\u30C9\u7F72\u540D\u3092\u8A31\u53EF\u3057\u306A\u3044\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002"},
         {".{0}.extension.does.not.support.code.signing.",
                  "[{0}\u62E1\u5F35\u6A5F\u80FD\u306F\u30B3\u30FC\u30C9\u7F72\u540D\u3092\u30B5\u30DD\u30FC\u30C8\u3057\u3066\u3044\u307E\u305B\u3093]"},
-        {"The.signer.s.certificate.chain.is.not.validated.",
-                "\u7F72\u540D\u8005\u306E\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u304C\u307E\u3060\u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
-        {"This.jar.contains.entries.whose.certificate.chain.is.not.validated.",
-                 "\u3053\u306Ejar\u306B\u306F\u3001\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u304C\u307E\u3060\u691C\u8A3C\u3055\u308C\u3066\u3044\u306A\u3044\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002"},
+        {"The.signer.s.certificate.chain.is.invalid.reason.1",
+                "\u7F72\u540D\u8005\u306E\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u304C\u7121\u52B9\u3067\u3059\u3002\u7406\u7531: %s"},
+        {"The.tsa.certificate.chain.is.invalid.reason.1",
+                "TSA\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u304C\u7121\u52B9\u3067\u3059\u3002\u7406\u7531: %s"},
+        {"The.signer.s.certificate.is.self.signed.",
+                "\u7F72\u540D\u8005\u306E\u8A3C\u660E\u66F8\u306F\u81EA\u5DF1\u7F72\u540D\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
+        {"The.1.algorithm.specified.for.the.2.option.is.considered.a.security.risk.",
+                "%1$s\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0(%2$s\u30AA\u30D7\u30B7\u30E7\u30F3\u306B\u6307\u5B9A)\u306F\u3001\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"},
+        {"This.jar.contains.entries.whose.certificate.chain.is.invalid.reason.1",
+                 "\u3053\u306Ejar\u306B\u306F\u3001\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u304C\u7121\u52B9\u306A\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002\u7406\u7531: %s"},
+        {"This.jar.contains.entries.whose.tsa.certificate.chain.is.invalid.reason.1",
+                "\u3053\u306Ejar\u306B\u306F\u3001TSA\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u304C\u7121\u52B9\u306A\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002\u7406\u7531: %s"},
         {"no.timestamp.signing",
                 "-tsa\u307E\u305F\u306F-tsacert\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u3053\u306Ejar\u306B\u306F\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u4ED8\u52A0\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u306A\u3044\u3068\u3001\u7F72\u540D\u8005\u8A3C\u660E\u66F8\u306E\u6709\u52B9\u671F\u9650(%1$tY-%1$tm-%1$td)\u5F8C\u307E\u305F\u306F\u5C06\u6765\u306E\u5931\u52B9\u65E5\u5F8C\u306B\u3001\u30E6\u30FC\u30B6\u30FC\u306F\u3053\u306Ejar\u3092\u691C\u8A3C\u3067\u304D\u306A\u3044\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002"},
         {"no.timestamp.verifying",
                 "\u3053\u306Ejar\u306B\u306F\u3001\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u306A\u3044\u7F72\u540D\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u306A\u3044\u3068\u3001\u7F72\u540D\u8005\u8A3C\u660E\u66F8\u306E\u6709\u52B9\u671F\u9650(%1$tY-%1$tm-%1$td)\u5F8C\u307E\u305F\u306F\u5C06\u6765\u306E\u5931\u52B9\u65E5\u5F8C\u306B\u3001\u30E6\u30FC\u30B6\u30FC\u306F\u3053\u306Ejar\u3092\u691C\u8A3C\u3067\u304D\u306A\u3044\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002"},
+        {"bad.timestamp.verifying",
+                "\u3053\u306Ejar\u306B\u306F\u3001\u7121\u52B9\u306A\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u306E\u3042\u308B\u7F72\u540D\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002\u6709\u52B9\u306A\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u306A\u3044\u3068\u3001\u3044\u305A\u308C\u304B\u306E\u7F72\u540D\u8005\u8A3C\u660E\u66F8\u306E\u6709\u52B9\u671F\u9650\u5F8C\u306B(\u65E9\u3051\u308C\u3070%1$tY-%1$tm-%1$td)\u30E6\u30FC\u30B6\u30FC\u306F\u3053\u306Ejar\u3092\u691C\u8A3C\u3067\u304D\u306A\u3044\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002\n\u8A73\u7D30\u306F\u3001-J-Djava.security.debug=jar\u3092\u6307\u5B9A\u3057\u3066jarsigner\u3092\u518D\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002"},
         {"Unknown.password.type.", "\u4E0D\u660E\u306A\u30D1\u30B9\u30EF\u30FC\u30C9\u30FB\u30BF\u30A4\u30D7: "},
         {"Cannot.find.environment.variable.",
                 "\u74B0\u5883\u5909\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: "},
--- a/src/share/classes/sun/security/tools/jarsigner/Resources_zh_CN.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/tools/jarsigner/Resources_zh_CN.java	Mon Oct 15 15:05:59 2018 +0100
@@ -199,7 +199,8 @@
         {"certificate.is.not.valid.until",
                 "\u76F4\u5230{0}, \u8BC1\u4E66\u624D\u6709\u6548"},
         {"certificate.will.expire.on", "\u8BC1\u4E66\u5C06\u5728{0}\u5230\u671F"},
-        {".CertPath.not.validated.", "[CertPath \u672A\u9A8C\u8BC1: "},
+        {".Invalid.certificate.chain.", "[\u65E0\u6548\u7684\u8BC1\u4E66\u94FE: "},
+        {".Invalid.TSA.certificate.chain.", "[\u65E0\u6548 TSA \u7684\u8BC1\u4E66\u94FE: "},
         {"requesting.a.signature.timestamp",
                 "\u6B63\u5728\u8BF7\u6C42\u7B7E\u540D\u65F6\u95F4\u6233"},
         {"TSA.location.", "TSA \u4F4D\u7F6E: "},
@@ -214,6 +215,8 @@
         {"entry.was.signed.on", "\u6761\u76EE\u7684\u7B7E\u540D\u65E5\u671F\u4E3A {0}"},
         {"Warning.", "\u8B66\u544A: "},
         {"Error.", "\u9519\u8BEF: "},
+        {"...Signer", ">>> \u7B7E\u540D\u8005"},
+        {"...TSA", ">>> TSA"},
         {"This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.",
                 "\u6B64 jar \u5305\u542B\u5C1A\u672A\u8FDB\u884C\u5B8C\u6574\u6027\u68C0\u67E5\u7684\u672A\u7B7E\u540D\u6761\u76EE\u3002 "},
         {"This.jar.contains.entries.whose.signer.certificate.has.expired.",
@@ -222,6 +225,8 @@
                 "\u6B64 jar \u5305\u542B\u7B7E\u540D\u8005\u8BC1\u4E66\u5C06\u5728\u516D\u4E2A\u6708\u5185\u8FC7\u671F\u7684\u6761\u76EE\u3002 "},
         {"This.jar.contains.entries.whose.signer.certificate.is.not.yet.valid.",
                 "\u6B64 jar \u5305\u542B\u7B7E\u540D\u8005\u8BC1\u4E66\u4ECD\u65E0\u6548\u7684\u6761\u76EE\u3002 "},
+        {"This.jar.contains.entries.whose.signer.certificate.is.self.signed.",
+                "\u6B64 jar \u5305\u542B\u5176\u7B7E\u540D\u8005\u8BC1\u4E66\u4E3A\u81EA\u7B7E\u540D\u8BC1\u4E66\u7684\u6761\u76EE\u3002"},
         {"Re.run.with.the.verbose.option.for.more.details.",
                 "\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F, \u8BF7\u4F7F\u7528 -verbose \u9009\u9879\u91CD\u65B0\u8FD0\u884C\u3002"},
         {"Re.run.with.the.verbose.and.certs.options.for.more.details.",
@@ -246,14 +251,24 @@
                  "\u6B64 jar \u5305\u542B\u7531\u4E8E\u7B7E\u540D\u8005\u8BC1\u4E66\u7684 NetscapeCertType \u6269\u5C55\u800C\u65E0\u6CD5\u8FDB\u884C\u4EE3\u7801\u7B7E\u540D\u7684\u6761\u76EE\u3002"},
         {".{0}.extension.does.not.support.code.signing.",
                  "[{0} \u6269\u5C55\u4E0D\u652F\u6301\u4EE3\u7801\u7B7E\u540D]"},
-        {"The.signer.s.certificate.chain.is.not.validated.",
-                "\u7B7E\u540D\u8005\u7684\u8BC1\u4E66\u94FE\u672A\u9A8C\u8BC1\u3002"},
-        {"This.jar.contains.entries.whose.certificate.chain.is.not.validated.",
-                 "\u6B64 jar \u5305\u542B\u8BC1\u4E66\u94FE\u672A\u9A8C\u8BC1\u7684\u6761\u76EE\u3002"},
+        {"The.signer.s.certificate.chain.is.invalid.reason.1",
+                "\u7B7E\u540D\u8005\u8BC1\u4E66\u94FE\u65E0\u6548\u3002\u539F\u56E0: %s"},
+        {"The.tsa.certificate.chain.is.invalid.reason.1",
+                "TSA \u8BC1\u4E66\u94FE\u65E0\u6548\u3002\u539F\u56E0: %s"},
+        {"The.signer.s.certificate.is.self.signed.",
+                "\u7B7E\u540D\u8005\u8BC1\u4E66\u4E3A\u81EA\u7B7E\u540D\u8BC1\u4E66\u3002"},
+        {"The.1.algorithm.specified.for.the.2.option.is.considered.a.security.risk.",
+                "\u4E3A %2$s \u9009\u9879\u6307\u5B9A\u7684 %1$s \u7B97\u6CD5\u88AB\u89C6\u4E3A\u5B58\u5728\u5B89\u5168\u98CE\u9669\u3002"},
+        {"This.jar.contains.entries.whose.certificate.chain.is.invalid.reason.1",
+                 "\u6B64 jar \u5305\u542B\u5176\u8BC1\u4E66\u94FE\u65E0\u6548\u7684\u6761\u76EE\u3002\u539F\u56E0: %s"},
+        {"This.jar.contains.entries.whose.tsa.certificate.chain.is.invalid.reason.1",
+                "\u6B64 jar \u5305\u542B\u5176 TSA \u8BC1\u4E66\u94FE\u65E0\u6548\u7684\u6761\u76EE\u3002\u539F\u56E0: %s"},
         {"no.timestamp.signing",
                 "\u672A\u63D0\u4F9B -tsa \u6216 -tsacert, \u6B64 jar \u6CA1\u6709\u65F6\u95F4\u6233\u3002\u5982\u679C\u6CA1\u6709\u65F6\u95F4\u6233, \u5219\u5728\u7B7E\u540D\u8005\u8BC1\u4E66\u7684\u5230\u671F\u65E5\u671F (%1$tY-%1$tm-%1$td) \u6216\u4EE5\u540E\u7684\u4EFB\u4F55\u64A4\u9500\u65E5\u671F\u4E4B\u540E, \u7528\u6237\u53EF\u80FD\u65E0\u6CD5\u9A8C\u8BC1\u6B64 jar\u3002"},
         {"no.timestamp.verifying",
                 "\u6B64 jar \u5305\u542B\u7684\u7B7E\u540D\u6CA1\u6709\u65F6\u95F4\u6233\u3002\u5982\u679C\u6CA1\u6709\u65F6\u95F4\u6233, \u5219\u5728\u7B7E\u540D\u8005\u8BC1\u4E66\u7684\u5230\u671F\u65E5\u671F (%1$tY-%1$tm-%1$td) \u6216\u4EE5\u540E\u7684\u4EFB\u4F55\u64A4\u9500\u65E5\u671F\u4E4B\u540E, \u7528\u6237\u53EF\u80FD\u65E0\u6CD5\u9A8C\u8BC1\u6B64 jar\u3002"},
+        {"bad.timestamp.verifying",
+                "\u6B64 jar \u5305\u542B\u5E26\u6709\u65E0\u6548\u65F6\u95F4\u6233\u7684\u7B7E\u540D\u3002\u5982\u679C\u6CA1\u6709\u6709\u6548\u65F6\u95F4\u6233, \u5219\u5728\u5176\u4E2D\u4EFB\u4E00\u7B7E\u540D\u8005\u8BC1\u4E66\u5230\u671F (\u6700\u65E9\u4E3A %1$tY-%1$tm-%1$td) \u4E4B\u540E, \u7528\u6237\u53EF\u80FD\u65E0\u6CD5\u9A8C\u8BC1\u6B64 jar\u3002\n\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F, \u8BF7\u4F7F\u7528 -J-Djava.security.debug=jar \u91CD\u65B0\u8FD0\u884C jarsigner\u3002"},
         {"Unknown.password.type.", "\u672A\u77E5\u53E3\u4EE4\u7C7B\u578B: "},
         {"Cannot.find.environment.variable.",
                 "\u627E\u4E0D\u5230\u73AF\u5883\u53D8\u91CF: "},
--- a/src/share/classes/sun/security/tools/keytool/Main.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/tools/keytool/Main.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1352,7 +1352,7 @@
         for (Certificate ca: keyStore.getCertificateChain(alias)) {
             if (ca instanceof X509Certificate) {
                 X509Certificate xca = (X509Certificate)ca;
-                if (!isSelfSigned(xca)) {
+                if (!KeyStoreUtil.isSelfSigned(xca)) {
                     dumpCert(xca, out);
                 }
             }
@@ -2869,7 +2869,7 @@
 
         // if certificate is self-signed, make sure it verifies
         boolean selfSigned = false;
-        if (isSelfSigned(cert)) {
+        if (KeyStoreUtil.isSelfSigned(cert)) {
             cert.verify(cert.getPublicKey());
             selfSigned = true;
         }
@@ -3173,25 +3173,6 @@
     }
 
     /**
-     * Returns true if the certificate is self-signed, false otherwise.
-     */
-    private boolean isSelfSigned(X509Certificate cert) {
-        return signedBy(cert, cert);
-    }
-
-    private boolean signedBy(X509Certificate end, X509Certificate ca) {
-        if (!ca.getSubjectDN().equals(end.getIssuerDN())) {
-            return false;
-        }
-        try {
-            end.verify(ca.getPublicKey());
-            return true;
-        } catch (Exception e) {
-            return false;
-        }
-    }
-
-    /**
      * Locates a signer for a given certificate from a given keystore and
      * returns the signer's certificate.
      * @param cert the certificate whose signer is searched, not null
@@ -3531,7 +3512,7 @@
             // find a cert in the reply who signs thisCert
             int j;
             for (j=i; j<replyCerts.length; j++) {
-                if (signedBy(thisCert, (X509Certificate)replyCerts[j])) {
+                if (KeyStoreUtil.signedBy(thisCert, (X509Certificate)replyCerts[j])) {
                     tmpCert = replyCerts[i];
                     replyCerts[i] = replyCerts[j];
                     replyCerts[j] = tmpCert;
@@ -3689,7 +3670,7 @@
     private boolean buildChain(Pair<String,X509Certificate> certToVerify,
             Vector<Pair<String,X509Certificate>> chain,
             Hashtable<Principal, Vector<Pair<String,X509Certificate>>> certs) {
-        if (isSelfSigned(certToVerify.snd)) {
+        if (KeyStoreUtil.isSelfSigned(certToVerify.snd)) {
             // reached self-signed root cert;
             // no verification needed because it's trusted.
             chain.addElement(certToVerify);
--- a/src/share/classes/sun/security/util/SignatureFileVerifier.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/classes/sun/security/util/SignatureFileVerifier.java	Mon Oct 15 15:05:59 2018 +0100
@@ -719,7 +719,8 @@
             if (signers == null) {
                 signers = new ArrayList<>();
             }
-            // Append the new code signer
+            // Append the new code signer. If timestamp is invalid, this
+            // jar will be treated as unsigned.
             signers.add(new CodeSigner(certChain, info.getTimestamp()));
 
             if (debug != null) {
--- a/src/share/lib/security/java.security-aix	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/lib/security/java.security-aix	Mon Oct 15 15:05:59 2018 +0100
@@ -619,8 +619,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224, DES40_CBC, RC4_40, 3DES_EDE_CBC
+jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, 3DES_EDE_CBC
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
--- a/src/share/lib/security/java.security-linux	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/lib/security/java.security-linux	Mon Oct 15 15:05:59 2018 +0100
@@ -619,8 +619,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224, DES40_CBC, RC4_40, 3DES_EDE_CBC
+jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, 3DES_EDE_CBC
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
--- a/src/share/lib/security/java.security-macosx	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/lib/security/java.security-macosx	Mon Oct 15 15:05:59 2018 +0100
@@ -622,8 +622,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224, DES40_CBC, RC4_40, 3DES_EDE_CBC
+jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, 3DES_EDE_CBC
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
--- a/src/share/lib/security/java.security-solaris	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/lib/security/java.security-solaris	Mon Oct 15 15:05:59 2018 +0100
@@ -621,8 +621,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224, DES40_CBC, RC4_40, 3DES_EDE_CBC
+jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, 3DES_EDE_CBC
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
--- a/src/share/lib/security/java.security-windows	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/lib/security/java.security-windows	Mon Oct 15 15:05:59 2018 +0100
@@ -622,8 +622,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224, DES40_CBC, RC4_40, 3DES_EDE_CBC
+jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, 3DES_EDE_CBC
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
--- a/src/share/native/sun/awt/libpng/CHANGES	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/CHANGES	Mon Oct 15 15:05:59 2018 +0100
@@ -1,4 +1,3 @@
-#if 0
 CHANGES - changes for libpng
 
 version 0.1 [March 29, 1995]
@@ -833,7 +832,7 @@
   Removed the new PNG_CREATED_READ_STRUCT and PNG_CREATED_WRITE_STRUCT modes
     which are no longer used.
   Eliminated the three new members of png_text when PNG_LEGACY_SUPPORTED is
-    defined or when neither PNG_READ_iTXt_SUPPORTED nor PNG_WRITE_iTXT_SUPPORTED
+    defined or when neither PNG_READ_iTXt_SUPPORTED nor PNG_WRITE_iTXt_SUPPORTED
     is defined.
   Made PNG_NO_READ|WRITE_iTXt the default setting, to avoid memory
     overrun when old applications fill the info_ptr->text structure directly.
@@ -1454,7 +1453,7 @@
     sequential read support.
   Added some "#if PNG_WRITE_SUPPORTED" blocks.
   Added #ifdef to remove some redundancy in png_malloc_default().
-  Use png_malloc instead of png_zalloc to allocate the pallete.
+  Use png_malloc instead of png_zalloc to allocate the palette.
 
 Version 1.0.16rc1 and 1.2.6rc1 [August 4, 2004]
   Fixed buffer overflow vulnerability (CVE-2004-0597) in png_handle_tRNS().
@@ -3259,7 +3258,7 @@
   Revised PNG_EXPORTA macro to not use an empty parameter, to accommodate the
     old VisualC++ preprocessor.
   Turned on interlace handling in png_read_png().
-  Fixed gcc pendantic warnings.
+  Fixed gcc pedantic warnings.
   Handle longjmp in Cygwin.
   Fixed png_get_current_row_number() in the interlaced case.
   Cleaned up ALPHA flags and transformations.
@@ -3359,7 +3358,7 @@
   Pass "" instead of '\0' to png_default_error() in png_err().  This mistake
     was introduced in libpng-1.2.20beta01.  This fixes CVE-2011-2691.
   Added PNG_WRITE_OPTIMIZE_CMF_SUPPORTED macro to make the zlib "CMF" byte
-    optimization configureable.
+    optimization configurable.
   IDAT compression failed if preceded by a compressed text chunk (bug
     introduced in libpng-1.5.3beta01-02).  This was because the attempt to
     reset the zlib stream in png_write_IDAT happened after the first IDAT
@@ -3643,7 +3642,7 @@
   Fixed bug in png_write_chunk_header() debug print, introduced in 1.5.6beta01.
 
 Version 1.5.6beta06 [October 17, 2011]
-  Removed two redundant tests for unitialized row.
+  Removed two redundant tests for uninitialized row.
   Fixed a relatively harmless memory overwrite in compressed text writing
     with a 1 byte zlib buffer.
   Add ability to call png_read_update_info multiple times to pngvalid.c.
@@ -3689,7 +3688,7 @@
     crash.  The pngmem.c implementation of png_malloc() included a cast
     to png_size_t which would fail on large allocations on 16-bit systems.
   Fix for the preprocessor of the Intel C compiler. The preprocessor
-    splits adjacent @ signs with a space; this changes the concatentation
+    splits adjacent @ signs with a space; this changes the concatenation
     token from @-@-@ to PNG_JOIN; that should work with all compiler
     preprocessors.
   Paeth filter speed improvements from work by Siarhei Siamashka. This
@@ -3735,7 +3734,7 @@
     gray (on palette) itself.
   Fixes for C++ compilation using g++ When libpng source is compiled
     using g++. The compiler imposes C++ rules on the C source; thus it
-    is desireable to make the source work with either C or C++ rules
+    is desirable to make the source work with either C or C++ rules
     without throwing away useful error information.  This change adds
     png_voidcast to allow C semantic (void*) cases or the corresponding
     C++ static_cast operation, as appropriate.
@@ -4061,7 +4060,7 @@
     possible to call png_inflate() incrementally.  A warning is no longer
     issued if the language tag or translated keyword in the iTXt chunk
     has zero length.
-  If benign errors are disabled use maximum window on ancilliary inflate.
+  If benign errors are disabled use maximum window on ancillary inflate.
     This works round a bug introduced in 1.5.4 where compressed ancillary
     chunks could end up with a too-small windowBits value in the deflate
     header.
@@ -4176,7 +4175,7 @@
     declared even though the functions are never actually defined.  This
     change provides a dummy definition so that the declarations work, yet any
     implementation will fail to compile because of an incomplete type.
-  Re-eliminated the use of strcpy() in pngtest.c.  An unncessary use of
+  Re-eliminated the use of strcpy() in pngtest.c.  An unnecessary use of
     strcpy() was accidentally re-introduced in libpng16; this change replaces
     it with strncpy().
   Eliminated use of png_sizeof(); use sizeof() instead.
@@ -4309,7 +4308,7 @@
     resulting in VS2010 having to update the files.
   Removed non-working ICC profile support code that was mostly added to
     libpng-1.6.0beta29 and beta30. There was too much code for too little
-    gain; implementing full ICC color correction may be desireable but is left
+    gain; implementing full ICC color correction may be desirable but is left
     up to applications.
 
 Version 1.6.0beta32 [November 25, 2012]
@@ -4592,7 +4591,7 @@
     the optimizations ('check' vs 'api') are exposed in the public header files
     except that the new setting PNG_ARM_NEON_OPT documents how libpng makes the
     decision about whether or not to use the optimizations.
-  Protect symbol prefixing against CC/CPPFLAGS/CFLAGS useage.
+  Protect symbol prefixing against CC/CPPFLAGS/CFLAGS usage.
     Previous iOS/Xcode fixes for the ARM NEON optimizations moved the test
     on __ARM_NEON__ from configure time to compile time.  This breaks symbol
     prefixing because the definition of the special png_init_filter_functions
@@ -5635,7 +5634,7 @@
     to All and adds a list of the warnings that need to be turned off.  This is
     semi-documentary; the intent is to tell libpng users which warnings have
     been examined and judged non-fixable at present.  The warning about
-    structure padding is fixable, but it would be a signficant change (moving
+    structure padding is fixable, but it would be a significant change (moving
     structure members around).
 
 Version 1.6.24beta03 [July 4, 2016]
@@ -5761,7 +5760,9 @@
     if built with zlib-1.2.8.1.
 
 Version 1.6.27rc01 [December 27, 2016]
-  Control ADLER32 checking with new PNG_IGNORE_ADLER32 option.
+  Control ADLER32 checking with new PNG_IGNORE_ADLER32 option. Fixes
+    an endless loop when handling erroneous ADLER32 checksums; bug
+    introduced in libpng-1.6.26.
   Removed the use of a macro containing the pre-processor 'defined'
     operator.  It is unclear whether this is valid; a macro that
     "generates" 'defined' is not permitted, but the use of the word
@@ -5779,7 +5780,7 @@
   Added option to Cmake build allowing a custom location of zlib to be
     specified in a scenario where libpng is being built as a subproject
     alongside zlib by another project (Sam Serrels).
-  Changed png_ptr->options from a png_byte to png_uint_32, to accomodate
+  Changed png_ptr->options from a png_byte to png_uint_32, to accommodate
     up to 16 options.
 
 Version 1.6.28rc02 [January 4, 2017]
@@ -5794,11 +5795,277 @@
 Version 1.6.28 [January 5, 2017]
   No changes.
 
+Version 1.6.29beta01 [January 12, 2017]
+  Readded "include(GNUInstallDirs)" to CMakeLists.txt (Gianfranco Costamagna).
+  Moved SSE2 optimization code into the main libpng source directory.
+    Configure libpng with "configure --enable-intel-sse" or compile
+    libpng with "-DPNG_INTEL_SSE" in CPPFLAGS to enable it.
+  Simplified conditional compilation in pngvalid.c, for AIX (Michael Felt).
+
+Version 1.6.29beta02 [February 22, 2017]
+  Avoid conditional directives that break statements in pngrutil.c (Romero
+    Malaquias)
+  The contrib/examples/pngtopng.c recovery code was in the wrong "if"
+    branches; the comments were correct.
+  Added code for PowerPC VSX optimisation (Vadim Barkov).
+
+Version 1.6.29beta03 [March 1, 2017]
+  Avoid potential overflow of shift operations in png_do_expand() (Aaron Boxer).
+  Change test ZLIB_VERNUM >= 0x1281 to ZLIB_VERNUM >= 0x1290 in pngrutil.c
+    because Solaris 11 distributes zlib-1.2.8.f that is older than 1.2.8.1,
+    as suggested in zlib FAQ, item 24.
+  Suppress clang warnings about implicit sign changes in png.c
+
+Version 1.6.29 [March 16, 2017]
+  No changes.
+
+Version 1.6.30beta01 [April 1, 2017]
+  Added missing "$(CPPFLAGS)" to the compile line for c.pic.o in
+    makefile.linux and makefile.solaris-x86 (Cosmin).
+  Revised documentation of png_get_error_ptr() in the libpng manual.
+  Silence clang -Wcomma and const drop warnings (Viktor Szakats).
+  Update Sourceforge URLs in documentation (https instead of http).
+
+Version 1.6.30beta02 [April 22, 2017]
+  Document need to check for integer overflow when allocating a pixel
+    buffer for multiple rows in contrib/gregbook, contrib/pngminus,
+    example.c, and in the manual (suggested by Jaeseung Choi). This
+    is similar to the bug reported against pngquant in CVE-2016-5735.
+  Removed reference to the obsolete PNG_SAFE_LIMITS macro in the documentation.
+
+Version 1.6.30beta03 [May 22, 2017]
+  Check for integer overflow in contrib/visupng and contrib/tools/genpng.
+  Do not double evaluate CMAKE_SYSTEM_PROCESSOR in CMakeLists.txt.
+  Test CMAKE_HOST_WIN32 instead of WIN32 in CMakeLists.txt.
+  Fix some URL in documentation.
+
+Version 1.6.30beta04 [June 7, 2017]
+  Avoid writing an empty IDAT when the last IDAT exactly fills the
+    compression buffer (bug report by Brian Baird). This bug was
+    introduced in libpng-1.6.0.
+
+Version 1.6.30rc01 [June 14, 2017]
+  No changes.
+
+Version 1.6.30rc02 [June 25, 2017]
+  Update copyright year in pnglibconf.h, make ltmain.sh executable.
+  Add a reference to the libpng.download site in README.
+
+Version 1.6.30 [June 28, 2017]
+  No changes.
+
+Version 1.6.31beta01 [July 5, 2017]
+  Guard the definition of _POSIX_SOURCE in pngpriv.h (AIX already defines it;
+    bug report by Michael Felt).
+  Revised pngpriv.h to work around failure to compile arm/filter_neon.S
+    ("typedef" directive is unrecognized by the assembler). The problem
+    was introduced in libpng-1.6.30beta01.
+  Added "Requires: zlib" to libpng.pc.in (Pieter Neerincx).
+  Added special case for FreeBSD in arm/filter_neon.S (Maya Rashish).
+
+Version 1.6.31beta02 [July 8, 2017]
+  Added instructions for disabling hardware optimizations in INSTALL.
+  Added "--enable-hardware-optimizations" configuration flag to enable
+    or disable all hardware optimizations with one flag.
+
+Version 1.6.31beta03 [July 9, 2017]
+  Updated CMakeLists.txt to add INTEL_SSE and MIPS_MSA platforms.
+  Changed "int" to "png_size_t" in intel/filter_sse2.c to prevent
+    possible integer overflow (Bug report by John Bowler).
+  Quieted "declaration after statement" warnings in intel/filter_sse2.c.
+  Added scripts/makefile-linux-opt, which has hardware optimizations enabled.
+
+Version 1.6.31beta04 [July 11, 2017]
+  Removed one of the GCC-7.1.0 'strict-overflow' warnings that result when
+    integers appear on both sides of a compare.  Worked around the others by
+    forcing the strict-overflow setting in the relevant functions to a level
+    where they are not reported (John Bowler).
+  Changed "FALL THROUGH" comments to "FALLTHROUGH" because GCC doesn't like
+    the space.
+  Worked around some C-style casts from (void*) because g++ 5.4.0 objects
+    to them.
+  Increased the buffer size for 'sprint' to pass the gcc 7.1.0 'sprint
+    overflow' check that is on by default with -Wall -Wextra.
+
+Version 1.6.31beta05 [July 13, 2017]
+  Added eXIf chunk support.
+
+Version 1.6.31beta06 [July 17, 2017]
+  Added a minimal eXIf chunk (with Orientation and FocalLengthIn35mmFilm
+    tags) to pngtest.png.
+
+Version 1.6.31beta07 [July 18, 2017]
+  Revised the eXIf chunk in pngtest.png to fix "Bad IFD1 Directory" warning.
+
+Version 1.6.31rc01 [July 19, 2017]
+  No changes.
+
+Version 1.6.31rc02 [July 25, 2017]
+  Fixed typo in example.c (png_free_image should be png_image_free) (Bug
+    report by John Smith)
+
+Version 1.6.31 [July 27, 2017]
+  No changes.
+
+Version 1.6.32beta01 [July 31, 2017]
+  Avoid possible NULL dereference in png_handle_eXIf when benign_errors
+    are allowed. Avoid leaking the input buffer "eXIf_buf".
+  Eliminated png_ptr->num_exif member from pngstruct.h and added num_exif
+    to arguments for png_get_eXIf() and png_set_eXIf().
+  Added calls to png_handle_eXIf(() in pngread.c and png_write_eXIf() in
+    pngwrite.c, and made various other fixes to png_write_eXIf().
+  Changed name of png_get_eXIF and png_set_eXIf() to png_get_eXIf_1() and
+    png_set_eXIf_1(), respectively, to avoid breaking API compatibility
+    with libpng-1.6.31.
+
+Version 1.6.32beta02 [August 1, 2017]
+  Updated contrib/libtests/pngunknown.c with eXIf chunk.
+
+Version 1.6.32beta03 [August 2, 2017]
+  Initialized btoa[] in pngstest.c
+  Stop memory leak when returning from png_handle_eXIf() with an error
+    (Bug report from the OSS-fuzz project).
+
+Version 1.6.32beta04 [August 2, 2017]
+  Replaced local eXIf_buf with info_ptr-eXIf_buf in png_handle_eXIf().
+  Update libpng.3 and libpng-manual.txt about eXIf functions.
+
+Version 1.6.32beta05 [August 2, 2017]
+  Restored png_get_eXIf() and png_set_eXIf() to maintain API compatibility.
+
+Version 1.6.32beta06 [August 2, 2017]
+  Removed png_get_eXIf_1() and png_set_eXIf_1().
+
+Version 1.6.32beta07 [August 3, 2017]
+  Check length of all chunks except IDAT against user limit to fix an
+    OSS-fuzz issue (Fixes CVE-2017-12652).
+
+Version 1.6.32beta08 [August 3, 2017]
+  Check length of IDAT against maximum possible IDAT size, accounting
+    for height, rowbytes, interlacing and zlib/deflate overhead.
+  Restored png_get_eXIf_1() and png_set_eXIf_1(), because strlen(eXIf_buf)
+    does not work (the eXIf chunk data can contain zeroes).
+
+Version 1.6.32beta09 [August 3, 2017]
+  Require cmake-2.8.8 in CMakeLists.txt. Revised symlink creation,
+    no longer using deprecated cmake LOCATION feature (Clifford Yapp).
+  Fixed five-byte error in the calculation of IDAT maximum possible size.
+  
+Version 1.6.32beta10 [August 5, 2017]
+  Moved chunk-length check into a png_check_chunk_length() private
+    function (Suggested by Max Stepin).
+  Moved bad pngs from tests to contrib/libtests/crashers
+  Moved testing of bad pngs into a separate tests/pngtest-badpngs script
+  Added the --xfail (expected FAIL) option to pngtest.c. It writes XFAIL
+    in the output but PASS for the libpng test.
+  Require cmake-3.0.2 in CMakeLists.txt (Clifford Yapp).
+  Fix "const" declaration info_ptr argument to png_get_eXIf_1() and the
+    num_exif argument to png_get_eXIf_1() (Github Issue 171).
+
+Version 1.6.32beta11 [August 7, 2017]
+  Added "eXIf" to "chunks_to_ignore[]" in png_set_keep_unknown_chunks().
+  Added huge_IDAT.png and empty_ancillary_chunks.png to testpngs/crashers.
+  Make pngtest --strict, --relax, --xfail options imply -m (multiple).
+  Removed unused chunk_name parameter from png_check_chunk_length().
+  Relocated setting free_me for eXIf data, to stop an OSS-fuzz leak.
+  Initialize profile_header[] in png_handle_iCCP() to fix OSS-fuzz issue.
+  Initialize png_ptr->row_buf[0] to 255 in png_read_row() to fix OSS-fuzz UMR.
+  Attempt to fix a UMR in png_set_text_2() to fix OSS-fuzz issue.
+  Increase minimum zlib stream from 9 to 14 in png_handle_iCCP(), to account
+    for the minimum 'deflate' stream, and relocate the test to a point
+    after the keyword has been read.
+  Check that the eXIf chunk has at least 2 bytes and begins with "II" or "MM".
+
+Version 1.6.32rc01 [August 18, 2017]
+  Added a set of "huge_xxxx_chunk.png" files to contrib/testpngs/crashers,
+    one for each known chunk type, with length = 2GB-1.
+  Check for 0 return from png_get_rowbytes() and added some (size_t) typecasts
+    in contrib/pngminus/*.c to stop some Coverity issues (162705, 162706,
+    and 162707).
+  Renamed chunks in contrib/testpngs/crashers to avoid having files whose
+    names differ only in case; this causes problems with some platforms
+    (github issue #172).
+
+Version 1.6.32rc02 [August 22, 2017]
+  Added contrib/oss-fuzz directory which contains files used by the oss-fuzz
+    project (https://github.com/google/oss-fuzz/tree/master/projects/libpng).
+
+Version 1.6.32 [August 24, 2017]
+  No changes.
+
+Version 1.6.33beta01 [August 28, 2017]
+  Added PNGMINUS_UNUSED macro to contrib/pngminus/p*.c and added missing
+    parenthesis in contrib/pngminus/pnm2png.c (bug report by Christian Hesse).
+  Fixed off-by-one error in png_do_check_palette_indexes() (Bug report
+    by Mick P., Source Forge Issue #269).
+
+Version 1.6.33beta02 [September 3, 2017]
+  Initialize png_handler.row_ptr in contrib/oss-fuzz/libpng_read_fuzzer.cc
+    to fix shortlived oss-fuzz issue 3234.
+  Compute a larger limit on IDAT because some applications write a deflate
+    buffer for each row (Bug report by Andrew Church).
+  Use current date (DATE) instead of release-date (RDATE) in last
+    changed date of contrib/oss-fuzz files.
+  Enabled ARM support in CMakeLists.txt (Bernd Kuhls).
+
+Version 1.6.33beta03 [September 14, 2017]
+  Fixed incorrect typecast of some arguments to png_malloc() and
+    png_calloc() that were png_uint_32 instead of png_alloc_size_t
+    (Bug report by "irwir" in Github libpng issue #175).
+  Use pnglibconf.h.prebuilt when building for ANDROID with cmake (Github
+    issue 162, by rcdailey).
+
+Version 1.6.33rc01 [September 20, 2017]
+  Initialize memory allocated by png_inflate to zero, using memset, to
+    stop an oss-fuzz "use of uninitialized value" detection in png_set_text_2()
+    due to truncated iTXt or zTXt chunk.
+  Initialize memory allocated by png_read_buffer to zero, using memset, to
+    stop an oss-fuzz "use of uninitialized value" detection in
+    png_icc_check_tag_table() due to truncated iCCP chunk.
+  Removed a redundant test (suggested by "irwir" in Github issue #180).
+
+Version 1.6.33rc02 [September 23, 2017]
+  Added an interlaced version of each file in contrib/pngsuite.
+  Relocate new memset() call in pngrutil.c.
+  Removed more redundant tests (suggested by "irwir" in Github issue #180).
+  Add support for loading images with associated alpha in the Simplified
+    API (Samuel Williams).
+
+Version 1.6.33 [September 28, 2017]
+  Revert contrib/oss-fuzz/libpng_read_fuzzer.cc to libpng-1.6.32 state.
+  Initialize png_handler.row_ptr in contrib/oss-fuzz/libpng_read_fuzzer.cc
+  Add end_info structure and png_read_end() to the libpng fuzzer.
+
+Version 1.6.34 [September 29, 2017]
+  Removed contrib/pngsuite/i*.png; some of them caused test failures.
+
+Version 1.6.35beta01 [March 6, 2018]
+  Restored 21 of the contrib/pngsuite/i*.png, which do not cause test
+    failures. Placed the remainder in contrib/pngsuite/interlaced/i*.png.
+  Added calls to png_set_*() transforms commonly used by browsers to
+    the fuzzer.
+  Removed some unnecessary brackets in pngrtran.c
+  Fixed miscellaneous typos (Patch by github user "luzpaz").
+  Change "ASM C" to "C ASM" in CMakeLists.txt
+  Fixed incorrect handling of bKGD chunk in sub-8-bit files (Cosmin)
+  Added hardware optimization directories to zip and 7z distributions.
+  Fixed incorrect bitmask for options.
+  Fixed many spelling typos.
+
+Version 1.6.35beta02 [March 28, 2018]
+  Make png_get_iCCP consistent with man page (allow compression-type argument
+  to be NULL, bug report by Lenard Szolnoki).
+
+Version 1.6.35 [July 15, 2018]
+  Replaced the remaining uses of png_size_t with size_t (Cosmin)
+  Fixed the calculation of row_factor in png_check_chunk_length
+    (reported by Thuan Pham in SourceForge issue #278)
+  Added missing parentheses to a macro definition
+    (suggested by "irwir" in GitHub issue #216)
+
 Send comments/corrections/commendations to png-mng-implement at lists.sf.net
 (subscription required; visit
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement
-to subscribe)
-or to glennrp at users.sourceforge.net
+to subscribe).
 
 Glenn R-P
-#endif
--- a/src/share/native/sun/awt/libpng/LICENSE	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/LICENSE	Mon Oct 15 15:05:59 2018 +0100
@@ -10,8 +10,8 @@
 
 This code is released under the libpng license.
 
-libpng versions 1.0.7, July 1, 2000 through 1.6.28, January 5, 2017 are
-Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are
+libpng versions 1.0.7, July 1, 2000 through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
 derived from libpng-1.0.6, and are distributed according to the same
 disclaimer and license as libpng-1.0.6 with the following individuals
 added to the list of Contributing Authors:
@@ -23,6 +23,8 @@
    Gilles Vollant
    James Yu
    Mandar Sahastrabuddhe
+   Google Inc.
+   Vadim Barkov
 
 and with the following additions to the disclaimer:
 
@@ -128,4 +130,4 @@
 
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-January 5, 2017
+July 15, 2018
--- a/src/share/native/sun/awt/libpng/README	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/README	Mon Oct 15 15:05:59 2018 +0100
@@ -1,4 +1,4 @@
-README for libpng version 1.6.28 - January 5, 2017 (shared library 16.0)
+README for libpng version 1.6.35 - July 15, 2018 (shared library 16.0)
 See the note about version numbers near the top of png.h
 
 See INSTALL for instructions on how to install libpng.
@@ -23,7 +23,7 @@
 png_uint_32, which will affect shared-library applications that use
 this function.
 
-To avoid problems with changes to the internals of png info_struct,
+To avoid problems with changes to the internals of the png info_struct,
 new APIs have been made available in 0.95 to avoid direct application
 access to info_ptr.  These functions are the png_set_<chunk> and
 png_get_<chunk> functions.  These functions should be used when
@@ -88,11 +88,11 @@
 
 You may also want a copy of the PNG specification.  It is available
 as an RFC, a W3C Recommendation, and an ISO/IEC Standard.  You can find
-these at http://www.libpng.org/pub/png/documents/
+these at http://www.libpng.org/pub/png/pngdocs.html .
 
-This code is currently being archived at libpng.sf.net in the
-[DOWNLOAD] area, and at ftp://ftp.simplesystems.org.  If you can't find it
-in any of those places, e-mail me, and I'll help you find it.
+This code is currently being archived at libpng.sourceforge.io in the
+[DOWNLOAD] area, and at http://libpng.download/src .  If you
+can't find it in any of those places, e-mail me, and I'll help you find it.
 
 I am not a lawyer, but I believe that the Export Control Classification
 Number (ECCN) for libpng is EAR99, which means not subject to export
@@ -118,7 +118,7 @@
 Send comments/corrections/commendations to png-mng-implement at
 lists.sourceforge.net (subscription required; visit
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement
-to subscribe) or to glennrp at users.sourceforge.net
+to subscribe).
 
 You can't reach Guy, the original libpng author, at the addresses
 given in previous versions of this document.  He and Andreas will
@@ -179,14 +179,16 @@
       pngwtran.c    =>  Write data transformations
       pngwutil.c    =>  Write utility functions
       arm           =>  Contains optimized code for the ARM platform
+      powerpc       =>  Contains optimized code for the PowerPC platform
       contrib       =>  Contributions
        arm-neon         =>  Optimized code for ARM-NEON platform
+       powerpc-vsx      =>  Optimized code for POWERPC-VSX platform
        examples         =>  Example programs
        gregbook         =>  source code for PNG reading and writing, from
                             Greg Roelofs' "PNG: The Definitive Guide",
                             O'Reilly, 1999
-       intel            =>  Optimized code for INTEL-SSE2 platform
        libtests         =>  Test programs
+       mips-msa         =>  Optimized code for MIPS-MSA platform
        pngminim         =>  Minimal decoder, encoder, and progressive decoder
                             programs demonstrating use of pngusr.dfa
        pngminus         =>  Simple pnm2png and png2pnm programs
@@ -194,6 +196,8 @@
        testpngs
        tools            =>  Various tools
        visupng          =>  Contains a MSVC workspace for VisualPng
+      intel             =>  Optimized code for INTEL-SSE2 platform
+      mips              =>  Optimized code for MIPS platform
       projects      =>  Contains project files and workspaces for
                         building a DLL
        owatcom          =>  Contains a WATCOM project for building libpng
--- a/src/share/native/sun/awt/libpng/png.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/png.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.28 [January 5, 2017]
- * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -42,7 +42,27 @@
 #include "pngpriv.h"
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef png_libpng_version_1_6_28 Your_png_h_is_not_version_1_6_28;
+typedef png_libpng_version_1_6_35 Your_png_h_is_not_version_1_6_35;
+
+#ifdef __GNUC__
+/* The version tests may need to be added to, but the problem warning has
+ * consistently been fixed in GCC versions which obtain wide-spread release.
+ * The problem is that many versions of GCC rearrange comparison expressions in
+ * the optimizer in such a way that the results of the comparison will change
+ * if signed integer overflow occurs.  Such comparisons are not permitted in
+ * ANSI C90, however GCC isn't clever enough to work out that that do not occur
+ * below in png_ascii_from_fp and png_muldiv, so it produces a warning with
+ * -Wextra.  Unfortunately this is highly dependent on the optimizer and the
+ * machine architecture so the warning comes and goes unpredictably and is
+ * impossible to "fix", even were that a good idea.
+ */
+#if __GNUC__ == 7 && __GNUC_MINOR__ == 1
+#define GCC_STRICT_OVERFLOW 1
+#endif /* GNU 7.1.x */
+#endif /* GNU */
+#ifndef GCC_STRICT_OVERFLOW
+#define GCC_STRICT_OVERFLOW 0
+#endif
 
 /* Tells libpng that we have already handled the first "num_bytes" bytes
  * of the PNG file signature.  If the PNG data is embedded into another
@@ -79,7 +99,7 @@
  * PNG signature (this is the same behavior as strcmp, memcmp, etc).
  */
 int PNGAPI
-png_sig_cmp(png_const_bytep sig, png_size_t start, png_size_t num_to_check)
+png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check)
 {
    png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
 
@@ -144,7 +164,7 @@
  * trouble of calculating it.
  */
 void /* PRIVATE */
-png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, png_size_t length)
+png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)
 {
    int need_crc = 1;
 
@@ -429,7 +449,7 @@
  * those cases where it does anything other than a memset.
  */
 PNG_FUNCTION(void,PNGAPI
-png_info_init_3,(png_infopp ptr_ptr, png_size_t png_info_struct_size),
+png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),
     PNG_DEPRECATED)
 {
    png_inforp info_ptr = *ptr_ptr;
@@ -623,6 +643,26 @@
    }
 #endif
 
+#ifdef PNG_eXIf_SUPPORTED
+   /* Free any eXIf entry */
+   if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)
+   {
+# ifdef PNG_READ_eXIf_SUPPORTED
+      if (info_ptr->eXIf_buf)
+      {
+         png_free(png_ptr, info_ptr->eXIf_buf);
+         info_ptr->eXIf_buf = NULL;
+      }
+# endif
+      if (info_ptr->exif)
+      {
+         png_free(png_ptr, info_ptr->exif);
+         info_ptr->exif = NULL;
+      }
+      info_ptr->valid &= ~PNG_INFO_eXIf;
+   }
+#endif
+
 #ifdef PNG_hIST_SUPPORTED
    /* Free any hIST entry */
    if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
@@ -804,15 +844,15 @@
 #else
 #  ifdef __STDC__
    return PNG_STRING_NEWLINE \
-      "libpng version 1.6.28 - January 5, 2017" PNG_STRING_NEWLINE \
-      "Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson" \
+      "libpng version 1.6.35 - July 15, 2018" PNG_STRING_NEWLINE \
+      "Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \
       PNG_STRING_NEWLINE \
       "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
       "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
       PNG_STRING_NEWLINE;
 #  else
-   return "libpng version 1.6.28 - January 5, 2017\
-      Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson\
+   return "libpng version 1.6.35 - July 15, 2018\
+      Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson\
       Copyright (c) 1996-1997 Andreas Dilger\
       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
 #  endif
@@ -930,7 +970,7 @@
 
    /* The code is the fifth byte after each four byte string.  Historically this
     * code was always searched from the end of the list, this is no longer
-    * necessary because the 'set' routine handles duplicate entries correcty.
+    * necessary because the 'set' routine handles duplicate entries correctly.
     */
    do /* num_chunk_list > 0, so at least one */
    {
@@ -1901,12 +1941,12 @@
     */
    if (intent < 0 || intent >= PNG_sRGB_INTENT_LAST)
       return png_icc_profile_error(png_ptr, colorspace, "sRGB",
-          (unsigned)intent, "invalid sRGB rendering intent");
+          (png_alloc_size_t)intent, "invalid sRGB rendering intent");
 
    if ((colorspace->flags & PNG_COLORSPACE_HAVE_INTENT) != 0 &&
        colorspace->rendering_intent != intent)
       return png_icc_profile_error(png_ptr, colorspace, "sRGB",
-         (unsigned)intent, "inconsistent rendering intents");
+         (png_alloc_size_t)intent, "inconsistent rendering intents");
 
    if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0)
    {
@@ -1967,7 +2007,6 @@
    if (profile_length < 132)
       return png_icc_profile_error(png_ptr, colorspace, name, profile_length,
           "too short");
-
    return 1;
 }
 
@@ -2056,7 +2095,7 @@
     */
 
    /* Data checks (could be skipped).  These checks must be independent of the
-    * version number; however, the version number doesn't accomodate changes in
+    * version number; however, the version number doesn't accommodate changes in
     * the header fields (just the known tags and the interpretation of the
     * data.)
     */
@@ -2212,15 +2251,6 @@
        * being in range.  All defined tag types have an 8 byte header - a 4 byte
        * type signature then 0.
        */
-      if ((tag_start & 3) != 0)
-      {
-         /* CNHP730S.icc shipped with Microsoft Windows 64 violates this, it is
-          * only a warning here because libpng does not care about the
-          * alignment.
-          */
-         (void)png_icc_profile_error(png_ptr, NULL, name, tag_id,
-             "ICC profile tag start not a multiple of 4");
-      }
 
       /* This is a hard error; potentially it can cause read outside the
        * profile.
@@ -2228,6 +2258,16 @@
       if (tag_start > profile_length || tag_length > profile_length - tag_start)
          return png_icc_profile_error(png_ptr, colorspace, name, tag_id,
              "ICC profile tag outside profile");
+
+      if ((tag_start & 3) != 0)
+      {
+         /* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is
+          * only a warning here because libpng does not care about the
+          * alignment.
+          */
+         (void)png_icc_profile_error(png_ptr, NULL, name, tag_id,
+             "ICC profile tag start not a multiple of 4");
+      }
    }
 
    return 1; /* success, maybe with warnings */
@@ -2695,7 +2735,7 @@
 
 #if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
 /* ASCII to fp functions */
-/* Check an ASCII formated floating point value, see the more detailed
+/* Check an ASCII formatted floating point value, see the more detailed
  * comments in pngpriv.h
  */
 /* The following is used internally to preserve the sticky flags */
@@ -2703,11 +2743,11 @@
 #define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))
 
 int /* PRIVATE */
-png_check_fp_number(png_const_charp string, png_size_t size, int *statep,
+png_check_fp_number(png_const_charp string, size_t size, int *statep,
     png_size_tp whereami)
 {
    int state = *statep;
-   png_size_t i = *whereami;
+   size_t i = *whereami;
 
    while (i < size)
    {
@@ -2830,10 +2870,10 @@
 
 /* The same but for a complete string. */
 int
-png_check_fp_string(png_const_charp string, png_size_t size)
+png_check_fp_string(png_const_charp string, size_t size)
 {
    int        state=0;
-   png_size_t char_index=0;
+   size_t char_index=0;
 
    if (png_check_fp_number(string, size, &state, &char_index) != 0 &&
       (char_index == size || string[char_index] == 0))
@@ -2860,7 +2900,7 @@
    if (power < 0)
    {
       if (power < DBL_MIN_10_EXP) return 0;
-      recip = 1, power = -power;
+      recip = 1; power = -power;
    }
 
    if (power > 0)
@@ -2885,8 +2925,16 @@
 /* Function to format a floating point value in ASCII with a given
  * precision.
  */
+#if GCC_STRICT_OVERFLOW
+#pragma GCC diagnostic push
+/* The problem arises below with exp_b10, which can never overflow because it
+ * comes, originally, from frexp and is therefore limited to a range which is
+ * typically +/-710 (log2(DBL_MAX)/log2(DBL_MIN)).
+ */
+#pragma GCC diagnostic warning "-Wstrict-overflow=2"
+#endif /* GCC_STRICT_OVERFLOW */
 void /* PRIVATE */
-png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
+png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size,
     double fp, unsigned int precision)
 {
    /* We use standard functions from math.h, but not printf because
@@ -2938,7 +2986,9 @@
             double test = png_pow10(exp_b10+1);
 
             if (test <= DBL_MAX)
-               ++exp_b10, base = test;
+            {
+               ++exp_b10; base = test;
+            }
 
             else
                break;
@@ -2952,7 +3002,10 @@
           * test on DBL_MAX above.
           */
          fp /= base;
-         while (fp >= 1) fp /= 10, ++exp_b10;
+         while (fp >= 1)
+         {
+            fp /= 10; ++exp_b10;
+         }
 
          /* Because of the code above fp may, at this point, be
           * less than .1, this is ok because the code below can
@@ -2969,7 +3022,7 @@
              */
             if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
             {
-               czero = (unsigned int)(-exp_b10); /* PLUS 2 digits: TOTAL 3 */
+               czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */
                exp_b10 = 0;      /* Dot added below before first output. */
             }
             else
@@ -3003,7 +3056,7 @@
                      /* Rounding up to 10, handle that here. */
                      if (czero > 0)
                      {
-                        --czero, d = 1;
+                        --czero; d = 1;
                         if (cdigits == 0) --clead;
                      }
                      else
@@ -3017,7 +3070,7 @@
 
                            else if (ch == 46)
                            {
-                              ch = *--ascii, ++size;
+                              ch = *--ascii; ++size;
                               /* Advance exp_b10 to '1', so that the
                                * decimal point happens after the
                                * previous digit.
@@ -3044,7 +3097,9 @@
                               int ch = *--ascii;
 
                               if (ch == 46)
-                                 ++size, exp_b10 = 1;
+                              {
+                                 ++size; exp_b10 = 1;
+                              }
 
                               /* Else lost a leading zero, so 'exp_b10' is
                                * still ok at (-1)
@@ -3080,21 +3135,26 @@
                       */
                      if (exp_b10 != (-1))
                      {
-                        if (exp_b10 == 0) *ascii++ = 46, --size;
+                        if (exp_b10 == 0)
+                        {
+                           *ascii++ = 46; --size;
+                        }
                         /* PLUS 1: TOTAL 4 */
                         --exp_b10;
                      }
-                     *ascii++ = 48, --czero;
+                     *ascii++ = 48; --czero;
                   }
 
                   if (exp_b10 != (-1))
                   {
                      if (exp_b10 == 0)
-                        *ascii++ = 46, --size; /* counted above */
+                     {
+                        *ascii++ = 46; --size; /* counted above */
+                     }
 
                      --exp_b10;
                   }
-                  *ascii++ = (char)(48 + (int)d), ++cdigits;
+                  *ascii++ = (char)(48 + (int)d); ++cdigits;
                }
             }
             while (cdigits+czero < precision+clead && fp > DBL_MIN);
@@ -3103,7 +3163,7 @@
 
             /* Check for an exponent, if we don't need one we are
              * done and just need to terminate the string.  At
-             * this point exp_b10==(-1) is effectively if flag - it got
+             * this point exp_b10==(-1) is effectively a flag - it got
              * to '-1' because of the decrement after outputting
              * the decimal point above (the exponent required is
              * *not* -1!)
@@ -3117,7 +3177,7 @@
                 * zeros were *not* output, so this doesn't increase
                 * the output count.
                 */
-               while (--exp_b10 >= 0) *ascii++ = 48;
+               while (exp_b10-- > 0) *ascii++ = 48;
 
                *ascii = 0;
 
@@ -3135,7 +3195,7 @@
              */
             size -= cdigits;
 
-            *ascii++ = 69, --size;    /* 'E': PLUS 1 TOTAL 2+precision */
+            *ascii++ = 69; --size;    /* 'E': PLUS 1 TOTAL 2+precision */
 
             /* The following use of an unsigned temporary avoids ambiguities in
              * the signed arithmetic on exp_b10 and permits GCC at least to do
@@ -3146,12 +3206,12 @@
 
                if (exp_b10 < 0)
                {
-                  *ascii++ = 45, --size; /* '-': PLUS 1 TOTAL 3+precision */
-                  uexp_b10 = (unsigned int)(-exp_b10);
+                  *ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */
+                  uexp_b10 = 0U-exp_b10;
                }
 
                else
-                  uexp_b10 = (unsigned int)exp_b10;
+                  uexp_b10 = 0U+exp_b10;
 
                cdigits = 0;
 
@@ -3194,6 +3254,9 @@
    /* Here on buffer too small. */
    png_error(png_ptr, "ASCII conversion buffer too small");
 }
+#if GCC_STRICT_OVERFLOW
+#pragma GCC diagnostic pop
+#endif /* GCC_STRICT_OVERFLOW */
 
 #  endif /* FLOATING_POINT */
 
@@ -3202,7 +3265,7 @@
  */
 void /* PRIVATE */
 png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
-    png_size_t size, png_fixed_point fp)
+    size_t size, png_fixed_point fp)
 {
    /* Require space for 10 decimal digits, a decimal point, a minus sign and a
     * trailing \0, 13 characters:
@@ -3213,7 +3276,9 @@
 
       /* Avoid overflow here on the minimum integer. */
       if (fp < 0)
-         *ascii++ = 45, num = (png_uint_32)(-fp);
+      {
+         *ascii++ = 45; num = (png_uint_32)(-fp);
+      }
       else
          num = (png_uint_32)fp;
 
@@ -3251,7 +3316,10 @@
                 * then ndigits digits to first:
                 */
                i = 5;
-               while (ndigits < i) *ascii++ = 48, --i;
+               while (ndigits < i)
+               {
+                  *ascii++ = 48; --i;
+               }
                while (ndigits >= first) *ascii++ = digits[--ndigits];
                /* Don't output the trailing zeros! */
             }
@@ -3302,6 +3370,15 @@
  * the nearest .00001).  Overflow and divide by zero are signalled in
  * the result, a boolean - true on success, false on overflow.
  */
+#if GCC_STRICT_OVERFLOW /* from above */
+/* It is not obvious which comparison below gets optimized in such a way that
+ * signed overflow would change the result; looking through the code does not
+ * reveal any tests which have the form GCC complains about, so presumably the
+ * optimizer is moving an add or subtract into the 'if' somewhere.
+ */
+#pragma GCC diagnostic push
+#pragma GCC diagnostic warning "-Wstrict-overflow=2"
+#endif /* GCC_STRICT_OVERFLOW */
 int
 png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
     png_int_32 divisor)
@@ -3416,6 +3493,9 @@
 
    return 0;
 }
+#if GCC_STRICT_OVERFLOW
+#pragma GCC diagnostic pop
+#endif /* GCC_STRICT_OVERFLOW */
 #endif /* READ_GAMMA || INCH_CONVERSIONS */
 
 #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
@@ -3709,7 +3789,7 @@
  * of getting this accuracy in practice.
  *
  * To deal with this the following exp() function works out the exponent of the
- * frational part of the logarithm by using an accurate 32-bit value from the
+ * fractional part of the logarithm by using an accurate 32-bit value from the
  * top four fractional bits then multiplying in the remaining bits.
  */
 static const png_uint_32
@@ -4288,13 +4368,13 @@
    if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
       (option & 1) == 0)
    {
-      png_uint_32 mask = 3 << option;
-      png_uint_32 setting = (2 + (onoff != 0)) << option;
+      png_uint_32 mask = 3U << option;
+      png_uint_32 setting = (2U + (onoff != 0)) << option;
       png_uint_32 current = png_ptr->options;
 
-      png_ptr->options = (png_uint_32)(((current & ~mask) | setting) & 0xff);
-
-      return (current & mask) >> option;
+      png_ptr->options = (png_uint_32)((current & ~mask) | setting);
+
+      return (int)(current & mask) >> option;
    }
 
    return PNG_OPTION_INVALID;
@@ -4306,7 +4386,7 @@
    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
 /* sRGB conversion tables; these are machine generated with the code in
  * contrib/tools/makesRGB.c.  The actual sRGB transfer curve defined in the
- * specification (see the article at http://en.wikipedia.org/wiki/SRGB)
+ * specification (see the article at https://en.wikipedia.org/wiki/SRGB)
  * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
  * The sRGB to linear table is exact (to the nearest 16-bit linear fraction).
  * The inverse (linear to sRGB) table has accuracies as follows:
--- a/src/share/native/sun/awt/libpng/png.h	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/png.h	Mon Oct 15 15:05:59 2018 +0100
@@ -29,9 +29,9 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * libpng version 1.6.28, January 5, 2017
+ * libpng version 1.6.35, July 15, 2018
  *
- * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -40,7 +40,7 @@
  * Authors and maintainers:
  *   libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  *   libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger
- *   libpng versions 0.97, January 1998, through 1.6.28, January 5, 2017:
+ *   libpng versions 0.97, January 1998, through 1.6.35, July 15, 2018:
  *     Glenn Randers-Pehrson.
  *   See also "Contributing Authors", below.
  */
@@ -53,8 +53,8 @@
  *
  * This code is released under the libpng license.
  *
- * libpng versions 1.0.7, July 1, 2000 through 1.6.28, January 5, 2017 are
- * Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are
+ * libpng versions 1.0.7, July 1, 2000 through 1.6.35, July 15, 2018 are
+ * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
  * derived from libpng-1.0.6, and are distributed according to the same
  * disclaimer and license as libpng-1.0.6 with the following individuals
  * added to the list of Contributing Authors:
@@ -66,6 +66,8 @@
  *    Gilles Vollant
  *    James Yu
  *    Mandar Sahastrabuddhe
+ *    Google Inc.
+ *    Vadim Barkov
  *
  * and with the following additions to the disclaimer:
  *
@@ -90,9 +92,6 @@
  *    Glenn Randers-Pehrson
  *    Willem van Schaik
  *
- * Some files in the "scripts" directory have different copyright owners
- * but are also released under this license.
- *
  * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  * Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
  * and are distributed according to the same disclaimer and license as
@@ -238,11 +237,11 @@
  *    ...
  *    1.0.19                  10    10019  10.so.0.19[.0]
  *    ...
- *    1.2.57                  13    10257  12.so.0.57[.0]
+ *    1.2.59                  13    10257  12.so.0.59[.0]
  *    ...
- *    1.5.28                  15    10527  15.so.15.28[.0]
+ *    1.5.30                  15    10527  15.so.15.30[.0]
  *    ...
- *    1.6.28                  16    10628  16.so.16.28[.0]
+ *    1.6.35                  16    10635  16.so.16.35[.0]
  *
  *    Henceforth the source version will match the shared-library major
  *    and minor numbers; the shared-library major version number will be
@@ -263,20 +262,20 @@
  *
  * See libpng.txt or libpng.3 for more information.  The PNG specification
  * is available as a W3C Recommendation and as an ISO Specification,
- * <http://www.w3.org/TR/2003/REC-PNG-20031110/
+ * <https://www.w3.org/TR/2003/REC-PNG-20031110/
  */
 
 /*
  * Y2K compliance in libpng:
  * =========================
  *
- *    January 5, 2017
+ *    July 15, 2018
  *
  *    Since the PNG Development group is an ad-hoc body, we can't make
  *    an official declaration.
  *
  *    This is your unofficial assurance that libpng from version 0.71 and
- *    upward through 1.6.28 are Y2K compliant.  It is my belief that
+ *    upward through 1.6.35 are Y2K compliant.  It is my belief that
  *    earlier versions were also Y2K compliant.
  *
  *    Libpng only has two year fields.  One is a 2-byte unsigned integer
@@ -338,8 +337,8 @@
  */
 
 /* Version information for png.h - this should match the version in png.c */
-#define PNG_LIBPNG_VER_STRING "1.6.28"
-#define PNG_HEADER_VERSION_STRING " libpng version 1.6.28 - January 5, 2017\n"
+#define PNG_LIBPNG_VER_STRING "1.6.35"
+#define PNG_HEADER_VERSION_STRING " libpng version 1.6.35 - July 15, 2018\n"
 
 #define PNG_LIBPNG_VER_SONUM   16
 #define PNG_LIBPNG_VER_DLLNUM  16
@@ -347,13 +346,13 @@
 /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
 #define PNG_LIBPNG_VER_MAJOR   1
 #define PNG_LIBPNG_VER_MINOR   6
-#define PNG_LIBPNG_VER_RELEASE 28
+#define PNG_LIBPNG_VER_RELEASE 35
 
 /* This should match the numeric part of the final component of
  * PNG_LIBPNG_VER_STRING, omitting any leading zero:
  */
 
-#define PNG_LIBPNG_VER_BUILD  0
+#define PNG_LIBPNG_VER_BUILD  02
 
 /* Release Status */
 #define PNG_LIBPNG_BUILD_ALPHA    1
@@ -370,7 +369,7 @@
 #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
                                        PNG_LIBPNG_BUILD_PRIVATE */
 
-#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
+#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_BETA
 
 /* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
  * We must not include leading zeros.
@@ -378,7 +377,7 @@
  * version 1.0.0 was mis-numbered 100 instead of 10000).  From
  * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release
  */
-#define PNG_LIBPNG_VER 10628 /* 1.6.28 */
+#define PNG_LIBPNG_VER 10635 /* 1.6.35 */
 
 /* Library configuration: these options cannot be changed after
  * the library has been built.
@@ -488,7 +487,7 @@
 /* This triggers a compiler error in png.c, if png.c and png.h
  * do not agree upon the version number.
  */
-typedef char* png_libpng_version_1_6_28;
+typedef char* png_libpng_version_1_6_35;
 
 /* Basic control structions.  Read libpng-manual.txt or libpng.3 for more info.
  *
@@ -629,8 +628,8 @@
    png_charp key;          /* keyword, 1-79 character description of "text" */
    png_charp text;         /* comment, may be an empty string (ie "")
                               or a NULL pointer */
-   png_size_t text_length; /* length of the text string */
-   png_size_t itxt_length; /* length of the itxt string */
+   size_t text_length;     /* length of the text string */
+   size_t itxt_length;     /* length of the itxt string */
    png_charp lang;         /* language code, 0-79 characters
                               or a NULL pointer */
    png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
@@ -683,7 +682,7 @@
 {
    png_byte name[5]; /* Textual chunk name with '\0' terminator */
    png_byte *data;   /* Data, should not be modified on read! */
-   png_size_t size;
+   size_t size;
 
    /* On write 'location' must be set using the flag values listed below.
     * Notice that on read it is set by libpng however the values stored have
@@ -708,7 +707,7 @@
 /* Maximum positive integer used in PNG is (2^31)-1 */
 #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
 #define PNG_UINT_32_MAX ((png_uint_32)(-1))
-#define PNG_SIZE_MAX ((png_size_t)(-1))
+#define PNG_SIZE_MAX ((size_t)(-1))
 
 /* These are constants for fixed point values encoded in the
  * PNG specification manner (x100000)
@@ -805,6 +804,7 @@
 #define PNG_INFO_sPLT 0x2000U  /* ESR, 1.0.6 */
 #define PNG_INFO_sCAL 0x4000U  /* ESR, 1.0.6 */
 #define PNG_INFO_IDAT 0x8000U  /* ESR, 1.0.6 */
+#define PNG_INFO_eXIf 0x10000U /* GR-P, 1.6.31 */
 
 /* This is used for the transformation routines, as some of them
  * change these values for the row.  It also should enable using
@@ -813,7 +813,7 @@
 typedef struct png_row_info_struct
 {
    png_uint_32 width;    /* width of row */
-   png_size_t rowbytes;  /* number of bytes in row */
+   size_t rowbytes;      /* number of bytes in row */
    png_byte color_type;  /* color type of row */
    png_byte bit_depth;   /* bit depth of row */
    png_byte channels;    /* number of channels (1, 2, 3, or 4) */
@@ -832,7 +832,7 @@
  * expected to return the read data in the buffer.
  */
 typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp));
-typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, png_size_t));
+typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, size_t));
 typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp));
 typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32,
     int));
@@ -969,8 +969,8 @@
  * signature, and non-zero otherwise.  Having num_to_check == 0 or
  * start > 7 will always fail (ie return non-zero).
  */
-PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start,
-    png_size_t num_to_check));
+PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, size_t start,
+    size_t num_to_check));
 
 /* Simple signature checking function.  This is the same as calling
  * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
@@ -989,11 +989,11 @@
     png_error_ptr warn_fn),
     PNG_ALLOCATED);
 
-PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size,
+PNG_EXPORT(6, size_t, png_get_compression_buffer_size,
     (png_const_structrp png_ptr));
 
 PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structrp png_ptr,
-    png_size_t size));
+    size_t size));
 
 /* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp
  * match up.
@@ -1046,7 +1046,7 @@
 
 /* Write a PNG chunk - size, type, (optional) data, CRC. */
 PNG_EXPORT(14, void, png_write_chunk, (png_structrp png_ptr, png_const_bytep
-    chunk_name, png_const_bytep data, png_size_t length));
+    chunk_name, png_const_bytep data, size_t length));
 
 /* Write the start of a PNG chunk - length and chunk name. */
 PNG_EXPORT(15, void, png_write_chunk_start, (png_structrp png_ptr,
@@ -1054,7 +1054,7 @@
 
 /* Write the data of a PNG chunk started with png_write_chunk_start(). */
 PNG_EXPORT(16, void, png_write_chunk_data, (png_structrp png_ptr,
-    png_const_bytep data, png_size_t length));
+    png_const_bytep data, size_t length));
 
 /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
 PNG_EXPORT(17, void, png_write_chunk_end, (png_structrp png_ptr));
@@ -1068,7 +1068,7 @@
  * the API will be removed in the future.
  */
 PNG_EXPORTA(19, void, png_info_init_3, (png_infopp info_ptr,
-    png_size_t png_info_struct_size), PNG_DEPRECATED);
+    size_t png_info_struct_size), PNG_DEPRECATED);
 
 /* Writes all the PNG information before the image. */
 PNG_EXPORT(20, void, png_write_info_before_PLTE,
@@ -1165,7 +1165,7 @@
  * corresponding composited pixel, and the color channels are unassociated
  * (not premultiplied).  The gamma encoded color channels must be scaled
  * according to the contribution and to do this it is necessary to undo
- * the encoding, scale the color values, perform the composition and reencode
+ * the encoding, scale the color values, perform the composition and re-encode
  * the values.  This is the 'PNG' mode.
  *
  * The alternative is to 'associate' the alpha with the color information by
@@ -1221,7 +1221,7 @@
  *
  * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
  *    In this case the output is assumed to be something like an sRGB conformant
- *    display preceeded by a power-law lookup table of power 1.45.  This is how
+ *    display preceded by a power-law lookup table of power 1.45.  This is how
  *    early Mac systems behaved.
  *
  * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_GAMMA_LINEAR);
@@ -1268,7 +1268,7 @@
  *
  * When the default gamma of PNG files doesn't match the output gamma.
  *    If you have PNG files with no gamma information png_set_alpha_mode allows
- *    you to provide a default gamma, but it also sets the ouput gamma to the
+ *    you to provide a default gamma, but it also sets the output gamma to the
  *    matching value.  If you know your PNG files have a gamma that doesn't
  *    match the output you can take advantage of the fact that
  *    png_set_alpha_mode always sets the output gamma but only sets the PNG
@@ -1719,7 +1719,7 @@
  *           chunk will cause an error at this point unless it is to be saved.
  * positive: The chunk was handled, libpng will ignore/discard it.
  *
- * See "INTERACTION WTIH USER CHUNK CALLBACKS" below for important notes about
+ * See "INTERACTION WITH USER CHUNK CALLBACKS" below for important notes about
  * how this behavior will change in libpng 1.7
  */
 PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structrp png_ptr,
@@ -1744,7 +1744,7 @@
 
 /* Function to be called when data becomes available */
 PNG_EXPORT(92, void, png_process_data, (png_structrp png_ptr,
-    png_inforp info_ptr, png_bytep buffer, png_size_t buffer_size));
+    png_inforp info_ptr, png_bytep buffer, size_t buffer_size));
 
 /* A function which may be called *only* within png_process_data to stop the
  * processing of any more data.  The function returns the number of bytes
@@ -1753,7 +1753,7 @@
  * 'save' is set to true the routine will first save all the pending data and
  * will always return 0.
  */
-PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structrp, int save));
+PNG_EXPORT(219, size_t, png_process_data_pause, (png_structrp, int save));
 
 /* A function which may be called *only* outside (after) a call to
  * png_process_data.  It returns the number of bytes of data to skip in the
@@ -1817,7 +1817,8 @@
 #define PNG_FREE_PLTE 0x1000U
 #define PNG_FREE_TRNS 0x2000U
 #define PNG_FREE_TEXT 0x4000U
-#define PNG_FREE_ALL  0x7fffU
+#define PNG_FREE_EXIF 0x8000U /* Added at libpng-1.6.31 */
+#define PNG_FREE_ALL  0xffffU
 #define PNG_FREE_MUL  0x4220U /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
 
 #ifdef PNG_USER_MEM_SUPPORTED
@@ -1897,7 +1898,7 @@
     png_const_inforp info_ptr, png_uint_32 flag));
 
 /* Returns number of bytes needed to hold a transformed row. */
-PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structrp png_ptr,
+PNG_EXPORT(111, size_t, png_get_rowbytes, (png_const_structrp png_ptr,
     png_const_inforp info_ptr));
 
 #ifdef PNG_INFO_IMAGE_SUPPORTED
@@ -2036,6 +2037,18 @@
     png_fixed_point int_blue_Z))
 #endif
 
+#ifdef PNG_eXIf_SUPPORTED
+PNG_EXPORT(246, png_uint_32, png_get_eXIf, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_bytep *exif));
+PNG_EXPORT(247, void, png_set_eXIf, (png_const_structrp png_ptr,
+    png_inforp info_ptr, const png_bytep exif));
+
+PNG_EXPORT(248, png_uint_32, png_get_eXIf_1, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, png_uint_32 *num_exif, png_bytep *exif));
+PNG_EXPORT(249, void, png_set_eXIf_1, (png_const_structrp png_ptr,
+    png_inforp info_ptr, const png_uint_32 num_exif, const png_bytep exif));
+#endif
+
 #ifdef PNG_gAMA_SUPPORTED
 PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA, (png_const_structrp png_ptr,
     png_const_inforp info_ptr, double *file_gamma))
@@ -2054,9 +2067,6 @@
 #ifdef PNG_hIST_SUPPORTED
 PNG_EXPORT(141, png_uint_32, png_get_hIST, (png_const_structrp png_ptr,
     png_inforp info_ptr, png_uint_16p *hist));
-#endif
-
-#ifdef PNG_hIST_SUPPORTED
 PNG_EXPORT(142, void, png_set_hIST, (png_const_structrp png_ptr,
     png_inforp info_ptr, png_const_uint_16p hist));
 #endif
@@ -2257,7 +2267,7 @@
  * to specifying "NEVER", however when "AS_DEFAULT" is used for specific chunks
  * it simply resets the behavior to the libpng default.
  *
- * INTERACTION WTIH USER CHUNK CALLBACKS:
+ * INTERACTION WITH USER CHUNK CALLBACKS:
  * The per-chunk handling is always used when there is a png_user_chunk_ptr
  * callback and the callback returns 0; the chunk is then always stored *unless*
  * it is critical and the per-chunk setting is other than ALWAYS.  Notice that
@@ -2676,7 +2686,7 @@
  * The simplified API hides the details of both libpng and the PNG file format
  * itself.  It allows PNG files to be read into a very limited number of
  * in-memory bitmap formats or to be written from the same formats.  If these
- * formats do not accomodate your needs then you can, and should, use the more
+ * formats do not accommodate your needs then you can, and should, use the more
  * sophisticated APIs above - these support a wide variety of in-memory formats
  * and a wide variety of sophisticated transformations to those formats as well
  * as a wide variety of APIs to manipulate ancillary information.
@@ -2782,7 +2792,7 @@
  *
  * When the simplified API needs to convert between sRGB and linear colorspaces,
  * the actual sRGB transfer curve defined in the sRGB specification (see the
- * article at http://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2
+ * article at https://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2
  * approximation used elsewhere in libpng.
  *
  * When an alpha channel is present it is expected to denote pixel coverage
@@ -2837,6 +2847,8 @@
 #  define PNG_FORMAT_FLAG_AFIRST 0x20U /* alpha channel comes first */
 #endif
 
+#define PNG_FORMAT_FLAG_ASSOCIATED_ALPHA 0x40U /* alpha channel is associated */
+
 /* Commonly used formats have predefined macros.
  *
  * First the single byte (sRGB) formats:
@@ -3036,7 +3048,7 @@
 #endif /* STDIO */
 
 PNG_EXPORT(236, int, png_image_begin_read_from_memory, (png_imagep image,
-   png_const_voidp memory, png_size_t size));
+   png_const_voidp memory, size_t size));
    /* The PNG header is read from the given memory buffer. */
 
 PNG_EXPORT(237, int, png_image_finish_read, (png_imagep image,
@@ -3149,7 +3161,7 @@
     * than or equal to the original value.
     *
     * If the function returns false and *memory_bytes was not changed an error
-    * occured during write.  If *memory_bytes was changed, or is not 0 if
+    * occurred during write.  If *memory_bytes was changed, or is not 0 if
     * 'memory' was NULL, the write would have succeeded but for the memory
     * buffer being too small.  *memory_bytes contains the required number of
     * bytes and will be bigger that the original value.
@@ -3233,7 +3245,7 @@
  * option and 'onoff' is 0 (off) or non-0 (on).  The value returned is given
  * by the PNG_OPTION_ defines below.
  *
- * HARDWARE: normally hardware capabilites, such as the Intel SSE instructions,
+ * HARDWARE: normally hardware capabilities, such as the Intel SSE instructions,
  *           are detected at run time, however sometimes it may be impossible
  *           to do this in user mode, in which case it is necessary to discover
  *           the capabilities in an OS specific way.  Such capabilities are
@@ -3255,7 +3267,10 @@
 #  define PNG_MIPS_MSA   6 /* HARDWARE: MIPS Msa SIMD instructions supported */
 #endif
 #define PNG_IGNORE_ADLER32 8
-#define PNG_OPTION_NEXT  10 /* Next option - numbers must be even */
+#ifdef PNG_POWERPC_VSX_API_SUPPORTED
+#  define PNG_POWERPC_VSX   10 /* HARDWARE: PowerPC VSX SIMD instructions supported */
+#endif
+#define PNG_OPTION_NEXT  12 /* Next option - numbers must be even */
 
 /* Return values: NOTE: there are four values and 'off' is *not* zero */
 #define PNG_OPTION_UNSET   0 /* Unset - defaults to off */
@@ -3279,7 +3294,7 @@
  * one to use is one more than this.)
  */
 #ifdef PNG_EXPORT_LAST_ORDINAL
-  PNG_EXPORT_LAST_ORDINAL(245);
+  PNG_EXPORT_LAST_ORDINAL(249);
 #endif
 
 #ifdef __cplusplus
--- a/src/share/native/sun/awt/libpng/pngconf.h	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngconf.h	Mon Oct 15 15:05:59 2018 +0100
@@ -29,9 +29,9 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * libpng version 1.6.28, January 5, 2017
+ * libpng version 1.6.35, July 15, 2018
  *
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2002,2004,2006-2016,2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -155,7 +155,7 @@
  *
  * These cases only differ if the operating system does not use the C
  * calling convention, at present this just means the above cases
- * (x86 DOS/Windows sytems) and, even then, this does not apply to
+ * (x86 DOS/Windows systems) and, even then, this does not apply to
  * Cygwin running on those systems.
  *
  * Note that the value must be defined in pnglibconf.h so that what
@@ -543,8 +543,10 @@
 #  error "libpng requires an unsigned 32-bit (or more) type"
 #endif
 
-/* Prior to 1.6.0 it was possible to disable the use of size_t, 1.6.0, however,
- * requires an ISOC90 compiler and relies on consistent behavior of sizeof.
+/* Prior to 1.6.0, it was possible to disable the use of size_t and ptrdiff_t.
+ * From 1.6.0 onwards, an ISO C90 compiler, as well as a standard-compliant
+ * behavior of sizeof and ptrdiff_t are required.
+ * The legacy typedefs are provided here for backwards compatibility.
  */
 typedef size_t png_size_t;
 typedef ptrdiff_t png_ptrdiff_t;
@@ -565,13 +567,12 @@
 #  endif
 #endif
 
-/* png_alloc_size_t is guaranteed to be no smaller than png_size_t, and no
- * smaller than png_uint_32.  Casts from png_size_t or png_uint_32 to
- * png_alloc_size_t are not necessary; in fact, it is recommended not to use
- * them at all so that the compiler can complain when something turns out to be
- * problematic.
+/* png_alloc_size_t is guaranteed to be no smaller than size_t, and no smaller
+ * than png_uint_32.  Casts from size_t or png_uint_32 to png_alloc_size_t are
+ * not necessary; in fact, it is recommended not to use them at all, so that
+ * the compiler can complain when something turns out to be problematic.
  *
- * Casts in the other direction (from png_alloc_size_t to png_size_t or
+ * Casts in the other direction (from png_alloc_size_t to size_t or
  * png_uint_32) should be explicitly applied; however, we do not expect to
  * encounter practical situations that require such conversions.
  *
@@ -581,7 +582,7 @@
 #ifdef PNG_SMALL_SIZE_T
    typedef png_uint_32 png_alloc_size_t;
 #else
-   typedef png_size_t png_alloc_size_t;
+   typedef size_t png_alloc_size_t;
 #endif
 
 /* Prior to 1.6.0 libpng offered limited support for Microsoft C compiler
@@ -617,8 +618,8 @@
 typedef const char            * png_const_charp;
 typedef png_fixed_point       * png_fixed_point_p;
 typedef const png_fixed_point * png_const_fixed_point_p;
-typedef png_size_t            * png_size_tp;
-typedef const png_size_t      * png_const_size_tp;
+typedef size_t                * png_size_tp;
+typedef const size_t          * png_const_size_tp;
 
 #ifdef PNG_STDIO_SUPPORTED
 typedef FILE            * png_FILE_p;
--- a/src/share/native/sun/awt/libpng/pngerror.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngerror.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.26 [October 20, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.31 [July 27, 2017]
+ * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -191,7 +191,7 @@
          case PNG_NUMBER_FORMAT_02u:
             /* Expects at least 2 digits. */
             mincount = 2;
-            /* FALL THROUGH */
+            /* FALLTHROUGH */
 
          case PNG_NUMBER_FORMAT_u:
             *--end = digits[number % 10];
@@ -201,7 +201,7 @@
          case PNG_NUMBER_FORMAT_02x:
             /* This format expects at least two digits */
             mincount = 2;
-            /* FALL THROUGH */
+            /* FALLTHROUGH */
 
          case PNG_NUMBER_FORMAT_x:
             *--end = digits[number & 0xf];
--- a/src/share/native/sun/awt/libpng/pngget.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngget.c	Mon Oct 15 15:05:59 2018 +0100
@@ -28,9 +28,9 @@
  * License version 2 only, as published by the Free Software Foundation.
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
-
- * Last changed in libpng 1.6.26 [October 20, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ *
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -54,7 +54,7 @@
    return(0);
 }
 
-png_size_t PNGAPI
+size_t PNGAPI
 png_get_rowbytes(png_const_structrp png_ptr, png_const_inforp info_ptr)
 {
    if (png_ptr != NULL && info_ptr != NULL)
@@ -395,7 +395,7 @@
 static png_fixed_point
 png_fixed_inches_from_microns(png_const_structrp png_ptr, png_int_32 microns)
 {
-   /* Convert from metres * 1,000,000 to inches * 100,000, meters to
+   /* Convert from meters * 1,000,000 to inches * 100,000, meters to
     * inches is simply *(100/2.54), so we want *(10/2.54) == 500/127.
     * Notice that this can overflow - a warning is output and 0 is
     * returned.
@@ -769,8 +769,7 @@
 
    if (png_ptr != NULL && info_ptr != NULL &&
        (info_ptr->valid & PNG_INFO_iCCP) != 0 &&
-       name != NULL && compression_type != NULL && profile != NULL &&
-           proflen != NULL)
+       name != NULL && profile != NULL && proflen != NULL)
    {
       *name = info_ptr->iccp_name;
       *profile = info_ptr->iccp_profile;
@@ -778,11 +777,13 @@
       /* This is somewhat irrelevant since the profile data returned has
        * actually been uncompressed.
        */
-      *compression_type = PNG_COMPRESSION_TYPE_BASE;
+      if (compression_type != NULL)
+         *compression_type = PNG_COMPRESSION_TYPE_BASE;
       return (PNG_INFO_iCCP);
    }
 
    return (0);
+
 }
 #endif
 
@@ -801,6 +802,35 @@
 }
 #endif
 
+#ifdef PNG_eXIf_SUPPORTED
+png_uint_32 PNGAPI
+png_get_eXIf(png_const_structrp png_ptr, png_inforp info_ptr,
+    png_bytep *exif)
+{
+  png_warning(png_ptr, "png_get_eXIf does not work; use png_get_eXIf_1");
+  PNG_UNUSED(info_ptr)
+  PNG_UNUSED(exif)
+  return 0;
+}
+
+png_uint_32 PNGAPI
+png_get_eXIf_1(png_const_structrp png_ptr, png_const_inforp info_ptr,
+    png_uint_32 *num_exif, png_bytep *exif)
+{
+   png_debug1(1, "in %s retrieval function", "eXIf");
+
+   if (png_ptr != NULL && info_ptr != NULL &&
+       (info_ptr->valid & PNG_INFO_eXIf) != 0 && exif != NULL)
+   {
+      *num_exif = info_ptr->num_exif;
+      *exif = info_ptr->exif;
+      return (PNG_INFO_eXIf);
+   }
+
+   return (0);
+}
+#endif
+
 #ifdef PNG_hIST_SUPPORTED
 png_uint_32 PNGAPI
 png_get_hIST(png_const_structrp png_ptr, png_inforp info_ptr,
@@ -1163,7 +1193,7 @@
 }
 #endif
 
-png_size_t PNGAPI
+size_t PNGAPI
 png_get_compression_buffer_size(png_const_structrp png_ptr)
 {
    if (png_ptr == NULL)
--- a/src/share/native/sun/awt/libpng/pnginfo.h	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pnginfo.h	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.1 [March 28, 2013]
- * Copyright (c) 1998-2002,2004,2006-2013 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2013,2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -83,10 +83,10 @@
 struct png_info_def
 {
    /* The following are necessary for every PNG file */
-   png_uint_32 width;  /* width of image in pixels (from IHDR) */
-   png_uint_32 height; /* height of image in pixels (from IHDR) */
-   png_uint_32 valid;  /* valid chunk data (see PNG_INFO_ below) */
-   png_size_t rowbytes; /* bytes needed to hold an untransformed row */
+   png_uint_32 width;       /* width of image in pixels (from IHDR) */
+   png_uint_32 height;      /* height of image in pixels (from IHDR) */
+   png_uint_32 valid;       /* valid chunk data (see PNG_INFO_ below) */
+   size_t rowbytes;         /* bytes needed to hold an untransformed row */
    png_colorp palette;      /* array of color values (valid & PNG_INFO_PLTE) */
    png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
    png_uint_16 num_trans;   /* number of transparent palette color (tRNS) */
@@ -213,6 +213,14 @@
    png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
 #endif
 
+#ifdef PNG_eXIf_SUPPORTED
+   int num_exif;  /* Added at libpng-1.6.31 */
+   png_bytep exif;
+# ifdef PNG_READ_eXIf_SUPPORTED
+   png_bytep eXIf_buf;  /* Added at libpng-1.6.32 */
+# endif
+#endif
+
 #ifdef PNG_hIST_SUPPORTED
    /* The hIST chunk contains the relative frequency or importance of the
     * various palette entries, so that a viewer can intelligently select a
@@ -267,7 +275,7 @@
    /* The sCAL chunk describes the actual physical dimensions of the
     * subject matter of the graphic.  The chunk contains a unit specification
     * a byte value, and two ASCII strings representing floating-point
-    * values.  The values are width and height corresponsing to one pixel
+    * values.  The values are width and height corresponding to one pixel
     * in the image.  Data values are valid if (valid & PNG_INFO_sCAL) is
     * non-zero.
     */
--- a/src/share/native/sun/awt/libpng/pnglibconf.h	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pnglibconf.h	Mon Oct 15 15:05:59 2018 +0100
@@ -1,6 +1,11 @@
 /*
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file and, per its terms, should not be removed:
+ *
  * 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
@@ -33,9 +38,9 @@
  * file and, per its terms, should not be removed:
  */
 
-/* libpng version 1.6.28, January 5, 2017 */
+/* libpng version 1.6.35, July 15, 2018 */
 
-/* Copyright (c) 1998-2016 Glenn Randers-Pehrson */
+/* Copyright (c) 1998-2018 Glenn Randers-Pehrson */
 
 /* This code is released under the libpng license. */
 /* For conditions of distribution and use, see the disclaimer */
--- a/src/share/native/sun/awt/libpng/pngpread.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngpread.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.24 [August 4, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -62,7 +62,7 @@
 
 void PNGAPI
 png_process_data(png_structrp png_ptr, png_inforp info_ptr,
-    png_bytep buffer, png_size_t buffer_size)
+    png_bytep buffer, size_t buffer_size)
 {
    if (png_ptr == NULL || info_ptr == NULL)
       return;
@@ -75,7 +75,7 @@
    }
 }
 
-png_size_t PNGAPI
+size_t PNGAPI
 png_process_data_pause(png_structrp png_ptr, int save)
 {
    if (png_ptr != NULL)
@@ -88,7 +88,7 @@
       else
       {
          /* This includes any pending saved bytes: */
-         png_size_t remaining = png_ptr->buffer_size;
+         size_t remaining = png_ptr->buffer_size;
          png_ptr->buffer_size = 0;
 
          /* So subtract the saved buffer size, unless all the data
@@ -161,8 +161,8 @@
 void /* PRIVATE */
 png_push_read_sig(png_structrp png_ptr, png_inforp info_ptr)
 {
-   png_size_t num_checked = png_ptr->sig_bytes, /* SAFE, does not exceed 8 */
-       num_to_check = 8 - num_checked;
+   size_t num_checked = png_ptr->sig_bytes; /* SAFE, does not exceed 8 */
+   size_t num_to_check = 8 - num_checked;
 
    if (png_ptr->buffer_size < num_to_check)
    {
@@ -217,6 +217,7 @@
       png_crc_read(png_ptr, chunk_tag, 4);
       png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(chunk_tag);
       png_check_chunk_name(png_ptr, png_ptr->chunk_name);
+      png_check_chunk_length(png_ptr, png_ptr->push_length);
       png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
    }
 
@@ -445,7 +446,7 @@
 }
 
 void PNGCBAPI
-png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
+png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, size_t length)
 {
    png_bytep ptr;
 
@@ -455,7 +456,7 @@
    ptr = buffer;
    if (png_ptr->save_buffer_size != 0)
    {
-      png_size_t save_size;
+      size_t save_size;
 
       if (length < png_ptr->save_buffer_size)
          save_size = length;
@@ -472,7 +473,7 @@
    }
    if (length != 0 && png_ptr->current_buffer_size != 0)
    {
-      png_size_t save_size;
+      size_t save_size;
 
       if (length < png_ptr->current_buffer_size)
          save_size = length;
@@ -494,7 +495,7 @@
    {
       if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
       {
-         png_size_t i, istop;
+         size_t i, istop;
          png_bytep sp;
          png_bytep dp;
 
@@ -509,7 +510,7 @@
    if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
        png_ptr->save_buffer_max)
    {
-      png_size_t new_max;
+      size_t new_max;
       png_bytep old_buffer;
 
       if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
@@ -521,7 +522,7 @@
       new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
       old_buffer = png_ptr->save_buffer;
       png_ptr->save_buffer = (png_bytep)png_malloc_warn(png_ptr,
-          (png_size_t)new_max);
+          (size_t)new_max);
 
       if (png_ptr->save_buffer == NULL)
       {
@@ -549,7 +550,7 @@
 
 void /* PRIVATE */
 png_push_restore_buffer(png_structrp png_ptr, png_bytep buffer,
-    png_size_t buffer_length)
+    size_t buffer_length)
 {
    png_ptr->current_buffer = buffer;
    png_ptr->current_buffer_size = buffer_length;
@@ -589,7 +590,7 @@
 
    if (png_ptr->idat_size != 0 && png_ptr->save_buffer_size != 0)
    {
-      png_size_t save_size = png_ptr->save_buffer_size;
+      size_t save_size = png_ptr->save_buffer_size;
       png_uint_32 idat_size = png_ptr->idat_size;
 
       /* We want the smaller of 'idat_size' and 'current_buffer_size', but they
@@ -599,7 +600,7 @@
        * will break on either 16-bit or 64-bit platforms.
        */
       if (idat_size < save_size)
-         save_size = (png_size_t)idat_size;
+         save_size = (size_t)idat_size;
 
       else
          idat_size = (png_uint_32)save_size;
@@ -616,7 +617,7 @@
 
    if (png_ptr->idat_size != 0 && png_ptr->current_buffer_size != 0)
    {
-      png_size_t save_size = png_ptr->current_buffer_size;
+      size_t save_size = png_ptr->current_buffer_size;
       png_uint_32 idat_size = png_ptr->idat_size;
 
       /* We want the smaller of 'idat_size' and 'current_buffer_size', but they
@@ -625,7 +626,7 @@
        * larger - this cannot overflow.
        */
       if (idat_size < save_size)
-         save_size = (png_size_t)idat_size;
+         save_size = (size_t)idat_size;
 
       else
          idat_size = (png_uint_32)save_size;
@@ -652,7 +653,7 @@
 
 void /* PRIVATE */
 png_process_IDAT_data(png_structrp png_ptr, png_bytep buffer,
-    png_size_t buffer_length)
+    size_t buffer_length)
 {
    /* The caller checks for a non-zero buffer length. */
    if (!(buffer_length > 0) || buffer == NULL)
--- a/src/share/native/sun/awt/libpng/pngpriv.h	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngpriv.h	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.26 [October 20, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -63,7 +63,9 @@
  * Windows/Visual Studio) there is no effect; the OS specific tests below are
  * still required (as of 2011-05-02.)
  */
-#define _POSIX_SOURCE 1 /* Just the POSIX 1003.1 and C89 APIs */
+#ifndef _POSIX_SOURCE
+# define _POSIX_SOURCE 1 /* Just the POSIX 1003.1 and C89 APIs */
+#endif
 
 #ifndef PNG_VERSION_INFO_ONLY
 /* Standard library headers not required by png.h: */
@@ -218,6 +220,56 @@
 #  endif
 #endif
 
+#ifndef PNG_POWERPC_VSX_OPT
+#  if defined(__PPC64__) && defined(__ALTIVEC__) && defined(__VSX__)
+#     define PNG_POWERPC_VSX_OPT 2
+#  else
+#     define PNG_POWERPC_VSX_OPT 0
+#  endif
+#endif
+
+#ifndef PNG_INTEL_SSE_OPT
+#   ifdef PNG_INTEL_SSE
+      /* Only check for SSE if the build configuration has been modified to
+       * enable SSE optimizations.  This means that these optimizations will
+       * be off by default.  See contrib/intel for more details.
+       */
+#     if defined(__SSE4_1__) || defined(__AVX__) || defined(__SSSE3__) || \
+       defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || \
+       (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
+#         define PNG_INTEL_SSE_OPT 1
+#      else
+#         define PNG_INTEL_SSE_OPT 0
+#      endif
+#   else
+#      define PNG_INTEL_SSE_OPT 0
+#   endif
+#endif
+
+#if PNG_INTEL_SSE_OPT > 0
+#   ifndef PNG_INTEL_SSE_IMPLEMENTATION
+#      if defined(__SSE4_1__) || defined(__AVX__)
+          /* We are not actually using AVX, but checking for AVX is the best
+             way we can detect SSE4.1 and SSSE3 on MSVC.
+          */
+#         define PNG_INTEL_SSE_IMPLEMENTATION 3
+#      elif defined(__SSSE3__)
+#         define PNG_INTEL_SSE_IMPLEMENTATION 2
+#      elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || \
+       (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
+#         define PNG_INTEL_SSE_IMPLEMENTATION 1
+#      else
+#         define PNG_INTEL_SSE_IMPLEMENTATION 0
+#      endif
+#   endif
+
+#   if PNG_INTEL_SSE_IMPLEMENTATION > 0
+#      define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_sse2
+#   endif
+#else
+#   define PNG_INTEL_SSE_IMPLEMENTATION 0
+#endif
+
 #if PNG_MIPS_MSA_OPT > 0
 #  define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_msa
 #  ifndef PNG_MIPS_MSA_IMPLEMENTATION
@@ -238,6 +290,13 @@
 #  endif
 #endif /* PNG_MIPS_MSA_OPT > 0 */
 
+#ifdef PNG_POWERPC_VSX_API_SUPPORTED
+#if PNG_POWERPC_VSX_OPT > 0
+#  define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_vsx
+#  define PNG_POWERPC_VSX_IMPLEMENTATION 1
+#endif
+#endif
+
 
 /* Is this a build of a DLL where compilation of the object modules requires
  * different preprocessor settings to those required for a simple library?  If
@@ -431,6 +490,21 @@
 #  define png_fixed_error(s1,s2) png_err(s1)
 #endif
 
+/* Some fixed point APIs are still required even if not exported because
+ * they get used by the corresponding floating point APIs.  This magic
+ * deals with this:
+ */
+#ifdef PNG_FIXED_POINT_SUPPORTED
+#  define PNGFAPI PNGAPI
+#else
+#  define PNGFAPI /* PRIVATE */
+#endif
+
+#ifndef PNG_VERSION_INFO_ONLY
+/* Other defines specific to compilers can go here.  Try to keep
+ * them inside an appropriate ifdef/endif pair for portability.
+ */
+
 /* C allows up-casts from (void*) to any pointer and (const void*) to any
  * pointer to a const object.  C++ regards this as a type error and requires an
  * explicit, static, cast and provides the static_cast<> rune to ensure that
@@ -445,25 +519,20 @@
    static_cast<type>(static_cast<const void*>(value))
 #else
 #  define png_voidcast(type, value) (value)
-#  define png_constcast(type, value) ((type)(value))
+#  ifdef _WIN64
+#     ifdef __GNUC__
+         typedef unsigned long long png_ptruint;
+#     else
+         typedef unsigned __int64 png_ptruint;
+#     endif
+#  else
+      typedef unsigned long png_ptruint;
+#  endif
+#  define png_constcast(type, value) ((type)(png_ptruint)(const void*)(value))
 #  define png_aligncast(type, value) ((void*)(value))
 #  define png_aligncastconst(type, value) ((const void*)(value))
 #endif /* __cplusplus */
 
-/* Some fixed point APIs are still required even if not exported because
- * they get used by the corresponding floating point APIs.  This magic
- * deals with this:
- */
-#ifdef PNG_FIXED_POINT_SUPPORTED
-#  define PNGFAPI PNGAPI
-#else
-#  define PNGFAPI /* PRIVATE */
-#endif
-
-#ifndef PNG_VERSION_INFO_ONLY
-/* Other defines specific to compilers can go here.  Try to keep
- * them inside an appropriate ifdef/endif pair for portability.
- */
 #if defined(PNG_FLOATING_POINT_SUPPORTED) ||\
     defined(PNG_FLOATING_ARITHMETIC_SUPPORTED)
    /* png.c requires the following ANSI-C constants if the conversion of
@@ -695,8 +764,8 @@
 /* Added to libpng-1.2.6 JB */
 #define PNG_ROWBYTES(pixel_bits, width) \
     ((pixel_bits) >= 8 ? \
-    ((png_size_t)(width) * (((png_size_t)(pixel_bits)) >> 3)) : \
-    (( ((png_size_t)(width) * ((png_size_t)(pixel_bits))) + 7) >> 3) )
+    ((size_t)(width) * (((size_t)(pixel_bits)) >> 3)) : \
+    (( ((size_t)(width) * ((size_t)(pixel_bits))) + 7) >> 3) )
 
 /* This returns the number of trailing bits in the last byte of a row, 0 if the
  * last byte is completely full of pixels.  It is, in principle, (pixel_bits x
@@ -809,6 +878,7 @@
 #define png_PLTE PNG_U32( 80,  76,  84,  69)
 #define png_bKGD PNG_U32( 98,  75,  71,  68)
 #define png_cHRM PNG_U32( 99,  72,  82,  77)
+#define png_eXIf PNG_U32(101,  88,  73, 102) /* registered July 2017 */
 #define png_fRAc PNG_U32(102,  82,  65,  99) /* registered, not defined */
 #define png_gAMA PNG_U32(103,  65,  77,  65)
 #define png_gIFg PNG_U32(103,  73,  70, 103)
@@ -883,7 +953,7 @@
     * PNG files the -I directives must match.
     *
     * The most likely explanation is that you passed a -I in CFLAGS. This will
-    * not work; all the preprocessor directories and in particular all the -I
+    * not work; all the preprocessor directives and in particular all the -I
     * directives must be in CPPFLAGS.
     */
 #endif
@@ -1012,15 +1082,15 @@
  */
 
 PNG_INTERNAL_FUNCTION(void PNGCBAPI,png_default_read_data,(png_structp png_ptr,
-    png_bytep data, png_size_t length),PNG_EMPTY);
+    png_bytep data, size_t length),PNG_EMPTY);
 
 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 PNG_INTERNAL_FUNCTION(void PNGCBAPI,png_push_fill_buffer,(png_structp png_ptr,
-    png_bytep buffer, png_size_t length),PNG_EMPTY);
+    png_bytep buffer, size_t length),PNG_EMPTY);
 #endif
 
 PNG_INTERNAL_FUNCTION(void PNGCBAPI,png_default_write_data,(png_structp png_ptr,
-    png_bytep data, png_size_t length),PNG_EMPTY);
+    png_bytep data, size_t length),PNG_EMPTY);
 
 #ifdef PNG_WRITE_FLUSH_SUPPORTED
 #  ifdef PNG_STDIO_SUPPORTED
@@ -1034,7 +1104,7 @@
 
 /* Write the "data" buffer to whatever output you are using */
 PNG_INTERNAL_FUNCTION(void,png_write_data,(png_structrp png_ptr,
-    png_const_bytep data, png_size_t length),PNG_EMPTY);
+    png_const_bytep data, size_t length),PNG_EMPTY);
 
 /* Read and check the PNG file signature */
 PNG_INTERNAL_FUNCTION(void,png_read_sig,(png_structrp png_ptr,
@@ -1046,7 +1116,7 @@
 
 /* Read data from whatever input you are using into the "data" buffer */
 PNG_INTERNAL_FUNCTION(void,png_read_data,(png_structrp png_ptr, png_bytep data,
-    png_size_t length),PNG_EMPTY);
+    size_t length),PNG_EMPTY);
 
 /* Read bytes into buf, and update png_ptr->crc */
 PNG_INTERNAL_FUNCTION(void,png_crc_read,(png_structrp png_ptr, png_bytep buf,
@@ -1064,7 +1134,7 @@
  * since this is the maximum buffer size we can specify.
  */
 PNG_INTERNAL_FUNCTION(void,png_calculate_crc,(png_structrp png_ptr,
-   png_const_bytep ptr, png_size_t length),PNG_EMPTY);
+   png_const_bytep ptr, size_t length),PNG_EMPTY);
 
 #ifdef PNG_WRITE_FLUSH_SUPPORTED
 PNG_INTERNAL_FUNCTION(void,png_flush,(png_structrp png_ptr),PNG_EMPTY);
@@ -1109,6 +1179,11 @@
     int intent),PNG_EMPTY);
 #endif
 
+#ifdef PNG_WRITE_eXIf_SUPPORTED
+PNG_INTERNAL_FUNCTION(void,png_write_eXIf,(png_structrp png_ptr,
+    png_bytep exif, int num_exif),PNG_EMPTY);
+#endif
+
 #ifdef PNG_WRITE_iCCP_SUPPORTED
 PNG_INTERNAL_FUNCTION(void,png_write_iCCP,(png_structrp png_ptr,
    png_const_charp name, png_const_bytep profile), PNG_EMPTY);
@@ -1142,7 +1217,7 @@
 /* Chunks that have keywords */
 #ifdef PNG_WRITE_tEXt_SUPPORTED
 PNG_INTERNAL_FUNCTION(void,png_write_tEXt,(png_structrp png_ptr,
-   png_const_charp key, png_const_charp text, png_size_t text_len),PNG_EMPTY);
+   png_const_charp key, png_const_charp text, size_t text_len),PNG_EMPTY);
 #endif
 
 #ifdef PNG_WRITE_zTXt_SUPPORTED
@@ -1284,6 +1359,38 @@
     row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
 #endif
 
+#if PNG_POWERPC_VSX_OPT > 0
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_up_vsx,(png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_vsx,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub4_vsx,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg3_vsx,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_vsx,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_vsx,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_vsx,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+#endif
+
+#if PNG_INTEL_SSE_IMPLEMENTATION > 0
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_sse2,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub4_sse2,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg3_sse2,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_sse2,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_sse2,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_sse2,(png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY);
+#endif
+
 /* Choose the best filter to use and filter the row data */
 PNG_INTERNAL_FUNCTION(void,png_write_find_filter,(png_structrp png_ptr,
     png_row_infop row_info),PNG_EMPTY);
@@ -1376,6 +1483,11 @@
     png_inforp info_ptr, png_uint_32 length),PNG_EMPTY);
 #endif
 
+#ifdef PNG_READ_eXIf_SUPPORTED
+PNG_INTERNAL_FUNCTION(void,png_handle_eXIf,(png_structrp png_ptr,
+    png_inforp info_ptr, png_uint_32 length),PNG_EMPTY);
+#endif
+
 #ifdef PNG_READ_gAMA_SUPPORTED
 PNG_INTERNAL_FUNCTION(void,png_handle_gAMA,(png_structrp png_ptr,
     png_inforp info_ptr, png_uint_32 length),PNG_EMPTY);
@@ -1451,8 +1563,11 @@
     png_inforp info_ptr, png_uint_32 length),PNG_EMPTY);
 #endif
 
-PNG_INTERNAL_FUNCTION(void,png_check_chunk_name,(png_structrp png_ptr,
-    png_uint_32 chunk_name),PNG_EMPTY);
+PNG_INTERNAL_FUNCTION(void,png_check_chunk_name,(png_const_structrp png_ptr,
+    const png_uint_32 chunk_name),PNG_EMPTY);
+
+PNG_INTERNAL_FUNCTION(void,png_check_chunk_length,(png_const_structrp png_ptr,
+    const png_uint_32 chunk_length),PNG_EMPTY);
 
 PNG_INTERNAL_FUNCTION(void,png_handle_unknown,(png_structrp png_ptr,
     png_inforp info_ptr, png_uint_32 length, int keep),PNG_EMPTY);
@@ -1495,10 +1610,10 @@
 PNG_INTERNAL_FUNCTION(void,png_push_save_buffer,(png_structrp png_ptr),
     PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_restore_buffer,(png_structrp png_ptr,
-    png_bytep buffer, png_size_t buffer_length),PNG_EMPTY);
+    png_bytep buffer, size_t buffer_length),PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_read_IDAT,(png_structrp png_ptr),PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_process_IDAT_data,(png_structrp png_ptr,
-    png_bytep buffer, png_size_t buffer_length),PNG_EMPTY);
+    png_bytep buffer, size_t buffer_length),PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_process_row,(png_structrp png_ptr),
     PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_handle_unknown,(png_structrp png_ptr,
@@ -1768,13 +1883,13 @@
 
 #ifdef PNG_FLOATING_POINT_SUPPORTED
 PNG_INTERNAL_FUNCTION(void,png_ascii_from_fp,(png_const_structrp png_ptr,
-   png_charp ascii, png_size_t size, double fp, unsigned int precision),
+   png_charp ascii, size_t size, double fp, unsigned int precision),
    PNG_EMPTY);
 #endif /* FLOATING_POINT */
 
 #ifdef PNG_FIXED_POINT_SUPPORTED
 PNG_INTERNAL_FUNCTION(void,png_ascii_from_fixed,(png_const_structrp png_ptr,
-   png_charp ascii, png_size_t size, png_fixed_point fp),PNG_EMPTY);
+   png_charp ascii, size_t size, png_fixed_point fp),PNG_EMPTY);
 #endif /* FIXED_POINT */
 #endif /* sCAL */
 
@@ -1867,7 +1982,7 @@
  * the problem character.)  This has not been tested within libpng.
  */
 PNG_INTERNAL_FUNCTION(int,png_check_fp_number,(png_const_charp string,
-   png_size_t size, int *statep, png_size_tp whereami),PNG_EMPTY);
+   size_t size, int *statep, png_size_tp whereami),PNG_EMPTY);
 
 /* This is the same but it checks a complete string and returns true
  * only if it just contains a floating point number.  As of 1.5.4 this
@@ -1876,7 +1991,7 @@
  * for negative or zero values using the sticky flag.
  */
 PNG_INTERNAL_FUNCTION(int,png_check_fp_string,(png_const_charp string,
-   png_size_t size),PNG_EMPTY);
+   size_t size),PNG_EMPTY);
 #endif /* pCAL || sCAL */
 
 #if defined(PNG_GAMMA_SUPPORTED) ||\
@@ -1951,7 +2066,7 @@
    png_voidp   error_buf;           /* Always a jmp_buf at present. */
 
    png_const_bytep memory;          /* Memory buffer. */
-   png_size_t      size;            /* Size of the memory buffer. */
+   size_t          size;            /* Size of the memory buffer. */
 
    unsigned int for_write       :1; /* Otherwise it is a read structure */
    unsigned int owned_file      :1; /* We own the file in io_ptr */
@@ -2019,6 +2134,11 @@
 PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_msa,
    (png_structp png_ptr, unsigned int bpp), PNG_EMPTY);
 #endif
+
+#  if PNG_INTEL_SSE_IMPLEMENTATION > 0
+PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_sse2,
+   (png_structp png_ptr, unsigned int bpp), PNG_EMPTY);
+#  endif
 #endif
 
 PNG_INTERNAL_FUNCTION(png_uint_32, png_check_keyword, (png_structrp png_ptr,
--- a/src/share/native/sun/awt/libpng/pngread.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngread.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.26 [October 20, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -203,6 +203,11 @@
          png_handle_cHRM(png_ptr, info_ptr, length);
 #endif
 
+#ifdef PNG_READ_eXIf_SUPPORTED
+      else if (chunk_name == png_eXIf)
+         png_handle_eXIf(png_ptr, info_ptr, length);
+#endif
+
 #ifdef PNG_READ_gAMA_SUPPORTED
       else if (chunk_name == png_gAMA)
          png_handle_gAMA(png_ptr, info_ptr, length);
@@ -562,6 +567,7 @@
       png_error(png_ptr, "Invalid attempt to read row data");
 
    /* Fill the row with IDAT data: */
+   png_ptr->row_buf[0]=255; /* to force error if no data was found */
    png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
 
    if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
@@ -870,6 +876,11 @@
          png_handle_cHRM(png_ptr, info_ptr, length);
 #endif
 
+#ifdef PNG_READ_eXIf_SUPPORTED
+      else if (chunk_name == png_eXIf)
+         png_handle_eXIf(png_ptr, info_ptr, length);
+#endif
+
 #ifdef PNG_READ_gAMA_SUPPORTED
       else if (chunk_name == png_gAMA)
          png_handle_gAMA(png_ptr, info_ptr, length);
@@ -1549,7 +1560,7 @@
 #endif /* STDIO */
 
 static void PNGCBAPI
-png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need)
+png_image_memory_read(png_structp png_ptr, png_bytep out, size_t need)
 {
    if (png_ptr != NULL)
    {
@@ -1560,7 +1571,7 @@
          if (cp != NULL)
          {
             png_const_bytep memory = cp->memory;
-            png_size_t size = cp->size;
+            size_t size = cp->size;
 
             if (memory != NULL && size >= need)
             {
@@ -1579,7 +1590,7 @@
 }
 
 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
-    png_const_voidp memory, png_size_t size)
+    png_const_voidp memory, size_t size)
 {
    if (image != NULL && image->version == PNG_IMAGE_VERSION)
    {
@@ -1911,7 +1922,7 @@
          {
             case 4:
                entry[afirst ? 0 : 3] = (png_uint_16)alpha;
-               /* FALL THROUGH */
+               /* FALLTHROUGH */
 
             case 3:
                if (alpha < 65535)
@@ -1933,7 +1944,7 @@
 
             case 2:
                entry[1 ^ afirst] = (png_uint_16)alpha;
-               /* FALL THROUGH */
+               /* FALLTHROUGH */
 
             case 1:
                if (alpha < 65535)
@@ -1962,6 +1973,7 @@
          {
             case 4:
                entry[afirst ? 0 : 3] = (png_byte)alpha;
+               /* FALLTHROUGH */
             case 3:
                entry[afirst + (2 ^ bgr)] = (png_byte)blue;
                entry[afirst + 1] = (png_byte)green;
@@ -1970,6 +1982,7 @@
 
             case 2:
                entry[1 ^ afirst] = (png_byte)alpha;
+               /* FALLTHROUGH */
             case 1:
                entry[afirst] = (png_byte)green;
                break;
@@ -2889,7 +2902,7 @@
       case P_sRGB:
          /* Change to 8-bit sRGB */
          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
-         /* FALL THROUGH */
+         /* FALLTHROUGH */
 
       case P_FILE:
          if (png_ptr->bit_depth > 8)
@@ -3207,8 +3220,7 @@
             image->colormap_entries == 244 /* 216 + 1 + 27 */)
             break;
 
-         /* goto bad_output; */
-         /* FALL THROUGH */
+         goto bad_output;
 
       default:
       bad_output:
@@ -3776,6 +3788,12 @@
          output_gamma = PNG_DEFAULT_sRGB;
       }
 
+      if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
+      {
+         mode = PNG_ALPHA_OPTIMIZED;
+         change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
+      }
+
       /* If 'do_local_background' is set check for the presence of gamma
        * correction; this is part of the work-round for the libpng bug
        * described above.
@@ -4001,6 +4019,10 @@
       else if (do_local_compose != 0) /* internal error */
          png_error(png_ptr, "png_image_read: alpha channel lost");
 
+      if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
+         info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
+      }
+
       if (info_ptr->bit_depth == 16)
          info_format |= PNG_FORMAT_FLAG_LINEAR;
 
@@ -4156,7 +4178,7 @@
              *
              * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
              * will be changed to use png_alloc_size_t; bigger images can be
-             * accomodated on 64-bit systems.
+             * accommodated on 64-bit systems.
              */
             if (image->height <=
                 0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
--- a/src/share/native/sun/awt/libpng/pngrio.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngrio.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.24 [August 4, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2016,2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -57,7 +57,7 @@
  * to read more than 64K on a 16-bit machine.
  */
 void /* PRIVATE */
-png_read_data(png_structrp png_ptr, png_bytep data, png_size_t length)
+png_read_data(png_structrp png_ptr, png_bytep data, size_t length)
 {
    png_debug1(4, "reading %d bytes", (int)length);
 
@@ -75,14 +75,14 @@
  * than changing the library.
  */
 void PNGCBAPI
-png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
+png_default_read_data(png_structp png_ptr, png_bytep data, size_t length)
 {
-   png_size_t check;
+   size_t check;
 
    if (png_ptr == NULL)
       return;
 
-   /* fread() returns 0 on error, so it is OK to store this in a png_size_t
+   /* fread() returns 0 on error, so it is OK to store this in a size_t
     * instead of an int, which is what fread() actually returns.
     */
    check = fread(data, 1, length, png_voidcast(png_FILE_p, png_ptr->io_ptr));
--- a/src/share/native/sun/awt/libpng/pngrtran.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngrtran.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.24 [August 4, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -77,6 +77,7 @@
       case PNG_CRC_WARN_DISCARD:    /* Not a valid action for critical data */
          png_warning(png_ptr,
              "Can't discard critical data on CRC error");
+         /* FALLTHROUGH */
       case PNG_CRC_ERROR_QUIT:                                /* Error/quit */
 
       case PNG_CRC_DEFAULT:
@@ -319,7 +320,7 @@
     * who use the inverse of the gamma value accidentally!  Since some of these
     * values are reasonable this may have to be changed:
     *
-    * 1.6.x: changed from 0.07..3 to 0.01..100 (to accomodate the optimal 16-bit
+    * 1.6.x: changed from 0.07..3 to 0.01..100 (to accommodate the optimal 16-bit
     * gamma of 36, and its reciprocal.)
     */
    if (output_gamma < 1000 || output_gamma > 10000000)
@@ -457,7 +458,7 @@
       int i;
 
       png_ptr->quantize_index = (png_bytep)png_malloc(png_ptr,
-          (png_uint_32)((png_uint_32)num_palette * (sizeof (png_byte))));
+          (png_alloc_size_t)((png_uint_32)num_palette * (sizeof (png_byte))));
       for (i = 0; i < num_palette; i++)
          png_ptr->quantize_index[i] = (png_byte)i;
    }
@@ -474,7 +475,7 @@
 
          /* Initialize an array to sort colors */
          png_ptr->quantize_sort = (png_bytep)png_malloc(png_ptr,
-             (png_uint_32)((png_uint_32)num_palette * (sizeof (png_byte))));
+             (png_alloc_size_t)((png_uint_32)num_palette * (sizeof (png_byte))));
 
          /* Initialize the quantize_sort array */
          for (i = 0; i < num_palette; i++)
@@ -608,9 +609,11 @@
 
          /* Initialize palette index arrays */
          png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
-             (png_uint_32)((png_uint_32)num_palette * (sizeof (png_byte))));
+             (png_alloc_size_t)((png_uint_32)num_palette *
+             (sizeof (png_byte))));
          png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
-             (png_uint_32)((png_uint_32)num_palette * (sizeof (png_byte))));
+             (png_alloc_size_t)((png_uint_32)num_palette *
+             (sizeof (png_byte))));
 
          /* Initialize the sort array */
          for (i = 0; i < num_palette; i++)
@@ -619,7 +622,7 @@
             png_ptr->palette_to_index[i] = (png_byte)i;
          }
 
-         hash = (png_dsortpp)png_calloc(png_ptr, (png_uint_32)(769 *
+         hash = (png_dsortpp)png_calloc(png_ptr, (png_alloc_size_t)(769 *
              (sizeof (png_dsortp))));
 
          num_new_palette = num_palette;
@@ -650,7 +653,7 @@
                   {
 
                      t = (png_dsortp)png_malloc_warn(png_ptr,
-                         (png_uint_32)(sizeof (png_dsort)));
+                         (png_alloc_size_t)(sizeof (png_dsort)));
 
                      if (t == NULL)
                          break;
@@ -772,12 +775,12 @@
       int num_red = (1 << PNG_QUANTIZE_RED_BITS);
       int num_green = (1 << PNG_QUANTIZE_GREEN_BITS);
       int num_blue = (1 << PNG_QUANTIZE_BLUE_BITS);
-      png_size_t num_entries = ((png_size_t)1 << total_bits);
+      size_t num_entries = ((size_t)1 << total_bits);
 
       png_ptr->palette_lookup = (png_bytep)png_calloc(png_ptr,
-          (png_uint_32)(num_entries * (sizeof (png_byte))));
-
-      distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
+          (png_alloc_size_t)(num_entries * (sizeof (png_byte))));
+
+      distance = (png_bytep)png_malloc(png_ptr, (png_alloc_size_t)(num_entries *
           (sizeof (png_byte))));
 
       memset(distance, 0xff, num_entries * (sizeof (png_byte)));
@@ -1281,7 +1284,7 @@
             default:
 
             case 8:
-               /* FALL THROUGH (Already 8 bits) */
+               /* FALLTHROUGH */ /*  (Already 8 bits) */
 
             case 16:
                /* Already a full 16 bits */
@@ -1342,7 +1345,7 @@
 
       else if (png_ptr->screen_gamma != 0)
          /* The converse - assume the file matches the screen, note that this
-          * perhaps undesireable default can (from 1.5.4) be changed by calling
+          * perhaps undesirable default can (from 1.5.4) be changed by calling
           * png_set_alpha_mode (even if the alpha handling mode isn't required
           * or isn't changed from the default.)
           */
@@ -1910,7 +1913,7 @@
 
       png_ptr->transformations &= ~PNG_SHIFT;
 
-      /* significant bits can be in the range 1 to 7 for a meaninful result, if
+      /* significant bits can be in the range 1 to 7 for a meaningful result, if
        * the number of significant bits is 0 then no shift is done (this is an
        * error condition which is silently ignored.)
        */
@@ -2176,8 +2179,8 @@
       {
          case 1:
          {
-            png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
-            png_bytep dp = row + (png_size_t)row_width - 1;
+            png_bytep sp = row + (size_t)((row_width - 1) >> 3);
+            png_bytep dp = row + (size_t)row_width - 1;
             png_uint_32 shift = 7U - ((row_width + 7U) & 0x07);
             for (i = 0; i < row_width; i++)
             {
@@ -2200,8 +2203,8 @@
          case 2:
          {
 
-            png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
-            png_bytep dp = row + (png_size_t)row_width - 1;
+            png_bytep sp = row + (size_t)((row_width - 1) >> 2);
+            png_bytep dp = row + (size_t)row_width - 1;
             png_uint_32 shift = ((3U - ((row_width + 3U) & 0x03)) << 1);
             for (i = 0; i < row_width; i++)
             {
@@ -2223,8 +2226,8 @@
 
          case 4:
          {
-            png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
-            png_bytep dp = row + (png_size_t)row_width - 1;
+            png_bytep sp = row + (size_t)((row_width - 1) >> 1);
+            png_bytep dp = row + (size_t)row_width - 1;
             png_uint_32 shift = ((1U - ((row_width + 1U) & 0x01)) << 2);
             for (i = 0; i < row_width; i++)
             {
@@ -2488,95 +2491,94 @@
 static void
 png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
 {
+   png_uint_32 row_width = row_info->width;
+
    png_debug(1, "in png_do_read_swap_alpha");
 
+   if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
    {
-      png_uint_32 row_width = row_info->width;
-      if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
+      /* This converts from RGBA to ARGB */
+      if (row_info->bit_depth == 8)
       {
-         /* This converts from RGBA to ARGB */
-         if (row_info->bit_depth == 8)
+         png_bytep sp = row + row_info->rowbytes;
+         png_bytep dp = sp;
+         png_byte save;
+         png_uint_32 i;
+
+         for (i = 0; i < row_width; i++)
          {
-            png_bytep sp = row + row_info->rowbytes;
-            png_bytep dp = sp;
-            png_byte save;
-            png_uint_32 i;
-
-            for (i = 0; i < row_width; i++)
-            {
-               save = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = save;
-            }
+            save = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = save;
          }
+      }
 
 #ifdef PNG_READ_16BIT_SUPPORTED
-         /* This converts from RRGGBBAA to AARRGGBB */
-         else
+      /* This converts from RRGGBBAA to AARRGGBB */
+      else
+      {
+         png_bytep sp = row + row_info->rowbytes;
+         png_bytep dp = sp;
+         png_byte save[2];
+         png_uint_32 i;
+
+         for (i = 0; i < row_width; i++)
          {
-            png_bytep sp = row + row_info->rowbytes;
-            png_bytep dp = sp;
-            png_byte save[2];
-            png_uint_32 i;
-
-            for (i = 0; i < row_width; i++)
-            {
-               save[0] = *(--sp);
-               save[1] = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = save[0];
-               *(--dp) = save[1];
-            }
+            save[0] = *(--sp);
+            save[1] = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = save[0];
+            *(--dp) = save[1];
          }
+      }
 #endif
-      }
-
-      else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
+   }
+
+   else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
+   {
+      /* This converts from GA to AG */
+      if (row_info->bit_depth == 8)
       {
-         /* This converts from GA to AG */
-         if (row_info->bit_depth == 8)
+         png_bytep sp = row + row_info->rowbytes;
+         png_bytep dp = sp;
+         png_byte save;
+         png_uint_32 i;
+
+         for (i = 0; i < row_width; i++)
          {
-            png_bytep sp = row + row_info->rowbytes;
-            png_bytep dp = sp;
-            png_byte save;
-            png_uint_32 i;
-
-            for (i = 0; i < row_width; i++)
-            {
-               save = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = save;
-            }
+            save = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = save;
          }
+      }
 
 #ifdef PNG_READ_16BIT_SUPPORTED
-         /* This converts from GGAA to AAGG */
-         else
+      /* This converts from GGAA to AAGG */
+      else
+      {
+         png_bytep sp = row + row_info->rowbytes;
+         png_bytep dp = sp;
+         png_byte save[2];
+         png_uint_32 i;
+
+         for (i = 0; i < row_width; i++)
          {
-            png_bytep sp = row + row_info->rowbytes;
-            png_bytep dp = sp;
-            png_byte save[2];
-            png_uint_32 i;
-
-            for (i = 0; i < row_width; i++)
-            {
-               save[0] = *(--sp);
-               save[1] = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = *(--sp);
-               *(--dp) = save[0];
-               *(--dp) = save[1];
-            }
+            save[0] = *(--sp);
+            save[1] = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = *(--sp);
+            *(--dp) = save[0];
+            *(--dp) = save[1];
          }
+      }
 #endif
-      }
    }
 }
 #endif
@@ -2706,8 +2708,8 @@
          if ((flags & PNG_FLAG_FILLER_AFTER) != 0)
          {
             /* This changes the data from G to GX */
-            png_bytep sp = row + (png_size_t)row_width;
-            png_bytep dp =  sp + (png_size_t)row_width;
+            png_bytep sp = row + (size_t)row_width;
+            png_bytep dp =  sp + (size_t)row_width;
             for (i = 1; i < row_width; i++)
             {
                *(--dp) = lo_filler;
@@ -2722,8 +2724,8 @@
          else
          {
             /* This changes the data from G to XG */
-            png_bytep sp = row + (png_size_t)row_width;
-            png_bytep dp = sp  + (png_size_t)row_width;
+            png_bytep sp = row + (size_t)row_width;
+            png_bytep dp = sp  + (size_t)row_width;
             for (i = 0; i < row_width; i++)
             {
                *(--dp) = *(--sp);
@@ -2741,8 +2743,8 @@
          if ((flags & PNG_FLAG_FILLER_AFTER) != 0)
          {
             /* This changes the data from GG to GGXX */
-            png_bytep sp = row + (png_size_t)row_width * 2;
-            png_bytep dp = sp  + (png_size_t)row_width * 2;
+            png_bytep sp = row + (size_t)row_width * 2;
+            png_bytep dp = sp  + (size_t)row_width * 2;
             for (i = 1; i < row_width; i++)
             {
                *(--dp) = lo_filler;
@@ -2760,8 +2762,8 @@
          else
          {
             /* This changes the data from GG to XXGG */
-            png_bytep sp = row + (png_size_t)row_width * 2;
-            png_bytep dp = sp  + (png_size_t)row_width * 2;
+            png_bytep sp = row + (size_t)row_width * 2;
+            png_bytep dp = sp  + (size_t)row_width * 2;
             for (i = 0; i < row_width; i++)
             {
                *(--dp) = *(--sp);
@@ -2783,8 +2785,8 @@
          if ((flags & PNG_FLAG_FILLER_AFTER) != 0)
          {
             /* This changes the data from RGB to RGBX */
-            png_bytep sp = row + (png_size_t)row_width * 3;
-            png_bytep dp = sp  + (png_size_t)row_width;
+            png_bytep sp = row + (size_t)row_width * 3;
+            png_bytep dp = sp  + (size_t)row_width;
             for (i = 1; i < row_width; i++)
             {
                *(--dp) = lo_filler;
@@ -2801,8 +2803,8 @@
          else
          {
             /* This changes the data from RGB to XRGB */
-            png_bytep sp = row + (png_size_t)row_width * 3;
-            png_bytep dp = sp + (png_size_t)row_width;
+            png_bytep sp = row + (size_t)row_width * 3;
+            png_bytep dp = sp + (size_t)row_width;
             for (i = 0; i < row_width; i++)
             {
                *(--dp) = *(--sp);
@@ -2822,8 +2824,8 @@
          if ((flags & PNG_FLAG_FILLER_AFTER) != 0)
          {
             /* This changes the data from RRGGBB to RRGGBBXX */
-            png_bytep sp = row + (png_size_t)row_width * 6;
-            png_bytep dp = sp  + (png_size_t)row_width * 2;
+            png_bytep sp = row + (size_t)row_width * 6;
+            png_bytep dp = sp  + (size_t)row_width * 2;
             for (i = 1; i < row_width; i++)
             {
                *(--dp) = lo_filler;
@@ -2845,8 +2847,8 @@
          else
          {
             /* This changes the data from RRGGBB to XXRRGGBB */
-            png_bytep sp = row + (png_size_t)row_width * 6;
-            png_bytep dp = sp  + (png_size_t)row_width * 2;
+            png_bytep sp = row + (size_t)row_width * 6;
+            png_bytep dp = sp  + (size_t)row_width * 2;
             for (i = 0; i < row_width; i++)
             {
                *(--dp) = *(--sp);
@@ -2887,8 +2889,8 @@
          if (row_info->bit_depth == 8)
          {
             /* This changes G to RGB */
-            png_bytep sp = row + (png_size_t)row_width - 1;
-            png_bytep dp = sp  + (png_size_t)row_width * 2;
+            png_bytep sp = row + (size_t)row_width - 1;
+            png_bytep dp = sp  + (size_t)row_width * 2;
             for (i = 0; i < row_width; i++)
             {
                *(dp--) = *sp;
@@ -2900,8 +2902,8 @@
          else
          {
             /* This changes GG to RRGGBB */
-            png_bytep sp = row + (png_size_t)row_width * 2 - 1;
-            png_bytep dp = sp  + (png_size_t)row_width * 4;
+            png_bytep sp = row + (size_t)row_width * 2 - 1;
+            png_bytep dp = sp  + (size_t)row_width * 4;
             for (i = 0; i < row_width; i++)
             {
                *(dp--) = *sp;
@@ -2919,8 +2921,8 @@
          if (row_info->bit_depth == 8)
          {
             /* This changes GA to RGBA */
-            png_bytep sp = row + (png_size_t)row_width * 2 - 1;
-            png_bytep dp = sp  + (png_size_t)row_width * 2;
+            png_bytep sp = row + (size_t)row_width * 2 - 1;
+            png_bytep dp = sp  + (size_t)row_width * 2;
             for (i = 0; i < row_width; i++)
             {
                *(dp--) = *(sp--);
@@ -2933,8 +2935,8 @@
          else
          {
             /* This changes GGAA to RRGGBBAA */
-            png_bytep sp = row + (png_size_t)row_width * 4 - 1;
-            png_bytep dp = sp  + (png_size_t)row_width * 4;
+            png_bytep sp = row + (size_t)row_width * 4 - 1;
+            png_bytep dp = sp  + (size_t)row_width * 4;
             for (i = 0; i < row_width; i++)
             {
                *(dp--) = *(sp--);
@@ -2962,7 +2964,7 @@
  * using the equation given in Poynton's ColorFAQ of 1998-01-04 at
  * <http://www.inforamp.net/~poynton/>  (THIS LINK IS DEAD June 2008 but
  * versions dated 1998 through November 2002 have been archived at
- * http://web.archive.org/web/20000816232553/http://www.inforamp.net/
+ * https://web.archive.org/web/20000816232553/www.inforamp.net/
  * ~poynton/notes/colour_and_gamma/ColorFAQ.txt )
  * Charles Poynton poynton at poynton.com
  *
@@ -3005,7 +3007,7 @@
  *  values this results in an implicit assumption that the original PNG RGB
  *  values were linear.
  *
- *  Other integer coefficents can be used via png_set_rgb_to_gray().  Because
+ *  Other integer coefficients can be used via png_set_rgb_to_gray().  Because
  *  the API takes just red and green coefficients the blue coefficient is
  *  calculated to make the sum 32768.  This will result in different rounding
  *  to that used above.
@@ -3234,351 +3236,75 @@
 
    png_debug(1, "in png_do_compose");
 
+   switch (row_info->color_type)
    {
-      switch (row_info->color_type)
+      case PNG_COLOR_TYPE_GRAY:
       {
-         case PNG_COLOR_TYPE_GRAY:
+         switch (row_info->bit_depth)
          {
-            switch (row_info->bit_depth)
+            case 1:
             {
-               case 1:
+               sp = row;
+               shift = 7;
+               for (i = 0; i < row_width; i++)
+               {
+                  if ((png_uint_16)((*sp >> shift) & 0x01)
+                     == png_ptr->trans_color.gray)
+                  {
+                     unsigned int tmp = *sp & (0x7f7f >> (7 - shift));
+                     tmp |=
+                         (unsigned int)(png_ptr->background.gray << shift);
+                     *sp = (png_byte)(tmp & 0xff);
+                  }
+
+                  if (shift == 0)
+                  {
+                     shift = 7;
+                     sp++;
+                  }
+
+                  else
+                     shift--;
+               }
+               break;
+            }
+
+            case 2:
+            {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+               if (gamma_table != NULL)
                {
                   sp = row;
-                  shift = 7;
+                  shift = 6;
                   for (i = 0; i < row_width; i++)
                   {
-                     if ((png_uint_16)((*sp >> shift) & 0x01)
-                        == png_ptr->trans_color.gray)
+                     if ((png_uint_16)((*sp >> shift) & 0x03)
+                         == png_ptr->trans_color.gray)
                      {
-                        unsigned int tmp = *sp & (0x7f7f >> (7 - shift));
+                        unsigned int tmp = *sp & (0x3f3f >> (6 - shift));
                         tmp |=
-                            (unsigned int)(png_ptr->background.gray << shift);
+                           (unsigned int)png_ptr->background.gray << shift;
+                        *sp = (png_byte)(tmp & 0xff);
+                     }
+
+                     else
+                     {
+                        unsigned int p = (*sp >> shift) & 0x03;
+                        unsigned int g = (gamma_table [p | (p << 2) |
+                            (p << 4) | (p << 6)] >> 6) & 0x03;
+                        unsigned int tmp = *sp & (0x3f3f >> (6 - shift));
+                        tmp |= (unsigned int)(g << shift);
                         *sp = (png_byte)(tmp & 0xff);
                      }
 
                      if (shift == 0)
                      {
-                        shift = 7;
+                        shift = 6;
                         sp++;
                      }
 
                      else
-                        shift--;
-                  }
-                  break;
-               }
-
-               case 2:
-               {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-                  if (gamma_table != NULL)
-                  {
-                     sp = row;
-                     shift = 6;
-                     for (i = 0; i < row_width; i++)
-                     {
-                        if ((png_uint_16)((*sp >> shift) & 0x03)
-                            == png_ptr->trans_color.gray)
-                        {
-                           unsigned int tmp = *sp & (0x3f3f >> (6 - shift));
-                           tmp |=
-                              (unsigned int)png_ptr->background.gray << shift;
-                           *sp = (png_byte)(tmp & 0xff);
-                        }
-
-                        else
-                        {
-                           unsigned int p = (*sp >> shift) & 0x03;
-                           unsigned int g = (gamma_table [p | (p << 2) |
-                               (p << 4) | (p << 6)] >> 6) & 0x03;
-                           unsigned int tmp = *sp & (0x3f3f >> (6 - shift));
-                           tmp |= (unsigned int)(g << shift);
-                           *sp = (png_byte)(tmp & 0xff);
-                        }
-
-                        if (shift == 0)
-                        {
-                           shift = 6;
-                           sp++;
-                        }
-
-                        else
-                           shift -= 2;
-                     }
-                  }
-
-                  else
-#endif
-                  {
-                     sp = row;
-                     shift = 6;
-                     for (i = 0; i < row_width; i++)
-                     {
-                        if ((png_uint_16)((*sp >> shift) & 0x03)
-                            == png_ptr->trans_color.gray)
-                        {
-                           unsigned int tmp = *sp & (0x3f3f >> (6 - shift));
-                           tmp |=
-                               (unsigned int)png_ptr->background.gray << shift;
-                           *sp = (png_byte)(tmp & 0xff);
-                        }
-
-                        if (shift == 0)
-                        {
-                           shift = 6;
-                           sp++;
-                        }
-
-                        else
-                           shift -= 2;
-                     }
-                  }
-                  break;
-               }
-
-               case 4:
-               {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-                  if (gamma_table != NULL)
-                  {
-                     sp = row;
-                     shift = 4;
-                     for (i = 0; i < row_width; i++)
-                     {
-                        if ((png_uint_16)((*sp >> shift) & 0x0f)
-                            == png_ptr->trans_color.gray)
-                        {
-                           unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
-                           tmp |=
-                              (unsigned int)(png_ptr->background.gray << shift);
-                           *sp = (png_byte)(tmp & 0xff);
-                        }
-
-                        else
-                        {
-                           unsigned int p = (*sp >> shift) & 0x0f;
-                           unsigned int g = (gamma_table[p | (p << 4)] >> 4) &
-                              0x0f;
-                           unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
-                           tmp |= (unsigned int)(g << shift);
-                           *sp = (png_byte)(tmp & 0xff);
-                        }
-
-                        if (shift == 0)
-                        {
-                           shift = 4;
-                           sp++;
-                        }
-
-                        else
-                           shift -= 4;
-                     }
-                  }
-
-                  else
-#endif
-                  {
-                     sp = row;
-                     shift = 4;
-                     for (i = 0; i < row_width; i++)
-                     {
-                        if ((png_uint_16)((*sp >> shift) & 0x0f)
-                            == png_ptr->trans_color.gray)
-                        {
-                           unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
-                           tmp |=
-                              (unsigned int)(png_ptr->background.gray << shift);
-                           *sp = (png_byte)(tmp & 0xff);
-                        }
-
-                        if (shift == 0)
-                        {
-                           shift = 4;
-                           sp++;
-                        }
-
-                        else
-                           shift -= 4;
-                     }
-                  }
-                  break;
-               }
-
-               case 8:
-               {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-                  if (gamma_table != NULL)
-                  {
-                     sp = row;
-                     for (i = 0; i < row_width; i++, sp++)
-                     {
-                        if (*sp == png_ptr->trans_color.gray)
-                           *sp = (png_byte)png_ptr->background.gray;
-
-                        else
-                           *sp = gamma_table[*sp];
-                     }
-                  }
-                  else
-#endif
-                  {
-                     sp = row;
-                     for (i = 0; i < row_width; i++, sp++)
-                     {
-                        if (*sp == png_ptr->trans_color.gray)
-                           *sp = (png_byte)png_ptr->background.gray;
-                     }
-                  }
-                  break;
-               }
-
-               case 16:
-               {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-                  if (gamma_16 != NULL)
-                  {
-                     sp = row;
-                     for (i = 0; i < row_width; i++, sp += 2)
-                     {
-                        png_uint_16 v;
-
-                        v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
-
-                        if (v == png_ptr->trans_color.gray)
-                        {
-                           /* Background is already in screen gamma */
-                           *sp = (png_byte)((png_ptr->background.gray >> 8)
-                                & 0xff);
-                           *(sp + 1) = (png_byte)(png_ptr->background.gray
-                                & 0xff);
-                        }
-
-                        else
-                        {
-                           v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
-                           *sp = (png_byte)((v >> 8) & 0xff);
-                           *(sp + 1) = (png_byte)(v & 0xff);
-                        }
-                     }
-                  }
-                  else
-#endif
-                  {
-                     sp = row;
-                     for (i = 0; i < row_width; i++, sp += 2)
-                     {
-                        png_uint_16 v;
-
-                        v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
-
-                        if (v == png_ptr->trans_color.gray)
-                        {
-                           *sp = (png_byte)((png_ptr->background.gray >> 8)
-                                & 0xff);
-                           *(sp + 1) = (png_byte)(png_ptr->background.gray
-                                & 0xff);
-                        }
-                     }
-                  }
-                  break;
-               }
-
-               default:
-                  break;
-            }
-            break;
-         }
-
-         case PNG_COLOR_TYPE_RGB:
-         {
-            if (row_info->bit_depth == 8)
-            {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-               if (gamma_table != NULL)
-               {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 3)
-                  {
-                     if (*sp == png_ptr->trans_color.red &&
-                         *(sp + 1) == png_ptr->trans_color.green &&
-                         *(sp + 2) == png_ptr->trans_color.blue)
-                     {
-                        *sp = (png_byte)png_ptr->background.red;
-                        *(sp + 1) = (png_byte)png_ptr->background.green;
-                        *(sp + 2) = (png_byte)png_ptr->background.blue;
-                     }
-
-                     else
-                     {
-                        *sp = gamma_table[*sp];
-                        *(sp + 1) = gamma_table[*(sp + 1)];
-                        *(sp + 2) = gamma_table[*(sp + 2)];
-                     }
-                  }
-               }
-               else
-#endif
-               {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 3)
-                  {
-                     if (*sp == png_ptr->trans_color.red &&
-                         *(sp + 1) == png_ptr->trans_color.green &&
-                         *(sp + 2) == png_ptr->trans_color.blue)
-                     {
-                        *sp = (png_byte)png_ptr->background.red;
-                        *(sp + 1) = (png_byte)png_ptr->background.green;
-                        *(sp + 2) = (png_byte)png_ptr->background.blue;
-                     }
-                  }
-               }
-            }
-            else /* if (row_info->bit_depth == 16) */
-            {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-               if (gamma_16 != NULL)
-               {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 6)
-                  {
-                     png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
-
-                     png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
-                         + *(sp + 3));
-
-                     png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
-                         + *(sp + 5));
-
-                     if (r == png_ptr->trans_color.red &&
-                         g == png_ptr->trans_color.green &&
-                         b == png_ptr->trans_color.blue)
-                     {
-                        /* Background is already in screen gamma */
-                        *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
-                        *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
-                                & 0xff);
-                        *(sp + 3) = (png_byte)(png_ptr->background.green
-                                & 0xff);
-                        *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
-                                & 0xff);
-                        *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
-                     }
-
-                     else
-                     {
-                        png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
-                        *sp = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(v & 0xff);
-
-                        v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
-                        *(sp + 2) = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 3) = (png_byte)(v & 0xff);
-
-                        v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
-                        *(sp + 4) = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 5) = (png_byte)(v & 0xff);
-                     }
+                        shift -= 2;
                   }
                }
 
@@ -3586,67 +3312,153 @@
 #endif
                {
                   sp = row;
-                  for (i = 0; i < row_width; i++, sp += 6)
+                  shift = 6;
+                  for (i = 0; i < row_width; i++)
                   {
-                     png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
-
-                     png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
-                         + *(sp + 3));
-
-                     png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
-                         + *(sp + 5));
-
-                     if (r == png_ptr->trans_color.red &&
-                         g == png_ptr->trans_color.green &&
-                         b == png_ptr->trans_color.blue)
+                     if ((png_uint_16)((*sp >> shift) & 0x03)
+                         == png_ptr->trans_color.gray)
+                     {
+                        unsigned int tmp = *sp & (0x3f3f >> (6 - shift));
+                        tmp |=
+                            (unsigned int)png_ptr->background.gray << shift;
+                        *sp = (png_byte)(tmp & 0xff);
+                     }
+
+                     if (shift == 0)
                      {
-                        *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
-                        *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
-                                & 0xff);
-                        *(sp + 3) = (png_byte)(png_ptr->background.green
-                                & 0xff);
-                        *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
-                                & 0xff);
-                        *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
+                        shift = 6;
+                        sp++;
                      }
+
+                     else
+                        shift -= 2;
+                  }
+               }
+               break;
+            }
+
+            case 4:
+            {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+               if (gamma_table != NULL)
+               {
+                  sp = row;
+                  shift = 4;
+                  for (i = 0; i < row_width; i++)
+                  {
+                     if ((png_uint_16)((*sp >> shift) & 0x0f)
+                         == png_ptr->trans_color.gray)
+                     {
+                        unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
+                        tmp |=
+                           (unsigned int)(png_ptr->background.gray << shift);
+                        *sp = (png_byte)(tmp & 0xff);
+                     }
+
+                     else
+                     {
+                        unsigned int p = (*sp >> shift) & 0x0f;
+                        unsigned int g = (gamma_table[p | (p << 4)] >> 4) &
+                           0x0f;
+                        unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
+                        tmp |= (unsigned int)(g << shift);
+                        *sp = (png_byte)(tmp & 0xff);
+                     }
+
+                     if (shift == 0)
+                     {
+                        shift = 4;
+                        sp++;
+                     }
+
+                     else
+                        shift -= 4;
                   }
                }
+
+               else
+#endif
+               {
+                  sp = row;
+                  shift = 4;
+                  for (i = 0; i < row_width; i++)
+                  {
+                     if ((png_uint_16)((*sp >> shift) & 0x0f)
+                         == png_ptr->trans_color.gray)
+                     {
+                        unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
+                        tmp |=
+                           (unsigned int)(png_ptr->background.gray << shift);
+                        *sp = (png_byte)(tmp & 0xff);
+                     }
+
+                     if (shift == 0)
+                     {
+                        shift = 4;
+                        sp++;
+                     }
+
+                     else
+                        shift -= 4;
+                  }
+               }
+               break;
             }
-            break;
-         }
-
-         case PNG_COLOR_TYPE_GRAY_ALPHA:
-         {
-            if (row_info->bit_depth == 8)
+
+            case 8:
             {
 #ifdef PNG_READ_GAMMA_SUPPORTED
-               if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
-                   gamma_table != NULL)
+               if (gamma_table != NULL)
+               {
+                  sp = row;
+                  for (i = 0; i < row_width; i++, sp++)
+                  {
+                     if (*sp == png_ptr->trans_color.gray)
+                        *sp = (png_byte)png_ptr->background.gray;
+
+                     else
+                        *sp = gamma_table[*sp];
+                  }
+               }
+               else
+#endif
+               {
+                  sp = row;
+                  for (i = 0; i < row_width; i++, sp++)
+                  {
+                     if (*sp == png_ptr->trans_color.gray)
+                        *sp = (png_byte)png_ptr->background.gray;
+                  }
+               }
+               break;
+            }
+
+            case 16:
+            {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+               if (gamma_16 != NULL)
                {
                   sp = row;
                   for (i = 0; i < row_width; i++, sp += 2)
                   {
-                     png_uint_16 a = *(sp + 1);
-
-                     if (a == 0xff)
-                        *sp = gamma_table[*sp];
-
-                     else if (a == 0)
+                     png_uint_16 v;
+
+                     v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
+
+                     if (v == png_ptr->trans_color.gray)
                      {
                         /* Background is already in screen gamma */
-                        *sp = (png_byte)png_ptr->background.gray;
+                        *sp = (png_byte)((png_ptr->background.gray >> 8)
+                             & 0xff);
+                        *(sp + 1) = (png_byte)(png_ptr->background.gray
+                             & 0xff);
                      }
 
                      else
                      {
-                        png_byte v, w;
-
-                        v = gamma_to_1[*sp];
-                        png_composite(w, v, a, png_ptr->background_1.gray);
-                        if (optimize == 0)
-                           w = gamma_from_1[w];
-                        *sp = w;
+                        v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
+                        *sp = (png_byte)((v >> 8) & 0xff);
+                        *(sp + 1) = (png_byte)(v & 0xff);
                      }
                   }
                }
@@ -3656,298 +3468,486 @@
                   sp = row;
                   for (i = 0; i < row_width; i++, sp += 2)
                   {
-                     png_byte a = *(sp + 1);
-
-                     if (a == 0)
-                        *sp = (png_byte)png_ptr->background.gray;
-
-                     else if (a < 0xff)
-                        png_composite(*sp, *sp, a, png_ptr->background.gray);
-                  }
-               }
-            }
-            else /* if (png_ptr->bit_depth == 16) */
-            {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-               if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
-                   gamma_16_to_1 != NULL)
-               {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 4)
-                  {
-                     png_uint_16 a = (png_uint_16)(((*(sp + 2)) << 8)
-                         + *(sp + 3));
-
-                     if (a == (png_uint_16)0xffff)
-                     {
-                        png_uint_16 v;
-
-                        v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
-                        *sp = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(v & 0xff);
-                     }
-
-                     else if (a == 0)
-                     {
-                        /* Background is already in screen gamma */
-                        *sp = (png_byte)((png_ptr->background.gray >> 8)
-                                & 0xff);
-                        *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff);
-                     }
-
-                     else
-                     {
-                        png_uint_16 g, v, w;
-
-                        g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
-                        png_composite_16(v, g, a, png_ptr->background_1.gray);
-                        if (optimize != 0)
-                           w = v;
-                        else
-                           w = gamma_16_from_1[(v & 0xff) >>
-                               gamma_shift][v >> 8];
-                        *sp = (png_byte)((w >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(w & 0xff);
-                     }
-                  }
-               }
-               else
-#endif
-               {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 4)
-                  {
-                     png_uint_16 a = (png_uint_16)(((*(sp + 2)) << 8)
-                         + *(sp + 3));
-
-                     if (a == 0)
+                     png_uint_16 v;
+
+                     v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
+
+                     if (v == png_ptr->trans_color.gray)
                      {
                         *sp = (png_byte)((png_ptr->background.gray >> 8)
-                                & 0xff);
-                        *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff);
-                     }
-
-                     else if (a < 0xffff)
-                     {
-                        png_uint_16 g, v;
-
-                        g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
-                        png_composite_16(v, g, a, png_ptr->background.gray);
-                        *sp = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(v & 0xff);
-                     }
-                  }
-               }
-            }
-            break;
-         }
-
-         case PNG_COLOR_TYPE_RGB_ALPHA:
-         {
-            if (row_info->bit_depth == 8)
-            {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-               if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
-                   gamma_table != NULL)
-               {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 4)
-                  {
-                     png_byte a = *(sp + 3);
-
-                     if (a == 0xff)
-                     {
-                        *sp = gamma_table[*sp];
-                        *(sp + 1) = gamma_table[*(sp + 1)];
-                        *(sp + 2) = gamma_table[*(sp + 2)];
-                     }
-
-                     else if (a == 0)
-                     {
-                        /* Background is already in screen gamma */
-                        *sp = (png_byte)png_ptr->background.red;
-                        *(sp + 1) = (png_byte)png_ptr->background.green;
-                        *(sp + 2) = (png_byte)png_ptr->background.blue;
-                     }
-
-                     else
-                     {
-                        png_byte v, w;
-
-                        v = gamma_to_1[*sp];
-                        png_composite(w, v, a, png_ptr->background_1.red);
-                        if (optimize == 0) w = gamma_from_1[w];
-                        *sp = w;
-
-                        v = gamma_to_1[*(sp + 1)];
-                        png_composite(w, v, a, png_ptr->background_1.green);
-                        if (optimize == 0) w = gamma_from_1[w];
-                        *(sp + 1) = w;
-
-                        v = gamma_to_1[*(sp + 2)];
-                        png_composite(w, v, a, png_ptr->background_1.blue);
-                        if (optimize == 0) w = gamma_from_1[w];
-                        *(sp + 2) = w;
+                             & 0xff);
+                        *(sp + 1) = (png_byte)(png_ptr->background.gray
+                             & 0xff);
                      }
                   }
                }
-               else
+               break;
+            }
+
+            default:
+               break;
+         }
+         break;
+      }
+
+      case PNG_COLOR_TYPE_RGB:
+      {
+         if (row_info->bit_depth == 8)
+         {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+            if (gamma_table != NULL)
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 3)
+               {
+                  if (*sp == png_ptr->trans_color.red &&
+                      *(sp + 1) == png_ptr->trans_color.green &&
+                      *(sp + 2) == png_ptr->trans_color.blue)
+                  {
+                     *sp = (png_byte)png_ptr->background.red;
+                     *(sp + 1) = (png_byte)png_ptr->background.green;
+                     *(sp + 2) = (png_byte)png_ptr->background.blue;
+                  }
+
+                  else
+                  {
+                     *sp = gamma_table[*sp];
+                     *(sp + 1) = gamma_table[*(sp + 1)];
+                     *(sp + 2) = gamma_table[*(sp + 2)];
+                  }
+               }
+            }
+            else
 #endif
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 3)
                {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 4)
+                  if (*sp == png_ptr->trans_color.red &&
+                      *(sp + 1) == png_ptr->trans_color.green &&
+                      *(sp + 2) == png_ptr->trans_color.blue)
+                  {
+                     *sp = (png_byte)png_ptr->background.red;
+                     *(sp + 1) = (png_byte)png_ptr->background.green;
+                     *(sp + 2) = (png_byte)png_ptr->background.blue;
+                  }
+               }
+            }
+         }
+         else /* if (row_info->bit_depth == 16) */
+         {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+            if (gamma_16 != NULL)
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 6)
+               {
+                  png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
+
+                  png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
+                      + *(sp + 3));
+
+                  png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
+                      + *(sp + 5));
+
+                  if (r == png_ptr->trans_color.red &&
+                      g == png_ptr->trans_color.green &&
+                      b == png_ptr->trans_color.blue)
+                  {
+                     /* Background is already in screen gamma */
+                     *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
+                     *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
+                             & 0xff);
+                     *(sp + 3) = (png_byte)(png_ptr->background.green
+                             & 0xff);
+                     *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
+                             & 0xff);
+                     *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
+                  }
+
+                  else
                   {
-                     png_byte a = *(sp + 3);
-
-                     if (a == 0)
-                     {
-                        *sp = (png_byte)png_ptr->background.red;
-                        *(sp + 1) = (png_byte)png_ptr->background.green;
-                        *(sp + 2) = (png_byte)png_ptr->background.blue;
-                     }
-
-                     else if (a < 0xff)
-                     {
-                        png_composite(*sp, *sp, a, png_ptr->background.red);
-
-                        png_composite(*(sp + 1), *(sp + 1), a,
-                            png_ptr->background.green);
-
-                        png_composite(*(sp + 2), *(sp + 2), a,
-                            png_ptr->background.blue);
-                     }
+                     png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
+                     *sp = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(v & 0xff);
+
+                     v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
+                     *(sp + 2) = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 3) = (png_byte)(v & 0xff);
+
+                     v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
+                     *(sp + 4) = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 5) = (png_byte)(v & 0xff);
+                  }
+               }
+            }
+
+            else
+#endif
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 6)
+               {
+                  png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
+
+                  png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
+                      + *(sp + 3));
+
+                  png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
+                      + *(sp + 5));
+
+                  if (r == png_ptr->trans_color.red &&
+                      g == png_ptr->trans_color.green &&
+                      b == png_ptr->trans_color.blue)
+                  {
+                     *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
+                     *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
+                             & 0xff);
+                     *(sp + 3) = (png_byte)(png_ptr->background.green
+                             & 0xff);
+                     *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
+                             & 0xff);
+                     *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
+                  }
+               }
+            }
+         }
+         break;
+      }
+
+      case PNG_COLOR_TYPE_GRAY_ALPHA:
+      {
+         if (row_info->bit_depth == 8)
+         {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+            if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
+                gamma_table != NULL)
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 2)
+               {
+                  png_uint_16 a = *(sp + 1);
+
+                  if (a == 0xff)
+                     *sp = gamma_table[*sp];
+
+                  else if (a == 0)
+                  {
+                     /* Background is already in screen gamma */
+                     *sp = (png_byte)png_ptr->background.gray;
+                  }
+
+                  else
+                  {
+                     png_byte v, w;
+
+                     v = gamma_to_1[*sp];
+                     png_composite(w, v, a, png_ptr->background_1.gray);
+                     if (optimize == 0)
+                        w = gamma_from_1[w];
+                     *sp = w;
+                  }
+               }
+            }
+            else
+#endif
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 2)
+               {
+                  png_byte a = *(sp + 1);
+
+                  if (a == 0)
+                     *sp = (png_byte)png_ptr->background.gray;
+
+                  else if (a < 0xff)
+                     png_composite(*sp, *sp, a, png_ptr->background.gray);
+               }
+            }
+         }
+         else /* if (png_ptr->bit_depth == 16) */
+         {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+            if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
+                gamma_16_to_1 != NULL)
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 4)
+               {
+                  png_uint_16 a = (png_uint_16)(((*(sp + 2)) << 8)
+                      + *(sp + 3));
+
+                  if (a == (png_uint_16)0xffff)
+                  {
+                     png_uint_16 v;
+
+                     v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
+                     *sp = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(v & 0xff);
+                  }
+
+                  else if (a == 0)
+                  {
+                     /* Background is already in screen gamma */
+                     *sp = (png_byte)((png_ptr->background.gray >> 8)
+                             & 0xff);
+                     *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff);
+                  }
+
+                  else
+                  {
+                     png_uint_16 g, v, w;
+
+                     g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
+                     png_composite_16(v, g, a, png_ptr->background_1.gray);
+                     if (optimize != 0)
+                        w = v;
+                     else
+                        w = gamma_16_from_1[(v & 0xff) >>
+                            gamma_shift][v >> 8];
+                     *sp = (png_byte)((w >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(w & 0xff);
                   }
                }
             }
-            else /* if (row_info->bit_depth == 16) */
+            else
+#endif
             {
-#ifdef PNG_READ_GAMMA_SUPPORTED
-               if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
-                   gamma_16_to_1 != NULL)
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 4)
                {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 8)
+                  png_uint_16 a = (png_uint_16)(((*(sp + 2)) << 8)
+                      + *(sp + 3));
+
+                  if (a == 0)
                   {
-                     png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
-                         << 8) + (png_uint_16)(*(sp + 7)));
-
-                     if (a == (png_uint_16)0xffff)
-                     {
-                        png_uint_16 v;
-
-                        v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
-                        *sp = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(v & 0xff);
-
-                        v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
-                        *(sp + 2) = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 3) = (png_byte)(v & 0xff);
-
-                        v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
-                        *(sp + 4) = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 5) = (png_byte)(v & 0xff);
-                     }
-
-                     else if (a == 0)
-                     {
-                        /* Background is already in screen gamma */
-                        *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
-                        *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
-                                & 0xff);
-                        *(sp + 3) = (png_byte)(png_ptr->background.green
-                                & 0xff);
-                        *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
-                                & 0xff);
-                        *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
-                     }
-
-                     else
-                     {
-                        png_uint_16 v, w;
-
-                        v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
-                        png_composite_16(w, v, a, png_ptr->background_1.red);
-                        if (optimize == 0)
-                           w = gamma_16_from_1[((w & 0xff) >> gamma_shift)][w >>
-                                8];
-                        *sp = (png_byte)((w >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(w & 0xff);
-
-                        v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
-                        png_composite_16(w, v, a, png_ptr->background_1.green);
-                        if (optimize == 0)
-                           w = gamma_16_from_1[((w & 0xff) >> gamma_shift)][w >>
-                                8];
-
-                        *(sp + 2) = (png_byte)((w >> 8) & 0xff);
-                        *(sp + 3) = (png_byte)(w & 0xff);
-
-                        v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
-                        png_composite_16(w, v, a, png_ptr->background_1.blue);
-                        if (optimize == 0)
-                           w = gamma_16_from_1[((w & 0xff) >> gamma_shift)][w >>
-                                8];
-
-                        *(sp + 4) = (png_byte)((w >> 8) & 0xff);
-                        *(sp + 5) = (png_byte)(w & 0xff);
-                     }
+                     *sp = (png_byte)((png_ptr->background.gray >> 8)
+                             & 0xff);
+                     *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff);
+                  }
+
+                  else if (a < 0xffff)
+                  {
+                     png_uint_16 g, v;
+
+                     g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
+                     png_composite_16(v, g, a, png_ptr->background.gray);
+                     *sp = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(v & 0xff);
                   }
                }
-
-               else
-#endif
+            }
+         }
+         break;
+      }
+
+      case PNG_COLOR_TYPE_RGB_ALPHA:
+      {
+         if (row_info->bit_depth == 8)
+         {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+            if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
+                gamma_table != NULL)
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 4)
                {
-                  sp = row;
-                  for (i = 0; i < row_width; i++, sp += 8)
+                  png_byte a = *(sp + 3);
+
+                  if (a == 0xff)
+                  {
+                     *sp = gamma_table[*sp];
+                     *(sp + 1) = gamma_table[*(sp + 1)];
+                     *(sp + 2) = gamma_table[*(sp + 2)];
+                  }
+
+                  else if (a == 0)
+                  {
+                     /* Background is already in screen gamma */
+                     *sp = (png_byte)png_ptr->background.red;
+                     *(sp + 1) = (png_byte)png_ptr->background.green;
+                     *(sp + 2) = (png_byte)png_ptr->background.blue;
+                  }
+
+                  else
                   {
-                     png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
-                         << 8) + (png_uint_16)(*(sp + 7)));
-
-                     if (a == 0)
-                     {
-                        *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
-                        *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
-                                & 0xff);
-                        *(sp + 3) = (png_byte)(png_ptr->background.green
-                                & 0xff);
-                        *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
-                                & 0xff);
-                        *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
-                     }
-
-                     else if (a < 0xffff)
-                     {
-                        png_uint_16 v;
-
-                        png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
-                        png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
-                            + *(sp + 3));
-                        png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
-                            + *(sp + 5));
-
-                        png_composite_16(v, r, a, png_ptr->background.red);
-                        *sp = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 1) = (png_byte)(v & 0xff);
-
-                        png_composite_16(v, g, a, png_ptr->background.green);
-                        *(sp + 2) = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 3) = (png_byte)(v & 0xff);
-
-                        png_composite_16(v, b, a, png_ptr->background.blue);
-                        *(sp + 4) = (png_byte)((v >> 8) & 0xff);
-                        *(sp + 5) = (png_byte)(v & 0xff);
-                     }
+                     png_byte v, w;
+
+                     v = gamma_to_1[*sp];
+                     png_composite(w, v, a, png_ptr->background_1.red);
+                     if (optimize == 0) w = gamma_from_1[w];
+                     *sp = w;
+
+                     v = gamma_to_1[*(sp + 1)];
+                     png_composite(w, v, a, png_ptr->background_1.green);
+                     if (optimize == 0) w = gamma_from_1[w];
+                     *(sp + 1) = w;
+
+                     v = gamma_to_1[*(sp + 2)];
+                     png_composite(w, v, a, png_ptr->background_1.blue);
+                     if (optimize == 0) w = gamma_from_1[w];
+                     *(sp + 2) = w;
+                  }
+               }
+            }
+            else
+#endif
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 4)
+               {
+                  png_byte a = *(sp + 3);
+
+                  if (a == 0)
+                  {
+                     *sp = (png_byte)png_ptr->background.red;
+                     *(sp + 1) = (png_byte)png_ptr->background.green;
+                     *(sp + 2) = (png_byte)png_ptr->background.blue;
+                  }
+
+                  else if (a < 0xff)
+                  {
+                     png_composite(*sp, *sp, a, png_ptr->background.red);
+
+                     png_composite(*(sp + 1), *(sp + 1), a,
+                         png_ptr->background.green);
+
+                     png_composite(*(sp + 2), *(sp + 2), a,
+                         png_ptr->background.blue);
                   }
                }
             }
-            break;
          }
-
-         default:
-            break;
+         else /* if (row_info->bit_depth == 16) */
+         {
+#ifdef PNG_READ_GAMMA_SUPPORTED
+            if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
+                gamma_16_to_1 != NULL)
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 8)
+               {
+                  png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
+                      << 8) + (png_uint_16)(*(sp + 7)));
+
+                  if (a == (png_uint_16)0xffff)
+                  {
+                     png_uint_16 v;
+
+                     v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
+                     *sp = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(v & 0xff);
+
+                     v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
+                     *(sp + 2) = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 3) = (png_byte)(v & 0xff);
+
+                     v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
+                     *(sp + 4) = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 5) = (png_byte)(v & 0xff);
+                  }
+
+                  else if (a == 0)
+                  {
+                     /* Background is already in screen gamma */
+                     *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
+                     *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
+                             & 0xff);
+                     *(sp + 3) = (png_byte)(png_ptr->background.green
+                             & 0xff);
+                     *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
+                             & 0xff);
+                     *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
+                  }
+
+                  else
+                  {
+                     png_uint_16 v, w;
+
+                     v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
+                     png_composite_16(w, v, a, png_ptr->background_1.red);
+                     if (optimize == 0)
+                        w = gamma_16_from_1[((w & 0xff) >> gamma_shift)][w >>
+                             8];
+                     *sp = (png_byte)((w >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(w & 0xff);
+
+                     v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
+                     png_composite_16(w, v, a, png_ptr->background_1.green);
+                     if (optimize == 0)
+                        w = gamma_16_from_1[((w & 0xff) >> gamma_shift)][w >>
+                             8];
+
+                     *(sp + 2) = (png_byte)((w >> 8) & 0xff);
+                     *(sp + 3) = (png_byte)(w & 0xff);
+
+                     v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
+                     png_composite_16(w, v, a, png_ptr->background_1.blue);
+                     if (optimize == 0)
+                        w = gamma_16_from_1[((w & 0xff) >> gamma_shift)][w >>
+                             8];
+
+                     *(sp + 4) = (png_byte)((w >> 8) & 0xff);
+                     *(sp + 5) = (png_byte)(w & 0xff);
+                  }
+               }
+            }
+
+            else
+#endif
+            {
+               sp = row;
+               for (i = 0; i < row_width; i++, sp += 8)
+               {
+                  png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
+                      << 8) + (png_uint_16)(*(sp + 7)));
+
+                  if (a == 0)
+                  {
+                     *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff);
+                     *(sp + 2) = (png_byte)((png_ptr->background.green >> 8)
+                             & 0xff);
+                     *(sp + 3) = (png_byte)(png_ptr->background.green
+                             & 0xff);
+                     *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8)
+                             & 0xff);
+                     *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff);
+                  }
+
+                  else if (a < 0xffff)
+                  {
+                     png_uint_16 v;
+
+                     png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
+                     png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
+                         + *(sp + 3));
+                     png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
+                         + *(sp + 5));
+
+                     png_composite_16(v, r, a, png_ptr->background.red);
+                     *sp = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 1) = (png_byte)(v & 0xff);
+
+                     png_composite_16(v, g, a, png_ptr->background.green);
+                     *(sp + 2) = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 3) = (png_byte)(v & 0xff);
+
+                     png_composite_16(v, b, a, png_ptr->background.blue);
+                     *(sp + 4) = (png_byte)((v >> 8) & 0xff);
+                     *(sp + 5) = (png_byte)(v & 0xff);
+                  }
+               }
+            }
+         }
+         break;
       }
+
+      default:
+         break;
    }
 }
 #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
@@ -4245,8 +4245,8 @@
          {
             case 1:
             {
-               sp = row + (png_size_t)((row_width - 1) >> 3);
-               dp = row + (png_size_t)row_width - 1;
+               sp = row + (size_t)((row_width - 1) >> 3);
+               dp = row + (size_t)row_width - 1;
                shift = 7 - (int)((row_width + 7) & 0x07);
                for (i = 0; i < row_width; i++)
                {
@@ -4272,8 +4272,8 @@
 
             case 2:
             {
-               sp = row + (png_size_t)((row_width - 1) >> 2);
-               dp = row + (png_size_t)row_width - 1;
+               sp = row + (size_t)((row_width - 1) >> 2);
+               dp = row + (size_t)row_width - 1;
                shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
                for (i = 0; i < row_width; i++)
                {
@@ -4295,8 +4295,8 @@
 
             case 4:
             {
-               sp = row + (png_size_t)((row_width - 1) >> 1);
-               dp = row + (png_size_t)row_width - 1;
+               sp = row + (size_t)((row_width - 1) >> 1);
+               dp = row + (size_t)row_width - 1;
                shift = (int)((row_width & 0x01) << 2);
                for (i = 0; i < row_width; i++)
                {
@@ -4329,8 +4329,8 @@
          {
             if (num_trans > 0)
             {
-               sp = row + (png_size_t)row_width - 1;
-               dp = row + (png_size_t)(row_width << 2) - 1;
+               sp = row + (size_t)row_width - 1;
+               dp = row + ((size_t)row_width << 2) - 1;
 
                for (i = 0; i < row_width; i++)
                {
@@ -4354,8 +4354,8 @@
 
             else
             {
-               sp = row + (png_size_t)row_width - 1;
-               dp = row + (png_size_t)(row_width * 3) - 1;
+               sp = row + (size_t)row_width - 1;
+               dp = row + (size_t)(row_width * 3) - 1;
 
                for (i = 0; i < row_width; i++)
                {
@@ -4390,195 +4390,130 @@
 
    png_debug(1, "in png_do_expand");
 
+   if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
    {
-      if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
+      unsigned int gray = trans_color != NULL ? trans_color->gray : 0;
+
+      if (row_info->bit_depth < 8)
       {
-         unsigned int gray = trans_color != NULL ? trans_color->gray : 0;
-
-         if (row_info->bit_depth < 8)
+         switch (row_info->bit_depth)
          {
-            switch (row_info->bit_depth)
+            case 1:
             {
-               case 1:
-               {
-                  gray = (gray & 0x01) * 0xff;
-                  sp = row + (png_size_t)((row_width - 1) >> 3);
-                  dp = row + (png_size_t)row_width - 1;
-                  shift = 7 - (int)((row_width + 7) & 0x07);
-                  for (i = 0; i < row_width; i++)
-                  {
-                     if ((*sp >> shift) & 0x01)
-                        *dp = 0xff;
-
-                     else
-                        *dp = 0;
-
-                     if (shift == 7)
-                     {
-                        shift = 0;
-                        sp--;
-                     }
-
-                     else
-                        shift++;
-
-                     dp--;
-                  }
-                  break;
-               }
-
-               case 2:
-               {
-                  gray = (gray & 0x03) * 0x55;
-                  sp = row + (png_size_t)((row_width - 1) >> 2);
-                  dp = row + (png_size_t)row_width - 1;
-                  shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
-                  for (i = 0; i < row_width; i++)
-                  {
-                     value = (*sp >> shift) & 0x03;
-                     *dp = (png_byte)(value | (value << 2) | (value << 4) |
-                        (value << 6));
-                     if (shift == 6)
-                     {
-                        shift = 0;
-                        sp--;
-                     }
-
-                     else
-                        shift += 2;
-
-                     dp--;
-                  }
-                  break;
-               }
-
-               case 4:
-               {
-                  gray = (gray & 0x0f) * 0x11;
-                  sp = row + (png_size_t)((row_width - 1) >> 1);
-                  dp = row + (png_size_t)row_width - 1;
-                  shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
-                  for (i = 0; i < row_width; i++)
-                  {
-                     value = (*sp >> shift) & 0x0f;
-                     *dp = (png_byte)(value | (value << 4));
-                     if (shift == 4)
-                     {
-                        shift = 0;
-                        sp--;
-                     }
-
-                     else
-                        shift = 4;
-
-                     dp--;
-                  }
-                  break;
-               }
-
-               default:
-                  break;
-            }
-
-            row_info->bit_depth = 8;
-            row_info->pixel_depth = 8;
-            row_info->rowbytes = row_width;
-         }
-
-         if (trans_color != NULL)
-         {
-            if (row_info->bit_depth == 8)
-            {
-               gray = gray & 0xff;
-               sp = row + (png_size_t)row_width - 1;
-               dp = row + (png_size_t)(row_width << 1) - 1;
-
+               gray = (gray & 0x01) * 0xff;
+               sp = row + (size_t)((row_width - 1) >> 3);
+               dp = row + (size_t)row_width - 1;
+               shift = 7 - (int)((row_width + 7) & 0x07);
                for (i = 0; i < row_width; i++)
                {
-                  if ((*sp & 0xffU) == gray)
-                     *dp-- = 0;
+                  if ((*sp >> shift) & 0x01)
+                     *dp = 0xff;
 
                   else
-                     *dp-- = 0xff;
-
-                  *dp-- = *sp--;
-               }
-            }
-
-            else if (row_info->bit_depth == 16)
-            {
-               unsigned int gray_high = (gray >> 8) & 0xff;
-               unsigned int gray_low = gray & 0xff;
-               sp = row + row_info->rowbytes - 1;
-               dp = row + (row_info->rowbytes << 1) - 1;
-               for (i = 0; i < row_width; i++)
-               {
-                  if ((*(sp - 1) & 0xffU) == gray_high &&
-                      (*(sp) & 0xffU) == gray_low)
+                     *dp = 0;
+
+                  if (shift == 7)
                   {
-                     *dp-- = 0;
-                     *dp-- = 0;
+                     shift = 0;
+                     sp--;
                   }
 
                   else
+                     shift++;
+
+                  dp--;
+               }
+               break;
+            }
+
+            case 2:
+            {
+               gray = (gray & 0x03) * 0x55;
+               sp = row + (size_t)((row_width - 1) >> 2);
+               dp = row + (size_t)row_width - 1;
+               shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
+               for (i = 0; i < row_width; i++)
+               {
+                  value = (*sp >> shift) & 0x03;
+                  *dp = (png_byte)(value | (value << 2) | (value << 4) |
+                     (value << 6));
+                  if (shift == 6)
                   {
-                     *dp-- = 0xff;
-                     *dp-- = 0xff;
+                     shift = 0;
+                     sp--;
                   }
 
-                  *dp-- = *sp--;
-                  *dp-- = *sp--;
+                  else
+                     shift += 2;
+
+                  dp--;
                }
+               break;
             }
 
-            row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
-            row_info->channels = 2;
-            row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
-            row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
-                row_width);
+            case 4:
+            {
+               gray = (gray & 0x0f) * 0x11;
+               sp = row + (size_t)((row_width - 1) >> 1);
+               dp = row + (size_t)row_width - 1;
+               shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
+               for (i = 0; i < row_width; i++)
+               {
+                  value = (*sp >> shift) & 0x0f;
+                  *dp = (png_byte)(value | (value << 4));
+                  if (shift == 4)
+                  {
+                     shift = 0;
+                     sp--;
+                  }
+
+                  else
+                     shift = 4;
+
+                  dp--;
+               }
+               break;
+            }
+
+            default:
+               break;
          }
+
+         row_info->bit_depth = 8;
+         row_info->pixel_depth = 8;
+         row_info->rowbytes = row_width;
       }
-      else if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
-          trans_color != NULL)
+
+      if (trans_color != NULL)
       {
          if (row_info->bit_depth == 8)
          {
-            png_byte red = (png_byte)(trans_color->red & 0xff);
-            png_byte green = (png_byte)(trans_color->green & 0xff);
-            png_byte blue = (png_byte)(trans_color->blue & 0xff);
-            sp = row + (png_size_t)row_info->rowbytes - 1;
-            dp = row + (png_size_t)(row_width << 2) - 1;
+            gray = gray & 0xff;
+            sp = row + (size_t)row_width - 1;
+            dp = row + ((size_t)row_width << 1) - 1;
+
             for (i = 0; i < row_width; i++)
             {
-               if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
+               if ((*sp & 0xffU) == gray)
                   *dp-- = 0;
 
                else
                   *dp-- = 0xff;
 
                *dp-- = *sp--;
-               *dp-- = *sp--;
-               *dp-- = *sp--;
             }
          }
+
          else if (row_info->bit_depth == 16)
          {
-            png_byte red_high = (png_byte)((trans_color->red >> 8) & 0xff);
-            png_byte green_high = (png_byte)((trans_color->green >> 8) & 0xff);
-            png_byte blue_high = (png_byte)((trans_color->blue >> 8) & 0xff);
-            png_byte red_low = (png_byte)(trans_color->red & 0xff);
-            png_byte green_low = (png_byte)(trans_color->green & 0xff);
-            png_byte blue_low = (png_byte)(trans_color->blue & 0xff);
+            unsigned int gray_high = (gray >> 8) & 0xff;
+            unsigned int gray_low = gray & 0xff;
             sp = row + row_info->rowbytes - 1;
-            dp = row + (png_size_t)(row_width << 3) - 1;
+            dp = row + (row_info->rowbytes << 1) - 1;
             for (i = 0; i < row_width; i++)
             {
-               if (*(sp - 5) == red_high &&
-                   *(sp - 4) == red_low &&
-                   *(sp - 3) == green_high &&
-                   *(sp - 2) == green_low &&
-                   *(sp - 1) == blue_high &&
-                   *(sp    ) == blue_low)
+               if ((*(sp - 1) & 0xffU) == gray_high &&
+                   (*(sp) & 0xffU) == gray_low)
                {
                   *dp-- = 0;
                   *dp-- = 0;
@@ -4592,17 +4527,80 @@
 
                *dp-- = *sp--;
                *dp-- = *sp--;
-               *dp-- = *sp--;
-               *dp-- = *sp--;
-               *dp-- = *sp--;
-               *dp-- = *sp--;
             }
          }
-         row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
-         row_info->channels = 4;
-         row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
-         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
+
+         row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
+         row_info->channels = 2;
+         row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
+         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
+             row_width);
+      }
+   }
+   else if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
+       trans_color != NULL)
+   {
+      if (row_info->bit_depth == 8)
+      {
+         png_byte red = (png_byte)(trans_color->red & 0xff);
+         png_byte green = (png_byte)(trans_color->green & 0xff);
+         png_byte blue = (png_byte)(trans_color->blue & 0xff);
+         sp = row + (size_t)row_info->rowbytes - 1;
+         dp = row + ((size_t)row_width << 2) - 1;
+         for (i = 0; i < row_width; i++)
+         {
+            if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
+               *dp-- = 0;
+
+            else
+               *dp-- = 0xff;
+
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+         }
       }
+      else if (row_info->bit_depth == 16)
+      {
+         png_byte red_high = (png_byte)((trans_color->red >> 8) & 0xff);
+         png_byte green_high = (png_byte)((trans_color->green >> 8) & 0xff);
+         png_byte blue_high = (png_byte)((trans_color->blue >> 8) & 0xff);
+         png_byte red_low = (png_byte)(trans_color->red & 0xff);
+         png_byte green_low = (png_byte)(trans_color->green & 0xff);
+         png_byte blue_low = (png_byte)(trans_color->blue & 0xff);
+         sp = row + row_info->rowbytes - 1;
+         dp = row + ((size_t)row_width << 3) - 1;
+         for (i = 0; i < row_width; i++)
+         {
+            if (*(sp - 5) == red_high &&
+                *(sp - 4) == red_low &&
+                *(sp - 3) == green_high &&
+                *(sp - 2) == green_low &&
+                *(sp - 1) == blue_high &&
+                *(sp    ) == blue_low)
+            {
+               *dp-- = 0;
+               *dp-- = 0;
+            }
+
+            else
+            {
+               *dp-- = 0xff;
+               *dp-- = 0xff;
+            }
+
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+            *dp-- = *sp--;
+         }
+      }
+      row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
+      row_info->channels = 4;
+      row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
+      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
    }
 }
 #endif
@@ -4629,7 +4627,9 @@
       png_byte *sp = row + row_info->rowbytes; /* source, last byte + 1 */
       png_byte *dp = sp + row_info->rowbytes;  /* destination, end + 1 */
       while (dp > sp)
-         dp[-2] = dp[-1] = *--sp, dp -= 2;
+      {
+         dp[-2] = dp[-1] = *--sp; dp -= 2;
+      }
 
       row_info->rowbytes *= 2;
       row_info->bit_depth = 16;
@@ -4783,8 +4783,7 @@
                 &(png_ptr->trans_color));
 
          else
-            png_do_expand(row_info, png_ptr->row_buf + 1,
-                NULL);
+            png_do_expand(row_info, png_ptr->row_buf + 1, NULL);
       }
    }
 #endif
@@ -5008,7 +5007,7 @@
              (png_ptr,     /* png_ptr */
              row_info,     /* row_info: */
                 /*  png_uint_32 width;       width of row */
-                /*  png_size_t rowbytes;     number of bytes in row */
+                /*  size_t rowbytes;         number of bytes in row */
                 /*  png_byte color_type;     color type of pixels */
                 /*  png_byte bit_depth;      bit depth of samples */
                 /*  png_byte channels;       number of channels (1-4) */
--- a/src/share/native/sun/awt/libpng/pngrutil.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngrutil.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.27 [January 5, 2017]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -130,7 +130,7 @@
 png_uint_16 (PNGAPI
 png_get_uint_16)(png_const_bytep buf)
 {
-   /* ANSI-C requires an int value to accomodate at least 16 bits so this
+   /* ANSI-C requires an int value to accommodate at least 16 bits so this
     * works and allows the compiler not to worry about possible narrowing
     * on 32-bit systems.  (Pre-ANSI systems did not make integers smaller
     * than 16 bits either.)
@@ -148,7 +148,7 @@
 void /* PRIVATE */
 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
 {
-   png_size_t num_checked, num_to_check;
+   size_t num_checked, num_to_check;
 
    /* Exit if the user application does not expect a signature. */
    if (png_ptr->sig_bytes >= 8)
@@ -209,6 +209,9 @@
    /* Check to see if chunk name is valid. */
    png_check_chunk_name(png_ptr, png_ptr->chunk_name);
 
+   /* Check for too-large chunk length */
+   png_check_chunk_length(png_ptr, length);
+
 #ifdef PNG_IO_STATE_SUPPORTED
    png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
 #endif
@@ -339,6 +342,7 @@
 
       if (buffer != NULL)
       {
+         memset(buffer, 0, new_size); /* just in case */
          png_ptr->read_buffer = buffer;
          png_ptr->read_buffer_size = new_size;
       }
@@ -446,7 +450,7 @@
             png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
       }
 
-#if ZLIB_VERNUM >= 0x1281 && \
+#if ZLIB_VERNUM >= 0x1290 && \
    defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32)
       if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON)
          /* Turn off validation of the ADLER32 checksum in IDAT chunks */
@@ -698,6 +702,8 @@
 
                if (text != NULL)
                {
+                  memset(text, 0, buffer_size);
+
                   ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
                       png_ptr->read_buffer + prefix_size, &lzsize,
                       text + prefix_size, newlength);
@@ -761,9 +767,7 @@
             {
                /* inflateReset failed, store the error message */
                png_zstream_error(png_ptr, ret);
-
-               if (ret == Z_STREAM_END)
-                  ret = PNG_UNEXPECTED_ZLIB_RETURN;
+               ret = PNG_UNEXPECTED_ZLIB_RETURN;
             }
          }
 
@@ -1405,11 +1409,13 @@
     * chunk is just ignored, so does not invalidate the color space.  An
     * alternative is to set the 'invalid' flags at the start of this routine
     * and only clear them in they were not set before and all the tests pass.
-    * The minimum 'deflate' stream is assumed to be just the 2 byte header and
-    * 4 byte checksum.  The keyword must be at least one character and there is
-    * a terminator (0) byte and the compression method.
     */
-   if (length < 9)
+
+   /* The keyword must be at least one character and there is a
+    * terminator (0) byte and the compression method byte, and the
+    * 'zlib' datastream is at least 11 bytes.
+    */
+   if (length < 14)
    {
       png_crc_finish(png_ptr, length);
       png_chunk_benign_error(png_ptr, "too short");
@@ -1441,6 +1447,16 @@
       png_crc_read(png_ptr, (png_bytep)keyword, read_length);
       length -= read_length;
 
+      /* The minimum 'zlib' stream is assumed to be just the 2 byte header,
+       * 5 bytes minimum 'deflate' stream, and the 4 byte checksum.
+       */
+      if (length < 11)
+      {
+         png_crc_finish(png_ptr, length);
+         png_chunk_benign_error(png_ptr, "too short");
+         return;
+      }
+
       keyword_length = 0;
       while (keyword_length < 80 && keyword_length < read_length &&
          keyword[keyword_length] != 0)
@@ -1459,7 +1475,7 @@
 
             if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
             {
-               Byte profile_header[132];
+               Byte profile_header[132]={0};
                Byte local_buffer[PNG_INFLATE_BUF_SIZE];
                png_alloc_size_t size = (sizeof profile_header);
 
@@ -1489,7 +1505,7 @@
                         /* Now read the tag table; a variable size buffer is
                          * needed at this point, allocate one for the whole
                          * profile.  The header check has already validated
-                         * that none of these stuff will overflow.
+                         * that none of this stuff will overflow.
                          */
                         const png_uint_32 tag_count = png_get_uint_32(
                             profile_header+128);
@@ -1596,19 +1612,11 @@
                                        return;
                                     }
                                  }
-
-                                 else if (size > 0)
-                                    errmsg = "truncated";
-
-#ifndef __COVERITY__
-                                 else
+                                 if (errmsg == NULL)
                                     errmsg = png_ptr->zstream.msg;
-#endif
                               }
-
                               /* else png_icc_check_tag_table output an error */
                            }
-
                            else /* profile truncated */
                               errmsg = png_ptr->zstream.msg;
                         }
@@ -1668,7 +1676,7 @@
    int entry_size, i;
    png_uint_32 skip = 0;
    png_uint_32 dl;
-   png_size_t max_dl;
+   size_t max_dl;
 
    png_debug(1, "in png_handle_sPLT");
 
@@ -2017,6 +2025,15 @@
 
    else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
    {
+      if (png_ptr->bit_depth <= 8)
+      {
+         if (buf[0] != 0 || buf[1] >= (unsigned int)(1 << png_ptr->bit_depth))
+         {
+            png_chunk_benign_error(png_ptr, "invalid gray level");
+            return;
+         }
+      }
+
       background.index = 0;
       background.red =
       background.green =
@@ -2026,6 +2043,15 @@
 
    else
    {
+      if (png_ptr->bit_depth <= 8)
+      {
+         if (buf[0] != 0 || buf[2] != 0 || buf[4] != 0)
+         {
+            png_chunk_benign_error(png_ptr, "invalid color");
+            return;
+         }
+      }
+
       background.index = 0;
       background.red = png_get_uint_16(buf);
       background.green = png_get_uint_16(buf + 2);
@@ -2037,6 +2063,69 @@
 }
 #endif
 
+#ifdef PNG_READ_eXIf_SUPPORTED
+void /* PRIVATE */
+png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
+{
+   unsigned int i;
+
+   png_debug(1, "in png_handle_eXIf");
+
+   if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
+      png_chunk_error(png_ptr, "missing IHDR");
+
+   if (length < 2)
+   {
+      png_crc_finish(png_ptr, length);
+      png_chunk_benign_error(png_ptr, "too short");
+      return;
+   }
+
+   else if (info_ptr == NULL || (info_ptr->valid & PNG_INFO_eXIf) != 0)
+   {
+      png_crc_finish(png_ptr, length);
+      png_chunk_benign_error(png_ptr, "duplicate");
+      return;
+   }
+
+   info_ptr->free_me |= PNG_FREE_EXIF;
+
+   info_ptr->eXIf_buf = png_voidcast(png_bytep,
+             png_malloc_warn(png_ptr, length));
+
+   if (info_ptr->eXIf_buf == NULL)
+   {
+      png_crc_finish(png_ptr, length);
+      png_chunk_benign_error(png_ptr, "out of memory");
+      return;
+   }
+
+   for (i = 0; i < length; i++)
+   {
+      png_byte buf[1];
+      png_crc_read(png_ptr, buf, 1);
+      info_ptr->eXIf_buf[i] = buf[0];
+      if (i == 1 && buf[0] != 'M' && buf[0] != 'I'
+                 && info_ptr->eXIf_buf[0] != buf[0])
+      {
+         png_crc_finish(png_ptr, length);
+         png_chunk_benign_error(png_ptr, "incorrect byte-order specifier");
+         png_free(png_ptr, info_ptr->eXIf_buf);
+         info_ptr->eXIf_buf = NULL;
+         return;
+      }
+   }
+
+   if (png_crc_finish(png_ptr, 0) != 0)
+      return;
+
+   png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf);
+
+   png_free(png_ptr, info_ptr->eXIf_buf);
+   info_ptr->eXIf_buf = NULL;
+}
+#endif
+
 #ifdef PNG_READ_hIST_SUPPORTED
 void /* PRIVATE */
 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
@@ -2316,7 +2405,7 @@
 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
 {
    png_bytep buffer;
-   png_size_t i;
+   size_t i;
    int state;
 
    png_debug(1, "in png_handle_sCAL");
@@ -2386,7 +2475,7 @@
 
    else
    {
-      png_size_t heighti = i;
+      size_t heighti = i;
 
       state = 0;
       if (png_check_fp_number((png_const_charp)buffer, length,
@@ -2565,6 +2654,9 @@
    if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
       png_ptr->mode |= PNG_AFTER_IDAT;
 
+   /* Note, "length" is sufficient here; we won't be adding
+    * a null terminator later.
+    */
    buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
 
    if (buffer == NULL)
@@ -2611,23 +2703,28 @@
       {
          png_text text;
 
-         /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
-          * for the extra compression type byte and the fact that it isn't
-          * necessarily '\0' terminated.
-          */
-         buffer = png_ptr->read_buffer;
-         buffer[uncompressed_length+(keyword_length+2)] = 0;
-
-         text.compression = PNG_TEXT_COMPRESSION_zTXt;
-         text.key = (png_charp)buffer;
-         text.text = (png_charp)(buffer + keyword_length+2);
-         text.text_length = uncompressed_length;
-         text.itxt_length = 0;
-         text.lang = NULL;
-         text.lang_key = NULL;
-
-         if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
-            errmsg = "insufficient memory";
+         if (png_ptr->read_buffer == NULL)
+           errmsg="Read failure in png_handle_zTXt";
+         else
+         {
+            /* It worked; png_ptr->read_buffer now looks like a tEXt chunk
+             * except for the extra compression type byte and the fact that
+             * it isn't necessarily '\0' terminated.
+             */
+            buffer = png_ptr->read_buffer;
+            buffer[uncompressed_length+(keyword_length+2)] = 0;
+
+            text.compression = PNG_TEXT_COMPRESSION_zTXt;
+            text.key = (png_charp)buffer;
+            text.text = (png_charp)(buffer + keyword_length+2);
+            text.text_length = uncompressed_length;
+            text.itxt_length = 0;
+            text.lang = NULL;
+            text.lang_key = NULL;
+
+            if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
+               errmsg = "insufficient memory";
+         }
       }
 
       else
@@ -2816,7 +2913,7 @@
    {
       PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
       /* The following is safe because of the PNG_SIZE_MAX init above */
-      png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
+      png_ptr->unknown_chunk.size = (size_t)length/*SAFE*/;
       /* 'mode' is a flag array, only the bottom four bits matter here */
       png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
 
@@ -3003,7 +3100,7 @@
          case 2:
             png_ptr->user_chunk_cache_max = 1;
             png_chunk_benign_error(png_ptr, "no space in chunk cache");
-            /* FALL THROUGH */
+            /* FALLTHROUGH */
          case 1:
             /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
              * chunk being skipped, now there will be a hard error below.
@@ -3012,7 +3109,7 @@
 
          default: /* not at limit */
             --(png_ptr->user_chunk_cache_max);
-            /* FALL THROUGH */
+            /* FALLTHROUGH */
          case 0: /* no limit */
 #  endif /* USER_LIMITS */
             /* Here when the limit isn't reached or when limits are compiled
@@ -3063,20 +3160,61 @@
  */
 
 void /* PRIVATE */
-png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
+png_check_chunk_name(png_const_structrp png_ptr, const png_uint_32 chunk_name)
 {
    int i;
+   png_uint_32 cn=chunk_name;
 
    png_debug(1, "in png_check_chunk_name");
 
    for (i=1; i<=4; ++i)
    {
-      int c = chunk_name & 0xff;
+      int c = cn & 0xff;
 
       if (c < 65 || c > 122 || (c > 90 && c < 97))
          png_chunk_error(png_ptr, "invalid chunk type");
 
-      chunk_name >>= 8;
+      cn >>= 8;
+   }
+}
+
+void /* PRIVATE */
+png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length)
+{
+   png_alloc_size_t limit = PNG_UINT_31_MAX;
+
+# ifdef PNG_SET_USER_LIMITS_SUPPORTED
+   if (png_ptr->user_chunk_malloc_max > 0 &&
+       png_ptr->user_chunk_malloc_max < limit)
+      limit = png_ptr->user_chunk_malloc_max;
+# elif PNG_USER_CHUNK_MALLOC_MAX > 0
+   if (PNG_USER_CHUNK_MALLOC_MAX < limit)
+      limit = PNG_USER_CHUNK_MALLOC_MAX;
+# endif
+   if (png_ptr->chunk_name == png_IDAT)
+   {
+      png_alloc_size_t idat_limit = PNG_UINT_31_MAX;
+      size_t row_factor =
+         (size_t)png_ptr->width
+         * (size_t)png_ptr->channels
+         * (png_ptr->bit_depth > 8? 2: 1)
+         + 1
+         + (png_ptr->interlaced? 6: 0);
+      if (png_ptr->height > PNG_UINT_32_MAX/row_factor)
+         idat_limit = PNG_UINT_31_MAX;
+      else
+         idat_limit = png_ptr->height * row_factor;
+      row_factor = row_factor > 32566? 32566 : row_factor;
+      idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */
+      idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;
+      limit = limit < idat_limit? idat_limit : limit;
+   }
+
+   if (length > limit)
+   {
+      png_debug2(0," length = %lu, limit = %lu",
+         (unsigned long)length,(unsigned long)limit);
+      png_chunk_error(png_ptr, "chunk data is too large");
    }
 }
 
@@ -3405,7 +3543,7 @@
                 */
                do
                {
-                  dp[0] = sp[0], dp[1] = sp[1];
+                  dp[0] = sp[0]; dp[1] = sp[1];
 
                   if (row_width <= bytes_to_jump)
                      return;
@@ -3426,7 +3564,7 @@
                 */
                for (;;)
                {
-                  dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
+                  dp[0] = sp[0]; dp[1] = sp[1]; dp[2] = sp[2];
 
                   if (row_width <= bytes_to_jump)
                      return;
@@ -3590,8 +3728,8 @@
       {
          case 1:
          {
-            png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
-            png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
+            png_bytep sp = row + (size_t)((row_info->width - 1) >> 3);
+            png_bytep dp = row + (size_t)((final_width - 1) >> 3);
             unsigned int sshift, dshift;
             unsigned int s_start, s_end;
             int s_inc;
@@ -3717,8 +3855,8 @@
 
          case 4:
          {
-            png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
-            png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
+            png_bytep sp = row + (size_t)((row_info->width - 1) >> 1);
+            png_bytep dp = row + (size_t)((final_width - 1) >> 1);
             unsigned int sshift, dshift;
             unsigned int s_start, s_end;
             int s_inc;
@@ -3780,12 +3918,12 @@
 
          default:
          {
-            png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
-
-            png_bytep sp = row + (png_size_t)(row_info->width - 1)
+            size_t pixel_bytes = (row_info->pixel_depth >> 3);
+
+            png_bytep sp = row + (size_t)(row_info->width - 1)
                 * pixel_bytes;
 
-            png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
+            png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes;
 
             int jstop = (int)png_pass_inc[pass];
             png_uint_32 i;
@@ -3822,8 +3960,8 @@
 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
     png_const_bytep prev_row)
 {
-   png_size_t i;
-   png_size_t istop = row_info->rowbytes;
+   size_t i;
+   size_t istop = row_info->rowbytes;
    unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
    png_bytep rp = row + bpp;
 
@@ -3840,8 +3978,8 @@
 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
     png_const_bytep prev_row)
 {
-   png_size_t i;
-   png_size_t istop = row_info->rowbytes;
+   size_t i;
+   size_t istop = row_info->rowbytes;
    png_bytep rp = row;
    png_const_bytep pp = prev_row;
 
@@ -3856,11 +3994,11 @@
 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
     png_const_bytep prev_row)
 {
-   png_size_t i;
+   size_t i;
    png_bytep rp = row;
    png_const_bytep pp = prev_row;
    unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
-   png_size_t istop = row_info->rowbytes - bpp;
+   size_t istop = row_info->rowbytes - bpp;
 
    for (i = 0; i < bpp; i++)
    {
@@ -3915,7 +4053,10 @@
       /* Find the best predictor, the least of pa, pb, pc favoring the earlier
        * ones in the case of a tie.
        */
-      if (pb < pa) pa = pb, a = b;
+      if (pb < pa)
+      {
+         pa = pb; a = b;
+      }
       if (pc < pa) a = c;
 
       /* Calculate the current pixel in a, and move the previous row pixel to c
@@ -3967,7 +4108,10 @@
       pc = (p + pc) < 0 ? -(p + pc) : p + pc;
 #endif
 
-      if (pb < pa) pa = pb, a = b;
+      if (pb < pa)
+      {
+         pa = pb; a = b;
+      }
       if (pc < pa) a = c;
 
       a += *row;
@@ -4290,7 +4434,7 @@
    static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
 
    unsigned int max_pixel_depth;
-   png_size_t row_bytes;
+   size_t row_bytes;
 
    png_debug(1, "in png_read_start_row");
 
--- a/src/share/native/sun/awt/libpng/pngset.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngset.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.26 [October 20, 2016]
- * Copyright (c) 1998-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -162,6 +162,53 @@
 
 #endif /* cHRM */
 
+#ifdef PNG_eXIf_SUPPORTED
+void PNGAPI
+png_set_eXIf(png_const_structrp png_ptr, png_inforp info_ptr,
+    const png_bytep eXIf_buf)
+{
+  png_warning(png_ptr, "png_set_eXIf does not work; use png_set_eXIf_1");
+  PNG_UNUSED(info_ptr)
+  PNG_UNUSED(eXIf_buf)
+}
+
+void PNGAPI
+png_set_eXIf_1(png_const_structrp png_ptr, png_inforp info_ptr,
+    const png_uint_32 num_exif, const png_bytep eXIf_buf)
+{
+   int i;
+
+   png_debug1(1, "in %s storage function", "eXIf");
+
+   if (png_ptr == NULL || info_ptr == NULL)
+      return;
+
+   if (info_ptr->exif)
+   {
+      png_free(png_ptr, info_ptr->exif);
+      info_ptr->exif = NULL;
+   }
+
+   info_ptr->num_exif = num_exif;
+
+   info_ptr->exif = png_voidcast(png_bytep, png_malloc_warn(png_ptr,
+       info_ptr->num_exif));
+
+   if (info_ptr->exif == NULL)
+   {
+      png_warning(png_ptr, "Insufficient memory for eXIf chunk data");
+      return;
+   }
+
+   info_ptr->free_me |= PNG_FREE_EXIF;
+
+   for (i = 0; i < (int) info_ptr->num_exif; i++)
+      info_ptr->exif[i] = eXIf_buf[i];
+
+   info_ptr->valid |= PNG_INFO_eXIf;
+}
+#endif /* eXIf */
+
 #ifdef PNG_gAMA_SUPPORTED
 void PNGFAPI
 png_set_gAMA_fixed(png_const_structrp png_ptr, png_inforp info_ptr,
@@ -294,7 +341,7 @@
     png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type,
     int nparams, png_const_charp units, png_charpp params)
 {
-   png_size_t length;
+   size_t length;
    int i;
 
    png_debug1(1, "in %s storage function", "pCAL");
@@ -371,7 +418,7 @@
    memcpy(info_ptr->pcal_units, units, length);
 
    info_ptr->pcal_params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
-       (png_size_t)(((unsigned int)nparams + 1) * (sizeof (png_charp)))));
+       (size_t)(((unsigned int)nparams + 1) * (sizeof (png_charp)))));
 
    if (info_ptr->pcal_params == NULL)
    {
@@ -411,7 +458,7 @@
 png_set_sCAL_s(png_const_structrp png_ptr, png_inforp info_ptr,
     int unit, png_const_charp swidth, png_const_charp sheight)
 {
-   png_size_t lengthw = 0, lengthh = 0;
+   size_t lengthw = 0, lengthh = 0;
 
    png_debug1(1, "in %s storage function", "sCAL");
 
@@ -672,7 +719,7 @@
 {
    png_charp new_iccp_name;
    png_bytep new_iccp_profile;
-   png_size_t length;
+   size_t length;
 
    png_debug1(1, "in %s storage function", "iCCP");
 
@@ -999,7 +1046,7 @@
          /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
           info_ptr->trans_alpha = png_voidcast(png_bytep,
               png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH));
-          memcpy(info_ptr->trans_alpha, trans_alpha, (png_size_t)num_trans);
+          memcpy(info_ptr->trans_alpha, trans_alpha, (size_t)num_trans);
        }
        png_ptr->trans_alpha = info_ptr->trans_alpha;
    }
@@ -1079,7 +1126,7 @@
 
    do
    {
-      png_size_t length;
+      size_t length;
 
       /* Skip invalid input entries */
       if (entries->name == NULL || entries->entries == NULL)
@@ -1130,8 +1177,9 @@
       info_ptr->valid |= PNG_INFO_sPLT;
       ++(info_ptr->splt_palettes_num);
       ++np;
+      ++entries;
    }
-   while (++entries, --nentries);
+   while (--nentries);
 
    if (nentries > 0)
       png_chunk_report(png_ptr, "sPLT out of memory", PNG_CHUNK_WRITE_ERROR);
@@ -1382,6 +1430,7 @@
       static PNG_CONST png_byte chunks_to_ignore[] = {
          98,  75,  71,  68, '\0',  /* bKGD */
          99,  72,  82,  77, '\0',  /* cHRM */
+        101,  88,  73, 102, '\0',  /* eXIf */
         103,  65,  77,  65, '\0',  /* gAMA */
         104,  73,  83,  84, '\0',  /* hIST */
         105,  67,  67,  80, '\0',  /* iCCP */
@@ -1542,7 +1591,7 @@
 #endif
 
 void PNGAPI
-png_set_compression_buffer_size(png_structrp png_ptr, png_size_t size)
+png_set_compression_buffer_size(png_structrp png_ptr, size_t size)
 {
    if (png_ptr == NULL)
       return;
@@ -1724,14 +1773,16 @@
       png_byte ch = (png_byte)*key++;
 
       if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))
-         *new_key++ = ch, ++key_len, space = 0;
+      {
+         *new_key++ = ch; ++key_len; space = 0;
+      }
 
       else if (space == 0)
       {
          /* A space or an invalid character when one wasn't seen immediately
           * before; output just a space.
           */
-         *new_key++ = 32, ++key_len, space = 1;
+         *new_key++ = 32; ++key_len; space = 1;
 
          /* If the character was not a space then it is invalid. */
          if (ch != 32)
@@ -1744,7 +1795,7 @@
 
    if (key_len > 0 && space != 0) /* trailing space */
    {
-      --key_len, --new_key;
+      --key_len; --new_key;
       if (bad_character == 0)
          bad_character = 32;
    }
--- a/src/share/native/sun/awt/libpng/pngstruct.h	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngstruct.h	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.28 [January 5, 2017]
- * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -75,7 +75,7 @@
 /* zlib.h declares a magic type 'uInt' that limits the amount of data that zlib
  * can handle at once.  This type need be no larger than 16 bits (so maximum of
  * 65535), this define allows us to discover how big it is, but limited by the
- * maximuum for png_size_t.  The value can be overriden in a library build
+ * maximum for size_t.  The value can be overridden in a library build
  * (pngusr.h, or set it in CPPFLAGS) and it works to set it to a considerably
  * lower value (e.g. 255 works).  A lower value may help memory usage (slightly)
  * and may even improve performance on some systems (and degrade it on others.)
@@ -242,7 +242,7 @@
    png_uint_32 height;        /* height of image in pixels */
    png_uint_32 num_rows;      /* number of rows in current pass */
    png_uint_32 usr_width;     /* width of row at start of write */
-   png_size_t rowbytes;       /* size of row in bytes */
+   size_t rowbytes;           /* size of row in bytes */
    png_uint_32 iwidth;        /* width of current interlaced row in pixels */
    png_uint_32 row_number;    /* current row in interlace pass */
    png_uint_32 chunk_name;    /* PNG_CHUNK() id of current chunk */
@@ -260,7 +260,7 @@
    png_bytep try_row;    /* buffer to save trial row when filtering */
    png_bytep tst_row;    /* buffer to save best trial row when filtering */
 #endif
-   png_size_t info_rowbytes;  /* Added in 1.5.4: cache of updated row bytes */
+   size_t info_rowbytes;      /* Added in 1.5.4: cache of updated row bytes */
 
    png_uint_32 idat_size;     /* current IDAT size for read */
    png_uint_32 crc;           /* current chunk CRC value */
@@ -335,7 +335,7 @@
 #endif
 
 #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
-   png_color_8 shift;         /* shift for significant bit tranformation */
+   png_color_8 shift;         /* shift for significant bit transformation */
 #endif
 
 #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
@@ -356,10 +356,10 @@
    png_bytep current_buffer;         /* buffer for recently used data */
    png_uint_32 push_length;          /* size of current input chunk */
    png_uint_32 skip_length;          /* bytes to skip in input data */
-   png_size_t save_buffer_size;      /* amount of data now in save_buffer */
-   png_size_t save_buffer_max;       /* total size of save_buffer */
-   png_size_t buffer_size;           /* total amount of available input data */
-   png_size_t current_buffer_size;   /* amount of data now in current_buffer */
+   size_t save_buffer_size;          /* amount of data now in save_buffer */
+   size_t save_buffer_max;           /* total size of save_buffer */
+   size_t buffer_size;               /* total amount of available input data */
+   size_t current_buffer_size;       /* amount of data now in current_buffer */
    int process_mode;                 /* what push library is currently doing */
    int cur_palette;                  /* current push library palette index */
 
@@ -479,7 +479,7 @@
 #endif
 
 /* New member added in libpng-1.2.26 */
-  png_size_t old_big_row_buf_size;
+   size_t old_big_row_buf_size;
 
 #ifdef PNG_READ_SUPPORTED
 /* New member added in libpng-1.2.30 */
--- a/src/share/native/sun/awt/libpng/pngtrans.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/share/native/sun/awt/libpng/pngtrans.c	Mon Oct 15 15:05:59 2018 +0100
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.26 [October 20, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.35 [July 15, 2018]
+ * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -297,8 +297,8 @@
    if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
    {
       png_bytep rp = row;
-      png_size_t i;
-      png_size_t istop = row_info->rowbytes;
+      size_t i;
+      size_t istop = row_info->rowbytes;
 
       for (i = 0; i < istop; i++)
       {
@@ -311,8 +311,8 @@
       row_info->bit_depth == 8)
    {
       png_bytep rp = row;
-      png_size_t i;
-      png_size_t istop = row_info->rowbytes;
+      size_t i;
+      size_t istop = row_info->rowbytes;
 
       for (i = 0; i < istop; i += 2)
       {
@@ -326,8 +326,8 @@
       row_info->bit_depth == 16)
    {
       png_bytep rp = row;
-      png_size_t i;
-      png_size_t istop = row_info->rowbytes;
+      size_t i;
+      size_t istop = row_info->rowbytes;
 
       for (i = 0; i < istop; i += 4)
       {
@@ -542,11 +542,15 @@
          if (at_start != 0) /* Skip initial filler */
             ++sp;
          else          /* Skip initial channel and, for sp, the filler */
-            sp += 2, ++dp;
+         {
+            sp += 2; ++dp;
+         }
 
          /* For a 1 pixel wide image there is nothing to do */
          while (sp < ep)
-            *dp++ = *sp, sp += 2;
+         {
+            *dp++ = *sp; sp += 2;
+         }
 
          row_info->pixel_depth = 8;
       }
@@ -556,10 +560,14 @@
          if (at_start != 0) /* Skip initial filler */
             sp += 2;
          else          /* Skip initial channel and, for sp, the filler */
-            sp += 4, dp += 2;
+         {
+            sp += 4; dp += 2;
+         }
 
          while (sp < ep)
-            *dp++ = *sp++, *dp++ = *sp, sp += 3;
+         {
+            *dp++ = *sp++; *dp++ = *sp; sp += 3;
+         }
 
          row_info->pixel_depth = 16;
       }
@@ -582,11 +590,15 @@
          if (at_start != 0) /* Skip initial filler */
             ++sp;
          else          /* Skip initial channels and, for sp, the filler */
-            sp += 4, dp += 3;
+         {
+            sp += 4; dp += 3;
+         }
 
          /* Note that the loop adds 3 to dp and 4 to sp each time. */
          while (sp < ep)
-            *dp++ = *sp++, *dp++ = *sp++, *dp++ = *sp, sp += 2;
+         {
+            *dp++ = *sp++; *dp++ = *sp++; *dp++ = *sp; sp += 2;
+         }
 
          row_info->pixel_depth = 24;
       }
@@ -596,14 +608,16 @@
          if (at_start != 0) /* Skip initial filler */
             sp += 2;
          else          /* Skip initial channels and, for sp, the filler */
-            sp += 8, dp += 6;
+         {
+            sp += 8; dp += 6;
+         }
 
          while (sp < ep)
          {
             /* Copy 6 bytes, skip 2 */
-            *dp++ = *sp++, *dp++ = *sp++;
-            *dp++ = *sp++, *dp++ = *sp++;
-            *dp++ = *sp++, *dp++ = *sp, sp += 3;
+            *dp++ = *sp++; *dp++ = *sp++;
+            *dp++ = *sp++; *dp++ = *sp++;
+            *dp++ = *sp++; *dp++ = *sp; sp += 3;
          }
 
          row_info->pixel_depth = 48;
@@ -623,7 +637,7 @@
       return; /* The filler channel has gone already */
 
    /* Fix the rowbytes value. */
-   row_info->rowbytes = (unsigned int)(dp-row);
+   row_info->rowbytes = (size_t)(dp-row);
 }
 #endif
 
@@ -722,7 +736,7 @@
        * forms produced on either GCC or MSVC.
        */
       int padding = PNG_PADBITS(row_info->pixel_depth, row_info->width);
-      png_bytep rp = png_ptr->row_buf + row_info->rowbytes;
+      png_bytep rp = png_ptr->row_buf + row_info->rowbytes - 1;
 
       switch (row_info->bit_depth)
       {
--- a/src/solaris/native/java/net/NetworkInterface.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/solaris/native/java/net/NetworkInterface.c	Mon Oct 15 15:05:59 2018 +0100
@@ -335,10 +335,18 @@
     jobject obj = NULL;
     jboolean match = JNI_FALSE;
 #if defined(AF_INET6)
-    int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
+    int family = getInetAddress_family(env, iaObj);
     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+
+    if (family == IPv4) {
+        family = AF_INET;
+    } else if (family == IPv6) {
+        family = AF_INET6;
+    } else {
+        return NULL; // Invalid family
+    }
 #else
-    int family =  AF_INET;
+    int family = AF_INET;
 #endif
     ifs = enumInterfaces(env);
     if (ifs == NULL) {
@@ -357,7 +365,9 @@
                     int address1 = htonl(
                         ((struct sockaddr_in *)addrP->addr)->sin_addr.s_addr);
                     int address2 = getInetAddress_addr(env, iaObj);
-                    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+                    if ((*env)->ExceptionCheck(env)) {
+                        goto cleanup;
+                    }
                     if (address1 == address2) {
                         match = JNI_TRUE;
                         break;
@@ -402,6 +412,7 @@
         obj = createNetworkInterface(env, curr);
     }
 
+cleanup:
     // release the interface list
     freeif(ifs);
 
--- a/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, 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
@@ -677,7 +677,7 @@
         }
 
         try {
-            return invoke(new Callable<File[]>() {
+                File[] files = invoke(new Callable<File[]>() {
                 public File[] call() throws InterruptedException {
                     if (!isDirectory()) {
                         return null;
@@ -732,6 +732,9 @@
                         : list.toArray(new ShellFolder[list.size()]);
                 }
             }, InterruptedException.class);
+
+            return Win32ShellFolderManager2.checkFiles(files);
+
         } catch (InterruptedException e) {
             return new File[0];
         }
--- a/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, 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
@@ -379,21 +379,30 @@
         return null;
     }
 
-    private File checkFile(File file) {
+    private static File checkFile(File file) {
         SecurityManager sm = System.getSecurityManager();
         return (sm == null || file == null) ? file : checkFile(file, sm);
     }
 
-    private File checkFile(File file, SecurityManager sm) {
+    private static File checkFile(File file, SecurityManager sm) {
         try {
             sm.checkRead(file.getPath());
+
+            if (file instanceof Win32ShellFolder2) {
+                Win32ShellFolder2 f = (Win32ShellFolder2)file;
+                if (f.isLink()) {
+                    Win32ShellFolder2 link = (Win32ShellFolder2)f.getLinkLocation();
+                    if (link != null)
+                        sm.checkRead(link.getPath());
+                }
+            }
             return file;
         } catch (SecurityException se) {
             return null;
         }
     }
 
-    private File[] checkFiles(File[] files) {
+    static File[] checkFiles(File[] files) {
         SecurityManager sm = System.getSecurityManager();
         if (sm == null || files == null || files.length == 0) {
             return files;
@@ -401,7 +410,7 @@
         return checkFiles(Arrays.stream(files), sm);
     }
 
-    private File[] checkFiles(List<File> files) {
+    private static File[] checkFiles(List<File> files) {
         SecurityManager sm = System.getSecurityManager();
         if (sm == null || files.isEmpty()) {
             return files.toArray(new File[files.size()]);
@@ -409,7 +418,7 @@
         return checkFiles(files.stream(), sm);
     }
 
-    private File[] checkFiles(Stream<File> filesStream, SecurityManager sm) {
+    private static File[] checkFiles(Stream<File> filesStream, SecurityManager sm) {
         return filesStream.filter((file) -> checkFile(file, sm) != null)
                 .toArray(File[]::new);
     }
--- a/src/windows/native/java/net/NetworkInterface.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/windows/native/java/net/NetworkInterface.c	Mon Oct 15 15:05:59 2018 +0100
@@ -287,6 +287,7 @@
             if (curr->name == NULL || curr->displayName == NULL) {
                 if (curr->name) free(curr->name);
                 if (curr->displayName) free(curr->displayName);
+                free(curr);
                 curr = NULL;
             }
         }
@@ -593,7 +594,10 @@
             /* default ctor will set family to AF_INET */
 
             setInetAddress_addr(env, iaObj, ntohl(addrs->addr.him4.sin_addr.s_addr));
-            JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+            if ((*env)->ExceptionCheck(env)) {
+                free_netaddr(netaddrP);
+                return NULL;
+            }
             if (addrs->mask != -1) {
               ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
               if (ibObj == NULL) {
@@ -607,7 +611,10 @@
                 return NULL;
               }
               setInetAddress_addr(env, ia2Obj, ntohl(addrs->brdcast.him4.sin_addr.s_addr));
-              JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+              if ((*env)->ExceptionCheck(env)) {
+                  free_netaddr(netaddrP);
+                  return NULL;
+              }
               (*env)->SetObjectField(env, ibObj, ni_ibbroadcastID, ia2Obj);
               (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
               (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
@@ -618,6 +625,7 @@
             if (iaObj) {
                 int ret = setInet6Address_ipaddress(env, iaObj,  (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
                 if (ret == JNI_FALSE) {
+                    free_netaddr(netaddrP);
                     return NULL;
                 }
 
--- a/src/windows/native/java/net/NetworkInterface_winXP.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/windows/native/java/net/NetworkInterface_winXP.c	Mon Oct 15 15:05:59 2018 +0100
@@ -488,8 +488,9 @@
     jobjectArray addrArr, bindsArr, childArr;
     netaddr *addrs;
     jint addr_index;
-    int netaddrCount=ifs->naddrs;
-    netaddr *netaddrP=ifs->addrs;
+    int netaddrCount = ifs->naddrs;
+    netaddr *netaddrP = ifs->addrs;
+    netaddr *netaddrPToFree = NULL;
     jint bind_index;
 
     /*
@@ -520,21 +521,23 @@
      * Note that 0 is a valid number of addresses.
      */
     if (netaddrCount < 0) {
-        netaddrCount = enumAddresses_win(env, ifs, &netaddrP);
+        netaddrCount = enumAddresses_win(env, ifs, &netaddrPToFree);
         if (netaddrCount == -1) {
             return NULL;
         }
+        netaddrP = netaddrPToFree;
     }
 
     addrArr = (*env)->NewObjectArray(env, netaddrCount, ia_class, NULL);
     if (addrArr == NULL) {
+        free_netaddr(netaddrPToFree);
         return NULL;
     }
 
     bindsArr = (*env)->NewObjectArray(env, netaddrCount, ni_ibcls, NULL);
     if (bindsArr == NULL) {
-      free_netaddr(netaddrP);
-      return NULL;
+        free_netaddr(netaddrPToFree);
+        return NULL;
     }
 
     addrs = netaddrP;
@@ -546,26 +549,32 @@
         if (addrs->addr.him.sa_family == AF_INET) {
             iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (iaObj == NULL) {
+                free_netaddr(netaddrPToFree);
                 return NULL;
             }
             /* default ctor will set family to AF_INET */
 
             setInetAddress_addr(env, iaObj, ntohl(addrs->addr.him4.sin_addr.s_addr));
-
-            JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+            if ((*env)->ExceptionCheck(env)) {
+                free_netaddr(netaddrPToFree);
+                return NULL;
+            }
             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
             if (ibObj == NULL) {
-              free_netaddr(netaddrP);
-              return NULL;
+                free_netaddr(netaddrPToFree);
+                return NULL;
             }
             (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
             ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (ia2Obj == NULL) {
-              free_netaddr(netaddrP);
-              return NULL;
+                free_netaddr(netaddrPToFree);
+                return NULL;
             }
             setInetAddress_addr(env, ia2Obj, ntohl(addrs->brdcast.him4.sin_addr.s_addr));
-            JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+            if ((*env)->ExceptionCheck(env)) {
+                free_netaddr(netaddrPToFree);
+                return NULL;
+            }
             (*env)->SetObjectField(env, ibObj, ni_ibbroadcastID, ia2Obj);
             (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
             (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
@@ -574,10 +583,12 @@
             int ret;
             iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
             if (iaObj == NULL) {
+                free_netaddr(netaddrPToFree);
                 return NULL;
             }
             ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
             if (ret == JNI_FALSE) {
+                free_netaddr(netaddrPToFree);
                 return NULL;
             }
             scope = addrs->addr.him6.sin6_scope_id;
@@ -587,8 +598,8 @@
             }
             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
             if (ibObj == NULL) {
-              free_netaddr(netaddrP);
-              return NULL;
+                free_netaddr(netaddrPToFree);
+                return NULL;
             }
             (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
             (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
@@ -601,6 +612,8 @@
     (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
     (*env)->SetObjectField(env, netifObj, ni_bindsID, bindsArr);
 
+    free_netaddr(netaddrPToFree);
+
     /*
      * Windows doesn't have virtual interfaces, so child array
      * is always empty.
@@ -640,7 +653,7 @@
     }
 
     /* if found create a NetworkInterface */
-    if (curr != NULL) {;
+    if (curr != NULL) {
         netifObj = createNetworkInterfaceXP(env, curr);
     }
 
@@ -767,6 +780,7 @@
     /* allocate a NetworkInterface array */
     netIFArr = (*env)->NewObjectArray(env, count, cls, NULL);
     if (netIFArr == NULL) {
+        free_netif(ifList);
         return NULL;
     }
 
@@ -781,6 +795,7 @@
 
         netifObj = createNetworkInterfaceXP(env, curr);
         if (netifObj == NULL) {
+            free_netif(ifList);
             return NULL;
         }
 
--- a/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c	Mon Oct 15 15:05:59 2018 +0100
@@ -445,7 +445,6 @@
                         "Protocol family not supported");
         return;
     }
-    JNU_CHECK_EXCEPTION(env);
     if (IS_NULL(fdObj) || (ipv6_supported && IS_NULL(fd1Obj))) {
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "socket closed");
         return;
--- a/src/windows/native/sun/security/mscapi/security.cpp	Sun Oct 14 19:45:50 2018 -0400
+++ b/src/windows/native/sun/security/mscapi/security.cpp	Mon Oct 15 15:05:59 2018 +0100
@@ -183,7 +183,6 @@
 {
 
     HCRYPTPROV hCryptProv = NULL;
-    BYTE*      pbData = NULL;
     jbyte*     reseedBytes = NULL;
     jbyte*     seedBytes = NULL;
     jbyteArray result = NULL;
@@ -227,28 +226,17 @@
 
             result = NULL;
 
-        } else if (length > 0) {
+        } else {
 
-            pbData = new (env) BYTE[length];
-            if (pbData == NULL) {
-                __leave;
+            if (length > 0) {
+                seed = env->NewByteArray(length);
+                if (seed == NULL) {
+                    __leave;
+                }
+            } else {
+                length = env->GetArrayLength(seed);
             }
 
-            if (::CryptGenRandom(
-                hCryptProv,
-                length,
-                pbData) == FALSE) {
-
-                ThrowException(env, PROVIDER_EXCEPTION, GetLastError());
-                __leave;
-            }
-
-            result = env->NewByteArray(length);
-            env->SetByteArrayRegion(result, 0, length, (jbyte*) pbData);
-
-        } else { // length == 0
-
-            length = env->GetArrayLength(seed);
             if ((seedBytes = env->GetByteArrayElements(seed, 0)) == NULL) {
                 __leave;
             }
@@ -273,9 +261,6 @@
         if (reseedBytes)
             env->ReleaseByteArrayElements(seed, reseedBytes, JNI_ABORT);
 
-        if (pbData)
-            delete [] pbData;
-
         if (seedBytes)
             env->ReleaseByteArrayElements(seed, seedBytes, 0); // update orig
 
--- a/test/javax/sound/midi/Gervill/RiffReaderWriter/Skip.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/javax/sound/midi/Gervill/RiffReaderWriter/Skip.java	Mon Oct 15 15:05:59 2018 +0100
@@ -27,9 +27,8 @@
 import java.io.File;
 import java.io.FileInputStream;
 
-import javax.sound.sampled.*;
-
-import com.sun.media.sound.*;
+import com.sun.media.sound.RIFFReader;
+import com.sun.media.sound.RIFFWriter;
 
 public class Skip {
 
@@ -40,6 +39,11 @@
     }
 
     public static void main(String[] args) throws Exception {
+        test(false);
+        test(true);
+    }
+
+    private static void test(boolean customStream) throws Exception {
         RIFFWriter writer = null;
         RIFFReader reader = null;
         File tempfile = File.createTempFile("test",".riff");
@@ -51,7 +55,17 @@
             chunk.write((byte)44);
             writer.close();
             writer = null;
-            FileInputStream fis = new FileInputStream(tempfile);
+            final FileInputStream fis;
+            if (customStream) {
+                fis = new FileInputStream(tempfile);
+            } else {
+                fis = new FileInputStream(tempfile) {
+                    @Override
+                    public long skip(long n) {
+                        return 0;
+                    }
+                };
+            }
             reader = new RIFFReader(fis);
             RIFFReader readchunk = reader.nextChunk();
             reader.skip(1);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/lib/testlibrary/jdk/testlibrary/InMemoryJavaCompiler.java	Mon Oct 15 15:05:59 2018 +0100
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.testlibrary;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import java.net.URI;
+import java.util.Arrays;
+
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.FileObject;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaCompiler.CompilationTask;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.JavaFileObject.Kind;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.ToolProvider;
+
+/**
+ * {@code InMemoryJavaCompiler} can be used for compiling a {@link
+ * CharSequence} to a {@code byte[]}.
+ *
+ * The compiler will not use the file system at all, instead using a {@link
+ * ByteArrayOutputStream} for storing the byte code. For the source code, any
+ * kind of {@link CharSequence} can be used, e.g. {@link String}, {@link
+ * StringBuffer} or {@link StringBuilder}.
+ *
+ * The {@code InMemoryCompiler} can easily be used together with a {@code
+ * ByteClassLoader} to easily compile and load source code in a {@link String}:
+ *
+ * <pre>
+ * {@code
+ * import com.oracle.java.testlibrary.InMemoryJavaCompiler;
+ * import com.oracle.java.testlibrary.ByteClassLoader;
+ *
+ * class Example {
+ *     public static void main(String[] args) {
+ *         String className = "Foo";
+ *         String sourceCode = "public class " + className + " {" +
+ *                             "    public void bar() {" +
+ *                             "        System.out.println("Hello from bar!");" +
+ *                             "    }" +
+ *                             "}";
+ *         byte[] byteCode = InMemoryJavaCompiler.compile(className, sourceCode);
+ *         Class fooClass = ByteClassLoader.load(className, byteCode);
+ *     }
+ * }
+ * }
+ * </pre>
+ */
+public class InMemoryJavaCompiler {
+    private static class MemoryJavaFileObject extends SimpleJavaFileObject {
+        private final String className;
+        private final CharSequence sourceCode;
+        private final ByteArrayOutputStream byteCode;
+
+        public MemoryJavaFileObject(String className, CharSequence sourceCode) {
+            super(URI.create("string:///" + className.replace('.','/') + Kind.SOURCE.extension), Kind.SOURCE);
+            this.className = className;
+            this.sourceCode = sourceCode;
+            this.byteCode = new ByteArrayOutputStream();
+        }
+
+        @Override
+        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+            return sourceCode;
+        }
+
+        @Override
+        public OutputStream openOutputStream() throws IOException {
+            return byteCode;
+        }
+
+        public byte[] getByteCode() {
+            return byteCode.toByteArray();
+        }
+
+        public String getClassName() {
+            return className;
+        }
+    }
+
+    private static class FileManagerWrapper extends ForwardingJavaFileManager {
+        private MemoryJavaFileObject file;
+
+        public FileManagerWrapper(MemoryJavaFileObject file) {
+            super(getCompiler().getStandardFileManager(null, null, null));
+            this.file = file;
+        }
+
+        @Override
+        public JavaFileObject getJavaFileForOutput(Location location, String className,
+                                                   Kind kind, FileObject sibling)
+            throws IOException {
+            if (!file.getClassName().equals(className)) {
+                throw new IOException("Expected class with name " + file.getClassName() +
+                                      ", but got " + className);
+            }
+            return file;
+        }
+    }
+
+    /**
+     * Compiles the class with the given name and source code.
+     *
+     * @param className The name of the class
+     * @param sourceCode The source code for the class with name {@code className}
+     * @throws RuntimeException if the compilation did not succeed
+     * @return The resulting byte code from the compilation
+     */
+    public static byte[] compile(String className, CharSequence sourceCode) {
+        MemoryJavaFileObject file = new MemoryJavaFileObject(className, sourceCode);
+        CompilationTask task = getCompilationTask(file);
+
+        if(!task.call()) {
+            throw new RuntimeException("Could not compile " + className + " with source code " + sourceCode);
+        }
+
+        return file.getByteCode();
+    }
+
+    private static JavaCompiler getCompiler() {
+        return ToolProvider.getSystemJavaCompiler();
+    }
+
+    private static CompilationTask getCompilationTask(MemoryJavaFileObject file) {
+        return getCompiler().getTask(null, new FileManagerWrapper(file), null, null, null, Arrays.asList(file));
+    }
+}
--- a/test/lib/testlibrary/jdk/testlibrary/JarUtils.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/lib/testlibrary/jdk/testlibrary/JarUtils.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -23,16 +23,21 @@
 
 package jdk.testlibrary;
 
+import java.io.ByteArrayOutputStream;
+import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.nio.file.Files;
 import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
@@ -45,6 +50,72 @@
 public final class JarUtils {
 
     /**
+     * Creates a JAR file.
+     *
+     * Equivalent to {@code jar cfm <jarfile> <manifest> -C <dir> file...}
+     *
+     * The input files are resolved against the given directory. Any input
+     * files that are directories are processed recursively.
+     */
+    public static void createJarFile(Path jarfile, Manifest man, Path dir, Path... file)
+        throws IOException
+    {
+        // create the target directory
+        Path parent = jarfile.getParent();
+        if (parent != null)
+            Files.createDirectories(parent);
+
+        List<Path> entries = new ArrayList<>();
+        for (Path entry : file) {
+            Files.find(dir.resolve(entry), Integer.MAX_VALUE,
+                        (p, attrs) -> attrs.isRegularFile())
+                    .map(e -> dir.relativize(e))
+                    .forEach(entries::add);
+        }
+
+        try (OutputStream out = Files.newOutputStream(jarfile);
+             JarOutputStream jos = new JarOutputStream(out))
+        {
+            if (man != null) {
+                JarEntry je = new JarEntry(JarFile.MANIFEST_NAME);
+                jos.putNextEntry(je);
+                man.write(jos);
+                jos.closeEntry();
+            }
+
+            for (Path entry : entries) {
+                String name = toJarEntryName(entry);
+                jos.putNextEntry(new JarEntry(name));
+                Files.copy(dir.resolve(entry), jos);
+                jos.closeEntry();
+            }
+        }
+    }
+
+   /**
+     * Creates a JAR file.
+     *
+     * Equivalent to {@code jar cf <jarfile>  -C <dir> file...}
+     *
+     * The input files are resolved against the given directory. Any input
+     * files that are directories are processed recursively.
+     */
+    public static void createJarFile(Path jarfile, Path dir, Path... file)
+        throws IOException
+    {
+        createJarFile(jarfile, null, dir, file);
+    }
+
+    /**
+     * Creates a JAR file from the contents of a directory.
+     *
+     * Equivalent to {@code jar cf <jarfile> -C <dir> .}
+     */
+    public static void createJarFile(Path jarfile, Path dir) throws IOException {
+        createJarFile(jarfile, dir, Paths.get("."));
+    }
+
+    /**
      * Create jar file with specified files. If a specified file does not exist,
      * a new jar entry will be created with the file name itself as the content.
      */
@@ -126,6 +197,11 @@
         changes = new HashMap<>(changes);
 
         System.out.printf("Creating %s from %s...\n", dest, src);
+
+        if (dest.equals(src)) {
+            throw new IOException("src and dest cannot be the same");
+        }
+
         try (JarOutputStream jos = new JarOutputStream(
                 new FileOutputStream(dest))) {
 
@@ -153,6 +229,24 @@
         System.out.println();
     }
 
+    /**
+     * Update the Manifest inside a jar.
+     *
+     * @param src the original jar file name
+     * @param dest the new jar file name
+     * @param man the Manifest
+     *
+     * @throws IOException
+     */
+    public static void updateManifest(String src, String dest, Manifest man)
+            throws IOException {
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        man.write(bout);
+        Map<String, Object> map = new HashMap<>();
+        map.put(JarFile.MANIFEST_NAME, bout.toByteArray());
+        updateJar(src, dest, map);
+    }
+
     private static void updateEntry(JarOutputStream jos, String name, Object content)
            throws IOException {
         if (content instanceof Boolean) {
@@ -172,4 +266,14 @@
             }
         }
     }
+
+    /**
+     * Map a file path to the equivalent name in a JAR file
+     */
+    private static String toJarEntryName(Path file) {
+        Path normalized = file.normalize();
+        return normalized.subpath(0, normalized.getNameCount())  // drop root
+                .toString()
+                .replace(File.separatorChar, '/');
+    }
 }
--- a/test/lib/testlibrary/jdk/testlibrary/OutputAnalyzer.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/lib/testlibrary/jdk/testlibrary/OutputAnalyzer.java	Mon Oct 15 15:05:59 2018 +0100
@@ -39,7 +39,7 @@
 
     private final String stdout;
     private final String stderr;
-    private final int exitValue;
+    private final int exitValue;    // useless now. output contains exit value.
 
     /**
      * Create an OutputAnalyzer, a utility class for verifying output and exit
--- a/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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,6 +25,7 @@
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.PrintStream;
 import java.lang.management.ManagementFactory;
 import java.lang.management.RuntimeMXBean;
@@ -353,9 +354,31 @@
      * @return The output from the process.
      */
     public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Throwable {
+        return executeProcess(pb, null);
+    }
+
+    /**
+     * Executes a process, pipe some text into its STDIN, waits for it
+     * to finish and returns the process output. The process will have exited
+     * before this method returns.
+     * @param pb The ProcessBuilder to execute.
+     * @param input The text to pipe into STDIN. Can be null.
+     * @return The {@linkplain OutputAnalyzer} instance wrapping the process.
+     */
+    public static OutputAnalyzer executeProcess(ProcessBuilder pb, String input)
+            throws Throwable {
         OutputAnalyzer output = null;
+        Process p = null;
         try {
-            output = new OutputAnalyzer(pb.start());
+            p = pb.start();
+            if (input != null) {
+                try (OutputStream os = p.getOutputStream();
+                        PrintStream ps = new PrintStream(os)) {
+                    ps.print(input);
+                    ps.flush();
+                }
+            }
+            output = new OutputAnalyzer(p);
             return output;
         } catch (Throwable t) {
             System.out.println("executeProcess() failed: " + t);
--- a/test/lib/testlibrary/jdk/testlibrary/SecurityTools.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/lib/testlibrary/jdk/testlibrary/SecurityTools.java	Mon Oct 15 15:05:59 2018 +0100
@@ -49,10 +49,7 @@
                 launcher.addToolArg(arg);
             }
         }
-        String[] cmds = launcher.getCommand();
-        String cmdLine = Arrays.stream(cmds).collect(Collectors.joining(" "));
-        System.out.println("Command line: [" + cmdLine + "]");
-        return new ProcessBuilder(cmds);
+        return new ProcessBuilder(launcher.getCommand());
     }
 
     // keytool
@@ -69,7 +66,7 @@
         pb.redirectInput(ProcessBuilder.Redirect.from(new File(RESPONSE_FILE)));
 
         try {
-            return ProcessTools.executeProcess(pb);
+            return execute(pb);
         } catch (Throwable t) {
             throw new RuntimeException("keytool failure: " + t);
         } finally {
@@ -101,11 +98,20 @@
 
     public static OutputAnalyzer jarsigner(List<String> args)
             throws Exception {
+        return execute(getProcessBuilder("jarsigner", args));
+    }
+
+    private static OutputAnalyzer execute(ProcessBuilder pb) throws Exception {
         try {
-            return ProcessTools.executeProcess(
-                getProcessBuilder("jarsigner", args));
+            OutputAnalyzer oa = ProcessTools.executeCommand(pb);
+            System.out.println("Exit value: " + oa.getExitValue());
+            return oa;
         } catch (Throwable t) {
-            throw new RuntimeException("jarsigner error: " + t);
+            if (t instanceof Exception) {
+                throw (Exception) t;
+            } else {
+                throw new Exception(t);
+            }
         }
     }
 
Binary file test/lib/testlibrary/jdk/testlibrary/testkeys has changed
--- a/test/sun/rmi/transport/tcp/DisableRMIOverHttp/DisableRMIOverHTTPTest.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/rmi/transport/tcp/DisableRMIOverHttp/DisableRMIOverHTTPTest.java	Mon Oct 15 15:05:59 2018 +0100
@@ -22,7 +22,7 @@
  */
 
 /* @test
- * @bug 8193833
+ * @bug 8158963
  *
  * @summary Disable RMI over HTTP by default
  *
--- a/test/sun/security/krb5/auto/UnboundSSL.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/krb5/auto/UnboundSSL.java	Mon Oct 15 15:05:59 2018 +0100
@@ -26,12 +26,13 @@
 import java.security.PrivilegedActionException;
 import java.util.HashMap;
 import java.util.Map;
+import java.security.Security;
 
 import javax.security.auth.login.LoginException;
 
 /*
  * @test
- * @bug 8025123
+ * @bug 8025123 8208350
  * @summary Checks if an unbound server can handle connections
  *          only for allowed service principals
  * @run main/othervm/java.security.policy=unbound.ssl.policy -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSL
@@ -44,6 +45,7 @@
     public static void main(String[] args) throws IOException,
             NoSuchAlgorithmException,LoginException, PrivilegedActionException,
             InterruptedException {
+        Security.setProperty("jdk.tls.disabledAlgorithms", "");
         UnboundSSL test = new UnboundSSL();
         test.start(args[0], args[1]);
     }
--- a/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java	Mon Oct 15 15:05:59 2018 +0100
@@ -26,12 +26,13 @@
 import java.security.PrivilegedActionException;
 import java.util.HashMap;
 import java.util.Map;
+import java.security.Security;
 
 import javax.security.auth.login.LoginException;
 
 /*
  * @test
- * @bug 8025123
+ * @bug 8025123 8208350
  * @summary Checks if an unbound server pick up a correct key from keytab
  * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSLMultipleKeys
  *                              unbound.ssl.jaas.conf server_star
@@ -43,6 +44,7 @@
     public static void main(String[] args)
             throws IOException, NoSuchAlgorithmException, LoginException,
             PrivilegedActionException, InterruptedException {
+        Security.setProperty("jdk.tls.disabledAlgorithms", "");
         UnboundSSLMultipleKeys test = new UnboundSSLMultipleKeys();
         test.start(args[0], args[1]);
     }
--- a/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java	Mon Oct 15 15:05:59 2018 +0100
@@ -27,10 +27,11 @@
 import java.util.HashMap;
 import java.util.Map;
 import javax.security.auth.login.LoginException;
+import java.security.Security;
 
 /*
  * @test
- * @bug 8025123
+ * @bug 8025123 8208350
  * @summary Checks if an unbound server uses a service principal
  *          from sun.security.krb5.principal system property if specified
  * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSLPrincipalProperty
@@ -43,6 +44,7 @@
     public static void main(String[] args) throws IOException,
             NoSuchAlgorithmException,LoginException, PrivilegedActionException,
             InterruptedException {
+        Security.setProperty("jdk.tls.disabledAlgorithms", "");
         UnboundSSLPrincipalProperty test = new UnboundSSLPrincipalProperty();
         test.start(args[0], args[1]);
     }
--- a/test/sun/security/krb5/auto/unbound.ssl.policy	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/krb5/auto/unbound.ssl.policy	Mon Oct 15 15:05:59 2018 +0100
@@ -26,4 +26,6 @@
 
     // permission to use SunJCE provider
     permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+    // permission to reset the tls disabledalgos
+    permission "java.security.SecurityPermission" "setProperty.jdk.tls.disabledAlgorithms";
 };
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/ssl/CipherSuite/NoDesRC4CiphSuite.java	Mon Oct 15 15:05:59 2018 +0100
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8208350
+ * @summary Disable all DES cipher suites
+ * @run main/othervm NoDesRC4CiphSuite
+ */
+
+/*
+ * SunJSSE does not support dynamic system properties, no way to re-use
+ * system properties in samevm/agentvm mode.
+ */
+
+import java.security.Security;
+import javax.net.ssl.*;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.security.GeneralSecurityException;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+public class NoDesRC4CiphSuite {
+
+    private static final boolean DEBUG = false;
+
+    private static final byte RECTYPE_HS = 0x16;
+    private static final byte HSMSG_CLIHELLO = 0x01;
+
+    // These are some groups of Cipher Suites by names and IDs
+    private static final List<Integer> DES_CS_LIST = Arrays.asList(
+        0x0009, 0x0015, 0x0012, 0x001A, 0x0008, 0x0014, 0x0011, 0x0019
+    );
+    private static final String[] DES_CS_LIST_NAMES = new String[] {
+        "SSL_RSA_WITH_DES_CBC_SHA",
+        "SSL_DHE_RSA_WITH_DES_CBC_SHA",
+        "SSL_DHE_DSS_WITH_DES_CBC_SHA",
+        "SSL_DH_anon_WITH_DES_CBC_SHA",
+        "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
+        "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
+        "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
+        "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"
+    };
+    private static final List<Integer> RC4_CS_LIST = Arrays.asList(
+        0xC007, 0xC011, 0x0005, 0xC002, 0xC00C, 0x0004, 0xC016, 0x0018,
+        0x0003, 0x0017
+    );
+    private static final String[] RC4_CS_LIST_NAMES = new String[] {
+        "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
+        "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
+        "SSL_RSA_WITH_RC4_128_SHA",
+        "TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
+        "TLS_ECDH_RSA_WITH_RC4_128_SHA",
+        "SSL_RSA_WITH_RC4_128_MD5",
+        "TLS_ECDH_anon_WITH_RC4_128_SHA",
+        "SSL_DH_anon_WITH_RC4_128_MD5",
+        "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
+        "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"
+    };
+
+    private static final ByteBuffer CLIOUTBUF =
+            ByteBuffer.wrap("Client Side".getBytes());
+
+    public static void main(String[] args) throws Exception {
+        boolean allGood = true;
+        String disAlg = Security.getProperty("jdk.tls.disabledAlgorithms");
+        System.err.println("Disabled Algs: " + disAlg);
+
+        // Disabled DES tests
+        allGood &= testDefaultCase(DES_CS_LIST);
+        allGood &= testEngAddDisabled(DES_CS_LIST_NAMES, DES_CS_LIST);
+        allGood &= testEngOnlyDisabled(DES_CS_LIST_NAMES);
+
+        // Disabled RC4 tests
+        allGood &= testDefaultCase(RC4_CS_LIST);
+        allGood &= testEngAddDisabled(RC4_CS_LIST_NAMES, RC4_CS_LIST);
+        allGood &= testEngOnlyDisabled(RC4_CS_LIST_NAMES);
+
+        if (allGood) {
+            System.err.println("All tests passed");
+        } else {
+            throw new RuntimeException("One or more tests failed");
+        }
+    }
+
+    /**
+     * Create an engine with the default set of cipher suites enabled and make
+     * sure none of the disabled suites are present in the client hello.
+     *
+     * @param disabledSuiteIds the {@code List} of disabled cipher suite IDs
+     *      to be checked for.
+     *
+     * @return true if the test passed (No disabled suites), false otherwise
+     */
+    private static boolean testDefaultCase(List<Integer> disabledSuiteIds)
+            throws Exception {
+        System.err.println("\nTest: Default SSLEngine suite set");
+        SSLEngine ssle = makeEngine();
+        if (DEBUG) {
+            listCiphers("Suite set upon creation", ssle);
+        }
+        SSLEngineResult clientResult;
+        ByteBuffer cTOs = makeClientBuf(ssle);
+        clientResult = ssle.wrap(CLIOUTBUF, cTOs);
+        if (DEBUG) {
+            dumpResult("ClientHello: ", clientResult);
+        }
+        cTOs.flip();
+        boolean foundSuite = areSuitesPresentCH(cTOs, disabledSuiteIds);
+        if (foundSuite) {
+            System.err.println("FAIL: Found disabled suites!");
+            return false;
+        } else {
+            System.err.println("PASS: No disabled suites found.");
+            return true;
+        }
+    }
+
+    /**
+     * Create an engine and set only disabled cipher suites.
+     * The engine should not create the client hello message since the only
+     * available suites to assert in the client hello are disabled ones.
+     *
+     * @param disabledSuiteNames an array of cipher suite names that
+     *      should be disabled cipher suites.
+     *
+     * @return true if the engine throws SSLHandshakeException during client
+     *      hello creation, false otherwise.
+     */
+    private static boolean testEngOnlyDisabled(String[] disabledSuiteNames)
+            throws Exception {
+        System.err.println(
+                "\nTest: SSLEngine configured with only disabled suites");
+        try {
+            SSLEngine ssle = makeEngine();
+            ssle.setEnabledCipherSuites(disabledSuiteNames);
+            if (DEBUG) {
+                listCiphers("Suite set upon creation", ssle);
+            }
+            SSLEngineResult clientResult;
+            ByteBuffer cTOs = makeClientBuf(ssle);
+            clientResult = ssle.wrap(CLIOUTBUF, cTOs);
+            if (DEBUG) {
+                dumpResult("ClientHello: ", clientResult);
+            }
+            cTOs.flip();
+        } catch (SSLHandshakeException shse) {
+            System.err.println("PASS: Caught expected exception: " + shse);
+            return true;
+        }
+        System.err.println("FAIL: Expected SSLHandshakeException not thrown");
+        return false;
+    }
+
+    /**
+     * Create an engine and add some disabled suites to the default
+     * set of cipher suites.  Make sure none of the disabled suites show up
+     * in the client hello even though they were explicitly added.
+     *
+     * @param disabledSuiteNames an array of cipher suite names that
+     *      should be disabled cipher suites.
+     * @param disabledIds the {@code List} of disabled cipher suite IDs
+     *      to be checked for.
+     *
+     * @return true if the test passed (No disabled suites), false otherwise
+     */
+    private static boolean testEngAddDisabled(String[] disabledNames,
+            List<Integer> disabledIds) throws Exception {
+        System.err.println("\nTest: SSLEngine with disabled suites added");
+        SSLEngine ssle = makeEngine();
+
+        // Add disabled suites to the existing engine's set of enabled suites
+        String[] initialSuites = ssle.getEnabledCipherSuites();
+        String[] plusDisSuites = Arrays.copyOf(initialSuites,
+                initialSuites.length + disabledNames.length);
+        System.arraycopy(disabledNames, 0, plusDisSuites,
+                initialSuites.length, disabledNames.length);
+        ssle.setEnabledCipherSuites(plusDisSuites);
+
+        if (DEBUG) {
+            listCiphers("Suite set upon creation", ssle);
+        }
+        SSLEngineResult clientResult;
+        ByteBuffer cTOs = makeClientBuf(ssle);
+        clientResult = ssle.wrap(CLIOUTBUF, cTOs);
+        if (DEBUG) {
+            dumpResult("ClientHello: ", clientResult);
+        }
+        cTOs.flip();
+        boolean foundDisabled = areSuitesPresentCH(cTOs, disabledIds);
+        if (foundDisabled) {
+            System.err.println("FAIL: Found disabled suites!");
+            return false;
+        } else {
+            System.err.println("PASS: No disabled suites found.");
+            return true;
+        }
+    }
+
+    private static SSLEngine makeEngine() throws GeneralSecurityException {
+        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
+        ctx.init(null, null, null);
+        return ctx.createSSLEngine();
+    }
+
+    private static ByteBuffer makeClientBuf(SSLEngine ssle) {
+        ssle.setUseClientMode(true);
+        ssle.setNeedClientAuth(false);
+        SSLSession sess = ssle.getSession();
+        ByteBuffer cTOs = ByteBuffer.allocateDirect(sess.getPacketBufferSize());
+        return cTOs;
+    }
+
+    private static void listCiphers(String prefix, SSLEngine ssle) {
+        System.err.println(prefix + "\n---------------");
+        String[] suites = ssle.getEnabledCipherSuites();
+        for (String suite : suites) {
+            System.err.println(suite);
+        }
+        System.err.println("---------------");
+    }
+
+    /**
+     * Walk a TLS 1.2 or earlier ClientHello looking for any of the suites
+     * in the suiteIdList.
+     *
+     * @param clientHello a ByteBuffer containing the ClientHello message as
+     *      a complete TLS record.  The position of the buffer should be
+     *      at the first byte of the TLS record header.
+     * @param suiteIdList a List of integer values corresponding to
+     *      TLS cipher suite identifiers.
+     *
+     * @return true if at least one of the suites in {@code suiteIdList}
+     * is found in the ClientHello's cipher suite list
+     *
+     * @throws IOException if the data in the {@code clientHello}
+     *      buffer is not a TLS handshake message or is not a client hello.
+     */
+    private static boolean areSuitesPresentCH(ByteBuffer clientHello,
+            List<Integer> suiteIdList) throws IOException {
+        byte val;
+
+        // Process the TLS Record
+        val = clientHello.get();
+        if (val != RECTYPE_HS) {
+            throw new IOException(
+                    "Not a handshake record, type = " + val);
+        }
+
+        // Just skip over the version and length
+        clientHello.position(clientHello.position() + 4);
+
+        // Check the handshake message type
+        val = clientHello.get();
+        if (val != HSMSG_CLIHELLO) {
+            throw new IOException(
+                    "Not a ClientHello handshake message, type = " + val);
+        }
+
+        // Skip over the length
+        clientHello.position(clientHello.position() + 3);
+
+        // Skip over the protocol version (2) and random (32);
+        clientHello.position(clientHello.position() + 34);
+
+        // Skip past the session ID (variable length <= 32)
+        int len = Byte.toUnsignedInt(clientHello.get());
+        if (len > 32) {
+            throw new IOException("Session ID is too large, len = " + len);
+        }
+        clientHello.position(clientHello.position() + len);
+
+        // Finally, we are at the cipher suites.  Walk the list and place them
+        // into a List.
+        int csLen = Short.toUnsignedInt(clientHello.getShort());
+        if (csLen % 2 != 0) {
+            throw new IOException("CipherSuite length is invalid, len = " +
+                    csLen);
+        }
+        int csCount = csLen / 2;
+        List<Integer> csSuiteList = new ArrayList<>(csCount);
+        log("Found following suite IDs in hello:");
+        for (int i = 0; i < csCount; i++) {
+            int curSuite = Short.toUnsignedInt(clientHello.getShort());
+            log(String.format("Suite ID: 0x%04x", curSuite));
+            csSuiteList.add(curSuite);
+        }
+
+        // Now check to see if any of the suites passed in match what is in
+        // the suite list.
+        boolean foundMatch = false;
+        for (Integer cs : suiteIdList) {
+            if (csSuiteList.contains(cs)) {
+                System.err.format("Found match for suite ID 0x%04x\n", cs);
+                foundMatch = true;
+                break;
+            }
+        }
+
+        // We don't care about the rest of the ClientHello message.
+        // Rewind and return whether we found a match or not.
+        clientHello.rewind();
+        return foundMatch;
+    }
+
+    private static void dumpResult(String str, SSLEngineResult result) {
+        System.err.println("The format of the SSLEngineResult is: \n" +
+            "\t\"getStatus() / getHandshakeStatus()\" +\n" +
+            "\t\"bytesConsumed() / bytesProduced()\"\n");
+        HandshakeStatus hsStatus = result.getHandshakeStatus();
+        System.err.println(str + result.getStatus() + "/" + hsStatus + ", " +
+            result.bytesConsumed() + "/" + result.bytesProduced() + " bytes");
+        if (hsStatus == HandshakeStatus.FINISHED) {
+            System.err.println("\t...ready for application data");
+        }
+    }
+
+    private static void log(String str) {
+        if (DEBUG) {
+            System.err.println(str);
+        }
+    }
+}
--- a/test/sun/security/ssl/SSLContextImpl/CustomizedCipherSuites.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/ssl/SSLContextImpl/CustomizedCipherSuites.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, 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
@@ -26,52 +26,52 @@
 
 /*
  * @test
- * @bug 8162362
+ * @bug 8162362 8208350
  * @summary Cannot enable previously default enabled cipher suites
  * @run main/othervm
  *      CustomizedCipherSuites Default true
  *      TLS_RSA_WITH_AES_128_CBC_SHA
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  * @run main/othervm
  *      -Djdk.tls.client.cipherSuites="unknown"
  *      CustomizedCipherSuites Default true
  *      TLS_RSA_WITH_AES_128_CBC_SHA
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  * @run main/othervm
  *      -Djdk.tls.client.cipherSuites=""
  *      CustomizedCipherSuites Default true
  *      TLS_RSA_WITH_AES_128_CBC_SHA
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  * @run main/othervm
- *      -Djdk.tls.client.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      -Djdk.tls.client.cipherSuites="TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
  *      CustomizedCipherSuites Default true
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  *      TLS_RSA_WITH_AES_128_CBC_SHA
  * @run main/othervm
- *      -Djdk.tls.server.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      -Djdk.tls.server.cipherSuites="TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
  *      CustomizedCipherSuites Default false
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  *      TLS_RSA_WITH_AES_128_CBC_SHA
  * @run main/othervm
- *      -Djdk.tls.client.cipherSuites="TLS_RSA_WITH_AES_128_CBC_SHA,unknown,SSL_RSA_WITH_DES_CBC_SHA"
+ *      -Djdk.tls.client.cipherSuites="TLS_RSA_WITH_AES_128_CBC_SHA,unknown,TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
  *      CustomizedCipherSuites Default true
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  *      ""
  * @run main/othervm
- *      -Djdk.tls.server.cipherSuites="TLS_RSA_WITH_AES_128_CBC_SHA,unknown,SSL_RSA_WITH_DES_CBC_SHA"
+ *      -Djdk.tls.server.cipherSuites="TLS_RSA_WITH_AES_128_CBC_SHA,unknown,TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
  *      CustomizedCipherSuites Default false
  *      TLS_RSA_WITH_AES_128_CBC_SHA
  *      ""
  * @run main/othervm
- *      -Djdk.tls.server.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      -Djdk.tls.server.cipherSuites="TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
  *      CustomizedCipherSuites Default true
  *      TLS_RSA_WITH_AES_128_CBC_SHA
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  * @run main/othervm
- *      -Djdk.tls.client.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      -Djdk.tls.client.cipherSuites="TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
  *      CustomizedCipherSuites Default false
  *      TLS_RSA_WITH_AES_128_CBC_SHA
- *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  */
 
 import javax.net.ssl.*;
@@ -79,7 +79,7 @@
 /**
  * Test the customized default cipher suites.
  *
- * This test is based on the behavior that SSL_RSA_WITH_DES_CBC_SHA is
+ * This test is based on the behavior that TLS_ECDH_anon_WITH_AES_128_CBC_SHA is
  * disabled by default, and TLS_RSA_WITH_AES_128_CBC_SHA is enabled by
  * default in JDK.  If the behavior is changed in the future, please
  * update the test cases above accordingly.
--- a/test/sun/security/tools/jarsigner/TimestampCheck.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/TimestampCheck.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -22,6 +22,8 @@
  */
 
 import com.sun.net.httpserver.*;
+
+import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
@@ -36,16 +38,18 @@
 import java.security.PrivateKey;
 import java.security.Signature;
 import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.List;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.*;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
 
 import sun.misc.IOUtils;
-import jdk.testlibrary.*;
+import jdk.testlibrary.SecurityTools;
+import jdk.testlibrary.OutputAnalyzer;
 import jdk.testlibrary.JarUtils;
 import sun.security.pkcs.ContentInfo;
 import sun.security.pkcs.PKCS7;
@@ -58,9 +62,12 @@
 import sun.security.x509.AlgorithmId;
 import sun.security.x509.X500Name;
 
+import jdk.testlibrary.Utils;
+
 /*
  * @test
  * @bug 6543842 6543440 6939248 8009636 8024302 8163304 8169911 8169688 8171121
+ *      8180289
  * @summary checking response of timestamp
  * @modules java.base/sun.security.pkcs
  *          java.base/sun.security.timestamp
@@ -68,7 +75,7 @@
  *          java.base/sun.security.util
  *          java.base/sun.security.tools.keytool
  * @library /lib/testlibrary
- * @run main/timeout=600 TimestampCheck
+ * @run main/othervm/timeout=600 TimestampCheck
  */
 public class TimestampCheck {
 
@@ -114,12 +121,12 @@
          */
         byte[] sign(byte[] input, String path) throws Exception {
             DerValue value = new DerValue(input);
-            System.err.println("\nIncoming Request\n===================");
-            System.err.println("Version: " + value.data.getInteger());
+            System.out.println("\nIncoming Request\n===================");
+            System.out.println("Version: " + value.data.getInteger());
             DerValue messageImprint = value.data.getDerValue();
             AlgorithmId aid = AlgorithmId.parse(
                     messageImprint.data.getDerValue());
-            System.err.println("AlgorithmId: " + aid);
+            System.out.println("AlgorithmId: " + aid);
 
             ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId);
             BigInteger nonce = null;
@@ -127,25 +134,24 @@
                 DerValue v = value.data.getDerValue();
                 if (v.tag == DerValue.tag_Integer) {
                     nonce = v.getBigInteger();
-                    System.err.println("nonce: " + nonce);
+                    System.out.println("nonce: " + nonce);
                 } else if (v.tag == DerValue.tag_Boolean) {
-                    System.err.println("certReq: " + v.getBoolean());
+                    System.out.println("certReq: " + v.getBoolean());
                 } else if (v.tag == DerValue.tag_ObjectId) {
                     policyId = v.getOID();
-                    System.err.println("PolicyID: " + policyId);
+                    System.out.println("PolicyID: " + policyId);
                 }
             }
 
-            System.err.println("\nResponse\n===================");
+            System.out.println("\nResponse\n===================");
             FileInputStream is = new FileInputStream(keystore);
             KeyStore ks = KeyStore.getInstance("JCEKS");
             ks.load(is, "changeit".toCharArray());
             is.close();
 
-            String alias = "ts";
-            if (path.startsWith("bad") || path.equals("weak")) {
-                alias = "ts" + path;
-            }
+            // If path starts with "ts", use the TSA it points to.
+            // Otherwise, always use "ts".
+            String alias = path.startsWith("ts") ? path : "ts";
 
             if (path.equals("diffpolicy")) {
                 policyId = new ObjectIdentifier(defaultPolicyId);
@@ -192,8 +198,11 @@
 
             tst.putInteger(1);
 
-            Calendar cal = Calendar.getInstance();
-            tst.putGeneralizedTime(cal.getTime());
+            Instant instant = Instant.now();
+            if (path.equals("tsold")) {
+                instant = instant.minus(20, ChronoUnit.DAYS);
+            }
+            tst.putGeneralizedTime(Date.from(instant));
 
             if (path.equals("diffnonce")) {
                 tst.putInteger(1234);
@@ -220,10 +229,10 @@
                     "1.2.840.113549.1.9.16.1.4"),
                     new DerValue(tstInfo2.toByteArray()));
 
-            System.err.println("Signing...");
-            System.err.println(new X500Name(signer
+            System.out.println("Signing...");
+            System.out.println(new X500Name(signer
                     .getIssuerX500Principal().getName()));
-            System.err.println(signer.getSerialNumber());
+            System.out.println(signer.getSerialNumber());
 
             SignerInfo signerInfo = new SignerInfo(
                     new X500Name(signer.getIssuerX500Principal().getName()),
@@ -296,24 +305,52 @@
 
         prepare();
 
-        try (Handler tsa = Handler.init(0, "tsks");) {
+        try (Handler tsa = Handler.init(0, "ks");) {
             tsa.start();
             int port = tsa.getPort();
 
             host = "http://localhost:" + port + "/";
 
             if (args.length == 0) {         // Run this test
-                sign("none")
+
+                sign("normal")
+                        .shouldNotContain("Warning")
+                        .shouldHaveExitValue(0);
+
+                verify("normal.jar")
+                        .shouldNotContain("Warning")
+                        .shouldHaveExitValue(0);
+
+                // Simulate signing at a previous date:
+                // 1. tsold will create a timestamp of 20 days ago.
+                // 2. oldsigner expired 10 days ago.
+                // jarsigner will show a warning at signing.
+                signVerbose("tsold", "unsigned.jar", "tsold.jar", "oldsigner")
+                        .shouldHaveExitValue(4);
+
+                // It verifies perfectly.
+                verify("tsold.jar", "-verbose", "-certs")
+                        .shouldNotContain("Warning")
+                        .shouldHaveExitValue(0);
+
+                signVerbose(null, "unsigned.jar", "none.jar", "signer")
                         .shouldContain("is not timestamped")
                         .shouldHaveExitValue(0);
 
-                sign("badku")
-                        .shouldHaveExitValue(0);
+                signVerbose(null, "unsigned.jar", "badku.jar", "badku")
+                        .shouldHaveExitValue(8);
                 checkBadKU("badku.jar");
 
-                sign("normal")
-                        .shouldNotContain("is not timestamped")
-                        .shouldHaveExitValue(0);
+                // 8180289: unvalidated TSA cert chain
+                sign("tsnoca")
+                        .shouldContain("TSA certificate chain is invalid")
+                        .shouldHaveExitValue(64);
+
+                verify("tsnoca.jar", "-verbose", "-certs")
+                        .shouldHaveExitValue(64)
+                        .shouldContain("jar verified")
+                        .shouldContain("Invalid TSA certificate chain")
+                        .shouldContain("TSA certificate chain is invalid");
 
                 sign("nononce")
                         .shouldHaveExitValue(1);
@@ -325,11 +362,11 @@
                         .shouldHaveExitValue(1);
                 sign("fullchain")
                         .shouldHaveExitValue(0);   // Success, 6543440 solved.
-                sign("bad1")
+                sign("tsbad1")
                         .shouldHaveExitValue(1);
-                sign("bad2")
+                sign("tsbad2")
                         .shouldHaveExitValue(1);
-                sign("bad3")
+                sign("tsbad3")
                         .shouldHaveExitValue(1);
                 sign("nocert")
                         .shouldHaveExitValue(1);
@@ -341,119 +378,171 @@
                 sign("diffpolicy", "-tsapolicyid", "1.2.3")
                         .shouldHaveExitValue(1);
 
-                sign("tsaalg", "-tsadigestalg", "SHA")
+                sign("sha1alg", "-tsadigestalg", "SHA")
                         .shouldHaveExitValue(0);
-                checkTimestamp("tsaalg.jar", defaultPolicyId, "SHA-1");
+                checkTimestamp("sha1alg.jar", defaultPolicyId, "SHA-1");
 
-                sign("weak", "-digestalg", "MD5",
+                sign("tsweak", "-digestalg", "MD5",
                                 "-sigalg", "MD5withRSA", "-tsadigestalg", "MD5")
-                        .shouldHaveExitValue(0);
-                checkWeak("weak.jar");
+                        .shouldHaveExitValue(68);
+                checkWeak("tsweak.jar");
+
+                signVerbose("tsweak", "unsigned.jar", "tsweak2.jar", "signer")
+                        .shouldHaveExitValue(64)
+                        .shouldContain("TSA certificate chain is invalid");
 
-                signWithAliasAndTsa("halfWeak", "old.jar", "old", "-digestalg", "MD5")
-                        .shouldHaveExitValue(0);
+                // Weak timestamp is an error and jar treated unsigned
+                verify("tsweak2.jar", "-verbose")
+                        .shouldHaveExitValue(16)
+                        .shouldContain("treated as unsigned")
+                        .shouldMatch("Timestamp.*512.*weak");
+
+                signVerbose("normal", "unsigned.jar", "halfWeak.jar", "signer",
+                        "-digestalg", "MD5")
+                        .shouldHaveExitValue(4);
                 checkHalfWeak("halfWeak.jar");
 
                 // sign with DSA key
-                signWithAliasAndTsa("sign1", "old.jar", "dsakey")
+                signVerbose("normal", "unsigned.jar", "sign1.jar", "dsakey")
                         .shouldHaveExitValue(0);
                 // sign with RSAkeysize < 1024
-                signWithAliasAndTsa("sign2", "sign1.jar", "weakkeysize")
-                        .shouldHaveExitValue(0);
+                signVerbose("normal", "sign1.jar", "sign2.jar", "weakkeysize")
+                        .shouldHaveExitValue(4);
                 checkMultiple("sign2.jar");
 
                 // When .SF or .RSA is missing or invalid
                 checkMissingOrInvalidFiles("normal.jar");
+
+                if (Files.exists(Paths.get("ts2.cert"))) {
+                    checkInvalidTsaCertKeyUsage();
+                }
             } else {                        // Run as a standalone server
-                System.err.println("Press Enter to quit server");
+                System.out.println("Press Enter to quit server");
                 System.in.read();
             }
         }
     }
 
+    private static void checkInvalidTsaCertKeyUsage() throws Exception {
+
+        // Hack: Rewrite the TSA cert inside normal.jar into ts2.jar.
+
+        // Both the cert and the serial number must be rewritten.
+        byte[] tsCert = Files.readAllBytes(Paths.get("ts.cert"));
+        byte[] ts2Cert = Files.readAllBytes(Paths.get("ts2.cert"));
+        byte[] tsSerial = getCert(tsCert)
+                .getSerialNumber().toByteArray();
+        byte[] ts2Serial = getCert(ts2Cert)
+                .getSerialNumber().toByteArray();
+
+        byte[] oldBlock;
+        try (JarFile normal = new JarFile("normal.jar")) {
+            oldBlock = Utils.readAllBytes(normal.getInputStream(
+                    normal.getJarEntry("META-INF/SIGNER.RSA")));
+        }
+
+        JarUtils.updateJar("normal.jar", "ts2.jar",
+                mapOf("META-INF/SIGNER.RSA",
+                        updateBytes(updateBytes(oldBlock, tsCert, ts2Cert),
+                                tsSerial, ts2Serial)));
+
+        verify("ts2.jar", "-verbose", "-certs")
+                .shouldHaveExitValue(64)
+                .shouldContain("jar verified")
+                .shouldContain("Invalid TSA certificate chain: Extended key usage does not permit use for TSA server");
+    }
+
+    public static X509Certificate getCert(byte[] data)
+            throws CertificateException, IOException {
+        return (X509Certificate)
+                CertificateFactory.getInstance("X.509")
+                        .generateCertificate(new ByteArrayInputStream(data));
+    }
+
+    private static byte[] updateBytes(byte[] old, byte[] from, byte[] to) {
+        int pos = 0;
+        while (true) {
+            if (pos + from.length > old.length) {
+                return null;
+            }
+            if (Arrays.equals(Arrays.copyOfRange(old, pos, pos+from.length), from)) {
+                byte[] result = old.clone();
+                System.arraycopy(to, 0, result, pos, from.length);
+                return result;
+            }
+            pos++;
+        }
+    }
+
     private static void checkMissingOrInvalidFiles(String s)
             throws Throwable {
-        JarUtils.updateJar(s, "1.jar", "-", "META-INF/OLD.SF");
+
+        JarUtils.updateJar(s, "1.jar", mapOf("META-INF/SIGNER.SF", Boolean.FALSE));
         verify("1.jar", "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
-                .shouldContain("Missing signature-related file META-INF/OLD.SF");
-        JarUtils.updateJar(s, "2.jar", "-", "META-INF/OLD.RSA");
+                .shouldContain("Missing signature-related file META-INF/SIGNER.SF");
+        JarUtils.updateJar(s, "2.jar", mapOf("META-INF/SIGNER.RSA", Boolean.FALSE));
         verify("2.jar", "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
-                .shouldContain("Missing block file for signature-related file META-INF/OLD.SF");
-        JarUtils.updateJar(s, "3.jar", "META-INF/OLD.SF");
+                .shouldContain("Missing block file for signature-related file META-INF/SIGNER.SF");
+        JarUtils.updateJar(s, "3.jar", mapOf("META-INF/SIGNER.SF", "dummy"));
         verify("3.jar", "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
-                .shouldContain("Unparsable signature-related file META-INF/OLD.SF");
-        JarUtils.updateJar(s, "4.jar", "META-INF/OLD.RSA");
+                .shouldContain("Unparsable signature-related file META-INF/SIGNER.SF");
+        JarUtils.updateJar(s, "4.jar", mapOf("META-INF/SIGNER.RSA", "dummy"));
         verify("4.jar", "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
-                .shouldContain("Unparsable signature-related file META-INF/OLD.RSA");
+                .shouldContain("Unparsable signature-related file META-INF/SIGNER.RSA");
     }
 
     static OutputAnalyzer jarsigner(List<String> extra)
-            throws Throwable {
-        JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jarsigner")
-                .addVMArg("-Duser.language=en")
-                .addVMArg("-Duser.country=US")
-                .addToolArg("-keystore")
-                .addToolArg("tsks")
-                .addToolArg("-storepass")
-                .addToolArg("changeit");
-        for (String s : extra) {
-            if (s.startsWith("-J")) {
-                launcher.addVMArg(s.substring(2));
-            } else {
-                launcher.addToolArg(s);
-            }
-        }
-        System.err.println("COMMAND: ");
-        for (String cmd : launcher.getCommand()) {
-            System.err.print(cmd + " ");
-        }
-        System.err.println();
-        return ProcessTools.executeCommand(launcher.getCommand());
+            throws Exception {
+        List<String> args = new ArrayList<>(
+                listOf("-keystore", "ks", "-storepass", "changeit"));
+        args.addAll(extra);
+        return SecurityTools.jarsigner(args);
     }
 
     static OutputAnalyzer verify(String file, String... extra)
-            throws Throwable {
+            throws Exception {
         List<String> args = new ArrayList<>();
         args.add("-verify");
+        args.add("-strict");
         args.add(file);
         args.addAll(Arrays.asList(extra));
         return jarsigner(args);
     }
 
-    static void checkBadKU(String file) throws Throwable {
+    static void checkBadKU(String file) throws Exception {
         System.err.println("BadKU: " + file);
         verify(file)
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
                 .shouldContain("re-run jarsigner with debug enabled");
         verify(file, "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("Signed by")
                 .shouldContain("treated as unsigned")
                 .shouldContain("re-run jarsigner with debug enabled");
         verify(file, "-J-Djava.security.debug=jar")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("SignatureException: Key usage restricted")
                 .shouldContain("treated as unsigned")
                 .shouldContain("re-run jarsigner with debug enabled");
     }
 
-    static void checkWeak(String file) throws Throwable {
+    static void checkWeak(String file) throws Exception {
         verify(file)
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
                 .shouldMatch("weak algorithm that is now disabled.")
                 .shouldMatch("Re-run jarsigner with the -verbose option for more details");
         verify(file, "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
                 .shouldMatch("weak algorithm that is now disabled by")
                 .shouldMatch("Digest algorithm: .*weak")
@@ -462,18 +551,18 @@
                 .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak")
                 .shouldMatch("Timestamp signature algorithm: .*key.*weak");
         verify(file, "-J-Djava.security.debug=jar")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldMatch("SignatureException:.*disabled");
     }
 
-    static void checkHalfWeak(String file) throws Throwable {
+    static void checkHalfWeak(String file) throws Exception {
         verify(file)
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
                 .shouldMatch("weak algorithm that is now disabled.")
                 .shouldMatch("Re-run jarsigner with the -verbose option for more details");
         verify(file, "-verbose")
-                .shouldHaveExitValue(0)
+                .shouldHaveExitValue(16)
                 .shouldContain("treated as unsigned")
                 .shouldMatch("weak algorithm that is now disabled by")
                 .shouldMatch("Digest algorithm: .*weak")
@@ -483,7 +572,7 @@
                 .shouldNotMatch("Timestamp signature algorithm: .*key.*weak");
      }
 
-    static void checkMultiple(String file) throws Throwable {
+    static void checkMultiple(String file) throws Exception {
         verify(file)
                 .shouldHaveExitValue(0)
                 .shouldContain("jar verified");
@@ -500,7 +589,7 @@
     static void checkTimestamp(String file, String policyId, String digestAlg)
             throws Exception {
         try (JarFile jf = new JarFile(file)) {
-            JarEntry je = jf.getJarEntry("META-INF/OLD.RSA");
+            JarEntry je = jf.getJarEntry("META-INF/SIGNER.RSA");
             try (InputStream is = jf.getInputStream(je)) {
                 byte[] content = IOUtils.readFully(is, -1, true);
                 PKCS7 p7 = new PKCS7(content);
@@ -526,26 +615,38 @@
     static int which = 0;
 
     /**
+     * Sign with a TSA path. Always use alias "signer" to sign "unsigned.jar".
+     * The signed jar name is always path.jar.
+     *
      * @param extra more args given to jarsigner
      */
     static OutputAnalyzer sign(String path, String... extra)
-            throws Throwable {
-        String alias = path.equals("badku") ? "badku" : "old";
-        return signWithAliasAndTsa(path, "old.jar", alias, extra);
+            throws Exception {
+        return signVerbose(
+                path,
+                "unsigned.jar",
+                path + ".jar",
+                "signer",
+                extra);
     }
 
-    static OutputAnalyzer signWithAliasAndTsa (String path, String jar,
-            String alias, String...extra) throws Throwable {
+    static OutputAnalyzer signVerbose(
+            String path,    // TSA URL path
+            String oldJar,
+            String newJar,
+            String alias,   // signer
+            String...extra) throws Exception {
         which++;
-        System.err.println("\n>> Test #" + which + ": " + Arrays.toString(extra));
+        System.out.println("\n>> Test #" + which);
         List<String> args = new ArrayList<>();
-        args.add("-J-Djava.security.egd=file:/dev/./urandom");
+        args.add("-strict");
+        args.add("-verbose");
         args.add("-debug");
         args.add("-signedjar");
-        args.add(path + ".jar");
-        args.add(jar);
+        args.add(newJar);
+        args.add(oldJar);
         args.add(alias);
-        if (!path.equals("none") && !path.equals("badku")) {
+        if (path != null) {
             args.add("-tsa");
             args.add(host + path);
          }
@@ -554,24 +655,54 @@
     }
 
     static void prepare() throws Exception {
-        jdk.testlibrary.JarUtils.createJar("old.jar", "A");
-        Files.deleteIfExists(Paths.get("tsks"));
-        keytool("-alias ca -genkeypair -ext bc -dname CN=CA");
-        keytool("-alias old -genkeypair -dname CN=old");
+        JarUtils.createJar("unsigned.jar", "A");
+        Files.deleteIfExists(Paths.get("ks"));
+        keytool("-alias signer -genkeypair -ext bc -dname CN=signer");
+        keytool("-alias oldsigner -genkeypair -dname CN=oldsigner");
         keytool("-alias dsakey -genkeypair -keyalg DSA -dname CN=dsakey");
         keytool("-alias weakkeysize -genkeypair -keysize 512 -dname CN=weakkeysize");
         keytool("-alias badku -genkeypair -dname CN=badku");
         keytool("-alias ts -genkeypair -dname CN=ts");
-        keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsbad1");
+        keytool("-alias tsold -genkeypair -dname CN=tsold");
+        keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsweak");
         keytool("-alias tsbad1 -genkeypair -dname CN=tsbad1");
         keytool("-alias tsbad2 -genkeypair -dname CN=tsbad2");
         keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3");
+        keytool("-alias tsnoca -genkeypair -dname CN=tsnoca");
 
-        gencert("old");
+        // tsnoca's issuer will be removed from keystore later
+        keytool("-alias ca -genkeypair -ext bc -dname CN=CA");
+        gencert("tsnoca", "-ext eku:critical=ts");
+        keytool("-delete -alias ca");
+        keytool("-alias ca -genkeypair -ext bc -dname CN=CA -startdate -40d");
+
+        gencert("signer");
+        gencert("oldsigner", "-startdate -30d -validity 20");
         gencert("dsakey");
         gencert("weakkeysize");
         gencert("badku", "-ext ku:critical=keyAgreement");
         gencert("ts", "-ext eku:critical=ts");
+
+
+        for (int i = 0; i < 5; i++) {
+            // Issue another cert for "ts" with a different EKU.
+            // Length might be different because serial number is
+            // random. Try several times until a cert with the same
+            // length is generated so we can substitute ts.cert
+            // embedded in the PKCS7 block with ts2.cert.
+            // If cannot create one, related test will be ignored.
+            keytool("-gencert -alias ca -infile ts.req -outfile ts2.cert " +
+                    "-ext eku:critical=1.3.6.1.5.5.7.3.9");
+            if (Files.size(Paths.get("ts.cert")) != Files.size(Paths.get("ts2.cert"))) {
+                Files.delete(Paths.get("ts2.cert"));
+                System.out.println("Warning: cannot create same length");
+            } else {
+                break;
+            }
+        }
+
+        gencert("tsold", "-ext eku:critical=ts -startdate -40d -validity 45");
+
         gencert("tsweak", "-ext eku:critical=ts");
         gencert("tsbad1");
         gencert("tsbad2", "-ext eku=ts");
@@ -590,8 +721,16 @@
     }
 
     static void keytool(String cmd) throws Exception {
-        cmd = "-keystore tsks -storepass changeit -keypass changeit " +
+        cmd = "-keystore ks -storepass changeit -keypass changeit " +
                 "-keyalg rsa -validity 200 " + cmd;
         sun.security.tools.keytool.Main.main(cmd.split(" "));
     }
+
+    static <K,V> Map<K,V> mapOf(K k1, V v1) {
+        return Collections.singletonMap(k1, v1);
+    }
+
+    static <E> List<E> listOf(E... elements) {
+        return Arrays.asList(elements);
+    }
 }
--- a/test/sun/security/tools/jarsigner/TsacertOptionTest.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/TsacertOptionTest.java	Mon Oct 15 15:05:59 2018 +0100
@@ -46,6 +46,7 @@
             + ".txt";
     private static final String PASSWORD = "changeit";
     private static final String KEYSTORE = "ks.jks";
+    private static final String CA_KEY_ALIAS = "ca";
     private static final String SIGNING_KEY_ALIAS = "sign_alias";
     private static final String TSA_KEY_ALIAS = "ts";
     private static final String KEY_ALG = "RSA";
@@ -73,20 +74,52 @@
 
         // look for free network port for TSA service
         int port = jdk.testlibrary.Utils.getFreePort();
-        String host = jdk.testlibrary.Utils.getHostname();
+        String host = "127.0.0.1";
         String tsaUrl = "http://" + host + ":" + port;
 
         // create key pair for jar signing
         ProcessTools.executeCommand(KEYTOOL,
                 "-genkey",
+                "-alias", CA_KEY_ALIAS,
+                "-keyalg", KEY_ALG,
+                "-keysize", Integer.toString(KEY_SIZE),
+                "-keystore", KEYSTORE,
+                "-storepass", PASSWORD,
+                "-keypass", PASSWORD,
+                "-dname", "CN=CA",
+                "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
+        ProcessTools.executeCommand(KEYTOOL,
+                "-genkey",
                 "-alias", SIGNING_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
                 "-keysize", Integer.toString(KEY_SIZE),
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
-                "-dname", "CN=Test",
-                "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
+                "-dname", "CN=Test").shouldHaveExitValue(0);
+        ProcessTools.executeCommand(KEYTOOL,
+                "-certreq",
+                "-alias", SIGNING_KEY_ALIAS,
+                "-keystore", KEYSTORE,
+                "-storepass", PASSWORD,
+                "-keypass", PASSWORD,
+                "-file", "certreq").shouldHaveExitValue(0);
+        ProcessTools.executeCommand(KEYTOOL,
+                "-gencert",
+                "-alias", CA_KEY_ALIAS,
+                "-keystore", KEYSTORE,
+                "-storepass", PASSWORD,
+                "-keypass", PASSWORD,
+                "-validity", Integer.toString(VALIDITY),
+                "-infile", "certreq",
+                "-outfile", "cert").shouldHaveExitValue(0);
+        ProcessTools.executeCommand(KEYTOOL,
+                "-importcert",
+                "-alias", SIGNING_KEY_ALIAS,
+                "-keystore", KEYSTORE,
+                "-storepass", PASSWORD,
+                "-keypass", PASSWORD,
+                "-file", "cert").shouldHaveExitValue(0);
 
         // create key pair for TSA service
         // SubjectInfoAccess extension contains URL to TSA service
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/tools/jarsigner/Warning.java	Mon Oct 15 15:05:59 2018 +0100
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import jdk.testlibrary.JDKToolLauncher;
+import jdk.testlibrary.JarUtils;
+import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.ProcessTools;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Arrays;
+
+/**
+ * @test
+ * @bug 8024302 8026037 8130132
+ * @summary warnings, errors and -strict
+ * @library /lib/testlibrary
+ */
+public class Warning {
+
+    public static void main(String[] args) throws Throwable {
+
+        Files.deleteIfExists(Paths.get("ks"));
+
+        newCert("ca", "-validity 365000");
+
+        recreateJar();
+
+        newCert("a");
+        run("jarsigner", "a.jar a")
+                .shouldContain("is self-signed");
+        run("jarsigner", "a.jar a -strict")
+                .shouldContain("is self-signed")
+                .shouldHaveExitValue(4);
+        // Trusted entry can be self-signed without a warning
+        run("jarsigner", "-verify a.jar")
+                .shouldNotContain("is self-signed")
+                .shouldNotContain("not signed by alias in this keystore");
+        run("keytool", "-delete -alias a");
+        // otherwise a warning will be shown
+        run("jarsigner", "-verify a.jar")
+                .shouldContain("is self-signed")
+                .shouldContain("not signed by alias in this keystore");
+
+        recreateJar();
+
+        newCert("b");
+        issueCert("b");
+        run("jarsigner", "a.jar b")
+                .shouldNotContain("is self-signed");
+        run("jarsigner", "-verify a.jar")
+                .shouldNotContain("is self-signed");
+
+        run("jarsigner", "a.jar b -digestalg MD5")
+                .shouldContain("-digestalg option is considered a security risk.");
+        run("jarsigner", "a.jar b -digestalg MD5 -strict")
+                .shouldHaveExitValue(4)
+                .shouldContain("-digestalg option is considered a security risk.");
+        run("jarsigner", "a.jar b -sigalg MD5withRSA")
+                .shouldContain("-sigalg option is considered a security risk");
+
+        issueCert("b", "-sigalg MD5withRSA");
+        run("jarsigner", "a.jar b")
+                .shouldMatch("chain is invalid. Reason:.*MD5withRSA");
+
+        recreateJar();
+
+        newCert("c", "-keysize 512");
+        issueCert("c");
+        run("jarsigner", "a.jar c")
+                .shouldContain("chain is invalid. " +
+                        "Reason: Algorithm constraints check failed");
+
+        recreateJar();
+
+        newCert("s1"); issueCert("s1", "-startdate 2000/01/01 -validity 36525");
+        run("jarsigner", "a.jar s1")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp").shouldContain("2100-01-01")
+                .shouldNotContain("with signer errors");
+        run("jarsigner", "a.jar s1 -strict")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp").shouldContain("2100-01-01")
+                .shouldNotContain("with signer errors");
+        run("jarsigner", "a.jar s1 -verify")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp").shouldContain("2100-01-01")
+                .shouldNotContain("with signer errors");
+        run("jarsigner", "a.jar s1 -verify -strict")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp").shouldContain("2100-01-01")
+                .shouldNotContain("with signer errors");
+
+        recreateJar();
+
+        newCert("s2"); issueCert("s2", "-validity 100");
+        run("jarsigner", "a.jar s2")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp")
+                .shouldContain("will expire")
+                .shouldNotContain("with signer errors");
+        run("jarsigner", "a.jar s2 -strict")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp")
+                .shouldContain("will expire")
+                .shouldNotContain("with signer errors");
+        run("jarsigner", "a.jar s2 -verify")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp")
+                .shouldContain("will expire")
+                .shouldNotContain("with signer errors");
+        run("jarsigner", "a.jar s2 -verify -strict")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("Error:")
+                .shouldContain("timestamp")
+                .shouldContain("will expire")
+                .shouldNotContain("with signer errors");
+
+        recreateJar();
+
+        newCert("s3"); issueCert("s3", "-startdate -200d -validity 100");
+        run("jarsigner", "a.jar s3")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldContain("has expired")
+                .shouldNotContain("with signer errors")
+                .shouldNotContain("Error:");
+        run("jarsigner", "a.jar s3 -strict")
+                .shouldHaveExitValue(4)
+                .shouldContain("with signer errors")
+                .shouldMatch("(?s).*Error:.*has expired.*Warning:.*");
+        run("jarsigner", "a.jar s3 -verify")
+                .shouldHaveExitValue(0)
+                .shouldContain("Warning:")
+                .shouldNotContain("with signer errors")
+                .shouldNotContain("Error:");
+        run("jarsigner", "a.jar s3 -verify -strict")
+                .shouldHaveExitValue(4)
+                .shouldContain("with signer errors")
+                .shouldMatch("(?s).*Error:.*has expired.*Warning:.*");
+    }
+
+    // Creates a new jar without signature
+    static void recreateJar() throws Exception {
+        JarUtils.createJar("a.jar", "ks");
+    }
+
+    // Creates a self-signed cert for alias with zero or more -genkey options
+    static void newCert(String alias, String... more) throws Throwable {
+        String args = "-genkeypair -alias " + alias + " -dname CN=" + alias;
+        for (String s: more) {
+            args += " " + s;
+        }
+        run("keytool", args).shouldHaveExitValue(0);
+    }
+
+    // Asks ca to issue a cert to alias with zero or more -gencert options
+    static void issueCert(String alias, String...more) throws Throwable {
+        String req = run("keytool", "-certreq -alias " + alias)
+                .shouldHaveExitValue(0).getStdout();
+        String args = "-gencert -alias ca -rfc";
+        for (String s: more) {
+            args += " " + s;
+        }
+        String cert = run("keytool", args, req)
+                .shouldHaveExitValue(0).getStdout();
+        run("keytool", "-import -alias " + alias, cert).shouldHaveExitValue(0);
+    }
+
+    // Runs a java tool with command line arguments
+    static OutputAnalyzer run(String command, String args)
+            throws Throwable {
+        return run(command, args, null);
+    }
+
+    // Runs a java tool with command line arguments and an optional input block
+    static OutputAnalyzer run(String command, String args, String input)
+            throws Throwable {
+        JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK(command);
+        launcher.addVMArg("-Duser.language=en").addVMArg("-Duser.country=US");
+        switch (command) {
+            case "keytool":
+                for (String s: new String[] {
+                        "-keystore", "ks", "-storepass", "changeit",
+                        "-storetype", "jks",
+                        "-keypass", "changeit", "-keyalg", "rsa", "-debug"}) {
+                    launcher.addToolArg(s);
+                }
+                break;
+            case "jarsigner":
+                for (String s: new String[] {
+                        "-keystore", "ks", "-storepass", "changeit",
+                        "-storetype", "jks"}) {
+                    launcher.addToolArg(s);
+                }
+                break;
+        }
+        for (String arg: args.split(" ")) {
+            launcher.addToolArg(arg);
+        }
+        String[] cmd = launcher.getCommand();
+        ProcessBuilder pb = new ProcessBuilder(cmd);
+        OutputAnalyzer out = ProcessTools.executeProcess(pb, input);
+        System.out.println("======================");
+        System.out.println(Arrays.toString(cmd));
+        String msg = " stdout: [" + out.getStdout() + "];\n"
+                + " stderr: [" + out.getStderr() + "]\n"
+                + " exitValue = " + out.getExitValue() + "\n";
+        System.out.println(msg);
+        return out;
+    }
+}
+
--- a/test/sun/security/tools/jarsigner/checkusage.sh	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/checkusage.sh	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2010, 2017, 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,7 +91,7 @@
 #[ $RESULT = 0 ] || exit 2
 
 # Test 3: When no keystore is specified, the error is only
-# "chain not validated"
+# "chain invalid"
 
 $JARSIGNER -strict -verify a.jar
 RESULT=$?
@@ -99,7 +99,7 @@
 #[ $RESULT = 4 ] || exit 3
 
 # Test 4: When unrelated keystore is specified, the error is
-# "chain not validated" and "not alias in keystore"
+# "chain invalid" and "not alias in keystore"
 
 $JARSIGNER -keystore unrelated.jks -strict -verify a.jar
 RESULT=$?
--- a/test/sun/security/tools/jarsigner/concise_jarsigner.sh	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/concise_jarsigner.sh	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2009, 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
@@ -22,10 +22,10 @@
 #
 
 # @test
-# @bug 6802846
+# @bug 6802846 8172529
 # @summary jarsigner needs enhanced cert validation(options)
 #
-# @run shell concise_jarsigner.sh
+# @run shell/timeout=240 concise_jarsigner.sh
 #
 
 if [ "${TESTJAVA}" = "" ] ; then
@@ -47,12 +47,15 @@
 # Choose 1024-bit RSA to make sure it runs fine and fast on all platforms. In
 # fact, every keyalg/keysize combination is OK for this test.
 
-KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit -keystore js.jks -keyalg rsa -keysize 1024"
-JAR=$TESTJAVA${FS}bin${FS}jar
-JARSIGNER=$TESTJAVA${FS}bin${FS}jarsigner
-JAVAC=$TESTJAVA${FS}bin${FS}javac
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
 
-rm js.jks
+KS=js.ks
+KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa -keysize 1024"
+JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
+JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -debug"
+JAVAC="$TESTJAVA${FS}bin${FS}javac ${TESTTOOLVMOPTS} ${TESTJAVACOPTS}"
+
+rm $KS
 
 echo class A1 {} > A1.java
 echo class A2 {} > A2.java
@@ -68,14 +71,14 @@
 # First part: output format
 # ==========================================================
 
-$KT -genkeypair -alias a1 -dname CN=a1 -validity 365
-$KT -genkeypair -alias a2 -dname CN=a2 -validity 365
+$KT -genkeypair -alias a1 -dname CN=a1 -validity 366
+$KT -genkeypair -alias a2 -dname CN=a2 -validity 366
 
 # a.jar includes 8 unsigned, 2 signed by a1 and a2, 2 signed by a3
 $JAR cvf a.jar A1.class A2.class
-$JARSIGNER -keystore js.jks -storepass changeit a.jar a1
+$JARSIGNER -keystore $KS -storepass changeit a.jar a1
 $JAR uvf a.jar A3.class A4.class
-$JARSIGNER -keystore js.jks -storepass changeit a.jar a2
+$JARSIGNER -keystore $KS -storepass changeit a.jar a2
 $JAR uvf a.jar A5.class A6.class
 
 # Verify OK
@@ -87,15 +90,15 @@
 [ $? = 20 ] || exit $LINENO
 
 # 16(hasUnsignedEntry)
-$JARSIGNER -verify a.jar -strict -keystore js.jks
+$JARSIGNER -verify a.jar -strict -keystore $KS -storepass changeit
 [ $? = 16 ] || exit $LINENO
 
 # 16(hasUnsignedEntry)+32(notSignedByAlias)
-$JARSIGNER -verify a.jar a1 -strict -keystore js.jks
+$JARSIGNER -verify a.jar a1 -strict -keystore $KS -storepass changeit
 [ $? = 48 ] || exit $LINENO
 
 # 16(hasUnsignedEntry)
-$JARSIGNER -verify a.jar a1 a2 -strict -keystore js.jks
+$JARSIGNER -verify a.jar a1 a2 -strict -keystore $KS -storepass changeit
 [ $? = 16 ] || exit $LINENO
 
 # 12 entries all together
@@ -135,43 +138,52 @@
 [ $LINES = 4 ] || exit $LINENO
 
 # ==========================================================
-# Second part: exit code 2, 4, 8
+# Second part: exit code 2, 4, 8.
 # 16 and 32 already covered in the first part
 # ==========================================================
 
-$KT -genkeypair -alias expired -dname CN=expired -startdate -10m
-$KT -genkeypair -alias notyetvalid -dname CN=notyetvalid -startdate +1m
-$KT -genkeypair -alias badku -dname CN=badku -ext KU=cRLSign -validity 365
-$KT -genkeypair -alias badeku -dname CN=badeku -ext EKU=sa -validity 365
-$KT -genkeypair -alias goodku -dname CN=goodku -ext KU=dig -validity 365
-$KT -genkeypair -alias goodeku -dname CN=goodeku -ext EKU=codesign -validity 365
+$KT -genkeypair -alias ca -dname CN=ca -ext bc -validity 365
+$KT -genkeypair -alias expired -dname CN=expired
+$KT -certreq -alias expired | $KT -gencert -alias ca -startdate -10m | $KT -import -alias expired
+$KT -genkeypair -alias notyetvalid -dname CN=notyetvalid
+$KT -certreq -alias notyetvalid | $KT -gencert -alias ca -startdate +1m | $KT -import -alias notyetvalid
+$KT -genkeypair -alias badku -dname CN=badku
+$KT -certreq -alias badku | $KT -gencert -alias ca -ext KU=cRLSign -validity 365 | $KT -import -alias badku
+$KT -genkeypair -alias badeku -dname CN=badeku
+$KT -certreq -alias badeku | $KT -gencert -alias ca -ext EKU=sa -validity 365 | $KT -import -alias badeku
+$KT -genkeypair -alias goodku -dname CN=goodku
+$KT -certreq -alias goodku | $KT -gencert -alias ca -ext KU=dig -validity 365 | $KT -import -alias goodku
+$KT -genkeypair -alias goodeku -dname CN=goodeku
+$KT -certreq -alias goodeku | $KT -gencert -alias ca -ext EKU=codesign -validity 365 | $KT -import -alias goodeku
 
-# badchain signed by ca, but ca is removed later
-$KT -genkeypair -alias badchain -dname CN=badchain -validity 365
-$KT -genkeypair -alias ca -dname CN=ca -ext bc -validity 365
-$KT -certreq -alias badchain | $KT -gencert -alias ca -validity 365 | \
-        $KT -importcert -alias badchain
-$KT -delete -alias ca
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar expired
+[ $? = 4 ] || exit $LINENO
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar expired
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar notyetvalid
 [ $? = 4 ] || exit $LINENO
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar notyetvalid
-[ $? = 4 ] || exit $LINENO
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar badku
+[ $? = 8 ] || exit $LINENO
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar badku
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar badeku
 [ $? = 8 ] || exit $LINENO
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar badeku
-[ $? = 8 ] || exit $LINENO
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar goodku
+[ $? = 0 ] || exit $LINENO
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar goodku
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar goodeku
 [ $? = 0 ] || exit $LINENO
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar goodeku
-[ $? = 0 ] || exit $LINENO
+# badchain signed by ca1, but ca1 is removed later
+$KT -genkeypair -alias badchain -dname CN=badchain -validity 365
+$KT -genkeypair -alias ca1 -dname CN=ca1 -ext bc -validity 365
+$KT -certreq -alias badchain | $KT -gencert -alias ca1 -validity 365 | \
+        $KT -importcert -alias badchain
+# save ca1.cert for easy replay
+$KT -exportcert -file ca1.cert -alias ca1
+$KT -delete -alias ca1
 
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar badchain
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar badchain
 [ $? = 4 ] || exit $LINENO
 
 $JARSIGNER -verify a.jar
@@ -181,23 +193,55 @@
 # Third part: -certchain test
 # ==========================================================
 
-# altchain signed by ca2, but ca2 is removed later
+# altchain signed by ca2
 $KT -genkeypair -alias altchain -dname CN=altchain -validity 365
 $KT -genkeypair -alias ca2 -dname CN=ca2 -ext bc -validity 365
 $KT -certreq -alias altchain | $KT -gencert -alias ca2 -validity 365 -rfc > certchain
 $KT -exportcert -alias ca2 -rfc >> certchain
-$KT -delete -alias ca2
 
-# Now altchain is still self-signed
-$JARSIGNER -strict -keystore js.jks -storepass changeit a.jar altchain
+# Self-signed cert does not work
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar altchain
+[ $? = 4 ] || exit $LINENO
+
+# -certchain works
+$JARSIGNER -strict -keystore $KS -storepass changeit -certchain certchain a.jar altchain
 [ $? = 0 ] || exit $LINENO
 
-# If -certchain is used, then it's bad
-$JARSIGNER -strict -keystore js.jks -storepass changeit -certchain certchain a.jar altchain
+# if ca2 is removed, -certchain still work because altchain is a self-signed entry and
+# it is trusted by jarsigner
+# save ca2.cert for easy replay
+$KT -exportcert -file ca2.cert -alias ca2
+$KT -delete -alias ca2
+$JARSIGNER -strict -keystore $KS -storepass changeit -certchain certchain a.jar altchain
+[ $? = 0 ] || exit $LINENO
+
+# if cert is imported, -certchain won't work because this certificate entry is not trusted
+$KT -importcert -file certchain -alias altchain -noprompt
+$JARSIGNER -strict -keystore $KS -storepass changeit -certchain certchain a.jar altchain
 [ $? = 4 ] || exit $LINENO
 
 $JARSIGNER -verify a.jar
 [ $? = 0 ] || exit $LINENO
 
+# ==========================================================
+# 8172529
+# ==========================================================
+
+$KT -genkeypair -alias ee -dname CN=ee
+$KT -genkeypair -alias caone -dname CN=caone
+$KT -genkeypair -alias catwo -dname CN=catwo
+
+$KT -certreq -alias ee | $KT -gencert -alias catwo -rfc > ee.cert
+$KT -certreq -alias catwo | $KT -gencert -alias caone -sigalg MD5withRSA -rfc > catwo.cert
+
+# This certchain contains a cross-signed weak catwo.cert
+cat ee.cert catwo.cert | $KT -importcert -alias ee
+
+$JAR cvf a.jar A1.class
+$JARSIGNER -strict -keystore $KS -storepass changeit a.jar ee
+[ $? = 0 ] || exit $LINENO
+$JARSIGNER -strict -keystore $KS -storepass changeit -verify a.jar
+[ $? = 0 ] || exit $LINENO
+
 echo OK
 exit 0
--- a/test/sun/security/tools/jarsigner/ec.sh	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/ec.sh	Mon Oct 15 15:05:59 2018 +0100
@@ -53,11 +53,20 @@
 echo A > A
 $JAR cvf $JFILE A
 
-$KT -alias a -dname CN=a -keyalg ec -genkey -validity 300 || exit 11
-$KT -alias b -dname CN=b -keyalg ec -genkey -validity 300 || exit 12
+$KT -alias ca -dname CN=ca -keyalg ec -genkey -validity 300 || exit 11
+
+$KT -alias a -dname CN=a -keyalg ec -genkey || exit 11
+$KT -alias a -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias a || exit 111
+
+$KT -alias b -dname CN=b -keyalg ec -genkey || exit 12
+$KT -alias b -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias b || exit 121
+
 # Ensure that key length is sufficient for the intended hash (SHA512withECDSA)
-$KT -alias c -dname CN=c -keyalg ec -genkey -validity 300 -keysize 521 || exit 13
+$KT -alias c -dname CN=c -keyalg ec -genkey -keysize 521 || exit 13
+$KT -alias c -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias c || exit 131
+
 $KT -alias x -dname CN=x -keyalg ec -genkey -validity 300 || exit 14
+$KT -alias x -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias x || exit 141
 
 $JARSIGNER -keystore $KS -storepass changeit $JFILE a -debug -strict || exit 21
 $JARSIGNER -keystore $KS -storepass changeit $JFILE b -debug -strict -sigalg SHA1withECDSA || exit 22
--- a/test/sun/security/tools/jarsigner/onlymanifest.sh	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/onlymanifest.sh	Mon Oct 15 15:05:59 2018 +0100
@@ -57,12 +57,14 @@
 echo "Key: Value" > manifest
 $JAR cvfm $JFILE manifest
 
-$KT -alias a -dname CN=a -genkey -validity 300 || exit 1
-$JARSIGNER -keystore $KS -storepass changeit $JFILE a -debug -strict || exit 2
+$KT -alias ca -dname CN=ca -genkey -validity 300 || exit 1
+$KT -alias a -dname CN=a -genkey -validity 300 || exit 2
+$KT -alias a -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias a || exit 3
+$JARSIGNER -keystore $KS -storepass changeit $JFILE a -debug -strict || exit 4
 $JARSIGNER -keystore $KS -storepass changeit -verify $JFILE a -debug -strict \
-        > onlymanifest.out || exit 3
+        > onlymanifest.out || exit 5
 
-grep unsigned onlymanifest.out && exit 4
+grep unsigned onlymanifest.out && exit 6
 
 exit 0
 
--- a/test/sun/security/tools/jarsigner/warnings.sh	Sun Oct 14 19:45:50 2018 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,122 +0,0 @@
-#
-# Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8024302
-# @bug 8026037 8134124
-# @summary Clarify jar verifications
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
-  JAVAC_CMD=`which javac`
-  TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  Windows_* )
-    FS="\\"
-    ;;
-  * )
-    FS="/"
-    ;;
-esac
-
-# make the test locale independent
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-KS=warnings.jks
-JFILE=warnings.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit \
-        -keystore $KS"
-JAR=$TESTJAVA${FS}bin${FS}jar
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -keystore $KS -storepass changeit"
-
-rm $KS 2> /dev/null
-
-LANG=C
-export LANG
-
-echo 12345 > file
-
-ERR=""
-
-# Normal signer expiring on 2100-01-01
-$KT -alias s1 -dname CN=s1 -genkey -startdate 2000/01/01 -validity 36525 || ERR="$ERR keytool s1,"
-# Cert expiring soon, informational warning
-$KT -alias s2 -dname CN=s2 -genkey -validity 100 || ERR="$ERR keytool s2,"
-# Cert expired, severe warning
-$KT -alias s3 -dname CN=s3 -genkey -startdate -200d -validity 100 || ERR="$ERR keytool s3,"
-
-# noTimestamp is informatiional warning and includes a date
-$JAR cvf $JFILE file
-$JARSIGNER $JFILE s1 > output1 || ERR="$ERR jarsigner s1,"
-$JARSIGNER -strict $JFILE s1 >> output1 || ERR="$ERR jarsigner s1 strict,"
-$JARSIGNER -verify $JFILE s1 >> output1 || ERR="$ERR jarsigner s1,"
-$JARSIGNER -verify -strict $JFILE s1 >> output1 || ERR="$ERR jarsigner s1 strict,"
-
-cat output1 | grep Warning || ERR="$ERR s1 warning,"
-cat output1 | grep Error && ERR="$ERR s1 error,"
-cat output1 | grep timestamp | grep 2100-01-01 || ERR="$ERR s1 timestamp,"
-cat output1 | grep "with signer errors" && ERR="$ERR s1 err,"
-
-# hasExpiringCert is informatiional warning
-$JAR cvf $JFILE file
-$JARSIGNER $JFILE s2 > output2 || ERR="$ERR jarsigner s2,"
-$JARSIGNER -strict $JFILE s2 >> output2 || ERR="$ERR jarsigner s2 strict,"
-$JARSIGNER -verify $JFILE s2 >> output2 || ERR="$ERR jarsigner s2,"
-$JARSIGNER -verify -strict $JFILE s2 >> output2 || ERR="$ERR jarsigner s2 strict,"
-
-cat output2 | grep Warning || ERR="$ERR s2 warning,"
-cat output2 | grep Error && ERR="$ERR s2 error,"
-cat output2 | grep timestamp || ERR="$ERR s2 timestamp,"
-cat output2 | grep "will expire" || ERR="$ERR s2 expiring,"
-cat output2 | grep "with signer errors" && ERR="$ERR s2 err,"
-
-# hasExpiredCert is severe warning
-$JAR cvf $JFILE file
-$JARSIGNER $JFILE s3 > output3 || ERR="$ERR jarsigner s3,"
-$JARSIGNER -strict $JFILE s3 > output3s && ERR="$ERR jarsigner s3 strict,"
-$JARSIGNER -verify $JFILE s3 >> output3 || ERR="$ERR jarsigner s3,"
-$JARSIGNER -verify -strict $JFILE s3 >> output3s && ERR="$ERR jarsigner s3 strict,"
-
-# warning without -strict
-cat output3 | grep Warning || ERR="$ERR s3 warning,"
-cat output3 | grep Error && ERR="$ERR s3 error,"
-cat output3 | grep "with signer errors" && ERR="$ERR s3 err,"
-
-# error with -strict
-cat output3s | grep Warning || ERR="$ERR s3s warning,"
-cat output3s | grep Error || ERR="$ERR s3s error,"
-cat output3s | grep "with signer errors" || ERR="$ERR s3 err,"
-
-if [ "$ERR" = "" ]; then
-    exit 0
-else
-    echo "ERR is $ERR"
-    exit 1
-fi
-
-
--- a/test/sun/security/tools/jarsigner/warnings/Test.java	Sun Oct 14 19:45:50 2018 -0400
+++ b/test/sun/security/tools/jarsigner/warnings/Test.java	Mon Oct 15 15:05:59 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -63,7 +63,7 @@
 
     static final String CHAIN_NOT_VALIDATED_VERIFYING_WARNING
             = "This jar contains entries "
-            + "whose certificate chain is not validated.";
+            + "whose certificate chain is invalid.";
 
     static final String ALIAS_NOT_IN_STORE_VERIFYING_WARNING
             = "This jar contains signed entries "
@@ -95,7 +95,7 @@
             + "doesn't allow code signing.";
 
     static final String CHAIN_NOT_VALIDATED_SIGNING_WARNING
-            = "The signer's certificate chain is not validated.";
+            = "The signer's certificate chain is invalid.";
 
     static final String HAS_EXPIRING_CERT_SIGNING_WARNING
             = "The signer certificate will expire within six months.";
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/tools/jarsigner/weaksize.sh	Mon Oct 15 15:05:59 2018 +0100
@@ -0,0 +1,60 @@
+#
+# Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# @test
+# @bug 8044755
+# @summary Add a test for algorithm constraints check in jarsigner
+#
+
+if [ "${TESTJAVA}" = "" ] ; then
+  JAVAC_CMD=`which javac`
+  TESTJAVA=`dirname $JAVAC_CMD`/..
+fi
+
+# The sigalg used is MD2withRSA, which is obsolete.
+
+KT="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -keystore ks
+    -storepass changeit -keypass changeit
+    -keyalg rsa -sigalg MD2withRSA -debug"
+JS="$TESTJAVA/bin/jarsigner ${TESTTOOLVMOPTS} -keystore ks
+    -storepass changeit -strict -debug"
+JAR="$TESTJAVA/bin/jar ${TESTTOOLVMOPTS}"
+
+rm ks 2> /dev/null
+
+$KT -genkeypair -alias ca -dname CN=CA -ext bc
+$KT -genkeypair -alias signer -dname CN=Signer
+
+$KT -certreq -alias signer | \
+        $KT -gencert -alias ca -ext ku=dS -rfc | \
+        $KT -importcert -alias signer
+
+$JAR cvf a.jar ks
+
+# We always trust a TrustedCertificateEntry
+$JS a.jar ca | grep "chain is invalid" && exit 1
+
+# An end-entity cert must follow algorithm constraints
+$JS a.jar signer | grep "chain is invalid" || exit 2
+
+exit 0